Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

28.5 KB
Raw Blame
/**
 * Pure TypeScript Tool Configurations, Presets & UI Geometry Helpers.
 *
 * Holds ZERO HTMLCanvasElement allocations and ZERO full-document pixel raster loops;
 * all raster execution runs natively in `crates/ink-engine` via `nativeEngineBridge.ts`.
 */

import type {
  FilterType,
  GradientStop,
  Point2D,
  ToneCurvePoints,
} from '../types/editor';
import type {
  NativeFilterSpec,
  NativeGradientParams,
  NativeTonalSpec,
} from './nativeEngineBridge';
import { parseHexRgb } from './tauriEnv';

// ============================================================================
// 1. Gradient Tool Configs, Presets & Mesh Handle Geometry (SVG UI only)
// ============================================================================

export type GradientType = 'linear' | 'radial' | 'conical' | 'diamond' | 'mesh';
export type GradientRepeatMode = 'clamp' | 'repeat' | 'reflect';
export type GradientBlendMode = 'normal' | 'multiply' | 'screen' | 'overlay';

export interface GradientToolStop {
  id: string;
  offset: number; // 0..1
  color: string; // #rrggbb
  opacity: number; // 0..1
}

export interface GradientMeshNode {
  x: number;
  y: number;
  color: string;
  opacity: number;
}

export interface GradientMeshState {
  cols: number;
  rows: number;
  nodes: GradientMeshNode[];
  selectedNodeIndex: number | null;
  selectedNodeIndices?: number[];
  rotationDeg?: number;
}

export interface GradientSettings {
  type: GradientType;
  stops: GradientToolStop[];
  useForegroundBackground: boolean;
  opacity: number;
  blendMode: GradientBlendMode;
  repeat: GradientRepeatMode;
  dither: boolean;
  pigmentBlending?: boolean;
  reverse: boolean;
  meshCols: number;
  meshRows: number;
}

export interface GradientDragPreview {
  type: 'linear' | 'radial' | 'conical' | 'diamond';
  start: Point2D;
  end: Point2D;
  settings: GradientSettings;
}

export interface GradientPreset {
  id: string;
  name: string;
  useForegroundBackground?: boolean;
  stops: Array<{ offset: number; color: string; opacity: number }>;
}

export const GRADIENT_PRESETS: readonly GradientPreset[] = [
  {
    id: 'fg-bg',
    name: 'FG to BG',
    useForegroundBackground: true,
    stops: [
      { offset: 0, color: '#000000', opacity: 1 },
      { offset: 1, color: '#ffffff', opacity: 1 },
    ],
  },
  {
    id: 'fg-transparent',
    name: 'FG to Clear',
    useForegroundBackground: false,
    stops: [
      { offset: 0, color: '#000000', opacity: 1 },
      { offset: 1, color: '#000000', opacity: 0 },
    ],
  },
  {
    id: 'sunset',
    name: 'Sunset',
    useForegroundBackground: false,
    stops: [
      { offset: 0, color: '#1e1b4b', opacity: 1 },
      { offset: 0.45, color: '#be185d', opacity: 1 },
      { offset: 0.78, color: '#f97316', opacity: 1 },
      { offset: 1, color: '#fde047', opacity: 1 },
    ],
  },
  {
    id: 'sky',
    name: 'Sky',
    useForegroundBackground: false,
    stops: [
      { offset: 0, color: '#0c4a6e', opacity: 1 },
      { offset: 0.55, color: '#38bdf8', opacity: 1 },
      { offset: 1, color: '#f0f9ff', opacity: 1 },
    ],
  },
  {
    id: 'chrome',
    name: 'Chrome',
    useForegroundBackground: false,
    stops: [
      { offset: 0, color: '#111827', opacity: 1 },
      { offset: 0.35, color: '#e5e7eb', opacity: 1 },
      { offset: 0.52, color: '#374151', opacity: 1 },
      { offset: 0.8, color: '#f9fafb', opacity: 1 },
      { offset: 1, color: '#1f2937', opacity: 1 },
    ],
  },
  {
    id: 'spectrum',
    name: 'Spectrum',
    useForegroundBackground: false,
    stops: [
      { offset: 0, color: '#ef4444', opacity: 1 },
      { offset: 0.2, color: '#f59e0b', opacity: 1 },
      { offset: 0.4, color: '#22c55e', opacity: 1 },
      { offset: 0.6, color: '#06b6d4', opacity: 1 },
      { offset: 0.8, color: '#6366f1', opacity: 1 },
      { offset: 1, color: '#ec4899', opacity: 1 },
    ],
  },
];

