Skip to content

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

9.9 KB
Raw Blame
/**
 * Pure non-engine brush math & UI metadata helpers.
 * All brush stroke rasterization, stabilization, splines, tapering, pigment mixing,
 * ribbon meshes, bristle dynamics, and impasto heightfields execute natively in
 * Rust + wgpu (`crates/ink-engine`).
 */

import type { BrushSettings, DirtyRect } from '../types/editor';

export interface SplinePoint {
  x: number;
  y: number;
  pressure: number;
  width: number;
  tiltX?: number;
  tiltY?: number;
  twist?: number;
  timestamp?: number;
  isCorner?: boolean;
}

export interface CubicBezierSegment {
  p0: SplinePoint;
  c1: SplinePoint;
  c2: SplinePoint;
  p3: SplinePoint;
}

export type LegacyPencilGrade = 'pencil-f' | 'pencil-hb' | 'pencil-2b' | 'pencil-4b';

export const LEGACY_PENCIL_PRESETS: Record<LegacyPencilGrade, Partial<BrushSettings>> = {
  'pencil-f': {
    size: 2.5,
    minSizeFactor: 0.35,
    hardness: 0.85,
    flow: 0.55,
    spacing: 0.08,
    grain: 0.55,
    textureDensity: 0.55,
    useTilt: true,
    tiltScale: 1.15,
    paperTextureMode: 'compare',
    opacitySensor: { usePressure: true, pressureMin: 0.25 },
  },
  'pencil-hb': {
    size: 3.2,
    minSizeFactor: 0.25,
    hardness: 0.75,
    flow: 0.65,
    spacing: 0.07,
    grain: 0.65,
    textureDensity: 0.65,
    useTilt: true,
    tiltScale: 1.25,
    paperTextureMode: 'compare',
    opacitySensor: { usePressure: true, pressureMin: 0.2 },
  },
  'pencil-2b': {
    size: 4.5,
    minSizeFactor: 0.2,
    hardness: 0.65,
    flow: 0.74,
    spacing: 0.06,
    grain: 0.75,
    textureDensity: 0.75,
    useTilt: true,
    tiltScale: 1.4,
    paperTextureMode: 'compare',
    opacitySensor: { usePressure: true, pressureMin: 0.18 },
  },
  'pencil-4b': {
    size: 6.5,
    minSizeFactor: 0.15,
    hardness: 0.5,
    flow: 0.88,
    spacing: 0.05,
    grain: 0.85,
    textureDensity: 0.85,
    useTilt: true,
    tiltScale: 1.6,
    paperTextureMode: 'compare',
    opacitySensor: { usePressure: true, pressureMin: 0.15 },
  },
};

export function getLegacyPencilPresetDefaults(preset?: string): Partial<BrushSettings> | null {
  if (!preset) return null;
  return (LEGACY_PENCIL_PRESETS as Record<string, Partial<BrushSettings>>)[preset] ?? null;
}

export const CSP_PRESSURE_CURVE_PRESETS: Record<
  string,
  { label: string; points: [number, number][] }
> = {
  linear: { label: 'Linear', points: [[0, 0], [1, 1]] },
  'g-pen': {
    label: 'G-Pen S-Curve',
    points: [
      [0, 0],
      [0.2, 0.08],
      [0.55, 0.52],
      [0.82, 0.88],
      [1, 1],
    ],
  },
  soft: {
    label: 'Soft Touch',
    points: [
      [0, 0],
      [0.25, 0.48],
      [0.65, 0.84],
      [1, 1],
    ],
  },
  firm: {
    label: 'Firm Nib',
    points: [
      [0, 0],
      [0.35, 0.12],
      [0.7, 0.48],
      [1, 1],
    ],
  },
  chisel: {
    label: 'Steep Threshold',
    points: [
      [0, 0],
      [0.15, 0.03],
      [0.45, 0.72],
      [1, 1],
    ],
  },
};

const LUT_SIZE = 256;
const LUT_MAX_IDX = LUT_SIZE - 1;
const curveWeakCache = new WeakMap<readonly [number, number][], Float32Array>();
const curveStringCache = new Map<string, Float32Array>();
const MAX_STRING_CURVE_CACHE = 128;

