Skip to content

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

18.1 KB
Raw Blame
/**
 * Pure utilities for Collaborative Drawing v2 features:
 *  - Follow Camera coordinate projection & 60fps smooth interpolation
 *  - "Grab an Artist's Brush" display-name resolution, non-destructive try-brush builder,
 *    and 1-click "Save to Custom Brushes" converter.
 */

import type {
  BrushSettings,
  CanvasDimensions,
  CspBrush,
  ToolType,
} from '../types/editor';
import type { BrushAssetRefs, CollabPeerCamera } from '../types/multiplayer';
import {
  CameraTransformState,
  MAX_ZOOM,
  MIN_ZOOM,
} from '../hooks/useCanvasNavigation';
import { NEUTRAL_BRUSH_DEFAULTS } from './brushPresetManager';
import { getCachedCustomBrushes } from './brushStorage';
import {
  ALL_BUILTIN_BRUSHES,
  getBuiltinBrushConfig,
  isDecorationPresetId,
} from './presetBrushes';
import { t } from '../i18n';

export const MAX_CHAT_MESSAGE_LENGTH = 1000;
export const MAX_CHAT_HISTORY = 200;
export const CAMERA_SYNC_THROTTLE_MS = 50; // ~20Hz network updates, smoothly interpolated at 60fps

function normalizeRotationDelta(targetDeg: number, currentDeg: number): number {
  let diff = (targetDeg - currentDeg) % 360;
  if (diff > 180) diff -= 360;
  if (diff <= -180) diff += 360;
  return diff;
}

/**
 * Projects the current viewport center into document space to produce a viewport-size-independent
 * camera snapshot suitable for network broadcast.
 */
export function buildCameraSyncSnapshot(
  camera: CameraTransformState,
  viewportWidth: number,
  viewportHeight: number,
  dimensions: CanvasDimensions
): Omit<CollabPeerCamera, 'updatedAt'> {
  const safeVw = Number.isFinite(viewportWidth) && viewportWidth > 0 ? Math.round(viewportWidth) : 1280;
  const safeVh = Number.isFinite(viewportHeight) && viewportHeight > 0 ? Math.round(viewportHeight) : 720;
  const safeZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Number.isFinite(camera.zoom) ? camera.zoom : 1));
  const safeRot = Number.isFinite(camera.rotation) ? camera.rotation : 0;

  const rx = safeVw / 2 - camera.pan.x;
  const ry = safeVh / 2 - camera.pan.y;
  const rad = (safeRot * Math.PI) / 180;
  const cos = Math.cos(rad);
  const sin = Math.sin(rad);
  const unrotX = rx * cos + ry * sin;
  const unrotY = -rx * sin + ry * cos;
  const fx = camera.flipX ? -1 : 1;
  const fy = camera.flipY ? -1 : 1;

  return {
    centerX: dimensions.width / 2 + (fx * unrotX) / safeZoom,
    centerY: dimensions.height / 2 + (fy * unrotY) / safeZoom,
    zoom: safeZoom,
    rotation: safeRot,
    flipX: Boolean(camera.flipX),
    flipY: Boolean(camera.flipY),
    viewportWidth: safeVw,
    viewportHeight: safeVh,
  };
}

/**
 * Computes the exact `pan` that places document point `(centerX, centerY)` at the center of
 * `(viewportWidth, viewportHeight)` under `(zoom, rotation, flipX, flipY)`.
 */
export function computePanForDocumentPoint(
  centerX: number,
  centerY: number,
  viewportWidth: number,
  viewportHeight: number,
  cam: Pick<CameraTransformState, 'zoom' | 'rotation' | 'flipX' | 'flipY'>,
  dimensions: CanvasDimensions
): { x: number; y: number } {
  const fx = cam.flipX ? -1 : 1;
  const fy = cam.flipY ? -1 : 1;
  const dx = (centerX - dimensions.width / 2) * fx;
  const dy = (centerY - dimensions.height / 2) * fy;
  const rad = (cam.rotation * Math.PI) / 180;
  const cos = Math.cos(rad);
  const sin = Math.sin(rad);
  const rx = cam.zoom * (dx * cos - dy * sin);
  const ry = cam.zoom * (dx * sin + dy * cos);
  return {
    x: viewportWidth / 2 - rx,
    y: viewportHeight / 2 - ry,
  };
}

/**
 * Projects a remote peer's `CollabPeerCamera` into the local follower's `CameraTransformState`.
 * Adapts zoom proportionally when viewport dimensions differ so the follower sees the exact same
 * canvas region without clipping, while remaining 1:1 exact when viewports match.
 */