export const DEFAULT_GRADIENT_SETTINGS: GradientSettings = {
  type: 'linear',
  stops: [
    { id: 'stop-0', offset: 0, color: '#000000', opacity: 1 },
    { id: 'stop-1', offset: 1, color: '#ffffff', opacity: 1 },
  ],
  useForegroundBackground: true,
  opacity: 1,
  blendMode: 'normal',
  repeat: 'clamp',
  dither: true,
  pigmentBlending: false,
  reverse: false,
  meshCols: 3,
  meshRows: 3,
};

export interface ParsedRgbaStop {
  offset: number;
  r: number;
  g: number;
  b: number;
  a: number;
}

export function resolveGradientStops(
  settings: GradientSettings,
  primaryColor: string,
  secondaryColor: string
): ParsedRgbaStop[] {
  const candidateStops = Array.isArray(settings?.stops)
    ? settings.stops.filter((s) => Boolean(s) && typeof s === 'object')
    : [];
  const raw = candidateStops.length >= 2 ? candidateStops : DEFAULT_GRADIENT_SETTINGS.stops;
  const sorted = [...raw]
    .map((s) => ({
      offset: Math.max(0, Math.min(1, Number.isFinite(s.offset) ? s.offset : 0)),
      color: typeof s.color === 'string' && s.color ? s.color : '#000000',
      opacity: Math.max(0, Math.min(1, Number.isFinite(s.opacity) ? s.opacity : 1)),
    }))
    .sort((a, b) => a.offset - b.offset);

  if (settings?.useForegroundBackground && sorted.length >= 2) {
    sorted[0] = { ...sorted[0], color: primaryColor || '#000000' };
    sorted[sorted.length - 1] = {
      ...sorted[sorted.length - 1],
      color: secondaryColor || '#ffffff',
    };
  }

  return sorted.map((s) => {
    const [r, g, b] = parseHexRgb(s.color);
    return { offset: s.offset, r, g, b, a: s.opacity * 255 };
  });
}

export function constrainGradientEndpoint(start: Point2D, end: Point2D): Point2D {
  const dx = end.x - start.x;
  const dy = end.y - start.y;
  const len = Math.hypot(dx, dy);
  if (len < 1e-4) return end;
  const angle = Math.atan2(dy, dx);
  const snapped = Math.round(angle / (Math.PI / 12)) * (Math.PI / 12);
  return {
    x: start.x + Math.cos(snapped) * len,
    y: start.y + Math.sin(snapped) * len,
  };
}

export function createDefaultGradientMesh(
  bounds: { x: number; y: number; width: number; height: number },
  cols: number,
  rows: number,
  primaryColor: string,
  secondaryColor: string,
  stops?: readonly GradientToolStop[]
): GradientMeshState {
  const cCount = Math.max(2, Math.min(6, Math.round(cols)));
  const rCount = Math.max(2, Math.min(6, Math.round(rows)));
  const w = Math.max(1, bounds.width);
  const h = Math.max(1, bounds.height);

  const safeStops = Array.isArray(stops) ? stops : [];
  const midStopColor = safeStops.length > 2 ? safeStops[Math.floor(safeStops.length / 2)]?.color : undefined;
  const endStopColor = safeStops.length > 0 ? safeStops[safeStops.length - 1]?.color : undefined;
  const cornerColors = [
    primaryColor || '#3b82f6',
    secondaryColor || '#f43f5e',
    typeof midStopColor === 'string' && midStopColor ? midStopColor : '#10b981',
    typeof endStopColor === 'string' && endStopColor ? endStopColor : '#f59e0b',
  ];
  const parsedCorners = cornerColors.map((c) => parseHexRgb(c));

  const nodes: GradientMeshNode[] = [];
  for (let r = 0; r < rCount; r++) {
    const v = rCount > 1 ? r / (rCount - 1) : 0;
    for (let c = 0; c < cCount; c++) {
      const u = cCount > 1 ? c / (cCount - 1) : 0;
      const topR = parsedCorners[0][0] * (1 - u) + parsedCorners[1][0] * u;
      const topG = parsedCorners[0][1] * (1 - u) + parsedCorners[1][1] * u;
      const topB = parsedCorners[0][2] * (1 - u) + parsedCorners[1][2] * u;
      const botR = parsedCorners[2][0] * (1 - u) + parsedCorners[3][0] * u;
      const botG = parsedCorners[2][1] * (1 - u) + parsedCorners[3][1] * u;
      const botB = parsedCorners[2][2] * (1 - u) + parsedCorners[3][2] * u;
      const rr = Math.round(topR * (1 - v) + botR * v);
      const gg = Math.round(topG * (1 - v) + botG * v);
      const bb = Math.round(topB * (1 - v) + botB * v);
      const hex =
        '#' +
        rr.toString(16).padStart(2, '0') +
        gg.toString(16).padStart(2, '0') +
        bb.toString(16).padStart(2, '0');
      nodes.push({
        x: bounds.x + u * w,
        y: bounds.y + v * h,
        color: hex,
        opacity: 1,
      });
    }
  }

  return {
    cols: cCount,
    rows: rCount,
    nodes,
    selectedNodeIndex: 0,
    selectedNodeIndices: [0],
    rotationDeg: 0,
  };
}

