Skip to content

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

17.3 KB
Raw Blame
import type { BrushSettings, CspTaperSettings } from '../types/editor';
import { evaluateFastSpline, isNaturalPaintBrush } from './brushMath';
import type { NativeScratchpadStrokeInput } from './nativeEngineBridge';

export interface ScratchpadSamplePoint {
  x: number;
  y: number;
  pressure: number;
  tiltX: number;
  tiltY: number;
  twist: number;
  timestampMs: number;
}

export interface RecordedScratchpadStroke {
  id: number;
  points: ScratchpadSamplePoint[];
  /** Explicit hex color captured at stroke creation (used when `followActiveColor` is false). */
  color: string;
  /** When true (default for strokes drawn with active foreground ink or the reference stroke), follows live color changes. */
  followActiveColor: boolean;
  /** Deterministic PRNG seed so dragging sliders never causes scatter/spray/angle jitter to flicker randomly. */
  seed: number;
}

function clamp(v: number, lo: number, hi: number): number {
  return v < lo ? lo : v > hi ? hi : v;
}

export function hexToRgb01(hex: string | undefined): [number, number, number] {
  if (!hex) return [0.11, 0.31, 0.85];
  const cleaned = hex.trim().replace(/^#/, '');
  if (cleaned.length === 3) {
    const r = parseInt(cleaned[0] + cleaned[0], 16) / 255;
    const g = parseInt(cleaned[1] + cleaned[1], 16) / 255;
    const b = parseInt(cleaned[2] + cleaned[2], 16) / 255;
    if (Number.isFinite(r) && Number.isFinite(g) && Number.isFinite(b)) return [r, g, b];
  } else if (cleaned.length >= 6) {
    const r = parseInt(cleaned.slice(0, 2), 16) / 255;
    const g = parseInt(cleaned.slice(2, 4), 16) / 255;
    const b = parseInt(cleaned.slice(4, 6), 16) / 255;
    if (Number.isFinite(r) && Number.isFinite(g) && Number.isFinite(b)) return [r, g, b];
  }
  return [0.11, 0.31, 0.85];
}

/**
 * Generates an expressive pressure-tapered S-curve sample stroke centered inside the scratchpad
 * so Brush Studio immediately shows live parameter edits before the user even draws a stroke.
 */
export function buildDefaultSampleStroke(
  width: number,
  height: number,
  color: string
): RecordedScratchpadStroke {
  const steps = 64;
  const padX = Math.max(44, width * 0.14);
  const spanX = Math.max(60, width - padX * 2);
  const midY = height * 0.5;
  const ampY = Math.max(24, height * 0.24);
  const points: ScratchpadSamplePoint[] = [];

  for (let i = 0; i <= steps; i++) {
    const t = i / steps;
    const x = padX + spanX * t;
    const y = midY - Math.sin(t * Math.PI * 2) * ampY;
    // Expressive manga/calligraphy pressure bell: delicate entry -> rich belly -> fine exit
    const pressure = clamp(Math.pow(Math.sin(t * Math.PI), 0.72), 0.06, 1.0);
    points.push({
      x,
      y,
      pressure,
      tiltX: 12 * Math.sin(t * Math.PI),
      tiltY: 18 * Math.cos(t * Math.PI * 0.5),
      twist: 0,
      timestampMs: i * 5,
    });
  }

  return {
    id: 0,
    points,
    color,
    followActiveColor: true,
    seed: 0x51a0c0de,
  };
}

export function toNativeScratchpadStrokes(
  strokes: RecordedScratchpadStroke[],
  activeColor: string
): NativeScratchpadStrokeInput[] {
  return strokes.map((s) => ({
    points: s.points.map((p) => ({
      x: p.x,
      y: p.y,
      pressure: p.pressure,
      tiltX: p.tiltX,
      tiltY: p.tiltY,
      twist: p.twist,
      timestampMs: p.timestampMs,
    })),
    color: hexToRgb01(s.followActiveColor ? activeColor : s.color),
    seed: s.seed >>> 0,
  }));
}

function createPrng(seed: number): () => number {
  let state = (seed >>> 0) || 0x2468ace1;
  return () => {
    state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
    return state / 4294967296;
  };
}

function evalBrushWidth(bs: BrushSettings, rawPressure: number): number {
  const baseSize = clamp(bs.size || 14, 1, 220);
  if (bs.usePressure === false) return baseSize;
  const p = clamp(rawPressure, 0, 1);
  let mapped = p;
  if (bs.pressureCurve && bs.pressureCurve.length >= 2) {
    mapped = clamp(evaluateFastSpline(p, bs.pressureCurve), 0, 1);
  } else if (bs.pressureCurveGamma && Math.abs(bs.pressureCurveGamma - 1) > 1e-3) {
    mapped = Math.pow(p, clamp(bs.pressureCurveGamma, 0.2, 5));
  }
  const minF = clamp(bs.minSizeFactor ?? 0.1, 0, 1);
  return Math.max(0.6, baseSize * (minF + (1 - minF) * mapped));
}

function shapeTaperRamp(t: number, sharpness: number): number {
  const tc = clamp(t, 0, 1);
  const s = clamp(sharpness, 0, 1);
  const exp = s < 0.5 ? 0.45 + (s / 0.5) * 0.55 : 1.0 + ((s - 0.5) / 0.5) * 1.1;
  const curved = Math.pow(tc, exp);
  const smooth = tc * tc * (3 - 2 * tc);
  return curved * 0.8 + smooth * 0.2;
}

function evalTaperFactors(
  taper: CspTaperSettings | undefined,
  arcDist: number,
  totalLen: number
): { size: number; opacity: number } {
  if (!taper || taper.inOutType === 0 || (!taper.useIn && !taper.useOut)) {
    return { size: 1, opacity: 1 };
  }
  let factor = 1;
  const mode = taper.inOutType ?? 2;
  if (taper.useIn) {
    const inSpan =
      mode === 1 ? totalLen * clamp(taper.inRatio ?? 0.2, 0, 0.95) : Math.max(0, taper.inLength ?? 0);
    if (inSpan > 0.1 && arcDist < inSpan) {
      factor = Math.min(factor, shapeTaperRamp(arcDist / inSpan, taper.startingSharpness ?? 0.5));
    }
  }
  if (taper.useOut) {
    const outSpan =
      mode === 1
        ? totalLen * clamp(taper.outRatio ?? 0.2, 0, 0.95)
        : Math.max(0, taper.outLength ?? 0);
    const distFromEnd = Math.max(0, totalLen - arcDist);
    if (outSpan > 0.1 && distFromEnd < outSpan) {
      factor = Math.min(factor, shapeTaperRamp(distFromEnd / outSpan, taper.endingSharpness ?? 0.5));
    }
  }
  const minSize = clamp(taper.minSizeRatio ?? 0, 0, 1);
  const minDens = clamp(taper.minDensityRatio ?? 0, 0, 1);
  return {
    size: taper.affectSize !== false ? minSize + (1 - minSize) * factor : 1,
    opacity: taper.affectOpacity || mode === 3 ? minDens + (1 - minDens) * factor : 1,
  };
}

/**
 * Lightly smooths recorded polyline points when stabilization or postCorrection > 0
 * so those sliders visibly smooth jittery strokes on the 2D fallback renderer too.
 */
function smoothPolylineForPreview(
  points: ScratchpadSamplePoint[],
  stabilization: number,
  postCorrection: number
): ScratchpadSamplePoint[] {
  if (points.length < 4) return points;
  const passes = Math.min(8, Math.floor((stabilization || 0) / 8) + (postCorrection || 0));
  if (passes <= 0) return points;
  let cur = points.map((p) => ({ ...p }));
  for (let pass = 0; pass < passes; pass++) {
    const next = cur.map((p) => ({ ...p }));
    for (let i = 1; i < cur.length - 1; i++) {
      next[i].x = 0.25 * cur[i - 1].x + 0.5 * cur[i].x + 0.25 * cur[i + 1].x;
      next[i].y = 0.25 * cur[i - 1].y + 0.5 * cur[i].y + 0.25 * cur[i + 1].y;
    }
    cur = next;
  }
  return cur;
}

let cachedTintedTipCanvas: HTMLCanvasElement | null = null;
let cachedTintedTipKey = '';

function getTintedTipCanvas(tipImg: HTMLImageElement, color: string): HTMLCanvasElement | null {
  if (typeof document === 'undefined') return null;
  const w = tipImg.naturalWidth || tipImg.width;
  const h = tipImg.naturalHeight || tipImg.height;
  if (w <= 0 || h <= 0) return null;
  const key = `${tipImg.src.slice(0, 64)}|${color}`;
  if (cachedTintedTipCanvas && cachedTintedTipKey === key) {
    return cachedTintedTipCanvas;
  }
  const c = document.createElement('canvas');
  c.width = Math.min(256, w);
  c.height = Math.min(256, h);
  const ctx = c.getContext('2d');
  if (!ctx) return null;
  ctx.drawImage(tipImg, 0, 0, c.width, c.height);
  ctx.globalCompositeOperation = 'source-in';
  ctx.fillStyle = color;
  ctx.fillRect(0, 0, c.width, c.height);
  cachedTintedTipCanvas = c;
  cachedTintedTipKey = key;
  return c;
}

/**
 * Renders a single stroke onto a 2D context with live BrushSettings fidelity.
 * Used both for real-time 2D replay (Web / tests / fallback) and for live in-progress draft painting.
 */
export function renderSingleScratchpadStroke2D(
  ctx: CanvasRenderingContext2D,
  stroke: RecordedScratchpadStroke,
  bs: BrushSettings,
  activeColor: string
): void {
  const rawPts = stroke.points;
  if (rawPts.length === 0) return;

  const pts = smoothPolylineForPreview(
    rawPts,
    bs.stabilization ?? 0,
    bs.postCorrection ?? 0
  );
  const strokeColor = stroke.followActiveColor ? activeColor : stroke.color;
  const rand = createPrng(stroke.seed);

  const flow = clamp((bs.flow ?? 1.0) * (bs.brushDensity ?? 1.0), 0.04, 1.0);
  const hardness = clamp(bs.hardness ?? 0.9, 0.02, 1.0);
  const spacingRatio = clamp(bs.spacing ?? 0.1, 0.025, 2.5);
  const thickness = clamp(bs.thickness ?? 1.0, 0.1, 1.0);
  const thicknessVertical = Boolean(bs.thicknessVertical);
  const baseAngleRad = ((bs.customTipAngle ?? 0) * Math.PI) / 180;
  const angleMode = bs.customTipAngleDynamics ?? 'none';
  const angleRandScale = bs.customTipRotationRandomScale ?? 1.0;
  const dyn = bs.dynamics;
  const scatter = clamp(dyn?.scatter ?? 0, 0, 5);
  const sizeJitter = clamp(dyn?.sizeJitter ?? 0, 0, 1);
  const angleJitter = clamp(dyn?.angleJitter ?? 0, 0, 1);
  const flowJitter = clamp(dyn?.flowJitter ?? 0, 0, 1);
  const grainAmount = clamp(bs.grain ?? bs.textureDensity ?? 0, 0, 1);
  const wetEdge = clamp(bs.wetEdge ?? 0, 0, 1);
  const isSpray = Boolean(bs.spray?.enabled);
  const naturalMode = isNaturalPaintBrush(bs);
  const tipImg = bs.customTipImage;
  const hasTipImg = Boolean(
    tipImg && tipImg.complete && (tipImg.naturalWidth || tipImg.width) > 0
  );
  const tintedTip =
    hasTipImg && tipImg && !bs.isColorTip ? getTintedTipCanvas(tipImg, strokeColor) : null;

  // Compute total arc length for CSP taper In/Out
  let totalLen = 0;
  for (let i = 1; i < pts.length; i++) {
    totalLen += Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y);
  }

  let initialAngle = 0;
  for (let i = 1; i < pts.length; i++) {
    const dx = pts[i].x - pts[i - 1].x;
    const dy = pts[i].y - pts[i - 1].y;
    if (Math.hypot(dx, dy) > 0.5) {
      initialAngle = Math.atan2(dy, dx);
      break;
    }
  }

  ctx.save();
  ctx.fillStyle = strokeColor;
  ctx.strokeStyle = strokeColor;
  ctx.lineCap = 'round';
  ctx.lineJoin = 'round';

  const drawDab = (
    x: number,
    y: number,
    diam: number,
    angleRad: number,
    alpha: number
  ) => {
    const jSize = sizeJitter > 0.001 ? 1 - rand() * sizeJitter : 1;
    const d = Math.max(0.8, diam * jSize);
    const jFlow = flowJitter > 0.001 ? 1 - rand() * flowJitter : 1;
    const grainAtten = grainAmount > 0.01 ? 1 - grainAmount * 0.45 * rand() : 1;
    const a = clamp(alpha * jFlow * grainAtten, 0.01, 1.0);

    let dx = 0;
    let dy = 0;
    if (scatter > 0.001) {
      const mag = (rand() * 2 - 1) * d * scatter * 0.5;
      const perp = angleRad + Math.PI * 0.5;
      dx = Math.cos(perp) * mag;
      dy = Math.sin(perp) * mag;
      if (dyn?.scatterBothAxes) {
        const along = (rand() * 2 - 1) * d * scatter * 0.5;
        dx += Math.cos(angleRad) * along;
        dy += Math.sin(angleRad) * along;
      }
    }

    const px = x + dx;
    const py = y + dy;

    if (isSpray) {
      const particles = Math.max(3, Math.min(18, Math.round((bs.spray?.density ?? 3) * 2.2)));
      const rad = Math.max(2, d * 0.55);
      const pSizeBase = Math.max(0.75, (bs.spray?.particleSize ?? 3) * 0.42);
      ctx.globalAlpha = a * 0.78;
      for (let j = 0; j < particles; j++) {
        const ang = rand() * Math.PI * 2;
        const r = Math.sqrt(rand()) * rad;
        const pr = Math.max(0.6, pSizeBase * (0.45 + rand() * 0.9));
        ctx.beginPath();
        ctx.arc(px + Math.cos(ang) * r, py + Math.sin(ang) * r, pr, 0, Math.PI * 2);
        ctx.fill();
      }
      return;
    }

    let dynAngle = 0;
    switch (angleMode) {
      case 'direction':
        dynAngle = angleRad;
        break;
      case 'initial-direction':
        dynAngle = initialAngle;
        break;
      case 'random':
        dynAngle = (rand() * 2 - 1) * Math.PI * angleRandScale;
        break;
      case 'direction-random':
        dynAngle = angleRad + (rand() * 2 - 1) * Math.PI * angleRandScale;
        break;
      default:
        dynAngle = 0;
    }
    const rot = baseAngleRad + dynAngle + (rand() * 2 - 1) * Math.PI * angleJitter;

    const rx = Math.max(0.5, (thicknessVertical ? d * thickness : d) * 0.5);
    const ry = Math.max(0.5, (thicknessVertical ? d : d * thickness) * 0.5);

    if (hasTipImg && tipImg) {
      ctx.save();
      ctx.translate(px, py);
      ctx.rotate(rot);
      ctx.globalAlpha = a;
      ctx.drawImage(tintedTip || tipImg, -rx, -ry, rx * 2, ry * 2);
      ctx.restore();
      return;
    }

    if (hardness < 0.85 && rx > 2 && ry > 2 && typeof ctx.createRadialGradient === 'function') {
      ctx.save();
      ctx.translate(px, py);
      ctx.rotate(rot);
      ctx.scale(1, ry / rx);
      const grad = ctx.createRadialGradient(0, 0, rx * hardness * 0.72, 0, 0, rx);
      grad.addColorStop(0, strokeColor);
      grad.addColorStop(1, 'rgba(0,0,0,0)');
      ctx.globalAlpha = a;
      ctx.fillStyle = grad;
      ctx.beginPath();
      ctx.arc(0, 0, rx, 0, Math.PI * 2);
      ctx.fill();
      ctx.restore();
      return;
    }

    ctx.save();
    ctx.translate(px, py);
    ctx.rotate(rot);
    ctx.globalAlpha = a;
    ctx.beginPath();
    if (typeof ctx.ellipse === 'function') {
      ctx.ellipse(0, 0, rx, ry, 0, 0, Math.PI * 2);
    } else {
      ctx.arc(0, 0, (rx + ry) * 0.5, 0, Math.PI * 2);
    }
    ctx.fill();
    if (wetEdge > 0.05 && rx > 2.5) {
      ctx.globalAlpha = a * wetEdge * 0.55;
      ctx.lineWidth = Math.max(0.8, (bs.wetEdgeRadius ?? 2) * 0.5);
      ctx.stroke();
    }
    ctx.restore();
  };

  if (naturalMode) {
    const strands = Math.max(6, Math.min(20, Math.round((bs.bristle?.count ?? 20) * 0.5)));
    const splay = clamp(bs.bristle?.splay ?? 0.35, 0, 1);
    let arcAcc = 0;
    for (let i = 1; i < pts.length; i++) {
      const p0 = pts[i - 1];
      const p1 = pts[i];
      const dx = p1.x - p0.x;
      const dy = p1.y - p0.y;
      const segLen = Math.hypot(dx, dy);
      if (segLen < 0.05) continue;
      const taper = evalTaperFactors(bs.taper, arcAcc + segLen * 0.5, totalLen);
      arcAcc += segLen;
      const nx = -dy / segLen;
      const ny = dx / segLen;
      const w0 = evalBrushWidth(bs, p0.pressure) * taper.size;
      const w1 = evalBrushWidth(bs, p1.pressure) * taper.size;
      const avgW = (w0 + w1) * 0.5 * (1 + splay * 0.25);
      for (let b = 0; b < strands; b++) {
        const frac = strands > 1 ? (b / (strands - 1)) * 2 - 1 : 0;
        const off = frac * avgW * 0.45;
        ctx.globalAlpha = clamp(
          flow * taper.opacity * (0.4 + 0.5 * (1 - Math.abs(frac) * 0.4)),
          0.02,
          1
        );
        ctx.lineWidth = Math.max(1.0, (avgW / strands) * 1.4);
        ctx.beginPath();
        ctx.moveTo(p0.x + nx * off, p0.y + ny * off);
        ctx.lineTo(p1.x + nx * off, p1.y + ny * off);
        ctx.stroke();
      }
    }
    ctx.restore();
    return;
  }

  // Single-point tap
  if (pts.length === 1 || totalLen < 0.25) {
    const p = pts[0];
    const diam = evalBrushWidth(bs, p.pressure);
    drawDab(p.x, p.y, diam, initialAngle, flow);
    ctx.restore();
    return;
  }

  // Exact arc-length carry-over dab stepping
  let arcAcc = 0;
  let residual = 0;
  const firstTaper = evalTaperFactors(bs.taper, 0, totalLen);
  drawDab(
    pts[0].x,
    pts[0].y,
    evalBrushWidth(bs, pts[0].pressure) * firstTaper.size,
    initialAngle,
    flow * firstTaper.opacity
  );

  for (let i = 1; i < pts.length; i++) {
    const p0 = pts[i - 1];
    const p1 = pts[i];
    const dx = p1.x - p0.x;
    const dy = p1.y - p0.y;
    const segLen = Math.hypot(dx, dy);
    if (segLen < 1e-4) continue;
    const segAngle = Math.atan2(dy, dx);

    let s = residual;
    let guard = 0;
    while (s <= segLen && guard < 1024) {
      guard++;
      const t = s / segLen;
      const x = p0.x + dx * t;
      const y = p0.y + dy * t;
      const pressure = p0.pressure + (p1.pressure - p0.pressure) * t;
      const taper = evalTaperFactors(bs.taper, arcAcc + s, totalLen);
      const diam = evalBrushWidth(bs, pressure) * taper.size;
      const step = Math.max(1.0, diam * spacingRatio);
      if (s > 0 || residual > 0) {
        drawDab(x, y, diam, segAngle, flow * taper.opacity);
      }
      s += step;
    }
    residual = Math.max(0, s - segLen);
    arcAcc += segLen;
  }

  ctx.restore();
}