export function computeFollowedCameraTransform(
  remoteCam: Pick<
    CollabPeerCamera,
    'centerX' | 'centerY' | 'zoom' | 'rotation' | 'flipX' | 'flipY' | 'viewportWidth' | 'viewportHeight'
  >,
  localViewportWidth: number,
  localViewportHeight: number,
  dimensions: CanvasDimensions
): CameraTransformState {
  const myVw = Number.isFinite(localViewportWidth) && localViewportWidth > 0 ? localViewportWidth : 1280;
  const myVh = Number.isFinite(localViewportHeight) && localViewportHeight > 0 ? localViewportHeight : 720;

  let effectiveZoom = Number.isFinite(remoteCam.zoom) ? remoteCam.zoom : 1;
  if (
    Number.isFinite(remoteCam.viewportWidth) &&
    remoteCam.viewportWidth > 0 &&
    Number.isFinite(remoteCam.viewportHeight) &&
    remoteCam.viewportHeight > 0
  ) {
    const scale = Math.min(myVw / remoteCam.viewportWidth, myVh / remoteCam.viewportHeight);
    if (Number.isFinite(scale) && scale > 0) {
      effectiveZoom *= scale;
    }
  }
  const clampedZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, effectiveZoom));
  const safeRot = Number.isFinite(remoteCam.rotation) ? remoteCam.rotation : 0;
  const flipX = Boolean(remoteCam.flipX);
  const flipY = Boolean(remoteCam.flipY);

  const pan = computePanForDocumentPoint(
    remoteCam.centerX,
    remoteCam.centerY,
    myVw,
    myVh,
    { zoom: clampedZoom, rotation: safeRot, flipX, flipY },
    dimensions
  );

  return {
    pan,
    zoom: clampedZoom,
    rotation: safeRot,
    flipX,
    flipY,
  };
}

/**
 * Smoothly steps `current` camera toward `targetRemoteCam` in document-center + log-zoom space
 * so Follow Camera glides cleanly at 60fps without curved zoom drift.
 */
export function stepInterpolatedFollowCamera(
  current: CameraTransformState,
  targetRemoteCam: Pick<
    CollabPeerCamera,
    'centerX' | 'centerY' | 'zoom' | 'rotation' | 'flipX' | 'flipY' | 'viewportWidth' | 'viewportHeight'
  >,
  localViewportWidth: number,
  localViewportHeight: number,
  dimensions: CanvasDimensions,
  dtSeconds: number
): { next: CameraTransformState; settled: boolean } {
  const target = computeFollowedCameraTransform(
    targetRemoteCam,
    localViewportWidth,
    localViewportHeight,
    dimensions
  );
  const curSnap = buildCameraSyncSnapshot(
    current,
    localViewportWidth,
    localViewportHeight,
    dimensions
  );

  const dx = targetRemoteCam.centerX - curSnap.centerX;
  const dy = targetRemoteCam.centerY - curSnap.centerY;
  const logZoomCur = Math.log(Math.max(MIN_ZOOM, current.zoom));
  const logZoomTarget = Math.log(Math.max(MIN_ZOOM, target.zoom));
  const dLogZoom = logZoomTarget - logZoomCur;
  const dRot = normalizeRotationDelta(target.rotation, current.rotation);
  const flipChanged = current.flipX !== target.flipX || current.flipY !== target.flipY;

  const isClose =
    !flipChanged &&
    Math.hypot(dx, dy) * target.zoom < 0.35 &&
    Math.abs(dLogZoom) < 0.002 &&
    Math.abs(dRot) < 0.05;

  if (isClose) {
    return { next: target, settled: true };
  }

  const dt = Math.min(0.05, Math.max(0.001, dtSeconds));
  const alpha = 1 - Math.exp(-dt * 18);

  const nextCenterX = curSnap.centerX + dx * alpha;
  const nextCenterY = curSnap.centerY + dy * alpha;
  const nextZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Math.exp(logZoomCur + dLogZoom * alpha)));
  const nextRotation = current.rotation + dRot * alpha;

  const nextPan = computePanForDocumentPoint(
    nextCenterX,
    nextCenterY,
    localViewportWidth > 0 ? localViewportWidth : 1280,
    localViewportHeight > 0 ? localViewportHeight : 720,
    {
      zoom: nextZoom,
      rotation: nextRotation,
      flipX: target.flipX,
      flipY: target.flipY,
    },
    dimensions
  );

  return {
    next: {
      pan: nextPan,
      zoom: nextZoom,
      rotation: nextRotation,
      flipX: target.flipX,
      flipY: target.flipY,
    },
    settled: false,
  };
}