export function normalizeMeshAngleDeg(deg: number): number {
  if (!Number.isFinite(deg)) return 0;
  let a = ((((deg + 180) % 360) + 360) % 360) - 180;
  if (a <= -180) a = 180;
  return Math.abs(a) < 1e-9 ? 0 : a;
}

export function getSelectedMeshNodeIndices(mesh: GradientMeshState): number[] {
  const n = mesh.nodes.length;
  if (n === 0) return [];
  if (Array.isArray(mesh.selectedNodeIndices)) {
    const seen = new Set<number>();
    const result: number[] = [];
    for (const idx of mesh.selectedNodeIndices) {
      if (Number.isInteger(idx) && idx >= 0 && idx < n && !seen.has(idx)) {
        seen.add(idx);
        result.push(idx);
      }
    }
    result.sort((a, b) => a - b);
    return result;
  }
  if (
    mesh.selectedNodeIndex !== null &&
    Number.isInteger(mesh.selectedNodeIndex) &&
    mesh.selectedNodeIndex >= 0 &&
    mesh.selectedNodeIndex < n
  ) {
    return [mesh.selectedNodeIndex];
  }
  return [];
}

export function setGradientMeshSelection(
  mesh: GradientMeshState,
  indices: readonly number[],
  primaryIndex?: number | null
): GradientMeshState {
  const n = mesh.nodes.length;
  const seen = new Set<number>();
  const unique: number[] = [];
  for (const idx of indices) {
    if (Number.isInteger(idx) && idx >= 0 && idx < n && !seen.has(idx)) {
      seen.add(idx);
      unique.push(idx);
    }
  }
  unique.sort((a, b) => a - b);
  const resolvedPrimary =
    primaryIndex !== undefined && primaryIndex !== null && seen.has(primaryIndex)
      ? primaryIndex
      : unique.length > 0
        ? unique[unique.length - 1]
        : null;
  return {
    ...mesh,
    selectedNodeIndex: resolvedPrimary,
    selectedNodeIndices: unique,
  };
}

export function toggleGradientMeshNodeSelection(
  mesh: GradientMeshState,
  index: number
): GradientMeshState {
  if (!Number.isInteger(index) || index < 0 || index >= mesh.nodes.length) return mesh;
  const current = getSelectedMeshNodeIndices(mesh);
  if (current.includes(index)) {
    return setGradientMeshSelection(
      mesh,
      current.filter((i) => i !== index)
    );
  }
  return setGradientMeshSelection(mesh, [...current, index], index);
}

export function selectAllGradientMeshNodes(mesh: GradientMeshState): GradientMeshState {
  const all = mesh.nodes.map((_, i) => i);
  const primary =
    mesh.selectedNodeIndex !== null &&
    mesh.selectedNodeIndex >= 0 &&
    mesh.selectedNodeIndex < mesh.nodes.length
      ? mesh.selectedNodeIndex
      : all.length > 0
        ? 0
        : null;
  return setGradientMeshSelection(mesh, all, primary);
}

