Skip to content

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

23.7 KB
Raw Blame
import {
  BristleSettings,
  BrushDynamics,
  BrushPresetId,
  BrushRenderMode,
  BrushSettings,
  CspAngleDynamicsMode,
  CspAntiAliasLevel,
  CspBlendTipsMode,
  CspBrushCombineMode,
  CspDualBrushConfig,
  CspPaperTextureMode,
  CspSensorConfig,
  CspSpraySettings,
  CspSubTip,
  CspSubTipOrder,
  CspTaperSettings,
  CspTipFlipMode,
  DualBrushCompositeMode,
  GrainMappingMode,
  ImpastoSettings,
  NaturalMixingMode,
  NaturalPaintSettings,
  Point,
  SurfaceTextureId,
} from '../types/editor';
import { getBuiltinBrushConfig } from './presetBrushes';
import { evaluateFastSpline, getLegacyPencilPresetDefaults } from './brushMath';
import { resolveDualBrushConfig } from './dualBrushConfig';
import { isNativeCanvasActive, renderNativeBrushPreview } from './nativeEngineBridge';
import { recoveryService } from '../services/recoveryService';

export interface BrushPreviewOptions {
  preset?: BrushPresetId;
  size?: number;
  flow?: number;
  brushDensity?: number;
  opacity?: number;
  grain?: number;
  textureDensity?: number;
  paperTexture?: string;
  paperTextureImage?: HTMLImageElement;
  paperTextureMode?: CspPaperTextureMode;
  paperTextureScale?: number;
  paperTextureRotate?: number;
  paperTextureOffsetX?: number;
  paperTextureOffsetY?: number;
  paperTextureContrast?: number;
  paperTextureBrightness?: number;
  paperTextureApplyEachPlot?: boolean;
  paperTextureEmphasizeDensity?: boolean;
  paperTextureInverted?: boolean;
  hardness?: number;
  spacing?: number;
  minSizeFactor?: number;
  usePressure?: boolean;
  useTilt?: boolean;
  tiltScale?: number;
  useVelocity?: boolean;
  color?: string;
  secondaryColor?: string;
  backgroundColor?: string;
  isSelected?: boolean;
  tool?: 'brush' | 'eraser';
  customTipDataUrl?: string;
  customTipImage?: HTMLImageElement;
  customTipAngle?: number;
  customTipAngleDynamics?: CspAngleDynamicsMode;
  customTipRotationRandomScale?: number;
  isColorTip?: boolean;
  isDualToneTip?: boolean;
  isRibbon?: boolean;
  subTips?: CspSubTip[];
  subTipOrder?: CspSubTipOrder;
  subTipImages?: HTMLImageElement[];
  thickness?: number;
  thicknessVertical?: boolean;
  thicknessSensor?: CspSensorConfig;
  flipH?: CspTipFlipMode;
  flipV?: CspTipFlipMode;
  blendTipsMode?: CspBlendTipsMode;
  brushCombineMode?: CspBrushCombineMode;
  adjustDensityByGap?: boolean;
  antiAlias?: number;
  pressureCurve?: [number, number][];
  velocityCurve?: [number, number][];
  sizeSensor?: CspSensorConfig;
  opacitySensor?: CspSensorConfig;
  densitySensor?: CspSensorConfig;
  intervalSensor?: CspSensorConfig;
  textureDensitySensor?: CspSensorConfig;
  angleSensor?: CspSensorConfig;
  scatterSensor?: CspSensorConfig;
  spray?: CspSpraySettings;
  taper?: CspTaperSettings;
  dynamics?: BrushDynamics;
  colorMixing?: boolean;
  perceptualMixing?: boolean;
  amountOfPaint?: number;
  densityOfPaint?: number;
  colorStretch?: number;
  amountOfPaintSensor?: CspSensorConfig;
  densityOfPaintSensor?: CspSensorConfig;
  colorStretchSensor?: CspSensorConfig;
  useBlur?: boolean;
  blurStrength?: number;
  mixingMode?: NaturalMixingMode;
  wetEdge?: number;
  wetEdgeRadius?: number;
  wetEdgeAlphaPower?: number;
  wetEdgeValuePower?: number;
  dualBrush?: boolean;
  dualBrushConfig?: CspDualBrushConfig;
  dualBrushCompositeMode?: DualBrushCompositeMode | string;
  dualTipDataUrl?: string;
  dualTipImage?: HTMLImageElement;
  dualSize?: number;
  dualLinkSize?: boolean;
  dualSpacing?: number;
  dualScatter?: number;
  dualThickness?: number;
  dualThicknessVertical?: boolean;
  dualAngle?: number;
  dualAngleDynamics?: CspAngleDynamicsMode;
  dualAngleSensor?: CspSensorConfig;
  dualHardness?: number;
  dualDensity?: number;
  dualSubTips?: CspSubTip[];
  dualSubTipImages?: HTMLImageElement[];
  dualSubTipOrder?: CspSubTipOrder;
  dualFlipH?: CspTipFlipMode;
  dualFlipV?: CspTipFlipMode;
  dualSpray?: CspSpraySettings;
  dualIsRibbon?: boolean;
  dualScale?: number;
  surfaceTextureId?: SurfaceTextureId;
  grainMappingMode?: GrainMappingMode;
  dualSurfaceTextureId?: SurfaceTextureId;
  dualGrainDepth?: number;
  renderMode?: BrushRenderMode;
  bristle?: BristleSettings;
  naturalPaint?: NaturalPaintSettings;
  impasto?: ImpastoSettings;
  width?: number;
  height?: number;
}