export function hasSignificantCameraDelta(
  prev: Omit<CollabPeerCamera, 'updatedAt'> | null,
  next: Omit<CollabPeerCamera, 'updatedAt'>
): boolean {
  if (!prev) return true;
  if (prev.flipX !== next.flipX || prev.flipY !== next.flipY) return true;
  if (Math.abs(prev.centerX - next.centerX) > 0.25) return true;
  if (Math.abs(prev.centerY - next.centerY) > 0.25) return true;
  if (Math.abs(prev.zoom - next.zoom) > Math.max(0.0005, prev.zoom * 0.002)) return true;
  if (Math.abs(normalizeRotationDelta(next.rotation, prev.rotation)) > 0.05) return true;
  if (
    Math.abs(prev.viewportWidth - next.viewportWidth) > 4 ||
    Math.abs(prev.viewportHeight - next.viewportHeight) > 4
  ) {
    return true;
  }
  return false;
}

/**
 * Resolves a human-readable display name for any BrushSettings (custom or built-in).
 */
export function resolveBrushDisplayName(
  bs: Partial<BrushSettings> | null | undefined,
  customBrushes: ReadonlyArray<Pick<CspBrush, 'id' | 'name'>> = getCachedCustomBrushes()
): string {
  if (!bs) return 'Brush';
  const explicit = typeof bs.brushName === 'string' ? bs.brushName.trim() : '';
  if (explicit) return explicit;

  const presetId = typeof bs.preset === 'string' ? bs.preset.trim() : '';
  if (presetId) {
    const customMatch = customBrushes.find((b) => b.id === presetId);
    if (customMatch?.name?.trim()) return customMatch.name.trim();

    const builtinMatch = ALL_BUILTIN_BRUSHES.find((b) => b.id === presetId);
    if (builtinMatch?.name?.trim()) return builtinMatch.name.trim();

    if (!presetId.startsWith('collab-shared-') && !presetId.startsWith('csp-')) {
      return presetId
        .split(/[-_]+/)
        .filter(Boolean)
        .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
        .join(' ');
    }
  }
  return 'Brush';
}

export function resolveShareableBrushTool(
  tool: ToolType | string | undefined,
  presetId?: string
): 'brush' | 'decoration' {
  if (tool === 'decoration' || (presetId && isDecorationPresetId(presetId))) {
    return 'decoration';
  }
  return 'brush';
}

/**
 * Builds a complete, non-destructive `BrushSettings` ready to equip locally when trying
 * another artist's brush. Starts from `NEUTRAL_BRUSH_DEFAULTS` so none of the local user's
 * previous brush settings leak in, keeps the local user's active colors, and assigns a unique
 * `collab-shared-...` preset ID so the user's own presets are never overwritten.
 */