export function invertGradientMeshSelection(mesh: GradientMeshState): GradientMeshState {
  const current = new Set(getSelectedMeshNodeIndices(mesh));
  const next: number[] = [];
  for (let i = 0; i < mesh.nodes.length; i++) {
    if (!current.has(i)) next.push(i);
  }
  return setGradientMeshSelection(mesh, next);
}

export function selectGradientMeshNodesInRect(
  mesh: GradientMeshState,
  rect: { x: number; y: number; width: number; height: number },
  additive = false
): GradientMeshState {
  const minX = Math.min(rect.x, rect.x + rect.width);
  const maxX = Math.max(rect.x, rect.x + rect.width);
  const minY = Math.min(rect.y, rect.y + rect.height);
  const maxY = Math.max(rect.y, rect.y + rect.height);
  const hit: number[] = [];
  for (let i = 0; i < mesh.nodes.length; i++) {
    const n = mesh.nodes[i];
    if (n.x >= minX && n.x <= maxX && n.y >= minY && n.y <= maxY) {
      hit.push(i);
    }
  }
  const combined = additive ? [...getSelectedMeshNodeIndices(mesh), ...hit] : hit;
  return setGradientMeshSelection(mesh, combined);
}

export function getGradientMeshCentroid(mesh: GradientMeshState): Point2D {
  const count = mesh.nodes.length;
  if (count === 0) return { x: 0, y: 0 };
  let sx = 0;
  let sy = 0;
  for (let i = 0; i < count; i++) {
    sx += mesh.nodes[i].x;
    sy += mesh.nodes[i].y;
  }
  return { x: sx / count, y: sy / count };
}

export function getGradientMeshBounds(mesh: GradientMeshState): {
  minX: number;
  minY: number;
  maxX: number;
  maxY: number;
  width: number;
  height: number;
} {
  if (mesh.nodes.length === 0) {
    return { minX: 0, minY: 0, maxX: 0, maxY: 0, width: 0, height: 0 };
  }
  let minX = Infinity;
  let minY = Infinity;
  let maxX = -Infinity;
  let maxY = -Infinity;
  for (const n of mesh.nodes) {
    if (n.x < minX) minX = n.x;
    if (n.y < minY) minY = n.y;
    if (n.x > maxX) maxX = n.x;
    if (n.y > maxY) maxY = n.y;
  }
  return { minX, minY, maxX, maxY, width: maxX - minX, height: maxY - minY };
}

export function rotateGradientMeshVertices(
  mesh: GradientMeshState,
  deltaDeg: number,
  pivot?: Point2D
): GradientMeshState {
  if (mesh.nodes.length === 0 || !Number.isFinite(deltaDeg)) return mesh;
  const center = pivot ?? getGradientMeshCentroid(mesh);
  const rad = (deltaDeg * Math.PI) / 180;
  const cos = Math.cos(rad);
  const sin = Math.sin(rad);
  return {
    ...mesh,
    nodes: mesh.nodes.map((node) => {
      const dx = node.x - center.x;
      const dy = node.y - center.y;
      return {
        ...node,
        x: center.x + dx * cos - dy * sin,
        y: center.y + dx * sin + dy * cos,
      };
    }),
    rotationDeg: normalizeMeshAngleDeg((mesh.rotationDeg ?? 0) + deltaDeg),
  };
}

export function rotateGradientMeshFromBase(
  basePositions: readonly Point2D[],
  baseRotationDeg: number,
  mesh: GradientMeshState,
  deltaDeg: number,
  pivot: Point2D
): GradientMeshState {
  if (
    mesh.nodes.length === 0 ||
    basePositions.length !== mesh.nodes.length ||
    !Number.isFinite(deltaDeg)
  ) {
    return mesh;
  }
  const rad = (deltaDeg * Math.PI) / 180;
  const cos = Math.cos(rad);
  const sin = Math.sin(rad);
  return {
    ...mesh,
    nodes: mesh.nodes.map((node, i) => {
      const dx = basePositions[i].x - pivot.x;
      const dy = basePositions[i].y - pivot.y;
      return {
        ...node,
        x: pivot.x + dx * cos - dy * sin,
        y: pivot.y + dx * sin + dy * cos,
      };
    }),
    rotationDeg: normalizeMeshAngleDeg(baseRotationDeg + deltaDeg),
  };
}