interface NativePreviewTask {
  canvas: HTMLCanvasElement;
  token: number;
  cacheKey: string;
  tool: 'brush' | 'eraser';
  previewSettings: BrushSettings;
  strokeColor: string;
  secondaryColor: string;
  bgColor: string;
  targetWidth: number;
  targetHeight: number;
}

const previewCache = new Map<string, HTMLCanvasElement>();
const gpuUpgradedCacheKeys = new Set<string>();
const inFlightNativeKeys = new Set<string>();
const nativePreviewQueue: NativePreviewTask[] = [];
const canvasRequestTokens = new WeakMap<HTMLCanvasElement, number>();
const liveCardDebounceTimers = new WeakMap<HTMLCanvasElement, ReturnType<typeof setTimeout>>();

const MAX_CACHE_ENTRIES = 220;
const MAX_CONCURRENT_NATIVE_PREVIEWS = 2;
const LIVE_CARD_NATIVE_DEBOUNCE_MS = 64;

let inFlightNativeCount = 0;
let drawingActiveUnsub: (() => void) | null = null;

function ensureDrawingIdleResumeListener(): void {
  if (drawingActiveUnsub !== null) return;
  drawingActiveUnsub = recoveryService.subscribeDrawingActive((active) => {
    if (!active && nativePreviewQueue.length > 0) {
      drainNativePreviewQueue();
    }
  });
}

function setCachedPreview(cacheKey: string, canvas: HTMLCanvasElement, isGpuUpgraded: boolean): void {
  if (previewCache.has(cacheKey)) {
    previewCache.delete(cacheKey);
  } else if (previewCache.size >= MAX_CACHE_ENTRIES) {
    const firstKey = previewCache.keys().next().value;
    if (firstKey) {
      previewCache.delete(firstKey);
      gpuUpgradedCacheKeys.delete(firstKey);
    }
  }
  previewCache.set(cacheKey, canvas);
  if (isGpuUpgraded) {
    gpuUpgradedCacheKeys.add(cacheKey);
  }
}

function removeQueuedTasksForCanvas(canvas: HTMLCanvasElement): void {
  for (let i = nativePreviewQueue.length - 1; i >= 0; i--) {
    if (nativePreviewQueue[i].canvas === canvas) {
      nativePreviewQueue.splice(i, 1);
    }
  }
}

/**
 * Cancels any pending or stale native GPU preview work associated with `canvas`
 * (called when a `BrushPreview` unmounts or starts a fresh render during slider drag).
 */