export function buildTryBrushSettings(params: {
  hydratedSettings: BrushSettings;
  brushAssetRefs?: BrushAssetRefs;
  peerId: string | number;
  peerName: string;
  brushName: string;
  localPrimaryColor: string;
  localSecondaryColor: string;
  localIsTransparentInk: boolean;
}): BrushSettings {
  const {
    hydratedSettings,
    brushAssetRefs,
    peerId,
    peerName,
    brushName,
    localPrimaryColor,
    localSecondaryColor,
    localIsTransparentInk,
  } = params;

  // If the remote artist is using a built-in brush whose static assets (e.g. decoration PNGs)
  // are bundled locally and didn't travel as base64 data URLs, enrich static tip fields from built-in config.
  let builtinStaticFallback: Partial<BrushSettings> | null = null;
  if (
    hydratedSettings.preset &&
    !brushAssetRefs?.tipHash &&
    !brushAssetRefs?.subTipHashes?.length &&
    !hydratedSettings.customTipDataUrl &&
    !hydratedSettings.subTips?.length
  ) {
    const cfg = getBuiltinBrushConfig(hydratedSettings.preset);
    if (cfg && (cfg.customTipDataUrl || cfg.subTips?.length || cfg.paperTexture)) {
      builtinStaticFallback = {
        customTipDataUrl: cfg.customTipDataUrl,
        customTipImage: cfg.customTipImage,
        subTips: cfg.subTips,
        subTipImages: cfg.subTipImages,
        paperTexture: cfg.paperTexture,
        paperTextureImage: cfg.paperTextureImage,
        dualTipDataUrl: cfg.dualTipDataUrl,
        dualTipImage: cfg.dualTipImage,
      };
    }
  }

  const peerSlug = String(peerId)
    .replace(/[^a-zA-Z0-9_-]/g, '')
    .slice(0, 24);
  const nameSlug = (brushName || 'brush')
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .slice(0, 24);
  const sharedPresetId = `collab-shared-${peerSlug || 'peer'}-${nameSlug || 'brush'}`;
  const displayLabel = peerName
    ? `${brushName || 'Brush'} (${peerName})`
    : brushName || 'Shared Brush';

  return {
    ...(NEUTRAL_BRUSH_DEFAULTS as Partial<BrushSettings>),
    ...(builtinStaticFallback || {}),
    ...hydratedSettings,
    size: Number.isFinite(hydratedSettings.size) ? hydratedSettings.size : 12,
    minSizeFactor: Number.isFinite(hydratedSettings.minSizeFactor)
      ? hydratedSettings.minSizeFactor
      : 0.05,
    opacity: Number.isFinite(hydratedSettings.opacity) ? hydratedSettings.opacity : 1,
    flow: Number.isFinite(hydratedSettings.flow) ? hydratedSettings.flow : 1,
    spacing: Number.isFinite(hydratedSettings.spacing) ? hydratedSettings.spacing : 0.08,
    usePressure: hydratedSettings.usePressure ?? true,
    smoothing: hydratedSettings.smoothing ?? true,
    stabilization: Number.isFinite(hydratedSettings.stabilization)
      ? hydratedSettings.stabilization
      : 10,
    hardness: Number.isFinite(hydratedSettings.hardness) ? hydratedSettings.hardness : 1,
    preset: sharedPresetId,
    brushName: displayLabel,
    color: localPrimaryColor,
    secondaryColor: localSecondaryColor,
    isTransparentInk: localIsTransparentInk,
  };
}

/**
 * Converts a grabbed `BrushSettings` into a persistent `CspBrush` record suitable for
 * saving to the user's IndexedDB Custom Brushes library in 1 click.
 */