export function setGradientMeshRotation(
  mesh: GradientMeshState,
  targetDeg: number,
  pivot?: Point2D
): GradientMeshState {
  if (!Number.isFinite(targetDeg)) return mesh;
  const delta = targetDeg - (mesh.rotationDeg ?? 0);
  const rotated = rotateGradientMeshVertices(mesh, delta, pivot);
  return { ...rotated, rotationDeg: normalizeMeshAngleDeg(targetDeg) };
}

export function updateGradientMeshNodes(
  mesh: GradientMeshState,
  indices: readonly number[],
  patch: { color?: string; opacity?: number }
): GradientMeshState {
  if (indices.length === 0 || mesh.nodes.length === 0) return mesh;
  const targetSet = new Set(indices);
  let changed = false;
  const nextNodes = mesh.nodes.map((node, i) => {
    if (!targetSet.has(i)) return node;
    const nextColor = patch.color !== undefined ? patch.color : node.color;
    const nextOpacity =
      patch.opacity !== undefined ? Math.max(0, Math.min(1, patch.opacity)) : node.opacity;
    if (nextColor === node.color && nextOpacity === node.opacity) return node;
    changed = true;
    return { ...node, color: nextColor, opacity: nextOpacity };
  });
  return changed ? { ...mesh, nodes: nextNodes } : mesh;
}

export function toNativeGradientParams(params: {
  settings: GradientSettings;
  start: Point2D;
  end: Point2D;
  primaryColor: string;
  secondaryColor: string;
  mesh?: GradientMeshState | null;
  layerId?: string | null;
}): NativeGradientParams {
  const { settings, start, end, primaryColor, secondaryColor, mesh, layerId } = params;
  const rawStops =
    settings.stops.length >= 2 ? settings.stops : DEFAULT_GRADIENT_SETTINGS.stops;
  const sorted = [...rawStops].sort((a, b) => a.offset - b.offset);
  const resolvedStops = sorted.map((s, idx) => ({
    position: Math.max(0, Math.min(1, s.offset)),
    color:
      settings.useForegroundBackground && idx === 0
        ? primaryColor || '#000000'
        : settings.useForegroundBackground && idx === sorted.length - 1
          ? secondaryColor || '#ffffff'
          : s.color,
    opacity: Math.max(0, Math.min(1, s.opacity)),
  }));

  let nativeMesh: NativeGradientParams['mesh'] = null;
  if (settings.type === 'mesh' && mesh && mesh.nodes.length > 0) {
    const b = getGradientMeshBounds(mesh);
    const w = Math.max(1, b.width);
    const h = Math.max(1, b.height);
    const cx = b.minX + w * 0.5;
    const cy = b.minY + h * 0.5;
    const rotRad = ((mesh.rotationDeg ?? 0) * Math.PI) / 180;
    const cRot = Math.cos(-rotRad);
    const sRot = Math.sin(-rotRad);
    // Rust GradientMeshParams uses cell counts (stride = cols + 1, expecting (cols+1)*(rows+1) nodes),
    // whereas TS GradientMeshState stores vertex counts (mesh.cols * mesh.rows === mesh.nodes.length).
    const cellCols = Math.max(1, mesh.cols - 1);
    const cellRows = Math.max(1, mesh.rows - 1);
    nativeMesh = {
      cols: cellCols,
      rows: cellRows,
      x: b.minX,
      y: b.minY,
      width: w,
      height: h,
      rotation: rotRad,
      nodes: mesh.nodes.map((n) => {
        const dx = n.x - cx;
        const dy = n.y - cy;
        const lx = dx * cRot - dy * sRot;
        const ly = dx * sRot + dy * cRot;
        return {
          u: Math.max(0, Math.min(1, lx / w + 0.5)),
          v: Math.max(0, Math.min(1, ly / h + 0.5)),
          color: n.color,
          opacity: n.opacity,
        };
      }),
    };
  }

  return {
    gradientType: settings.type,
    stops: resolvedStops,
    start: [start.x, start.y],
    end: [end.x, end.y],
    repeat: settings.repeat,
    blendMode: settings.blendMode,
    opacity: settings.opacity,
    dither: settings.dither,
    reverse: settings.reverse,
    pigmentBlending: Boolean(settings.pigmentBlending),
    mesh: nativeMesh,
    layerId: layerId ?? null,
  };
}

// ============================================================================
// 2. Retouch Settings (Direct Rust Execution)
// ============================================================================