export function cancelBrushPreviewForCanvas(canvas: HTMLCanvasElement | null | undefined): void {
  if (!canvas) return;
  const nextToken = (canvasRequestTokens.get(canvas) ?? 0) + 1;
  canvasRequestTokens.set(canvas, nextToken);
  const timer = liveCardDebounceTimers.get(canvas);
  if (timer !== undefined) {
    clearTimeout(timer);
    liveCardDebounceTimers.delete(canvas);
  }
  removeQueuedTasksForCanvas(canvas);
}

function paintCanvasIfCurrent(
  canvas: HTMLCanvasElement,
  token: number,
  source: HTMLCanvasElement,
  targetWidth: number,
  targetHeight: number
): void {
  if (canvasRequestTokens.get(canvas) !== token) return;
  const liveCtx = canvas.getContext('2d');
  if (liveCtx && canvas.width === targetWidth && canvas.height === targetHeight) {
    liveCtx.clearRect(0, 0, targetWidth, targetHeight);
    liveCtx.drawImage(source, 0, 0, targetWidth, targetHeight);
  }
}

function drainNativePreviewQueue(): void {
  if (!isNativeCanvasActive()) return;
  if (recoveryService.getIsDrawingActive()) return;

  while (inFlightNativeCount < MAX_CONCURRENT_NATIVE_PREVIEWS && nativePreviewQueue.length > 0) {
    if (recoveryService.getIsDrawingActive()) return;

    const idx = nativePreviewQueue.findIndex((t) => !inFlightNativeKeys.has(t.cacheKey));
    if (idx < 0) return;

    const [task] = nativePreviewQueue.splice(idx, 1);
    if (!task) continue;

    // Drop stale request if the canvas has already been re-rendered or unmounted
    if (canvasRequestTokens.get(task.canvas) !== task.token) {
      continue;
    }

    // If an identical config was already GPU-rendered while this task waited, paint from cache
    if (gpuUpgradedCacheKeys.has(task.cacheKey)) {
      const cached = previewCache.get(task.cacheKey);
      if (cached) {
        paintCanvasIfCurrent(task.canvas, task.token, cached, task.targetWidth, task.targetHeight);
      }
      continue;
    }

    inFlightNativeCount += 1;
    inFlightNativeKeys.add(task.cacheKey);

    void renderNativeBrushPreview(
      task.tool,
      task.previewSettings,
      task.strokeColor,
      task.secondaryColor,
      task.targetWidth,
      task.targetHeight
    )
      .then((img) => {
        if (!img || typeof ImageData === 'undefined') return;
        const gpuCanvas = document.createElement('canvas');
        gpuCanvas.width = img.width;
        gpuCanvas.height = img.height;
        const gCtx = gpuCanvas.getContext('2d');
        if (!gCtx) return;
        if (task.bgColor && task.bgColor !== 'transparent') {
          gCtx.fillStyle = task.bgColor;
          gCtx.fillRect(0, 0, gpuCanvas.width, gpuCanvas.height);
          const tmp = document.createElement('canvas');
          tmp.width = img.width;
          tmp.height = img.height;
          const tCtx = tmp.getContext('2d');
          tCtx?.putImageData(new ImageData(img.rgba, img.width, img.height), 0, 0);
          gCtx.drawImage(tmp, 0, 0);
        } else {
          gCtx.putImageData(new ImageData(img.rgba, img.width, img.height), 0, 0);
        }
        setCachedPreview(task.cacheKey, gpuCanvas, true);
        paintCanvasIfCurrent(task.canvas, task.token, gpuCanvas, task.targetWidth, task.targetHeight);

        // Paint any other queued canvases waiting on the exact same config hash
        for (let i = nativePreviewQueue.length - 1; i >= 0; i--) {
          const waiter = nativePreviewQueue[i];
          if (waiter.cacheKey === task.cacheKey) {
            nativePreviewQueue.splice(i, 1);
            paintCanvasIfCurrent(
              waiter.canvas,
              waiter.token,
              gpuCanvas,
              waiter.targetWidth,
              waiter.targetHeight
            );
          }
        }
      })
      .finally(() => {
        inFlightNativeCount = Math.max(0, inFlightNativeCount - 1);
        inFlightNativeKeys.delete(task.cacheKey);
        drainNativePreviewQueue();
      });
  }
}