export function buildSaveableCspBrush(
  bs: BrushSettings,
  displayName: string,
  category: 'custom' | 'brush' = 'custom'
): CspBrush {
  const id = `csp-shared-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
  const cleanName = (displayName || bs.brushName || 'Shared Brush').trim().slice(0, 64);
  return {
    id,
    name: cleanName,
    category,
    badge: 'Shared',
    desc: t('Grabbed from collaborative drawing session'),
    tipDataUrl: bs.customTipDataUrl,
    tipWidth: bs.customTipImage?.naturalWidth || bs.customTipImage?.width || undefined,
    tipHeight: bs.customTipImage?.naturalHeight || bs.customTipImage?.height || undefined,
    secondaryTipDataUrl: bs.dualTipDataUrl || bs.dualBrushConfig?.tipDataUrl,
    secondaryTipWidth: bs.dualTipImage?.naturalWidth || bs.dualTipImage?.width || undefined,
    secondaryTipHeight: bs.dualTipImage?.naturalHeight || bs.dualTipImage?.height || undefined,
    subTips: bs.subTips,
    subTipOrder: bs.subTipOrder,
    size: bs.size,
    brushSizeUnit: bs.brushSizeUnit,
    brushSizeSpecifiedByScreen: bs.brushSizeSpecifiedByScreen,
    minSizeFactor: bs.minSizeFactor,
    opacity: bs.opacity,
    flow: bs.flow,
    spacing: bs.spacing,
    hardness: bs.hardness,
    thickness: bs.thickness ?? 1.0,
    thicknessVertical: bs.thicknessVertical,
    thicknessSensor: bs.thicknessSensor,
    angle: bs.customTipAngle ?? 0,
    angleDynamics: bs.customTipAngleDynamics,
    rotationRandomScale: bs.customTipRotationRandomScale,
    rotateCursor: bs.rotateCursor,
    flipH: bs.flipH,
    flipV: bs.flipV,
    antiAlias: bs.antiAlias,
    usePressure: bs.usePressure,
    useTilt: bs.useTilt,
    tiltScale: bs.tiltScale,
    useVelocity: bs.useVelocity,
    smoothing: bs.smoothing,
    stabilization: bs.stabilization,
    postCorrection: bs.postCorrection,
    sharpCorners: bs.sharpCorners,
    pressureCurve: bs.pressureCurve,
    velocityCurve: bs.velocityCurve,
    brushDensity: bs.brushDensity,
    adjustDensityByGap: bs.adjustDensityByGap,
    blendTipsMode: bs.blendTipsMode,
    brushCombineMode: bs.brushCombineMode,
    sizeSensor: bs.sizeSensor,
    opacitySensor: bs.opacitySensor,
    densitySensor: bs.densitySensor,
    intervalSensor: bs.intervalSensor,
    textureDensitySensor: bs.textureDensitySensor,
    bristleSplaySensor: bs.bristleSplaySensor,
    paintLoadSensor: bs.paintLoadSensor,
    grainPenetrationSensor: bs.grainPenetrationSensor,
    angleSensor: bs.angleSensor,
    scatterSensor: bs.scatterSensor,
    colorMixing: bs.colorMixing,
    perceptualMixing: bs.perceptualMixing,
    amountOfPaint: bs.amountOfPaint,
    densityOfPaint: bs.densityOfPaint,
    colorStretch: bs.colorStretch,
    amountOfPaintSensor: bs.amountOfPaintSensor,
    densityOfPaintSensor: bs.densityOfPaintSensor,
    colorStretchSensor: bs.colorStretchSensor,
    mixGroundColor: bs.mixGroundColor,
    useBlur: bs.useBlur,
    blurStrength: bs.blurStrength,
    mixingMode: bs.mixingMode,
    wetEdge: bs.wetEdge,
    wetEdgeRadius: bs.wetEdgeRadius,
    wetEdgeAlphaPower: bs.wetEdgeAlphaPower,
    wetEdgeValuePower: bs.wetEdgeValuePower,
    paperTexture: bs.paperTexture,
    surfaceTextureId: bs.surfaceTextureId,
    grainMappingMode: bs.grainMappingMode,
    textureDensity: bs.textureDensity ?? bs.grain,
    paperTextureMode: bs.paperTextureMode,
    paperTextureBrightness: bs.paperTextureBrightness,
    paperTextureContrast: bs.paperTextureContrast,
    paperTextureApplyEachPlot: bs.paperTextureApplyEachPlot,
    paperTextureEmphasizeDensity: bs.paperTextureEmphasizeDensity,
    paperTextureScale: bs.paperTextureScale,
    paperTextureRotate: bs.paperTextureRotate,
    paperTextureOffsetX: bs.paperTextureOffsetX,
    paperTextureOffsetY: bs.paperTextureOffsetY,
    paperTextureInverted: bs.paperTextureInverted,
    dualBrush: bs.dualBrush,
    dualBrushConfig: bs.dualBrushConfig
      ? {
          ...bs.dualBrushConfig,
          tipDataUrl: bs.dualBrushConfig.tipDataUrl || bs.dualTipDataUrl,
          subTips: bs.dualBrushConfig.subTips || bs.dualSubTips,
        }
      : undefined,
    dualBrushCompositeMode: bs.dualBrushCompositeMode,
    dualSize: bs.dualSize,
    dualLinkSize: bs.dualLinkSize,
    dualSpacing: bs.dualSpacing,
    dualScatter: bs.dualScatter,
    dualThickness: bs.dualThickness,
    dualThicknessVertical: bs.dualThicknessVertical,
    dualAngle: bs.dualAngle,
    dualAngleDynamics: bs.dualAngleDynamics,
    dualAngleSensor: bs.dualAngleSensor,
    dualHardness: bs.dualHardness,
    dualDensity: bs.dualDensity,
    dualSubTips: bs.dualSubTips,
    dualSubTipOrder: bs.dualSubTipOrder,
    dualFlipH: bs.dualFlipH,
    dualFlipV: bs.dualFlipV,
    dualSpray: bs.dualSpray,
    dualIsRibbon: bs.dualIsRibbon,
    dualScale: bs.dualScale,
    dualSurfaceTextureId: bs.dualSurfaceTextureId,
    dualGrainDepth: bs.dualGrainDepth,
    spray: bs.spray,
    taper: bs.taper,
    isRibbon: bs.isRibbon,
    isColorTip: bs.isColorTip,
    isDualToneTip: bs.isDualToneTip,
    pressureCurveGamma: bs.pressureCurveGamma,
    velocityDynamics: bs.velocityDynamics,
    dynamics: bs.dynamics,
    renderMode: bs.renderMode,
    bristle: bs.bristle,
    naturalPaint: bs.naturalPaint,
    impasto: bs.impasto,
    importedAt: Date.now(),
  };
}