/**
 * Re-renders all recorded scratchpad strokes cleanly onto `ctx` with stroke-level opacity
 * (matching CSP/DX12 stroke accumulation where opacity applies per stroke, not per dab).
 */
export function renderScratchpadStrokes2D(
  ctx: CanvasRenderingContext2D,
  width: number,
  height: number,
  strokes: RecordedScratchpadStroke[],
  bs: BrushSettings,
  activeColor: string
): void {
  ctx.clearRect(0, 0, width, height);
  if (strokes.length === 0) return;

  const strokeOpacity = clamp(bs.opacity ?? 1.0, 0.01, 1.0);
  const canOffscreen = typeof document !== 'undefined' && strokeOpacity < 0.995;

  if (!canOffscreen) {
    for (const stroke of strokes) {
      renderSingleScratchpadStroke2D(ctx, stroke, bs, activeColor);
    }
    return;
  }

  const off = document.createElement('canvas');
  off.width = width;
  off.height = height;
  const oCtx = off.getContext('2d');
  if (!oCtx) {
    for (const stroke of strokes) {
      renderSingleScratchpadStroke2D(ctx, stroke, bs, activeColor);
    }
    return;
  }

  for (const stroke of strokes) {
    oCtx.clearRect(0, 0, width, height);
    renderSingleScratchpadStroke2D(oCtx, stroke, bs, activeColor);
    ctx.save();
    ctx.globalAlpha = strokeOpacity;
    ctx.drawImage(off, 0, 0);
    ctx.restore();
  }
}