function enqueueNativePreviewTask(task: NativePreviewTask, debounceMs: number): void {
  ensureDrawingIdleResumeListener();
  removeQueuedTasksForCanvas(task.canvas);
  const existingTimer = liveCardDebounceTimers.get(task.canvas);
  if (existingTimer !== undefined) {
    clearTimeout(existingTimer);
    liveCardDebounceTimers.delete(task.canvas);
  }

  const pushAndDrain = () => {
    if (canvasRequestTokens.get(task.canvas) !== task.token) return;
    removeQueuedTasksForCanvas(task.canvas);
    nativePreviewQueue.push(task);
    drainNativePreviewQueue();
  };

  if (debounceMs > 0) {
    const timer = setTimeout(() => {
      liveCardDebounceTimers.delete(task.canvas);
      pushAndDrain();
    }, debounceMs);
    liveCardDebounceTimers.set(task.canvas, timer);
  } else {
    pushAndDrain();
  }
}

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

function buildCacheKey(
  options: BrushPreviewOptions,
  targetWidth: number,
  targetHeight: number,
  strokeColor: string,
  bgColor: string
): string {
  return JSON.stringify([
    targetWidth,
    targetHeight,
    options.preset ?? '',
    options.tool ?? 'brush',
    Math.round((options.size ?? 12) * 10),
    Math.round((options.opacity ?? 1) * 100),
    Math.round((options.flow ?? 1) * 100),
    Math.round((options.hardness ?? 0.9) * 100),
    Math.round((options.spacing ?? 0.1) * 100),
    Math.round((options.grain ?? options.textureDensity ?? 0) * 100),
    options.renderMode ?? 'stamp',
    Boolean(options.isRibbon),
    Boolean(options.colorMixing),
    Boolean(options.dualBrush),
    Boolean(options.spray?.enabled),
    options.bristle?.profile ?? '',
    options.bristle?.count ?? 0,
    options.naturalPaint?.enabled ?? false,
    options.impasto?.enabled ?? false,
    options.customTipDataUrl?.slice(0, 40) ?? '',
    options.subTips?.length ?? 0,
    strokeColor,
    bgColor,
  ]);
}

function buildScurvePoints(
  width: number,
  height: number,
  displayWidth: number,
  minSizeFactor: number,
  usePressure: boolean,
  pressureCurve?: [number, number][]
): Point[] {
  const steps = 48;
  const padX = Math.max(8, width * 0.1);
  const spanX = Math.max(16, width - padX * 2);
  const midY = height * 0.5;
  const ampY = Math.max(4, height * 0.28);
  const pts: Point[] = [];
  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;
    const rawP = clamp(Math.pow(Math.sin(t * Math.PI), 0.65), 0.08, 1.0);
    const p = pressureCurve ? evaluateFastSpline(rawP, pressureCurve) : rawP;
    const w = usePressure ? displayWidth * (minSizeFactor + (1 - minSizeFactor) * p) : displayWidth;
    pts.push({
      x,
      y,
      pressure: p,
      width: Math.max(0.75, w),
      tiltX: 0,
      tiltY: 0,
      twist: 0,
      timestamp: i * 4,
    });
  }
  return pts;
}

export function calculatePreviewWidth(size: number, height: number, dpr: number = 1): number {
  return clamp(size * dpr * 0.75, 2.0 * dpr, Math.max(4, height * 0.54));
}