export type RetouchMode = 'smudge' | 'blur' | 'dodge' | 'burn' | 'sponge' | 'clone-stamp' | 'heal';
export type RetouchTonalRange = 'shadows' | 'midtones' | 'highlights';
export type CloneSampleMode = 'active' | 'all-visible';

export interface RetouchSettings {
  mode: RetouchMode;
  size: number;
  strength: number;
  hardness: number;
  spacing: number;
  usePressure: boolean;
  tonalRange: RetouchTonalRange;
  protectTones: boolean;
  smudgeFingerPainting: boolean;
  pigmentBlending: boolean;
  pigmentStrength: number;
  cloneAligned: boolean;
  cloneSampleMode: CloneSampleMode;
  spongeMode?: 'saturate' | 'desaturate';
}

export const DEFAULT_RETOUCH_SETTINGS: RetouchSettings = {
  mode: 'smudge',
  size: 40,
  strength: 50,
  hardness: 45,
  spacing: 0.15,
  usePressure: true,
  tonalRange: 'midtones',
  protectTones: true,
  smudgeFingerPainting: false,
  pigmentBlending: true,
  pigmentStrength: 100,
  cloneAligned: true,
  cloneSampleMode: 'active',
  spongeMode: 'saturate',
};

// ============================================================================
// 3. Liquify Types (Direct GPU Execution)
// ============================================================================

export type LiquifyMode =
  | 'push'
  | 'expand'
  | 'pinch'
  | 'push-left'
  | 'push-right'
  | 'twirl-cw'
  | 'twirl-ccw'
  | 'reconstruct';

export interface LiquifySettings {
  mode: LiquifyMode;
  size: number;
  strength: number;
  hardness: number;
  usePressure: boolean;
  multiLayer?: boolean;
}

// ============================================================================
// 4. Tonal Corrections & Filters (Types + Small 256-entry UI Curve LUT only)
// ============================================================================

export type TonalCorrectionType =
  | 'brightness-contrast'
  | 'binarization'
  | 'hue-saturation'
  | 'posterization'
  | 'level-correction'
  | 'reverse-gradient';

export interface BrightnessContrastParams {
  brightness: number;
  contrast: number;
}

export interface BinarizationParams {
  threshold: number;
}

export interface HueSaturationParams {
  hue: number;
  saturation: number;
  luminosity: number;
}

export interface PosterizationParams {
  levels: number;
}

export interface LevelCorrectionParams {
  channel: 'rgb' | 'r' | 'g' | 'b';
  inputMin: number;
  gamma: number;
  inputMax: number;
  outputMin: number;
  outputMax: number;
}

export interface ProcessingBounds {
  x0: number;
  y0: number;
  x1: number;
  y1: number;
}

export interface GaussianBlurParams {
  radius: number;
}

export interface MotionBlurParams {
  distance: number;
  angle: number;
}

export interface UnsharpMaskParams {
  radius: number;
  amount: number;
  threshold?: number;
}

export interface FilmGrainParams {
  intensity: number;
  size?: number;
  monochromatic?: boolean;
  seed?: number;
}

export interface TileHistogramMap {
  rgb: Uint32Array;
  r: Uint32Array;
  g: Uint32Array;
  b: Uint32Array;
}

/**
 * Pure 256-entry Fritsch-Carlson monotone cubic spline LUT (used strictly to plot
 * the 200×200 interactive Tone Curve graph widget in `AdjustmentModal.tsx`).
 */