export function getCompiledCurveLut(curve?: readonly [number, number][]): Float32Array | null {
  if (!Array.isArray(curve) || curve.length === 0) return null;

  const weakHit = curveWeakCache.get(curve);
  if (weakHit) return weakHit;

  const validPts: [number, number][] = [];
  for (let i = 0; i < curve.length; i++) {
    const p = curve[i];
    if (
      Array.isArray(p) &&
      p.length >= 2 &&
      typeof p[0] === 'number' &&
      typeof p[1] === 'number' &&
      Number.isFinite(p[0]) &&
      Number.isFinite(p[1])
    ) {
      validPts.push([p[0], p[1]]);
    }
  }
  if (validPts.length === 0) return null;

  let key = '';
  for (let i = 0; i < validPts.length; i++) {
    key += `${validPts[i][0].toFixed(4)},${validPts[i][1].toFixed(4)};`;
  }
  const strHit = curveStringCache.get(key);
  if (strHit) {
    curveWeakCache.set(curve, strHit);
    return strHit;
  }

  const lut = new Float32Array(LUT_SIZE);
  const pts = validPts.slice().sort((a, b) => a[0] - b[0]);
  const dedup: [number, number][] = [pts[0]];
  for (let i = 1; i < pts.length; i++) {
    if (pts[i][0] - dedup[dedup.length - 1][0] > 1e-5) {
      dedup.push(pts[i]);
    }
  }

  const n = dedup.length;
  if (n === 1) {
    lut.fill(Math.max(0, Math.min(1, dedup[0][1])));
  } else if (n === 2) {
    const [x0, y0] = dedup[0];
    const [x1, y1] = dedup[1];
    const span = Math.max(1e-5, x1 - x0);
    for (let s = 0; s < LUT_SIZE; s++) {
      const x = s / LUT_MAX_IDX;
      if (x <= x0) lut[s] = Math.max(0, Math.min(1, y0));
      else if (x >= x1) lut[s] = Math.max(0, Math.min(1, y1));
      else {
        const t = (x - x0) / span;
        lut[s] = Math.max(0, Math.min(1, y0 + t * (y1 - y0)));
      }
    }
  } else {
    const hArr = new Float64Array(n - 1);
    const deltas = new Float64Array(n - 1);
    const m = new Float64Array(n);
    for (let k = 0; k < n - 1; k++) {
      hArr[k] = Math.max(1e-5, dedup[k + 1][0] - dedup[k][0]);
      deltas[k] = (dedup[k + 1][1] - dedup[k][1]) / hArr[k];
    }
    m[0] = deltas[0];
    for (let k = 1; k < n - 1; k++) {
      if (deltas[k - 1] * deltas[k] <= 0) {
        if (
          k === 1 &&
          Math.abs(deltas[0]) < 1e-6 &&
          hArr[0] < 0.025 &&
          Math.abs(deltas[1]) > 1e-6
        ) {
          m[k] = deltas[1];
        } else if (
          k === n - 2 &&
          Math.abs(deltas[n - 2]) < 1e-6 &&
          hArr[n - 2] < 0.025 &&
          Math.abs(deltas[n - 3]) > 1e-6
        ) {
          m[k] = deltas[n - 3];
        } else {
          m[k] = 0;
        }
      } else {
        const w1 = 2 * hArr[k] + hArr[k - 1];
        const w2 = hArr[k] + 2 * hArr[k - 1];
        m[k] = (w1 + w2) / (w1 / deltas[k - 1] + w2 / deltas[k]);
      }
    }
    m[n - 1] = deltas[n - 2];

    for (let k = 0; k < n - 1; k++) {
      const dk = deltas[k];
      if (Math.abs(dk) < 1e-6) {
        if (k === 0 && hArr[0] < 0.025) {
          m[0] = 0;
        } else if (k === n - 2 && hArr[n - 2] < 0.025) {
          m[n - 1] = 0;
        } else {
          m[k] = 0;
          m[k + 1] = 0;
        }
      } else {
        const alpha = m[k] / dk;
        const beta = m[k + 1] / dk;
        const sumSq = alpha * alpha + beta * beta;
        if (sumSq > 9) {
          const tau = 3 / Math.sqrt(sumSq);
          m[k] = tau * alpha * dk;
          m[k + 1] = tau * beta * dk;
        }
      }
    }

    let segIdx = 0;
    for (let s = 0; s < LUT_SIZE; s++) {
      const x = s / LUT_MAX_IDX;
      if (x <= dedup[0][0]) {
        lut[s] = Math.max(0, Math.min(1, dedup[0][1]));
        continue;
      }
      if (x >= dedup[n - 1][0]) {
        lut[s] = Math.max(0, Math.min(1, dedup[n - 1][1]));
        continue;
      }
      while (segIdx < n - 2 && x > dedup[segIdx + 1][0]) segIdx++;
      const [x0, y0] = dedup[segIdx];
      const [x1, y1] = dedup[segIdx + 1];
      const h = Math.max(1e-5, x1 - x0);
      const t = (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[segIdx] +
        (-2 * t3 + 3 * t2) * y1 +
        (t3 - t2) * h * m[segIdx + 1];
      lut[s] = Math.max(0, Math.min(1, y));
    }
  }

  if (curveStringCache.size >= MAX_STRING_CURVE_CACHE) {
    const oldest = curveStringCache.keys().next().value;
    if (oldest !== undefined) curveStringCache.delete(oldest);
  }
  curveStringCache.set(key, lut);
  curveWeakCache.set(curve, lut);
  return lut;
}

export function evaluateFastSpline(x: number, curve?: readonly [number, number][]): number {
  const clamped = !Number.isFinite(x) ? 0 : x <= 0 ? 0 : x >= 1 ? 1 : x;
  if (!Array.isArray(curve) || curve.length === 0) return clamped;
  const lut = getCompiledCurveLut(curve);
  if (!lut) return clamped;

  const pos = clamped * LUT_MAX_IDX;
  const idx = pos | 0;
  if (idx >= LUT_MAX_IDX) return lut[LUT_MAX_IDX];
  const frac = pos - idx;
  return lut[idx] + (lut[idx + 1] - lut[idx]) * frac;
}

export function computeTipStampDimensions(
  baseSize: number,
  thickness: number = 1.0,
  thicknessVertical: boolean = false,
  tipW: number = 1,
  tipH: number = 1
): { width: number; height: number } {
  const safeW = tipW > 0 ? tipW : 1;
  const safeH = tipH > 0 ? tipH : 1;
  const effThick = Math.max(0.05, Math.min(20.0, thickness || 1.0));
  const rawW = thicknessVertical ? safeW * effThick : safeW;
  const rawH = thicknessVertical ? safeH : safeH * effThick;
  const maxRaw = Math.max(rawW, rawH, 1e-4);
  return {
    width: (baseSize * rawW) / maxRaw,
    height: (baseSize * rawH) / maxRaw,
  };
}

export function isNaturalPaintBrush(bs: Partial<BrushSettings> | undefined): boolean {
  if (!bs) return false;
  return Boolean(
    bs.renderMode === 'bristle-ribbon' ||
      bs.renderMode === 'bristle-hybrid' ||
      bs.naturalPaint?.enabled ||
      bs.impasto?.enabled
  );
}

export function computeClampedBakeDirtyRect(
  dirty: { minX: number; minY: number; maxX: number; maxY: number } | null | undefined,
  canvasWidth: number,
  canvasHeight: number,
  brushSize: number,
  wetEdge: number = 0,
  wetEdgeRadius: number = 3.0
): DirtyRect | null {
  if (
    !dirty ||
    !Number.isFinite(dirty.minX) ||
    !Number.isFinite(dirty.minY) ||
    !Number.isFinite(dirty.maxX) ||
    !Number.isFinite(dirty.maxY) ||
    dirty.maxX < dirty.minX ||
    dirty.maxY < dirty.minY ||
    canvasWidth <= 0 ||
    canvasHeight <= 0
  ) {
    return null;
  }

  const wetMargin = wetEdge > 0.01 ? Math.ceil(wetEdgeRadius * 2 + 8) : 0;
  const pad = Math.ceil(Math.max(32, (brushSize || 10) * 1.5)) + wetMargin;

  const sx = Math.max(0, Math.floor(dirty.minX - pad));
  const sy = Math.max(0, Math.floor(dirty.minY - pad));
  const maxX = Math.min(canvasWidth, Math.ceil(dirty.maxX + pad));
  const maxY = Math.min(canvasHeight, Math.ceil(dirty.maxY + pad));
  const dw = maxX - sx;
  const dh = maxY - sy;

  if (dw <= 0 || dh <= 0) {
    return null;
  }

  return { x: sx, y: sy, width: dw, height: dh };
}