function renderLightweightScurvePreview(
  ctx: CanvasRenderingContext2D,
  pts: Point[],
  strokeColor: string,
  options: BrushPreviewOptions,
  displayWidth: number
): void {
  const hardness = clamp(options.hardness ?? 0.9, 0.05, 1.0);
  const opacity = clamp(options.opacity ?? 1.0, 0.08, 1.0);
  const isBristle =
    options.renderMode === 'bristle-ribbon' ||
    options.renderMode === 'bristle-hybrid' ||
    Boolean(options.naturalPaint?.enabled) ||
    Boolean(options.impasto?.enabled);
  const isSpray = Boolean(options.spray?.enabled);
  const tipImg = options.customTipImage;
  const spacingPx = Math.max(1.2, displayWidth * clamp(options.spacing ?? 0.12, 0.05, 0.85));

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

  if (isSpray) {
    let seed = 0x13579bdf;
    const rand = () => {
      seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
      return seed / 4294967296;
    };
    const count = Math.max(3, Math.min(12, Math.round((options.spray?.density ?? 3) * 2)));
    for (let i = 0; i < pts.length; i += 2) {
      const pt = pts[i];
      const rad = Math.max(2, pt.width * 0.65);
      for (let j = 0; j < count; j++) {
        const ang = rand() * Math.PI * 2;
        const dist = Math.sqrt(rand()) * rad;
        const pr = Math.max(0.7, (options.spray?.particleSize ?? 3) * 0.25 * (0.5 + rand()));
        ctx.beginPath();
        ctx.arc(pt.x + Math.cos(ang) * dist, pt.y + Math.sin(ang) * dist, pr, 0, Math.PI * 2);
        ctx.fill();
      }
    }
    ctx.restore();
    return;
  }

  if (isBristle) {
    const strands = Math.max(5, Math.min(14, Math.round((options.bristle?.count ?? 18) * 0.45)));
    for (let s = 0; s < strands; s++) {
      const frac = strands > 1 ? (s / (strands - 1)) * 2 - 1 : 0;
      ctx.beginPath();
      for (let i = 0; i < pts.length; i++) {
        const pt = pts[i];
        const prev = pts[Math.max(0, i - 1)];
        const next = pts[Math.min(pts.length - 1, i + 1)];
        const tx = next.x - prev.x;
        const ty = next.y - prev.y;
        const len = Math.hypot(tx, ty) || 1;
        const nx = -ty / len;
        const ny = tx / len;
        const off = frac * pt.width * 0.42;
        const sx = pt.x + nx * off;
        const sy = pt.y + ny * off;
        if (i === 0) ctx.moveTo(sx, sy);
        else ctx.lineTo(sx, sy);
      }
      ctx.globalAlpha = opacity * (0.45 + 0.45 * (1 - Math.abs(frac) * 0.5));
      ctx.lineWidth = Math.max(0.8, (displayWidth / strands) * 1.15);
      ctx.stroke();
    }
    ctx.restore();
    return;
  }

  if (tipImg && tipImg.complete && (tipImg.naturalWidth || tipImg.width) > 0) {
    let acc = 0;
    for (let i = 1; i < pts.length; i++) {
      const p0 = pts[i - 1];
      const p1 = pts[i];
      const segLen = Math.hypot(p1.x - p0.x, p1.y - p0.y);
      const steps = Math.max(1, Math.ceil((segLen + acc) / spacingPx));
      for (let k = 0; k < steps; k++) {
        const t = k / steps;
        const x = p0.x + (p1.x - p0.x) * t;
        const y = p0.y + (p1.y - p0.y) * t;
        const w = p0.width + (p1.width - p0.width) * t;
        ctx.drawImage(tipImg, x - w * 0.5, y - w * 0.5, w, w);
      }
      acc = 0;
    }
    ctx.restore();
    return;
  }

  // Smooth tapered soft/hard S-curve stamp preview
  const blurPasses = hardness < 0.75 ? 2 : 1;
  for (let pass = 0; pass < blurPasses; pass++) {
    const scale = pass === 0 && blurPasses === 2 ? 1.28 : 1.0;
    const alpha = pass === 0 && blurPasses === 2 ? opacity * 0.35 : opacity;
    ctx.globalAlpha = alpha;
    for (let i = 1; i < pts.length; i++) {
      const p0 = pts[i - 1];
      const p1 = pts[i];
      ctx.beginPath();
      ctx.moveTo(p0.x, p0.y);
      ctx.lineTo(p1.x, p1.y);
      ctx.lineWidth = Math.max(0.8, ((p0.width + p1.width) * 0.5) * scale);
      ctx.stroke();
    }
  }
  ctx.restore();
}