export function buildMonotonicCubicSplineLut(points: [number, number][]): Uint8Array {
  const lut = new Uint8Array(256);
  const validPoints: [number, number][] = Array.isArray(points)
    ? points
        .filter(
          (pt): pt is [number, number] =>
            Array.isArray(pt) &&
            pt.length >= 2 &&
            typeof pt[0] === 'number' &&
            typeof pt[1] === 'number' &&
            Number.isFinite(pt[0]) &&
            Number.isFinite(pt[1])
        )
        .map(([x, y]) => [x, y])
    : [];
  if (validPoints.length === 0) {
    for (let i = 0; i < 256; i++) lut[i] = i;
    return lut;
  }
  const sorted = validPoints.sort((a, b) => a[0] - b[0]);
  const unique: [number, number][] = [];
  for (const pt of sorted) {
    if (unique.length > 0 && Math.abs(unique[unique.length - 1][0] - pt[0]) < 1e-4) {
      unique[unique.length - 1] = pt;
    } else {
      unique.push(pt);
    }
  }
  const n = unique.length;
  if (n === 1) {
    lut.fill(Math.max(0, Math.min(255, Math.round(unique[0][1]))));
    return lut;
  }
  const deltas = new Float64Array(n - 1);
  for (let k = 0; k < n - 1; k++) {
    const dx = unique[k + 1][0] - unique[k][0];
    deltas[k] = dx === 0 ? 0 : (unique[k + 1][1] - unique[k][1]) / dx;
  }
  const m = new Float64Array(n);
  m[0] = deltas[0];
  m[n - 1] = deltas[n - 2];
  for (let k = 1; k < n - 1; k++) {
    m[k] = (deltas[k - 1] + deltas[k]) / 2;
  }
  for (let k = 0; k < n - 1; k++) {
    if (deltas[k] === 0) {
      m[k] = 0;
      m[k + 1] = 0;
    } else {
      const alpha = m[k] / deltas[k];
      const beta = m[k + 1] / deltas[k];
      if (alpha < 0) m[k] = 0;
      if (beta < 0) m[k + 1] = 0;
      const hypSq = alpha * alpha + beta * beta;
      if (hypSq > 9) {
        const tau = 3 / Math.sqrt(hypSq);
        m[k] = tau * alpha * deltas[k];
        m[k + 1] = tau * beta * deltas[k];
      }
    }
  }
  for (let x = 0; x < 256; x++) {
    if (x <= unique[0][0]) {
      lut[x] = Math.max(0, Math.min(255, Math.round(unique[0][1])));
      continue;
    }
    if (x >= unique[n - 1][0]) {
      lut[x] = Math.max(0, Math.min(255, Math.round(unique[n - 1][1])));
      continue;
    }
    let k = 0;
    while (k < n - 1 && x > unique[k + 1][0]) k++;
    const x0 = unique[k][0];
    const x1 = unique[k + 1][0];
    const y0 = unique[k][1];
    const y1 = unique[k + 1][1];
    const h = x1 - x0;
    const t = h === 0 ? 0 : (x - x0) / h;
    const t2 = t * t;
    const t3 = t2 * t;
    const y =
      (2 * t3 - 3 * t2 + 1) * y0 +
      (t3 - 2 * t2 + t) * h * m[k] +
      (-2 * t3 + 3 * t2) * y1 +
      (t3 - t2) * h * m[k + 1];
    lut[x] = Math.max(0, Math.min(255, Math.round(y)));
  }
  return lut;
}

export function buildCurvesCombinedLut(curveData: ToneCurvePoints): {
  rLut: Uint8Array;
  gLut: Uint8Array;
  bLut: Uint8Array;
} {
  const masterLut = buildMonotonicCubicSplineLut(curveData.rgb || [[0, 0], [255, 255]]);
  const rRaw = buildMonotonicCubicSplineLut(curveData.r || [[0, 0], [255, 255]]);
  const gRaw = buildMonotonicCubicSplineLut(curveData.g || [[0, 0], [255, 255]]);
  const bRaw = buildMonotonicCubicSplineLut(curveData.b || [[0, 0], [255, 255]]);
  const rLut = new Uint8Array(256);
  const gLut = new Uint8Array(256);
  const bLut = new Uint8Array(256);
  for (let i = 0; i < 256; i++) {
    rLut[i] = masterLut[rRaw[i]];
    gLut[i] = masterLut[gRaw[i]];
    bLut[i] = masterLut[bRaw[i]];
  }
  return { rLut, gLut, bLut };
}