export function renderBrushStrokePreview(
  canvas: HTMLCanvasElement,
  width: number,
  height: number,
  options: BrushPreviewOptions = {},
  isLiveCard: boolean = false
): void {
  renderBrushPreview(canvas, { ...options, width, height }, isLiveCard);
}

export function renderBrushPreview(
  canvas: HTMLCanvasElement,
  options: BrushPreviewOptions = {},
  isLiveCard: boolean = false
): void {
  const ctx = canvas.getContext('2d');
  if (!ctx) return;

  const token = (canvasRequestTokens.get(canvas) ?? 0) + 1;
  canvasRequestTokens.set(canvas, token);
  const existingTimer = liveCardDebounceTimers.get(canvas);
  if (existingTimer !== undefined) {
    clearTimeout(existingTimer);
    liveCardDebounceTimers.delete(canvas);
  }
  removeQueuedTasksForCanvas(canvas);

  const dpr = typeof window !== 'undefined' ? Math.min(2, window.devicePixelRatio || 1) : 1;
  const targetWidth = Math.max(32, Math.round((options.width ?? canvas.width ?? 160) * (options.width ? dpr : 1)));
  const targetHeight = Math.max(16, Math.round((options.height ?? canvas.height ?? 44) * (options.height ? dpr : 1)));
  if (canvas.width !== targetWidth) canvas.width = targetWidth;
  if (canvas.height !== targetHeight) canvas.height = targetHeight;

  const builtinCfg = options.preset ? getBuiltinBrushConfig(options.preset) : undefined;
  const legacyPencil = getLegacyPencilPresetDefaults(options.preset);
  const merged = { ...legacyPencil, ...builtinCfg, ...options };

  const isEraser = options.tool === 'eraser';
  const strokeColor =
    options.color ??
    (isEraser ? '#9ca3af' : options.isSelected ? '#ffffff' : '#e4e4e7');
  const bgColor = options.backgroundColor ?? 'transparent';

  const cacheKey = buildCacheKey(merged, targetWidth, targetHeight, strokeColor, bgColor);
  const cached = previewCache.get(cacheKey);
  if (cached) {
    ctx.clearRect(0, 0, targetWidth, targetHeight);
    ctx.drawImage(cached, 0, 0);
    if (!isNativeCanvasActive() || gpuUpgradedCacheKeys.has(cacheKey)) {
      return;
    }
  }

  const size = merged.size ?? 12;
  const displayWidth = calculatePreviewWidth(size, targetHeight, dpr);
  const minSizeFactor = clamp(merged.minSizeFactor ?? 0.15, 0.02, 1.0);
  const usePressure = merged.usePressure !== false;

  if (!cached) {
    const pts = buildScurvePoints(
      targetWidth,
      targetHeight,
      displayWidth,
      minSizeFactor,
      usePressure,
      merged.pressureCurve
    );

    const offscreen = document.createElement('canvas');
    offscreen.width = targetWidth;
    offscreen.height = targetHeight;
    const offCtx = offscreen.getContext('2d');
    if (!offCtx) return;

    if (bgColor && bgColor !== 'transparent') {
      offCtx.fillStyle = bgColor;
      offCtx.fillRect(0, 0, targetWidth, targetHeight);
    }
    renderLightweightScurvePreview(offCtx, pts, strokeColor, merged, displayWidth);

    ctx.clearRect(0, 0, targetWidth, targetHeight);
    ctx.drawImage(offscreen, 0, 0);

    setCachedPreview(cacheKey, offscreen, false);
  }

  // On Windows Desktop with native DX12 engine active, queue a concurrency-limited GPU upgrade
  // (max 2 in-flight, stale requests cancelled on slider drag, skipped while actively drawing).
  if (isNativeCanvasActive() && !gpuUpgradedCacheKeys.has(cacheKey)) {
    const dualCfg = resolveDualBrushConfig(merged as BrushSettings);
    const previewSettings: BrushSettings = {
      size: displayWidth,
      minSizeFactor,
      color: strokeColor,
      secondaryColor: merged.secondaryColor ?? '#ffffff',
      opacity: clamp(merged.opacity ?? 1.0, 0.05, 1.0),
      flow: clamp(merged.flow ?? 1.0, 0.05, 1.0),
      brushDensity: merged.brushDensity ?? merged.flow ?? 1.0,
      adjustDensityByGap: Boolean(merged.adjustDensityByGap),
      blendTipsMode: merged.blendTipsMode,
      brushCombineMode: merged.brushCombineMode,
      spacing: clamp(merged.spacing ?? 0.1, 0.02, 0.65),
      hardness: clamp(merged.hardness ?? 0.9, 0.0, 1.0),
      thickness: merged.thickness ?? 1.0,
      thicknessVertical: Boolean(merged.thicknessVertical),
      flipH: merged.flipH,
      flipV: merged.flipV,
      antiAlias: (merged.antiAlias ?? 2) as CspAntiAliasLevel,
      usePressure,
      useTilt: Boolean(merged.useTilt),
      tiltScale: merged.tiltScale,
      smoothing: true,
      stabilization: 0,
      postCorrection: 0,
      sharpCorners: true,
      pressureCurve: merged.pressureCurve,
      sizeSensor: merged.sizeSensor,
      opacitySensor: merged.opacitySensor,
      densitySensor: merged.densitySensor,
      thicknessSensor: merged.thicknessSensor,
      intervalSensor: merged.intervalSensor,
      textureDensitySensor: merged.textureDensitySensor,
      customTipDataUrl: merged.customTipDataUrl,
      customTipImage: merged.customTipImage,
      customTipAngle: merged.customTipAngle,
      customTipAngleDynamics: merged.customTipAngleDynamics,
      customTipRotationRandomScale: merged.customTipRotationRandomScale,
      isColorTip: merged.isColorTip,
      isDualToneTip: merged.isDualToneTip,
      isRibbon: merged.isRibbon,
      subTips: merged.subTips,
      subTipOrder: merged.subTipOrder,
      subTipImages: merged.subTipImages,
      spray: merged.spray,
      taper: merged.taper,
      dynamics: merged.dynamics,
      colorMixing: merged.colorMixing,
      perceptualMixing: merged.perceptualMixing,
      amountOfPaint: merged.amountOfPaint,
      densityOfPaint: merged.densityOfPaint,
      colorStretch: merged.colorStretch,
      useBlur: merged.useBlur,
      blurStrength: merged.blurStrength,
      mixingMode: merged.mixingMode,
      wetEdge: merged.wetEdge,
      wetEdgeRadius: merged.wetEdgeRadius,
      wetEdgeAlphaPower: merged.wetEdgeAlphaPower,
      wetEdgeValuePower: merged.wetEdgeValuePower,
      grain: merged.grain,
      textureDensity: merged.textureDensity ?? merged.grain,
      paperTexture: merged.paperTexture,
      surfaceTextureId: merged.surfaceTextureId,
      grainMappingMode: merged.grainMappingMode,
      paperTextureMode: merged.paperTextureMode,
      paperTextureScale: merged.paperTextureScale,
      paperTextureRotate: merged.paperTextureRotate,
      dualBrush: Boolean(dualCfg?.enabled),
      dualBrushConfig: dualCfg ?? undefined,
      dualSurfaceTextureId: merged.dualSurfaceTextureId,
      dualGrainDepth: merged.dualGrainDepth,
      renderMode: merged.renderMode,
      bristle: merged.bristle,
      naturalPaint: merged.naturalPaint,
      impasto: merged.impasto,
      preset: merged.preset,
    };

    enqueueNativePreviewTask(
      {
        canvas,
        token,
        cacheKey,
        tool: isEraser ? 'eraser' : 'brush',
        previewSettings,
        strokeColor,
        secondaryColor: merged.secondaryColor ?? '#ffffff',
        bgColor,
        targetWidth,
        targetHeight,
      },
      isLiveCard ? LIVE_CARD_NATIVE_DEBOUNCE_MS : 0
    );
  }
}

export function clearBrushPreviewCache() {
  previewCache.clear();
  gpuUpgradedCacheKeys.clear();
  inFlightNativeKeys.clear();
  nativePreviewQueue.length = 0;
  inFlightNativeCount = 0;
}