export function buildGradientMapLut(
  stops: GradientStop[],
  interpolation: 'linear' | 'smooth' = 'linear'
): Uint8ClampedArray {
  const lut = new Uint8ClampedArray(256 * 4);
  const validStops = Array.isArray(stops)
    ? stops.filter(
        (s) =>
          Boolean(s) &&
          typeof s === 'object' &&
          typeof s.position === 'number' &&
          Number.isFinite(s.position)
      )
    : [];
  if (validStops.length === 0) {
    for (let i = 0; i < 256; i++) {
      lut[i * 4] = i;
      lut[i * 4 + 1] = i;
      lut[i * 4 + 2] = i;
      lut[i * 4 + 3] = 255;
    }
    return lut;
  }
  const sorted = [...validStops]
    .sort((a, b) => a.position - b.position)
    .map((s) => ({
      pos: Math.max(0, Math.min(1, s.position)),
      rgb: parseHexRgb(s.color),
    }));
  for (let i = 0; i < 256; i++) {
    const t = i / 255;
    const off = i * 4;
    if (t <= sorted[0].pos) {
      lut[off] = sorted[0].rgb[0];
      lut[off + 1] = sorted[0].rgb[1];
      lut[off + 2] = sorted[0].rgb[2];
      lut[off + 3] = 255;
      continue;
    }
    const last = sorted[sorted.length - 1];
    if (t >= last.pos) {
      lut[off] = last.rgb[0];
      lut[off + 1] = last.rgb[1];
      lut[off + 2] = last.rgb[2];
      lut[off + 3] = 255;
      continue;
    }
    let idx = 0;
    while (idx < sorted.length - 1 && sorted[idx + 1].pos < t) idx++;
    const a = sorted[idx];
    const b = sorted[idx + 1];
    const span = b.pos - a.pos;
    let f = span > 1e-6 ? (t - a.pos) / span : 0;
    if (interpolation === 'smooth') {
      f = f * f * (3 - 2 * f);
    }
    lut[off] = Math.round(a.rgb[0] + (b.rgb[0] - a.rgb[0]) * f);
    lut[off + 1] = Math.round(a.rgb[1] + (b.rgb[1] - a.rgb[1]) * f);
    lut[off + 2] = Math.round(a.rgb[2] + (b.rgb[2] - a.rgb[2]) * f);
    lut[off + 3] = 255;
  }
  return lut;
}

export function toNativeFilterSpec(type: FilterType, params: Record<string, unknown>): NativeFilterSpec {
  switch (type) {
    case 'gaussian-blur':
      return { kind: 'gaussian-blur', radius: Number(params.radius ?? 5) };
    case 'motion-blur':
      return {
        kind: 'motion-blur',
        distance: Number(params.distance ?? 15),
        angle: Number(params.angle ?? 0),
      };
    case 'unsharp-mask':
      return {
        kind: 'unsharp-mask',
        amount: Number(params.amount ?? 1.0),
        radius: Number(params.radius ?? 2.0),
        threshold: Math.max(0, Math.min(255, Math.round(Number(params.threshold ?? 0)))),
      };
    case 'film-grain':
    default:
      return {
        kind: 'film-grain',
        intensity: Number(params.intensity ?? 25),
        size: Number(params.size ?? 1),
        monochrome: params.monochromatic !== false,
        seed: Math.max(0, Math.round(Number(params.seed ?? 1337))) >>> 0,
      };
  }
}

export function toNativeTonalSpec(
  type: TonalCorrectionType,
  params: Record<string, unknown>
): NativeTonalSpec {
  switch (type) {
    case 'brightness-contrast':
      return {
        kind: 'brightness-contrast',
        brightness: Number(params.brightness ?? 0),
        contrast: Number(params.contrast ?? 0),
      };
    case 'binarization':
      return {
        kind: 'binarization',
        threshold: Math.max(0, Math.min(255, Math.round(Number(params.threshold ?? 128)))),
      };
    case 'hue-saturation':
      return {
        kind: 'hue-saturation',
        hue: Number(params.hue ?? 0),
        saturation: Number(params.saturation ?? 0),
        luminosity: Number(params.luminosity ?? 0),
      };
    case 'posterization':
      return {
        kind: 'posterization',
        levels: Math.max(2, Math.min(32, Math.round(Number(params.levels ?? 4)))),
      };
    case 'level-correction':
      return {
        kind: 'level-correction',
        inBlack: Math.max(0, Math.min(254, Math.round(Number(params.inputMin ?? 0)))),
        inWhite: Math.max(1, Math.min(255, Math.round(Number(params.inputMax ?? 255)))),
        gamma: Math.max(0.1, Math.min(9.99, Number(params.gamma ?? 1.0))),
        outBlack: Math.max(0, Math.min(255, Math.round(Number(params.outputMin ?? 0)))),
        outWhite: Math.max(0, Math.min(255, Math.round(Number(params.outputMax ?? 255)))),
      };
    case 'reverse-gradient':
    default:
      return { kind: 'reverse-gradient' };
  }
}