Skip to content

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

extra sut brush import fix

sora7dcbb2daa342
diff --git a/src-tauri/src/clip_parser.rs b/src-tauri/src/clip_parser.rs
index f208088..21756fa 100644
--- a/src-tauri/src/clip_parser.rs
+++ b/src-tauri/src/clip_parser.rs
@@ -1551,19 +1551,23 @@ pub fn extract_sut_sqlite_binary(bytes: &[u8]) -> Result<Vec<u8>, String> {
let mut variant_blobs = HashMap::new();
if tables.contains("Variant") {
+ let query_variant_by_col = |col: &str, vid: i64| -> rusqlite::Result<(Vec<String>, Vec<Value>)> {
+ let sql = format!("SELECT * FROM Variant WHERE {} = ?1 LIMIT 1", col);
+ let mut s = conn.prepare(&sql)?;
+ let cols: Vec<String> = s.column_names().into_iter().map(String::from).collect();
+ let row = s.query_row([vid], |r| {
+ let mut vals = Vec::with_capacity(cols.len());
+ for i in 0..cols.len() {
+ vals.push(r.get::<_, Value>(i).unwrap_or(Value::Null));
+ }
+ Ok(vals)
+ })?;
+ Ok((cols, row))
+ };
+
let query_res: rusqlite::Result<(Vec<String>, Vec<Value>)> = if let Some(vid) = variant_id {
- conn.prepare("SELECT * FROM Variant WHERE _PW_ID = ?1 LIMIT 1")
- .and_then(|mut s| {
- let cols: Vec<String> = s.column_names().into_iter().map(String::from).collect();
- let row = s.query_row([vid], |r| {
- let mut vals = Vec::with_capacity(cols.len());
- for i in 0..cols.len() {
- vals.push(r.get::<_, Value>(i).unwrap_or(Value::Null));
- }
- Ok(vals)
- })?;
- Ok((cols, row))
- })
+ query_variant_by_col("VariantID", vid)
+ .or_else(|_| query_variant_by_col("_PW_ID", vid))
} else {
Err(rusqlite::Error::QueryReturnedNoRows)
}
diff --git a/src/components/canvasArea/CanvasViewportHud.tsx b/src/components/canvasArea/CanvasViewportHud.tsx
index d93f12b..b835001 100644
--- a/src/components/canvasArea/CanvasViewportHud.tsx
+++ b/src/components/canvasArea/CanvasViewportHud.tsx
@@ -133,6 +133,7 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({
>
<svg
viewBox={isCustomTip && tipOutline ? tipOutline.viewBox : '0 0 100 100'}
+ preserveAspectRatio="none"
className="w-full h-full overflow-visible pointer-events-none select-none"
style={{ display: 'block' }}
>
@@ -223,6 +224,7 @@ export const CanvasViewportHud: React.FC<CanvasViewportHudProps> = ({
{isCustomTip && tipOutline ? (
<svg
viewBox={tipOutline.viewBox}
+ preserveAspectRatio="none"
className="w-full h-full overflow-visible pointer-events-none"
style={{ display: 'block' }}
>
diff --git a/src/components/canvasArea/types.ts b/src/components/canvasArea/types.ts
index 92d2ded..b9d6054 100644
--- a/src/components/canvasArea/types.ts
+++ b/src/components/canvasArea/types.ts
@@ -156,6 +156,8 @@ export interface CursorConfig {
thicknessRatio: number;
thicknessVertical: boolean;
tipAngleDeg: number;
+ followDirection?: boolean;
+ dynamicDirDeg?: number;
rotation: number;
flipX: boolean;
flipY: boolean;
diff --git a/src/components/canvasArea/useCanvasEffects.ts b/src/components/canvasArea/useCanvasEffects.ts
index afcf592..d38120a 100644
--- a/src/components/canvasArea/useCanvasEffects.ts
+++ b/src/components/canvasArea/useCanvasEffects.ts
@@ -124,6 +124,10 @@ export function useCanvasEffects({
const thicknessRatio = tool === 'brush' ? (brushSettings.thickness ?? 1.0) : 1.0;
const thicknessVertical = Boolean(brushSettings.thicknessVertical && tool === 'brush');
const tipAngleDeg = tool === 'brush' ? (brushSettings.customTipAngle ?? 0) : 0;
+ const followDirection =
+ tool === 'brush' &&
+ (brushSettings.customTipAngleDynamics === 'direction' ||
+ brushSettings.customTipAngleDynamics === 'direction-random');
const cursorWidth = thicknessVertical
? Math.max(2, cursorBaseWidth * thicknessRatio)
@@ -134,12 +138,16 @@ export function useCanvasEffects({
// Brush tip rotation: tip angle relative to canvas + viewport canvas rotation
const totalAngleDeg = tipAngleDeg + liveRotation;
+ const dynamicDirDegRef = useRef<number>(0);
+ const lastDirAnchorRef = useRef<{ x: number; y: number } | null>(null);
const cursorConfigRef = useRef<CursorConfig>({
activeToolSize,
tipAspect,
thicknessRatio,
thicknessVertical,
tipAngleDeg,
+ followDirection,
+ dynamicDirDeg: 0,
rotation: liveRotation,
flipX: liveFlipX,
flipY: liveFlipY,
@@ -150,6 +158,8 @@ export function useCanvasEffects({
thicknessRatio,
thicknessVertical,
tipAngleDeg,
+ followDirection,
+ dynamicDirDeg: dynamicDirDegRef.current,
rotation: liveRotation,
flipX: liveFlipX,
flipY: liveFlipY,
@@ -198,7 +208,7 @@ export function useCanvasEffects({
cfg.rotation,
cfg.flipX,
cfg.flipY,
- cfg.tipAngleDeg
+ cfg.tipAngleDeg + (cfg.followDirection ? cfg.dynamicDirDeg ?? 0 : 0)
);
}
}, [tipAngleDeg, liveRotation, liveFlipX, liveFlipY]);
@@ -234,13 +244,38 @@ export function useCanvasEffects({
const ring = cursorRingRef.current;
if (!ring) return;
const cfg = cursorConfigRef.current;
+ let effectiveTipAngle = cfg.tipAngleDeg;
+ if (cfg.followDirection) {
+ const anchor = lastDirAnchorRef.current;
+ if (anchor) {
+ const sdx = x - anchor.x;
+ const sdy = y - anchor.y;
+ if (sdx * sdx + sdy * sdy >= 16) {
+ const rad = (-cfg.rotation * Math.PI) / 180;
+ const c = Math.cos(rad);
+ const s = Math.sin(rad);
+ const cdx = (sdx * c - sdy * s) * (cfg.flipX ? -1 : 1);
+ const cdy = (sdx * s + sdy * c) * (cfg.flipY ? -1 : 1);
+ const targetDeg = (Math.atan2(cdy, cdx) * 180) / Math.PI;
+ let delta = targetDeg - dynamicDirDegRef.current;
+ while (delta > 180) delta -= 360;
+ while (delta < -180) delta += 360;
+ dynamicDirDegRef.current += delta * 0.45;
+ cfg.dynamicDirDeg = dynamicDirDegRef.current;
+ lastDirAnchorRef.current = { x, y };
+ }
+ } else {
+ lastDirAnchorRef.current = { x, y };
+ }
+ effectiveTipAngle = cfg.tipAngleDeg + dynamicDirDegRef.current;
+ }
ring.style.transform = formatCursorRingTransform(
x,
y,
cfg.rotation,
cfg.flipX,
cfg.flipY,
- cfg.tipAngleDeg
+ effectiveTipAngle
);
if (ring.style.display !== 'block') {
ring.style.display = 'block';
diff --git a/src/components/canvasArea/useCompositorViewport.ts b/src/components/canvasArea/useCompositorViewport.ts
index 65e96bd..bbe19c8 100644
--- a/src/components/canvasArea/useCompositorViewport.ts
+++ b/src/components/canvasArea/useCompositorViewport.ts
@@ -222,7 +222,7 @@ export function useCompositorViewport({
cam.rotation,
cam.flipX,
cam.flipY,
- cfg.tipAngleDeg
+ cfg.tipAngleDeg + (cfg.followDirection ? cfg.dynamicDirDeg ?? 0 : 0)
);
}
}
diff --git a/src/engine/BrushEngine.ts b/src/engine/BrushEngine.ts
index 9bbed89..80c4177 100644
--- a/src/engine/BrushEngine.ts
+++ b/src/engine/BrushEngine.ts
@@ -32,6 +32,7 @@ import {
import { enforceColorMode } from '../utils/colorUtils';
import {
PaintReservoir,
+ SpatialTipMixer,
LayerPixelSampler,
sampleCanvasColor,
parseColorToRgb,
@@ -127,6 +128,8 @@ export interface BrushRenderOptions {
strokeIndex?: number;
totalLength?: number;
currentStrokeDist?: number;
+ exitSpeed?: number;
+ initialAngleRad?: number;
dynamics?: BrushDynamics;
secondaryColor?: string;
}
@@ -531,7 +534,7 @@ export function computeEllipticalStepDistance(
spacingRatio: number,
minStepPx: number = 0.12
): number {
- const ratio = Math.max(0.01, Math.min(2.0, spacingRatio));
+ const ratio = Math.max(0.003, Math.min(2.0, spacingRatio));
const w = Math.max(0.1, width);
const h = Math.max(0.1, height);
@@ -899,6 +902,19 @@ const sharedBezierSample: EvaluatedBezierSample = {
twist: 0,
};
+const peekBezierSample: EvaluatedBezierSample = {
+ x: 0,
+ y: 0,
+ width: 0,
+ pressure: 0,
+ dx: 0,
+ dy: 0,
+ speed: 0,
+ tiltX: 0,
+ tiltY: 0,
+ twist: 0,
+};
+
function evalCubicBezierInto(
p0: Point,
c1: Point,
@@ -1046,10 +1062,10 @@ export function centripetalCatmullRomToBezier(
const dt1 = Math.max(1e-4, Math.sqrt(d12));
const dt2 = Math.max(1e-4, Math.sqrt(d23));
- const t1x = (p2.x - p1.x) / dt1 - (p1.x - effP0.x) / dt0 + (p2.x - effP0.x) / (dt0 + dt1);
- const t1y = (p2.y - p1.y) / dt1 - (p1.y - effP0.y) / dt0 + (p2.y - effP0.y) / (dt0 + dt1);
- const t2x = (effP3.x - p2.x) / dt2 - (p2.x - p1.x) / dt1 + (effP3.x - p1.x) / (dt1 + dt2);
- const t2y = (effP3.y - p2.y) / dt2 - (p2.y - p1.y) / dt1 + (effP3.y - p1.y) / (dt1 + dt2);
+ const t1x = (p1.x - effP0.x) / dt0 - (p2.x - effP0.x) / (dt0 + dt1) + (p2.x - p1.x) / dt1;
+ const t1y = (p1.y - effP0.y) / dt0 - (p2.y - effP0.y) / (dt0 + dt1) + (p2.y - p1.y) / dt1;
+ const t2x = (p2.x - p1.x) / dt1 - (effP3.x - p1.x) / (dt1 + dt2) + (effP3.x - p2.x) / dt2;
+ const t2y = (p2.y - p1.y) / dt1 - (effP3.y - p1.y) / (dt1 + dt2) + (effP3.y - p2.y) / dt2;
let dx1 = (t1x * dt1) / 3;
let dy1 = (t1y * dt1) / 3;
@@ -1429,11 +1445,14 @@ function getInvertedGrainPattern(
const img = gCtx.getImageData(0, 0, w, h);
const d = img.data;
for (let i = 0; i < d.length; i += 4) {
- const lum = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];
+ const aNorm = d[i + 3] / 255;
+ const rgbLum = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];
+ // CSP paper textures are black-on-transparent RGBA (RGB=0, A=density); composite over white
+ const effLum = rgbLum * aNorm + 255 * (1 - aNorm);
d[i] = 255;
d[i + 1] = 255;
d[i + 2] = 255;
- d[i + 3] = 255 - Math.round(lum);
+ d[i + 3] = 255 - Math.round(effLum);
}
gCtx.putImageData(img, 0, 0);
const pat = scratchCtx.createPattern(c, 'repeat');
@@ -1601,6 +1620,184 @@ export function flushGpuDabs(
// 9. Unified Dab & Stroke Renderer (Textured, Radial & Pencil Presets)
// ============================================================================
+const _customGrainLumCache = new WeakMap<
+ HTMLImageElement,
+ { width: number; height: number; lum: Uint8Array }
+>();
+
+function getCustomPaperLuminance(
+ img: HTMLImageElement
+): { width: number; height: number; lum: Uint8Array } | null {
+ const cached = _customGrainLumCache.get(img);
+ if (cached) return cached;
+ if (typeof document === 'undefined') return null;
+ if (img.complete === false) return null;
+ const w = img.naturalWidth || img.width;
+ const h = img.naturalHeight || img.height;
+ if (w <= 0 || h <= 0) return null;
+ const c = document.createElement('canvas');
+ c.width = w;
+ c.height = h;
+ const gCtx = c.getContext('2d', { willReadFrequently: true });
+ if (!gCtx || typeof gCtx.getImageData !== 'function') return null;
+ gCtx.drawImage(img, 0, 0, w, h);
+ const d = gCtx.getImageData(0, 0, w, h).data;
+ const lum = new Uint8Array(w * h);
+ for (let i = 0; i < lum.length; i++) {
+ const p = i << 2;
+ const aNorm = d[p + 3] / 255;
+ const rgbLum = 0.299 * d[p] + 0.587 * d[p + 1] + 0.114 * d[p + 2];
+ // CSP paper textures encode density in alpha with RGB=0; composite over white to recover height
+ lum[i] = Math.round(rgbLum * aNorm + 255 * (1 - aNorm));
+ }
+ const entry = { width: w, height: h, lum };
+ _customGrainLumCache.set(img, entry);
+ return entry;
+}
+
+function sampleWorldPaperGrainNorm(
+ wx: number,
+ wy: number,
+ scale: number,
+ rotateDeg: number,
+ customPaper?: { width: number; height: number; lum: Uint8Array } | null
+): number {
+ const invScale = 1.0 / Math.max(0.05, scale);
+ let sx = wx * invScale;
+ let sy = wy * invScale;
+ if (rotateDeg !== 0) {
+ const rad = (-rotateDeg * Math.PI) / 180;
+ const c = Math.cos(rad);
+ const s = Math.sin(rad);
+ const rx = sx * c - sy * s;
+ const ry = sx * s + sy * c;
+ sx = rx;
+ sy = ry;
+ }
+ if (customPaper) {
+ const cw = customPaper.width;
+ const ch = customPaper.height;
+ const fx = Math.floor(sx);
+ const fy = Math.floor(sy);
+ const tx = sx - fx;
+ const ty = sy - fy;
+ const x0 = ((fx % cw) + cw) % cw;
+ const y0 = ((fy % ch) + ch) % ch;
+ const x1 = (x0 + 1) % cw;
+ const y1 = (y0 + 1) % ch;
+ const v00 = customPaper.lum[y0 * cw + x0];
+ const v10 = customPaper.lum[y0 * cw + x1];
+ const v01 = customPaper.lum[y1 * cw + x0];
+ const v11 = customPaper.lum[y1 * cw + x1];
+ const top = v00 + (v10 - v00) * tx;
+ const bot = v01 + (v11 - v01) * tx;
+ return (top + (bot - top) * ty) / 255.0;
+ }
+ return getPaperGrain(sx, sy) / 255.0;
+}
+
+function evaluateCspTaperFactors(
+ taper: CspTaperSettings | undefined,
+ strokeDist: number,
+ totalLength: number | undefined,
+ exitSpeed?: number
+): { sizeScale: number; alphaScale: number; amountScale: number; paintDensityScale: number } {
+ if (!taper || (!taper.useIn && !taper.useOut)) {
+ return { sizeScale: 1.0, alphaScale: 1.0, amountScale: 1.0, paintDensityScale: 1.0 };
+ }
+
+ const inSharp = 0.35 + (1.0 - (taper.startingSharpness ?? 0.5)) * 1.1;
+ const outSharp = 0.35 + (1.0 - (taper.endingSharpness ?? 0.5)) * 1.1;
+ const minSize = Math.max(0, Math.min(1, taper.minSizeRatio ?? 0));
+ const minDens = Math.max(0, Math.min(1, taper.minDensityRatio ?? 0));
+ const minAmount = Math.max(0, Math.min(1, taper.minAmountRatio ?? 0));
+ const minPaintDens = Math.max(0, Math.min(1, taper.minPaintDensityRatio ?? 0));
+ const affectSize = taper.affectSize !== false;
+ const affectFlow = Boolean(taper.affectDensity || taper.affectOpacity);
+ const affectAmount = Boolean(taper.affectAmountOfPaint || taper.affectOpacity);
+ const affectPaintDensity = Boolean(taper.affectDensityOfPaint);
+
+ // CSP BrushInOutType enum:
+ // 0 = Off
+ // 1 = Specify by percentage (inRatio / outRatio of totalLength)
+ // 2 = Specify by length (inLength px at start, outLength px at END — never kills mid-stroke!)
+ // 3 = Fade (continuous decay from strokeDist=0 over outLength px)
+ if (taper.inOutType === 3 && taper.useOut) {
+ const fadeLen = taper.outLength > 0 ? taper.outLength : 200;
+ const remain = Math.max(0, Math.min(1, 1.0 - strokeDist / fadeLen));
+ return {
+ sizeScale: affectSize ? minSize + (1.0 - minSize) * remain : 1.0,
+ alphaScale: affectFlow ? minDens + (1.0 - minDens) * Math.pow(remain, 1.1) : 1.0,
+ amountScale: affectAmount ? minAmount + (1.0 - minAmount) * remain : 1.0,
+ paintDensityScale: affectPaintDensity ? minPaintDens + (1.0 - minPaintDens) * remain : 1.0,
+ };
+ }
+
+ const usePercentage = taper.inOutType === 1 && (taper.inRatio > 0 || taper.outRatio > 0);
+
+ let inLen = 0;
+ if (taper.useIn) {
+ if (usePercentage && totalLength && totalLength > 0) {
+ inLen = totalLength * Math.max(0, Math.min(1, taper.inRatio));
+ } else {
+ inLen = taper.inLength > 0 ? taper.inLength : taper.inRatio > 0 ? taper.inRatio * 120 : 0;
+ }
+ if (taper.inOutBySpeed) {
+ // Pen lands near zero entry velocity in CSP "Starting and ending by speed"
+ inLen *= 0.15;
+ }
+ }
+
+ let outLen = 0;
+ if (taper.useOut && totalLength && totalLength > 0) {
+ if (usePercentage) {
+ outLen = totalLength * Math.max(0, Math.min(1, taper.outRatio));
+ } else {
+ outLen = taper.outLength > 0 ? taper.outLength : taper.outRatio > 0 ? taper.outRatio * 180 : 0;
+ }
+ if (taper.inOutBySpeed && exitSpeed !== undefined && Number.isFinite(exitSpeed)) {
+ // Faster flick exits stretch the ending taper toward full outLength; deliberate stops stay crisp
+ const speedNorm = Math.max(0, Math.min(1, exitSpeed / 1.1));
+ outLen *= 0.35 + 0.65 * speedNorm;
+ }
+ if (inLen + outLen > totalLength && inLen + outLen > 0) {
+ const ratio = totalLength / (inLen + outLen);
+ inLen *= ratio;
+ outLen *= ratio;
+ }
+ }
+
+ let sizeScale = 1.0;
+ let alphaScale = 1.0;
+ let amountScale = 1.0;
+ let paintDensityScale = 1.0;
+
+ if (taper.useIn && inLen > 0 && strokeDist < inLen) {
+ const u = Math.max(0.08, Math.min(1.0, strokeDist / inLen));
+ const smoothU = u * u * (3 - 2 * u);
+ const t = Math.pow(smoothU, inSharp);
+ if (affectSize) sizeScale *= minSize + (1.0 - minSize) * t;
+ if (affectFlow) alphaScale *= minDens + (1.0 - minDens) * t;
+ if (affectAmount) amountScale *= minAmount + (1.0 - minAmount) * t;
+ if (affectPaintDensity) paintDensityScale *= minPaintDens + (1.0 - minPaintDens) * t;
+ }
+
+ if (taper.useOut && outLen > 0 && totalLength && totalLength > 0) {
+ const distFromEnd = Math.max(0, totalLength - strokeDist);
+ if (distFromEnd < outLen) {
+ const u = Math.max(0.0, Math.min(1.0, distFromEnd / outLen));
+ const smoothU = u * u * (3 - 2 * u);
+ const t = Math.pow(smoothU, outSharp);
+ if (affectSize) sizeScale *= minSize + (1.0 - minSize) * t;
+ if (affectFlow) alphaScale *= minDens + (1.0 - minDens) * t;
+ if (affectAmount) amountScale *= minAmount + (1.0 - minAmount) * t;
+ if (affectPaintDensity) paintDensityScale *= minPaintDens + (1.0 - minPaintDens) * t;
+ }
+ }
+
+ return { sizeScale, alphaScale, amountScale, paintDensityScale };
+}
+
function sampleScalarPaperGrainNorm(x: number, y: number, width: number, scale: number): number {
const invScale = 1.0 / Math.max(0.1, scale);
const sx = x * invScale;
@@ -1729,6 +1926,16 @@ export function drawBrushDot(
? Math.max(0.4, point.width)
: Math.max(0.5, (options.size ?? 10) * (minFactor + (1.0 - minFactor) * effPressure));
+ let startAmountScale = 1.0;
+ let startPaintDensityScale = 1.0;
+ if (options.taper && options.totalLength && options.totalLength > 0) {
+ const startTaper = evaluateCspTaperFactors(options.taper, 0, options.totalLength, options.exitSpeed);
+ effWidth *= startTaper.sizeScale;
+ effectiveFlow *= startTaper.alphaScale;
+ startAmountScale = startTaper.amountScale;
+ startPaintDensityScale = startTaper.paintDensityScale;
+ }
+
const tiltX = useTilt ? point.tiltX ?? 0 : 0;
const tiltY = useTilt ? point.tiltY ?? 0 : 0;
const tiltAngleDeg = Math.min(90, Math.sqrt(tiltX * tiltX + tiltY * tiltY));
@@ -1738,9 +1945,14 @@ export function drawBrushDot(
useTilt && tiltMagnitude > 0.01 ? effPressure * (1.0 - tiltMagnitude * 0.55) : effPressure;
if (options.sizeSensor) {
+ // Avoid double-applying pressure when point.width already has pressure baked from calculateStrokeWidth
+ const effectiveSizeSensor =
+ point.width > 0 && options.usePressure !== false && options.sizeSensor.usePressure
+ ? { ...options.sizeSensor, usePressure: false }
+ : options.sizeSensor;
effWidth = Math.max(
0.15,
- effWidth * evaluateCspSensor(options.sizeSensor, effPressure, tiltMagnitude, 0, dabHashFloat(point.x, point.y, 0, 50))
+ effWidth * evaluateCspSensor(effectiveSizeSensor, effPressure, tiltMagnitude, 0, dabHashFloat(point.x, point.y, 0, 50))
);
}
if (options.opacitySensor) {
@@ -1753,15 +1965,6 @@ export function drawBrushDot(
effectiveFlow *= 1.0 - tiltMagnitude * 0.28;
}
- const isColorMixing = Boolean(options.colorMixing) && !isEraser && !isBgEraser;
- if (isColorMixing) {
- if (!options.reservoir) options.reservoir = new PaintReservoir(effectiveColor);
- const mixed = sampleAndMixColor(ctx, point.x, point.y, Math.max(1, effWidth * 0.5), effPressure, effectiveFlow, 0, options);
- effectiveColor = mixed.colorHex;
- effectiveFlow = mixed.alpha;
- }
- if (effectiveFlow <= 0.002) return;
-
const gpuDabs = batchGpuDabs || null;
const activeTip = options.tipImage
? selectTipImage(options.subTipImages, options.tipImage, options.subTipOrder, 0, 0, point.x, point.y)
@@ -1771,14 +1974,127 @@ export function drawBrushDot(
? (activeTip.naturalHeight || activeTip.height || 1) / (activeTip.naturalWidth || activeTip.width || 1)
: 1.0;
- let angleRad = ((options.angle ?? 0) * Math.PI) / 180;
+ let angleRad =
+ options.initialAngleRad !== undefined
+ ? options.initialAngleRad
+ : ((options.angle ?? 0) * Math.PI) / 180;
if (useTilt && tiltMagnitude > 0.05) {
- angleRad = Math.atan2(tiltY, tiltX) + angleRad;
+ angleRad = Math.atan2(tiltY, tiltX) + ((options.angle ?? 0) * Math.PI) / 180;
}
if (point.twist && (options.angleDynamics === 'twist' || useTilt)) {
angleRad += (point.twist * Math.PI) / 180;
}
+ const isColorMixing = Boolean(options.colorMixing) && !isEraser && !isBgEraser;
+ const useSpatialTipMixing =
+ isColorMixing &&
+ !gpuDabs &&
+ !isColorTip &&
+ !options.dynamics?.colorJitterEnabled &&
+ !options.spray?.enabled;
+
+ if (useSpatialTipMixing) {
+ if (!options.reservoir) options.reservoir = new PaintReservoir(effectiveColor);
+ if (!options.reservoir.spatialMixer) {
+ options.reservoir.spatialMixer = new SpatialTipMixer(effectiveColor);
+ }
+ const pressureAlreadyApplied = Boolean(
+ options.opacitySensor?.usePressure || options.densitySensor?.usePressure
+ );
+ let finalW = isVert ? effWidth * thickness : effWidth;
+ let finalH = isVert ? effWidth * aspect : effWidth * aspect * thickness;
+ if (useTilt && tiltMagnitude > 0.01) {
+ finalW *= 1.0 + tiltSpread * 1.85;
+ finalH *= Math.max(0.55, 1.0 / (1.0 + tiltMagnitude * 0.45));
+ }
+ const flips = resolveTipFlipSigns(options.flipH, options.flipV, 0, point.x, point.y);
+ const customPaper = options.paperTextureImage ? getCustomPaperLuminance(options.paperTextureImage) : null;
+ const texScale = options.paperTextureScale ?? 1.0;
+ const texRot = options.paperTextureRotate ?? 0;
+ const texMode = options.paperTextureMode ?? 'multiply';
+ const texBright = options.paperTextureBrightness ?? 0;
+ const texContrast = options.paperTextureContrast ?? 0;
+ const texInv = Boolean(options.paperTextureInverted);
+
+ const built = options.reservoir.spatialMixer.stepAndBuildStamp({
+ x: point.x,
+ y: point.y,
+ width: finalW,
+ height: finalH,
+ angleRad,
+ dirX: 0,
+ dirY: 0,
+ stepDist: 0,
+ spacingRatio: spacing,
+ adjustDensityByGap: Boolean(options.adjustDensityByGap),
+ hardness,
+ antiAlias: aaMode,
+ flipX: flips.signX,
+ flipY: flips.signY,
+ flow: effectiveFlow,
+ pressure: effPressure,
+ pressureAlreadyApplied,
+ amountOfPaint: (options.amountOfPaint ?? 0.65) * startAmountScale,
+ densityOfPaint: (options.densityOfPaint ?? 0.9) * startPaintDensityScale,
+ colorStretch: options.colorStretch ?? 0.75,
+ mixingMode: options.mixingMode ?? 'blend',
+ perceptualMixing: options.perceptualMixing !== false,
+ tipImage: activeTip,
+ sampler: options.sampler,
+ grainDensity: grainAmount,
+ grainModulate:
+ grainAmount > 0.005
+ ? (wx, wy, tipA) =>
+ applyCspPaperTextureAlpha(
+ tipA,
+ sampleWorldPaperGrainNorm(wx, wy, texScale, texRot, customPaper),
+ grainAmount,
+ grainPressure,
+ texMode,
+ texBright,
+ texContrast,
+ texInv
+ )
+ : undefined,
+ });
+ if (built) {
+ options.reservoir.r = built.avgR;
+ options.reservoir.g = built.avgG;
+ options.reservoir.b = built.avgB;
+ options.reservoir.a = built.avgA;
+ if (built.pickedUpCanvas) options.reservoir.isLoadedWithCanvasColor = true;
+ }
+ if (built && built.hasVisiblePixels) {
+ drawSingleStamp(
+ ctx,
+ built.canvas,
+ point.x,
+ point.y,
+ built.drawW,
+ built.drawH,
+ angleRad,
+ 1.0,
+ false,
+ false,
+ options.alphaLocked,
+ options.isTransparentInk,
+ 1,
+ 1,
+ aaMode,
+ options.blendTipsMode
+ );
+ }
+ return;
+ }
+
+ if (isColorMixing) {
+ if (!options.reservoir) options.reservoir = new PaintReservoir(effectiveColor);
+ const mixed = sampleAndMixColor(ctx, point.x, point.y, Math.max(1, effWidth * 0.5), effPressure, effectiveFlow, 0, options);
+ effectiveColor = mixed.colorHex;
+ effectiveFlow = mixed.alpha;
+ }
+ if (effectiveFlow <= 0.002) return;
+
const hasPerPixelCpuGrain = !gpuDabs && grainAmount > 0.005 && typeof ctx.createPattern === 'function';
if (!gpuDabs && grainAmount > 0.005 && !hasPerPixelCpuGrain) {
const gNorm = sampleScalarPaperGrainNorm(point.x, point.y, effWidth, options.paperTextureScale ?? 1.0);
@@ -1933,7 +2249,7 @@ export function drawBrushCubicBezierSegment(
color: string,
options: BrushRenderOptions = {},
remainderDist: number = 0,
- dabCounter: { count: number } = { count: 0 },
+ dabCounter: { count: number; lastAngle?: number; lastStepDist?: number } = { count: 0 },
batchGpuDabs?: GpuDab[]
): number {
const { totalLength: totalCurveLength, steps: arcSteps } = buildFastArcLengthScratch(p0, c1, c2, p3);
@@ -1957,7 +2273,7 @@ export function drawBrushCubicBezierSegment(
: 1.0;
const baseAngleRad = ((options.angle ?? 0) * Math.PI) / 180;
const rawDensity = options.brushDensity ?? options.flow ?? (tipImage ? 0.85 : 1.0);
- const spacingRatio = Math.max(0.015, Math.min(1.0, options.spacing ?? (tipImage ? 0.07 : 0.08)));
+ const spacingRatio = Math.max(0.003, Math.min(2.0, options.spacing ?? (tipImage ? 0.07 : 0.08)));
const baseFlow = computeGapAdjustedAlpha(rawDensity, spacingRatio, options.adjustDensityByGap);
const thickness = options.thickness ?? 1.0;
const isVert = Boolean(options.thicknessVertical);
@@ -1970,11 +2286,6 @@ export function drawBrushCubicBezierSegment(
const gpuDabs = batchGpuDabs || null;
const avgSegWidth = Math.max(0.5, (p0.width + p3.width) * 0.5);
const hasMultiSubTips = Boolean(tipImage && options.subTipImages && options.subTipImages.length > 1);
- const staticMaster =
- isColorMixing || gpuDabs || hasMultiSubTips
- ? null
- : resolveCpuMaster(tipImage, baseColor, hardness, isEraser, isBgEraser, isColorTip, avgSegWidth, aaMode);
-
const dynamics = options.dynamics;
const dabCount = Math.max(1, Math.min(10, Math.round(dynamics?.count ?? 1)));
const sizeJitter = Math.max(0, Math.min(1, dynamics?.sizeJitter ?? 0));
@@ -1984,14 +2295,51 @@ export function drawBrushCubicBezierSegment(
const scatterBothAxes = Boolean(dynamics?.scatterBothAxes);
const flowJitter = Math.max(0, Math.min(1, dynamics?.flowJitter ?? 0));
const colorJitterEnabled = Boolean(dynamics?.colorJitterEnabled);
+ const useSpatialTipMixing =
+ isColorMixing &&
+ !gpuDabs &&
+ !isColorTip &&
+ !colorJitterEnabled &&
+ !options.spray?.enabled;
+ if (useSpatialTipMixing && options.reservoir && !options.reservoir.spatialMixer) {
+ options.reservoir.spatialMixer = new SpatialTipMixer(baseColor);
+ }
+ const pressureAlreadyAppliedToFlow = Boolean(
+ options.opacitySensor?.usePressure || options.densitySensor?.usePressure
+ );
+ const customPaper =
+ useSpatialTipMixing && grainAmount > 0.005 && options.paperTextureImage
+ ? getCustomPaperLuminance(options.paperTextureImage)
+ : null;
+ const texScale = options.paperTextureScale ?? 1.0;
+ const texRot = options.paperTextureRotate ?? 0;
+ const texMode = options.paperTextureMode ?? 'multiply';
+ const texBright = options.paperTextureBrightness ?? 0;
+ const texContrast = options.paperTextureContrast ?? 0;
+ const texInv = Boolean(options.paperTextureInverted);
+
+ const staticMaster =
+ isColorMixing || gpuDabs || hasMultiSubTips
+ ? null
+ : resolveCpuMaster(tipImage, baseColor, hardness, isEraser, isBgEraser, isColorTip, avgSegWidth, aaMode);
+
const baseRgb = colorJitterEnabled || gpuDabs ? parseColorToRgb(baseColor) : null;
const secRgb = colorJitterEnabled ? parseColorToRgb(options.secondaryColor || '#ffffff') : null;
- const minStepPx = tipImage ? 0.15 : 0.12;
- const hasPerPixelCpuGrain = !gpuDabs && grainAmount > 0.005 && typeof ctx.createPattern === 'function';
+ const baseMinStepPx = tipImage ? 0.15 : 0.12;
+ const hasPerPixelCpuGrain =
+ !gpuDabs && !useSpatialTipMixing && grainAmount > 0.005 && typeof ctx.createPattern === 'function';
- let smoothCos = Math.cos(baseAngleRad);
- let smoothSin = Math.sin(baseAngleRad);
+ let hasSmoothAngle = dabCounter.lastAngle !== undefined;
+ let smoothCos = hasSmoothAngle ? Math.cos(dabCounter.lastAngle!) : Math.cos(baseAngleRad);
+ let smoothSin = hasSmoothAngle ? Math.sin(dabCounter.lastAngle!) : Math.sin(baseAngleRad);
let currentDist = remainderDist > 0 ? remainderDist : 0;
+ // Preserve true inter-stamp arc distance across Bezier segment boundaries (never reset to partial remainderDist)
+ let prevStepDist =
+ dabCounter.lastStepDist !== undefined && dabCounter.lastStepDist > 0
+ ? dabCounter.lastStepDist
+ : remainderDist > 0
+ ? remainderDist
+ : 0;
while (currentDist <= totalCurveLength) {
const pt = sampleFastArcLengthInto(p0, c1, c2, p3, currentDist, totalCurveLength, arcSteps, sharedBezierSample);
@@ -2008,26 +2356,16 @@ export function drawBrushCubicBezierSegment(
const strokeDist = (options.currentStrokeDist ?? 0) + currentDist;
- let taperAlphaScale = 1.0;
- if (options.taper) {
- const inSharp = 0.35 + (1.0 - (options.taper.startingSharpness ?? 0.5)) * 1.1;
- const outSharp = 0.35 + (1.0 - (options.taper.endingSharpness ?? 0.5)) * 1.1;
- const inLen = options.taper.inLength || (options.taper.inRatio ? options.taper.inRatio * 2.5 : 0);
- if (options.taper.useIn && inLen > 0 && strokeDist < inLen) {
- const inFactor = Math.pow(Math.max(0.01, Math.min(1.0, strokeDist / inLen)), inSharp);
- if (options.taper.affectSize !== false) curWidth *= inFactor;
- if (options.taper.affectDensity || options.taper.affectOpacity) taperAlphaScale *= inFactor;
- }
- if (options.totalLength && options.totalLength > 0) {
- const distFromEnd = options.totalLength - strokeDist;
- const outLen = options.taper.outLength || (options.taper.outRatio ? options.taper.outRatio * 3.0 : 0);
- if (options.taper.useOut && outLen > 0 && distFromEnd < outLen) {
- const outFactor = Math.pow(Math.max(0.01, Math.min(1.0, distFromEnd / outLen)), outSharp);
- if (options.taper.affectSize !== false) curWidth *= outFactor;
- if (options.taper.affectDensity || options.taper.affectOpacity) taperAlphaScale *= outFactor;
- }
- }
- }
+ const taperFactors = evaluateCspTaperFactors(
+ options.taper,
+ strokeDist,
+ options.totalLength,
+ options.exitSpeed
+ );
+ curWidth *= taperFactors.sizeScale;
+ const taperAlphaScale = taperFactors.alphaScale;
+ const taperAmountScale = taperFactors.amountScale;
+ const taperPaintDensityScale = taperFactors.paintDensityScale;
const dabSeq = dabCounter.count++;
const tiltX = useTilt ? pt.tiltX : 0;
@@ -2039,8 +2377,13 @@ export function drawBrushCubicBezierSegment(
useTilt && tiltMagnitude > 0.01 ? effPressure * (1.0 - tiltMagnitude * 0.55) : effPressure;
if (options.sizeSensor) {
+ // Avoid double-applying pressure when pt.width already has pressure baked from calculateStrokeWidth
+ const effectiveSizeSensor =
+ pt.width > 0 && options.usePressure !== false && options.sizeSensor.usePressure
+ ? { ...options.sizeSensor, usePressure: false }
+ : options.sizeSensor;
curWidth *= evaluateCspSensor(
- options.sizeSensor,
+ effectiveSizeSensor,
effPressure,
tiltMagnitude,
pt.speed * 0.05,
@@ -2051,11 +2394,36 @@ export function drawBrushCubicBezierSegment(
let stampAngle = baseAngleRad;
const angleMode = options.angleDynamics;
- if ((angleMode === 'direction' || angleMode === 'direction-random') && pt.speed > 0.05) {
- const targetAngle = Math.atan2(pt.dy, pt.dx) + baseAngleRad;
- smoothCos = smoothCos * 0.6 + Math.cos(targetAngle) * 0.4;
- smoothSin = smoothSin * 0.6 + Math.sin(targetAngle) * 0.4;
- stampAngle = Math.atan2(smoothSin, smoothCos);
+ if (angleMode === 'direction' || angleMode === 'direction-random') {
+ // Deadzone + arc-length-bounded turn rate prevents micro-jitter / pointer-up hooks
+ // from spinning flat blades into starbursts while tracking smooth curves faithfully
+ const minTangentSpeed = hasSmoothAngle ? 1.2 : 0.2;
+ const segLongEnough = !hasSmoothAngle || totalCurveLength >= 1.2;
+ if (segLongEnough && pt.speed > minTangentSpeed) {
+ const targetAngle = Math.atan2(pt.dy, pt.dx) + baseAngleRad;
+ if (!hasSmoothAngle) {
+ smoothCos = Math.cos(targetAngle);
+ smoothSin = Math.sin(targetAngle);
+ hasSmoothAngle = true;
+ } else {
+ const curA = Math.atan2(smoothSin, smoothCos);
+ let delta = targetAngle - curA;
+ while (delta > Math.PI) delta -= Math.PI * 2;
+ while (delta < -Math.PI) delta += Math.PI * 2;
+ const stepRef = prevStepDist > 0 ? prevStepDist : 1.0;
+ const halfBlade = Math.max(2.0, curWidth * 0.5);
+ // Bound per-step rotation so the outer edge of a wide flat blade never sweeps > 1.8px per stamp
+ const maxOuterTipTurn = Math.max(0.025, Math.min(0.45, (1.8 + stepRef * 0.45) / halfBlade));
+ const clampedDelta = Math.max(-maxOuterTipTurn, Math.min(maxOuterTipTurn, delta * 0.52));
+ const nextA = curA + clampedDelta;
+ smoothCos = Math.cos(nextA);
+ smoothSin = Math.sin(nextA);
+ }
+ stampAngle = Math.atan2(smoothSin, smoothCos);
+ dabCounter.lastAngle = stampAngle;
+ } else if (hasSmoothAngle) {
+ stampAngle = Math.atan2(smoothSin, smoothCos);
+ }
}
if (angleMode === 'random' || angleMode === 'direction-random') {
const rScale = angleMode === 'random' ? 1.0 : rotationRandomScale || 0.35;
@@ -2097,10 +2465,11 @@ export function drawBrushCubicBezierSegment(
dabAlpha *= 1.0 - tiltMagnitude * 0.28;
}
- if (isColorMixing && options.reservoir) {
+ const dirX = pt.speed > 0.001 ? pt.dx / pt.speed : 0;
+ const dirY = pt.speed > 0.001 ? pt.dy / pt.speed : 0;
+
+ if (isColorMixing && !useSpatialTipMixing && options.reservoir) {
const prelimStep = Math.max(0.15, curWidth * spacingRatio);
- const dirX = pt.speed > 0.001 ? pt.dx / pt.speed : 0;
- const dirY = pt.speed > 0.001 ? pt.dy / pt.speed : 0;
const mixed = sampleAndMixColor(
ctx,
pt.x,
@@ -2121,7 +2490,7 @@ export function drawBrushCubicBezierSegment(
}
}
- if (!gpuDabs && grainAmount > 0.005 && !hasPerPixelCpuGrain) {
+ if (!gpuDabs && !useSpatialTipMixing && grainAmount > 0.005 && !hasPerPixelCpuGrain) {
const gNorm = sampleScalarPaperGrainNorm(pt.x, pt.y, curWidth, options.paperTextureScale ?? 1.0);
const scalarMode = options.paperTextureMode === 'compare' ? 'subtract' : (options.paperTextureMode ?? 'subtract');
dabAlpha *= applyCspPaperTextureAlpha(
@@ -2142,17 +2511,18 @@ export function drawBrushCubicBezierSegment(
const activeTip = tipImage
? selectTipImage(options.subTipImages, tipImage, options.subTipOrder, dabSeq, stampAngle, pt.x, pt.y)
: undefined;
- const baseMaster = gpuDabs
- ? null
- : staticMaster ?? resolveCpuMaster(activeTip, dabColor, hardness, isEraser, isBgEraser, isColorTip, curWidth, aaMode);
+ const baseMaster =
+ gpuDabs || useSpatialTipMixing
+ ? null
+ : staticMaster ?? resolveCpuMaster(activeTip, dabColor, hardness, isEraser, isBgEraser, isColorTip, curWidth, aaMode);
let tx = 1;
let ty = 0;
let nx = 0;
let ny = 1;
if (pt.speed > 0.001) {
- tx = pt.dx / pt.speed;
- ty = pt.dy / pt.speed;
+ tx = dirX;
+ ty = dirY;
nx = -ty;
ny = tx;
}
@@ -2191,6 +2561,94 @@ export function drawBrushCubicBezierSegment(
let curDabAlpha = dabAlpha;
if (flowJitter > 0) curDabAlpha *= Math.max(0.005, 1.0 - dabHashFloat(pt.x, pt.y, seedIdx, 6) * flowJitter);
+ let finalW = isVert ? curDabW * curDabThickness : curDabW;
+ let finalH = isVert ? curDabW * aspect : curDabW * aspect * curDabThickness;
+ if (useTilt && tiltMagnitude > 0.01) {
+ finalW *= 1.0 + tiltSpread * 1.85;
+ finalH *= Math.max(0.55, 1.0 / (1.0 + tiltMagnitude * 0.45));
+ }
+ stepRefW = finalW;
+ stepRefH = finalH;
+
+ if (curDabAlpha <= 0.002) continue;
+
+ const flips = resolveTipFlipSigns(options.flipH, options.flipV, seedIdx, curDabX, curDabY);
+
+ if (useSpatialTipMixing && options.reservoir?.spatialMixer) {
+ const effectiveStep =
+ prevStepDist > 0 ? prevStepDist : Math.max(0.85, Math.min(finalW, finalH) * Math.max(0.12, spacingRatio));
+ const built = options.reservoir.spatialMixer.stepAndBuildStamp({
+ x: curDabX,
+ y: curDabY,
+ width: finalW,
+ height: finalH,
+ angleRad: curDabAngle,
+ dirX,
+ dirY,
+ stepDist: effectiveStep,
+ spacingRatio,
+ adjustDensityByGap: Boolean(options.adjustDensityByGap),
+ dabSeq,
+ hardness,
+ antiAlias: aaMode,
+ flipX: flips.signX,
+ flipY: flips.signY,
+ flow: curDabAlpha,
+ pressure: effPressure,
+ pressureAlreadyApplied: pressureAlreadyAppliedToFlow,
+ amountOfPaint: (options.amountOfPaint ?? 0.65) * taperAmountScale,
+ densityOfPaint: (options.densityOfPaint ?? 0.9) * taperPaintDensityScale,
+ colorStretch: options.colorStretch ?? 0.75,
+ mixingMode: options.mixingMode ?? 'blend',
+ perceptualMixing: options.perceptualMixing !== false,
+ tipImage: activeTip,
+ sampler: options.sampler,
+ grainDensity: grainAmount,
+ grainModulate:
+ grainAmount > 0.005
+ ? (wx, wy, tipA) =>
+ applyCspPaperTextureAlpha(
+ tipA,
+ sampleWorldPaperGrainNorm(wx, wy, texScale, texRot, customPaper),
+ grainAmount,
+ grainPressure,
+ texMode,
+ texBright,
+ texContrast,
+ texInv
+ )
+ : undefined,
+ });
+ if (built) {
+ options.reservoir.r = built.avgR;
+ options.reservoir.g = built.avgG;
+ options.reservoir.b = built.avgB;
+ options.reservoir.a = built.avgA;
+ if (built.pickedUpCanvas) options.reservoir.isLoadedWithCanvasColor = true;
+ }
+ if (built && built.hasVisiblePixels) {
+ drawSingleStamp(
+ ctx,
+ built.canvas,
+ curDabX,
+ curDabY,
+ built.drawW,
+ built.drawH,
+ curDabAngle,
+ 1.0,
+ false,
+ false,
+ options.alphaLocked,
+ options.isTransparentInk,
+ 1,
+ 1,
+ aaMode,
+ options.blendTipsMode
+ );
+ }
+ continue;
+ }
+
let curMaster: CanvasImageSource | null = baseMaster;
let dabR = primRgb ? primRgb.r / 255 : 0;
let dabG = primRgb ? primRgb.g / 255 : 0;
@@ -2212,19 +2670,6 @@ export function drawBrushCubicBezierSegment(
}
}
- let finalW = isVert ? curDabW * curDabThickness : curDabW;
- let finalH = isVert ? curDabW * aspect : curDabW * aspect * curDabThickness;
- if (useTilt && tiltMagnitude > 0.01) {
- finalW *= 1.0 + tiltSpread * 1.85;
- finalH *= Math.max(0.55, 1.0 / (1.0 + tiltMagnitude * 0.45));
- }
- stepRefW = finalW;
- stepRefH = finalH;
-
- if (curDabAlpha <= 0.002) continue;
-
- const flips = resolveTipFlipSigns(options.flipH, options.flipV, seedIdx, curDabX, curDabY);
-
if (curMaster && hasPerPixelCpuGrain) {
const grained = applyCpuPerPixelPaperGrain(
curMaster,
@@ -2282,15 +2727,51 @@ export function drawBrushCubicBezierSegment(
}
}
- currentDist += computeEllipticalStepDistance(
+ const effectiveMinStep = useSpatialTipMixing
+ ? Math.max(0.55, Math.min(1.05, Math.min(stepRefW, stepRefH) * 0.1))
+ : baseMinStepPx;
+ let stepAdvance = computeEllipticalStepDistance(
stepRefW,
stepRefH,
stampAngle,
pt.dx,
pt.dy,
spacingRatio,
- minStepPx
+ effectiveMinStep
);
+ // Angular-sweep stepping: tighten step on curves so outer tips of wide flat blades never fan into comb teeth
+ const maxAxis = Math.max(stepRefW, stepRefH);
+ const minAxis = Math.max(0.5, Math.min(stepRefW, stepRefH));
+ if (
+ (angleMode === 'direction' || angleMode === 'direction-random') &&
+ maxAxis > minAxis * 1.35 &&
+ currentDist + stepAdvance <= totalCurveLength
+ ) {
+ const peek = sampleFastArcLengthInto(
+ p0,
+ c1,
+ c2,
+ p3,
+ currentDist + stepAdvance,
+ totalCurveLength,
+ arcSteps,
+ peekBezierSample
+ );
+ if (peek.speed > 0.5) {
+ const peekAngle = Math.atan2(peek.dy, peek.dx) + baseAngleRad;
+ let dTheta = peekAngle - stampAngle;
+ while (dTheta > Math.PI) dTheta -= Math.PI * 2;
+ while (dTheta < -Math.PI) dTheta += Math.PI * 2;
+ const outerArc = 0.5 * maxAxis * Math.abs(dTheta);
+ const maxOuterArc = Math.max(0.75, minAxis * 0.14);
+ if (outerArc > maxOuterArc) {
+ stepAdvance = Math.max(0.2, stepAdvance * (maxOuterArc / outerArc));
+ }
+ }
+ }
+ prevStepDist = stepAdvance;
+ dabCounter.lastStepDist = stepAdvance;
+ currentDist += stepAdvance;
}
return Math.max(0, currentDist - totalCurveLength);
@@ -2433,7 +2914,8 @@ export function renderCompleteStroke(
underlyingCanvas?: HTMLCanvasElement,
alphaLocked: boolean = false,
explicitSampler?: LayerPixelSampler,
- allowGpuForMonochrome: boolean = false
+ allowGpuForMonochrome: boolean = false,
+ exitSpeed?: number
): void {
if (!points || points.length === 0) return;
@@ -2506,13 +2988,45 @@ export function renderCompleteStroke(
totalLen += Math.hypot(effectivePoints[i].x - effectivePoints[i - 1].x, effectivePoints[i].y - effectivePoints[i - 1].y);
}
options.totalLength = totalLen;
+ options.exitSpeed = exitSpeed;
+
+ // Align initial dot with initial stroke tangent using a >=4px lookahead chord to ignore landing jitter
+ let initAngleRad: number | undefined = undefined;
+ if (
+ effectivePoints.length >= 2 &&
+ (options.angleDynamics === 'direction' || options.angleDynamics === 'direction-random')
+ ) {
+ const p0 = effectivePoints[0];
+ const minChord = Math.max(4.0, (options.size ?? 10) * 0.12);
+ const minChordSq = minChord * minChord;
+ let fallbackAngle: number | undefined = undefined;
+ for (let i = 1; i < effectivePoints.length; i++) {
+ const dx = effectivePoints[i].x - p0.x;
+ const dy = effectivePoints[i].y - p0.y;
+ const dSq = dx * dx + dy * dy;
+ if (dSq > 0.25 && fallbackAngle === undefined) {
+ fallbackAngle = Math.atan2(dy, dx) + ((options.angle ?? 0) * Math.PI) / 180;
+ }
+ if (dSq >= minChordSq) {
+ initAngleRad = Math.atan2(dy, dx) + ((options.angle ?? 0) * Math.PI) / 180;
+ break;
+ }
+ }
+ if (initAngleRad === undefined) {
+ initAngleRad = fallbackAngle;
+ }
+ }
+ options.initialAngleRad = initAngleRad;
const emitStroke = (batchGpuDabs: GpuDab[] | undefined) => {
options.currentStrokeDist = 0;
drawBrushDot(ctx, effectivePoints[0], strokeColor, options, batchGpuDabs);
if (effectivePoints.length === 1) return;
- const dabCounter = { count: 0 };
+ const dabCounter: { count: number; lastAngle?: number } = {
+ count: 0,
+ lastAngle: initAngleRad,
+ };
const minInitDist = options.tipImage ? 0.15 : 0.12;
let accDist = Math.max(minInitDist, Math.max(0.2, effectivePoints[0].width) * strokeSpacing);
diff --git a/src/engine/SplineGenerator.ts b/src/engine/SplineGenerator.ts
index 58e1f0e..776e956 100644
--- a/src/engine/SplineGenerator.ts
+++ b/src/engine/SplineGenerator.ts
@@ -197,12 +197,13 @@ export class SplineGenerator {
const dt1 = Math.max(1e-4, Math.sqrt(d12));
const dt2 = Math.max(1e-4, Math.sqrt(d23));
- // Tangents at P1 and P2
- const t1x = (p2.x - p1.x) / dt1 - (p1.x - p0.x) / dt0 + (p2.x - p0.x) / (dt0 + dt1);
- const t1y = (p2.y - p1.y) / dt1 - (p1.y - p0.y) / dt0 + (p2.y - p0.y) / (dt0 + dt1);
+ // Non-uniform centripetal Catmull-Rom tangents at P1 and P2:
+ // m1 = (P1-P0)/dt0 - (P2-P0)/(dt0+dt1) + (P2-P1)/dt1 (reduces to (P2-P0)/2 for uniform knots)
+ const t1x = (p1.x - p0.x) / dt0 - (p2.x - p0.x) / (dt0 + dt1) + (p2.x - p1.x) / dt1;
+ const t1y = (p1.y - p0.y) / dt0 - (p2.y - p0.y) / (dt0 + dt1) + (p2.y - p1.y) / dt1;
- const t2x = (p3.x - p2.x) / dt2 - (p2.x - p1.x) / dt1 + (p3.x - p1.x) / (dt1 + dt2);
- const t2y = (p3.y - p2.y) / dt2 - (p2.y - p1.y) / dt1 + (p3.y - p1.y) / (dt1 + dt2);
+ const t2x = (p2.x - p1.x) / dt1 - (p3.x - p1.x) / (dt1 + dt2) + (p3.x - p2.x) / dt2;
+ const t2y = (p2.y - p1.y) / dt1 - (p3.y - p1.y) / (dt1 + dt2) + (p3.y - p2.y) / dt2;
let dx1 = (t1x * dt1) / 3.0;
let dy1 = (t1y * dt1) / 3.0;
diff --git a/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts b/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts
index db06700..1f35be0 100644
--- a/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts
+++ b/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts
@@ -366,29 +366,46 @@ export function runPointerDown(
params.onCollabStrokeStartRef.current?.(strokeId, currentLayerId, bs, currentTool, startPoint);
state.liveDabCounter.count = 0;
+ state.liveDabCounter.lastAngle = undefined;
+ state.liveDabCounter.lastStepDist = undefined;
state.stampRemainderDist = bs.customTipImage
? Math.max(0.15, startPoint.width * (bs.spacing ?? 0.07))
: Math.max(0.12, startPoint.width * (bs.spacing ?? 0.08));
const firstDotPoint = state.allStrokePoints[0];
- renderInitialStrokeDot(state, helpers, {
- draftCtx,
- firstDotPoint,
- bs,
- strokeColor,
- strokeHardness,
- strokeFlow,
- strokeSpacing,
- isMonochrome,
- isEraser,
- isBgEraser,
- useWireframeEraser,
- draftScale,
- zoom: params.zoomRef.current,
- canvas: maskCanvas,
- activeLayer,
- });
+ // For flat/elliptical direction-following brushes, wait for the first real movement segment
+ // to determine tangent orientation instead of stamping a sideways notch at baseAngleRad on pointerdown.
+ const deferDirectionInitialDot =
+ !isShiftLine &&
+ !state.naturalPaintSession &&
+ !useWireframeEraser &&
+ (bs.customTipAngleDynamics === 'direction' ||
+ bs.customTipAngleDynamics === 'direction-random') &&
+ (bs.thickness ?? 1.0) < 0.85;
+
+ if (!deferDirectionInitialDot) {
+ renderInitialStrokeDot(state, helpers, {
+ draftCtx,
+ firstDotPoint,
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isEraser,
+ isBgEraser,
+ useWireframeEraser,
+ draftScale,
+ zoom: params.zoomRef.current,
+ canvas: maskCanvas,
+ activeLayer,
+ });
+ } else {
+ // Start stamping right at distance 0 on the first movement segment so there is no gap at stroke start
+ state.stampRemainderDist = 0;
+ }
if (isShiftLine && prevStrokeEnd) {
renderShiftLineInitialSegment(state, helpers, {
diff --git a/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts b/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts
index 33a2e17..74c0aaa 100644
--- a/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts
+++ b/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts
@@ -76,7 +76,8 @@ export function runPointerUp(
!isEraser &&
!state.isShiftLineStroke &&
activeLayer?.type !== 'vector' &&
- Boolean(bs.taper?.useOut);
+ Boolean(bs.taper?.useOut) &&
+ bs.taper?.inOutType === undefined;
let addedFlickPoints = false;
const tailSegments: CubicBezierSegment[] = [];
@@ -151,9 +152,16 @@ export function runPointerUp(
exitSpeed = Math.hypot(pB.x - pA.x, pB.y - pA.y) / dt;
}
+ const hasCspArcLengthTaper = Boolean(
+ bs.taper &&
+ (bs.taper.inOutType !== undefined ||
+ bs.taper.affectDensity ||
+ bs.taper.affectOpacity ||
+ bs.taper.minSizeRatio !== undefined)
+ );
const shouldTaper =
- Boolean(bs.taper?.useIn) || (Boolean(bs.taper?.useOut) && !addedFlickPoints);
- if (shouldTaper && state.allStrokePoints.length >= 3) {
+ Boolean(bs.taper?.useIn) || (Boolean(bs.taper?.useOut) && (!addedFlickPoints || hasCspArcLengthTaper));
+ if (shouldTaper && !hasCspArcLengthTaper && state.allStrokePoints.length >= 3) {
applyParametricTaper(state.allStrokePoints, {
useIn: Boolean(bs.taper?.useIn),
useOut: Boolean(bs.taper?.useOut) && !addedFlickPoints,
@@ -258,6 +266,7 @@ export function runPointerUp(
isMonochrome,
hasWetEdge,
shouldTaper,
+ exitSpeed,
strokeColor,
allPoints,
tailSegments,
diff --git a/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts b/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts
index 76dbbbe..fad1d9d 100644
--- a/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts
+++ b/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts
@@ -59,6 +59,7 @@ export interface CommitRasterStrokeParams {
isMonochrome: boolean;
hasWetEdge: boolean;
shouldTaper: boolean;
+ exitSpeed?: number;
strokeColor: string;
allPoints: Point[];
tailSegments: CubicBezierSegment[];
@@ -91,6 +92,7 @@ export function commitRasterStrokeToTiles(
isMonochrome,
hasWetEdge,
shouldTaper,
+ exitSpeed,
strokeColor,
allPoints,
tailSegments,
@@ -284,7 +286,8 @@ export function commitRasterStrokeToTiles(
undefined,
false,
undefined,
- allowGpuMonoBake
+ allowGpuMonoBake,
+ exitSpeed
);
bCtx.restore();
@@ -386,7 +389,8 @@ export function commitRasterStrokeToTiles(
undefined,
Boolean(activeLayer?.alphaLocked),
bakeSampler,
- allowGpuMonoBake
+ allowGpuMonoBake,
+ exitSpeed
);
} else {
rCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bakeBs.opacity ?? 1.0));
@@ -414,7 +418,8 @@ export function commitRasterStrokeToTiles(
undefined,
false,
bakeSampler,
- allowGpuMonoBake
+ allowGpuMonoBake,
+ exitSpeed
);
bCtx.restore();
diff --git a/src/hooks/drawing/brushStrokeSession/types.ts b/src/hooks/drawing/brushStrokeSession/types.ts
index 8b0b644..ad8def5 100644
--- a/src/hooks/drawing/brushStrokeSession/types.ts
+++ b/src/hooks/drawing/brushStrokeSession/types.ts
@@ -145,7 +145,7 @@ export interface StrokeSessionState {
lastQueuedPressure: number;
stabilizedPoint: Point | null;
stampRemainderDist: number;
- liveDabCounter: { count: number };
+ liveDabCounter: { count: number; lastAngle?: number; lastStepDist?: number };
activeReservoir: PaintReservoir | null;
layerPixelSampler: LayerPixelSampler | null;
naturalPaintSession: NaturalPaintStrokeSession | null;
diff --git a/src/types/editor.ts b/src/types/editor.ts
index 8b4c3d7..13233d9 100644
--- a/src/types/editor.ts
+++ b/src/types/editor.ts
@@ -224,9 +224,15 @@ export interface CspTaperSettings {
startingSharpness?: number; // 0.0 to 1.0 (CSP Starting sharpness)
endingSharpness?: number; // 0.0 to 1.0 (CSP Ending sharpness)
affectSize?: boolean; // Taper modulates brush size (default true)
- affectDensity?: boolean; // Taper modulates brush density
- affectOpacity?: boolean; // Taper modulates dab opacity
+ affectDensity?: boolean; // Taper modulates brush density (CSP 0x411)
+ affectOpacity?: boolean; // Taper modulates dab opacity (CSP 0x3e9)
+ affectAmountOfPaint?: boolean; // Taper modulates CSP Amount of Paint (CSP 0x43a)
+ minAmountRatio?: number; // 0.0 to 1.0 minimum Amount of Paint ratio at taper endpoint
+ affectDensityOfPaint?: boolean; // Taper modulates CSP Density of Paint (CSP 0x43c)
+ minPaintDensityRatio?: number; // 0.0 to 1.0 minimum Density of Paint ratio at taper endpoint
affectLoad?: boolean; // Taper modulates Natural Paint load / dry-brush fade
+ minSizeRatio?: number; // 0.0 to 1.0 minimum size ratio at taper endpoint (CSP BrushInOutTarget 0x3fd)
+ minDensityRatio?: number; // 0.0 to 1.0 minimum density ratio at taper endpoint
}
export type CspAntiAliasLevel = 0 | 1 | 2 | 3; // 0: None (Binary), 1: Weak, 2: Medium, 3: Strong
diff --git a/src/utils/__tests__/sutImportParity.test.ts b/src/utils/__tests__/sutImportParity.test.ts
new file mode 100644
index 0000000..4cfc559
--- /dev/null
+++ b/src/utils/__tests__/sutImportParity.test.ts
@@ -0,0 +1,593 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ parseCspEffector,
+ parseCspInOutTarget,
+ parseSutExtractedData,
+} from '../sutParser';
+import { NativeSutExtract } from '../nativeBackend';
+import {
+ centripetalCatmullRomToBezier,
+ buildCubicArcLengthTable,
+ getCubicPointAtArcLength,
+ renderCompleteStroke,
+} from '../../engine/BrushEngine';
+import { LayerPixelSampler } from '../colorMixingEngine';
+import { BrushSettings, Point } from '../../types/editor';
+
+/**
+ * Software Canvas2D rasterizer with accurate affine translate/rotate + bilinear drawImage
+ * + Porter-Duff source-over compositing for pixel-exact headless verification.
+ */
+function createSoftwareCanvas(initW: number, initH: number) {
+ let width = initW;
+ let height = initH;
+ let buf = new Uint8ClampedArray(width * height * 4);
+ type State = { tx: number; ty: number; rot: number; sx: number; sy: number; alpha: number; op: string };
+ const stack: State[] = [];
+ let st: State = { tx: 0, ty: 0, rot: 0, sx: 1, sy: 1, alpha: 1, op: 'source-over' };
+
+ const ctx: any = {
+ get canvas() { return surfaceObj; },
+ get globalAlpha() { return st.alpha; },
+ set globalAlpha(v: number) { st.alpha = v; },
+ get globalCompositeOperation() { return st.op; },
+ set globalCompositeOperation(v: string) { st.op = v; },
+ imageSmoothingEnabled: true,
+ save: () => stack.push({ ...st }),
+ restore: () => { const p = stack.pop(); if (p) st = p; },
+ translate: (x: number, y: number) => {
+ const c = Math.cos(st.rot), s = Math.sin(st.rot);
+ st.tx += (x * c - y * s) * st.sx;
+ st.ty += (x * s + y * c) * st.sy;
+ },
+ rotate: (rad: number) => { st.rot += rad; },
+ scale: (sx: number, sy: number) => { st.sx *= sx; st.sy *= sy; },
+ clearRect: () => buf.fill(0),
+ fillRect: () => {},
+ createImageData: (w: number, h: number) => ({
+ width: w,
+ height: h,
+ data: new Uint8ClampedArray(w * h * 4),
+ }),
+ putImageData: (img: { width: number; height: number; data: Uint8ClampedArray }, dx = 0, dy = 0) => {
+ for (let y = 0; y < img.height; y++) {
+ const ty = dy + y;
+ if (ty < 0 || ty >= height) continue;
+ for (let x = 0; x < img.width; x++) {
+ const tx = dx + x;
+ if (tx < 0 || tx >= width) continue;
+ const si = (y * img.width + x) * 4;
+ const di = (ty * width + tx) * 4;
+ buf[di] = img.data[si];
+ buf[di + 1] = img.data[si + 1];
+ buf[di + 2] = img.data[si + 2];
+ buf[di + 3] = img.data[si + 3];
+ }
+ }
+ },
+ getImageData: (sx: number, sy: number, sw: number, sh: number) => {
+ const data = new Uint8ClampedArray(sw * sh * 4);
+ for (let y = 0; y < sh; y++) {
+ const py = sy + y;
+ if (py < 0 || py >= height) continue;
+ for (let x = 0; x < sw; x++) {
+ const px = sx + x;
+ if (px < 0 || px >= width) continue;
+ const si = (py * width + px) * 4;
+ const di = (y * sw + x) * 4;
+ data[di] = buf[si];
+ data[di + 1] = buf[si + 1];
+ data[di + 2] = buf[si + 2];
+ data[di + 3] = buf[si + 3];
+ }
+ }
+ return { width: sw, height: sh, data };
+ },
+ drawImage: (src: any, dx: number, dy: number, dw?: number, dh?: number) => {
+ const srcBuf: Uint8ClampedArray | undefined = src?.buf;
+ if (!srcBuf) return;
+ const sw = src.width;
+ const sh = src.height;
+ const w = dw ?? sw;
+ const h = dh ?? sh;
+ if (w <= 0 || h <= 0) return;
+
+ const c = Math.cos(st.rot);
+ const s = Math.sin(st.rot);
+ const corners = [
+ [dx, dy],
+ [dx + w, dy],
+ [dx, dy + h],
+ [dx + w, dy + h],
+ ];
+ let minX = width, minY = height, maxX = -1, maxY = -1;
+ for (const [lx, ly] of corners) {
+ const wx = st.tx + (lx * st.sx * c - ly * st.sy * s);
+ const wy = st.ty + (lx * st.sx * s + ly * st.sy * c);
+ if (wx < minX) minX = wx;
+ if (wy < minY) minY = wy;
+ if (wx > maxX) maxX = wx;
+ if (wy > maxY) maxY = wy;
+ }
+ const x0 = Math.max(0, Math.floor(minX));
+ const y0 = Math.max(0, Math.floor(minY));
+ const x1 = Math.min(width - 1, Math.ceil(maxX));
+ const y1 = Math.min(height - 1, Math.ceil(maxY));
+
+ for (let py = y0; py <= y1; py++) {
+ for (let px = x0; px <= x1; px++) {
+ const rx = px + 0.5 - st.tx;
+ const ry = py + 0.5 - st.ty;
+ const lx = (rx * c + ry * s) / st.sx;
+ const ly = (-rx * s + ry * c) / st.sy;
+ const u = (lx - dx) / w;
+ const v = (ly - dy) / h;
+ if (u < 0 || u >= 1 || v < 0 || v >= 1) continue;
+
+ const fx = u * sw - 0.5;
+ const fy = v * sh - 0.5;
+ const ix0 = Math.max(0, Math.min(sw - 1, Math.floor(fx)));
+ const iy0 = Math.max(0, Math.min(sh - 1, Math.floor(fy)));
+ const ix1 = Math.min(sw - 1, ix0 + 1);
+ const iy1 = Math.min(sh - 1, iy0 + 1);
+ const tx = Math.max(0, Math.min(1, fx - ix0));
+ const ty = Math.max(0, Math.min(1, fy - iy0));
+
+ const i00 = (iy0 * sw + ix0) * 4;
+ const i10 = (iy0 * sw + ix1) * 4;
+ const i01 = (iy1 * sw + ix0) * 4;
+ const i11 = (iy1 * sw + ix1) * 4;
+ const w00 = (1 - tx) * (1 - ty);
+ const w10 = tx * (1 - ty);
+ const w01 = (1 - tx) * ty;
+ const w11 = tx * ty;
+
+ const a00 = (srcBuf[i00 + 3] / 255) * w00;
+ const a10 = (srcBuf[i10 + 3] / 255) * w10;
+ const a01 = (srcBuf[i01 + 3] / 255) * w01;
+ const a11 = (srcBuf[i11 + 3] / 255) * w11;
+ const srcA = (a00 + a10 + a01 + a11) * st.alpha;
+ if (srcA <= 0.001) continue;
+ const aSum = a00 + a10 + a01 + a11;
+ const sr = (srcBuf[i00] * a00 + srcBuf[i10] * a10 + srcBuf[i01] * a01 + srcBuf[i11] * a11) / aSum;
+ const sg = (srcBuf[i00 + 1] * a00 + srcBuf[i10 + 1] * a10 + srcBuf[i01 + 1] * a01 + srcBuf[i11 + 1] * a11) / aSum;
+ const sb = (srcBuf[i00 + 2] * a00 + srcBuf[i10 + 2] * a10 + srcBuf[i01 + 2] * a01 + srcBuf[i11 + 2] * a11) / aSum;
+
+ const di = (py * width + px) * 4;
+ const dstA = buf[di + 3] / 255;
+ const outA = srcA + dstA * (1 - srcA);
+ if (outA > 0.001) {
+ const inv = 1 / outA;
+ buf[di] = Math.round((sr * srcA + buf[di] * dstA * (1 - srcA)) * inv);
+ buf[di + 1] = Math.round((sg * srcA + buf[di + 1] * dstA * (1 - srcA)) * inv);
+ buf[di + 2] = Math.round((sb * srcA + buf[di + 2] * dstA * (1 - srcA)) * inv);
+ buf[di + 3] = Math.round(Math.min(255, outA * 255));
+ }
+ }
+ }
+ },
+ };
+
+ const surfaceObj: any = {
+ get width() { return width; },
+ set width(v: number) { width = v; buf = new Uint8ClampedArray(width * height * 4); },
+ get height() { return height; },
+ set height(v: number) { height = v; buf = new Uint8ClampedArray(width * height * 4); },
+ get buf() { return buf; },
+ getContext: (type: string) => (type === '2d' ? ctx : null),
+ ctx,
+ };
+ return surfaceObj;
+}
+
+function makeFakeEffector(flags: number, minVal: number, maxVal: number, pts?: [number, number][]): Uint8Array {
+ const curveBytes = pts ? 12 + pts.length * 16 : 0;
+ const buf = new Uint8Array(48 + curveBytes);
+ const v = new DataView(buf.buffer);
+ v.setUint32(0, 48, false);
+ v.setUint32(4, 0xf0, false);
+ v.setUint32(8, flags, false);
+ v.setUint32(12, minVal, false);
+ v.setUint32(16, maxVal, false);
+ if (pts) {
+ v.setUint32(48, 12, false);
+ v.setUint32(52, pts.length, false);
+ v.setUint32(56, 16, false);
+ for (let i = 0; i < pts.length; i++) {
+ v.setFloat64(60 + i * 16, pts[i][0], false);
+ v.setFloat64(68 + i * 16, pts[i][1], false);
+ }
+ }
+ return buf;
+}
+
+function makeFakeInOutTarget(entries: Array<[number, number, number]>): Uint8Array {
+ const buf = new Uint8Array(12 + entries.length * 12);
+ const v = new DataView(buf.buffer);
+ v.setUint32(0, 12, false);
+ v.setUint32(4, entries.length, false);
+ v.setUint32(8, 12, false);
+ for (let i = 0; i < entries.length; i++) {
+ v.setUint32(12 + i * 12, entries[i][0], false);
+ v.setUint32(16 + i * 12, entries[i][1], false);
+ v.setUint32(20 + i * 12, entries[i][2], false);
+ }
+ return buf;
+}
+
+describe('CSP .sut Import & Oil Paint Parity', () => {
+ beforeEach(() => {
+ (globalThis as any).document = {
+ createElement: (tag: string) => {
+ if (tag === 'canvas') return createSoftwareCanvas(64, 64);
+ return {};
+ },
+ };
+ });
+
+ it('parses 48-byte CSP effector headers and curves accurately', () => {
+ const blob = makeFakeEffector(0x10, 55, 100, [
+ [0, 0],
+ [0.5, 0.7],
+ [1, 1],
+ ]);
+ const eff = parseCspEffector(blob);
+ expect(eff).not.toBeNull();
+ expect(eff!.usePressure).toBe(true);
+ expect(eff!.minValue).toBeCloseTo(0.55, 4);
+ expect(eff!.pressureCurve).toEqual([
+ [0, 0],
+ [0.5, 0.7],
+ [1, 1],
+ ]);
+ });
+
+ it('parses BrushInOutTarget table (size min 53%, amount of paint 0%, density of paint 0%)', () => {
+ const blob = makeFakeInOutTarget([
+ [0x3fd, 1, 53],
+ [0x43a, 1, 0],
+ [0x43c, 1, 0],
+ ]);
+ const target = parseCspInOutTarget(blob);
+ expect(target).not.toBeNull();
+ expect(target!.affectSize).toBe(true);
+ expect(target!.minSizeRatio).toBeCloseTo(0.53, 4);
+ expect(target!.affectAmountOfPaint).toBe(true);
+ expect(target!.minAmountRatio).toBe(0);
+ expect(target!.affectDensityOfPaint).toBe(true);
+ expect(target!.minPaintDensityRatio).toBe(0);
+ expect(target!.affectDensity).toBe(false);
+ expect(target!.affectOpacity).toBe(false);
+ });
+
+ it('maps Oil Paint Brush.sut fields cleanly without hijacking paper texture or forcing random spin', async () => {
+ // Minimal 1x1 PNG
+ const tinyPng = new Uint8Array([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
+ 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
+ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
+ 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53,
+ 0xde, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e,
+ 0x44, 0xae, 0x42, 0x60, 0x82,
+ ]);
+ const catPath = '.:09:66:0b8aa316f6-5440-3783-ad01-182ac015dd';
+ const texBlob = new TextEncoder().encode(catPath);
+
+ const extracted: NativeSutExtract = {
+ nodeName: 'Oil Paint Brush',
+ variantId: 828,
+ variantValues: new Map<string, unknown>([
+ ['brushsize', 32.8],
+ ['brushsizeeffector', makeFakeEffector(0x10, 55, 100, [[0, 0], [1, 1]])],
+ ['brushflow', 100],
+ ['brushfloweffector', makeFakeEffector(0x10, 0, 100, [[0, 0], [1, 1]])],
+ ['opacity', 100],
+ ['brushhardness', 100],
+ ['brushinterval', 0.3],
+ ['brushautointervaltype', 0],
+ ['brushthickness', 17],
+ ['brushverticalthicknes', 0],
+ ['brushrotation', 0],
+ ['brushrotationeffector', 67], // direction of line (0x43 -> low nibble 3)
+ ['brushrotationrandomscale', 100], // default 100 when random is OFF
+ ['brushusepatternimage', 0], // Circle tip!
+ ['textureimage', texBlob],
+ ['texturecompositemode', 0],
+ ['texturedensity', 62],
+ ['textureforplot', 1],
+ ['brushusewatercolor', 1],
+ ['brushwatercolor', 0],
+ ['brushmixcolor', 62],
+ ['brushmixalpha', 74],
+ ['brushmixcolorextension', 82],
+ ['brushcolormixingmode', 0],
+ ['brushusewateredge', 0],
+ ['brushwateredgealphapower', 20],
+ ['brushusein', 1],
+ ['brushinlength', 20],
+ ['brushinratio', 30],
+ ['brushuseout', 1],
+ ['brushoutlength', 381],
+ ['brushoutratio', 30],
+ ['brushinouttype', 2],
+ ['brushinouttarget', makeFakeInOutTarget([[0x3fd, 1, 53], [0x43a, 1, 0], [0x43c, 1, 0]])],
+ ]),
+ materials: [
+ {
+ pwId: '1',
+ originalPath: `${catPath}:data:material.layer`,
+ catalogPath: catPath,
+ fileData: tinyPng,
+ },
+ ],
+ };
+
+ const brush = await parseSutExtractedData(extracted, 'Oil Paint Brush.sut');
+ expect(brush.name).toBe('Oil Paint Brush');
+ expect(brush.tipDataUrl).toBeUndefined(); // Circle tip, NOT paper texture!
+ expect(brush.paperTexture).toBeDefined();
+ expect(brush.paperTextureMode).toBe('multiply');
+ expect(brush.paperTextureApplyEachPlot).toBe(true);
+ expect(brush.textureDensity).toBeCloseTo(0.62, 4);
+ expect(brush.spacing).toBeCloseTo(0.003, 5); // 0.3% = 0.003, NOT 30%!
+ expect(brush.thickness).toBeCloseTo(0.17, 4);
+ expect(brush.angleDynamics).toBe('direction');
+ expect(brush.angle).toBe(90); // CSP 12-o'clock forward -> +90 deg
+ expect(brush.rotationRandomScale).toBe(0); // Random is OFF!
+ expect(brush.wetEdge).toBe(0); // BrushUseWaterEdge=0!
+ expect(brush.colorMixing).toBe(true);
+ expect(brush.mixingMode).toBe('blend');
+ expect(brush.perceptualMixing).toBe(false);
+ expect(brush.amountOfPaint).toBeCloseTo(0.62, 4);
+ expect(brush.densityOfPaint).toBeCloseTo(0.74, 4);
+ expect(brush.colorStretch).toBeCloseTo(0.82, 4);
+ expect(brush.taper?.useOut).toBe(true);
+ expect(brush.taper?.outLength).toBe(381);
+ expect(brush.taper?.inOutType).toBe(2);
+ expect(brush.taper?.affectAmountOfPaint).toBe(true);
+ expect(brush.taper?.affectDensityOfPaint).toBe(true);
+ expect(brush.taper?.affectOpacity).toBe(false);
+ expect(brush.taper?.minSizeRatio).toBeCloseTo(0.53, 4);
+ });
+
+ it('SpatialTipMixer mixes side-by-side strokes independently (left stays pure red, right drags black)', () => {
+ const surface = createSoftwareCanvas(160, 160);
+ // Paint a solid black vertical half on the right side (x >= 80)
+ for (let y = 0; y < 160; y++) {
+ for (let x = 80; x < 160; x++) {
+ const i = (y * 160 + x) * 4;
+ surface.buf[i] = 10;
+ surface.buf[i + 1] = 10;
+ surface.buf[i + 2] = 10;
+ surface.buf[i + 3] = 255;
+ }
+ }
+
+ const sampler = new LayerPixelSampler(surface as unknown as HTMLCanvasElement);
+ const settings: BrushSettings = {
+ size: 40,
+ minSizeFactor: 0.55,
+ color: '#d82218',
+ opacity: 1.0,
+ flow: 1.0,
+ spacing: 0.003,
+ hardness: 1.0,
+ thickness: 0.17,
+ thicknessVertical: false,
+ customTipAngle: 90,
+ customTipAngleDynamics: 'direction',
+ customTipRotationRandomScale: 0,
+ antiAlias: 2,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 0,
+ colorMixing: true,
+ perceptualMixing: true,
+ amountOfPaint: 0.62,
+ densityOfPaint: 0.74,
+ colorStretch: 0.82,
+ mixingMode: 'blend',
+ useGpu: false,
+ };
+
+ // Draw a vertical red flat stroke centered right on the x=80 boundary (x=60..100)
+ const pts: Point[] = [];
+ for (let i = 0; i <= 12; i++) {
+ pts.push({ x: 80, y: 20 + i * 10, pressure: 1.0, width: 40 });
+ }
+
+ renderCompleteStroke(
+ surface.ctx,
+ pts,
+ settings,
+ 'brush',
+ 'color',
+ false,
+ surface as unknown as HTMLCanvasElement,
+ false,
+ sampler
+ );
+
+ // Sample at y=80: left side of brush (x=68, over blank canvas) must be bright red
+ const leftIdx = (80 * 160 + 68) * 4;
+ // Right side of brush (x=92, over black paint) must be darkened by picked-up black
+ const rightIdx = (80 * 160 + 92) * 4;
+
+ expect(surface.buf[leftIdx + 3]).toBeGreaterThan(220); // Solid opaque body
+ expect(surface.buf[leftIdx]).toBeGreaterThan(190); // Pure bright red on left edge
+ expect(surface.buf[rightIdx]).toBeLessThan(surface.buf[leftIdx] - 35); // Noticeably darkened on right edge!
+ expect(surface.buf[rightIdx]).toBeGreaterThan(40); // Blended red+black, not untouched pure black!
+ });
+
+ it('maintains crisp opaque edges on large 130px CSP Fade flat strokes and ignores pointer-up reverse micro-hooks', () => {
+ const surface = createSoftwareCanvas(240, 240);
+ const sampler = new LayerPixelSampler(surface as unknown as HTMLCanvasElement);
+ const settings: BrushSettings = {
+ size: 130,
+ minSizeFactor: 0.55,
+ color: '#101010',
+ opacity: 1.0,
+ flow: 1.0,
+ spacing: 0.003,
+ adjustDensityByGap: false,
+ hardness: 1.0,
+ thickness: 0.17,
+ thicknessVertical: false,
+ customTipAngle: 90,
+ customTipAngleDynamics: 'direction',
+ customTipRotationRandomScale: 0,
+ antiAlias: 2,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 0,
+ colorMixing: true,
+ perceptualMixing: true,
+ amountOfPaint: 0.62,
+ densityOfPaint: 0.74,
+ colorStretch: 0.82,
+ mixingMode: 'blend',
+ taper: {
+ useIn: true,
+ inLength: 20,
+ inRatio: 0.3,
+ useOut: true,
+ outLength: 381,
+ outRatio: 0.3,
+ inOutType: 2, // CSP Specify length (ending taper)
+ inOutBySpeed: true,
+ affectSize: true,
+ minSizeRatio: 0.53,
+ affectDensity: false,
+ minDensityRatio: 0,
+ affectOpacity: false,
+ affectAmountOfPaint: true,
+ minAmountRatio: 0,
+ affectDensityOfPaint: true,
+ minPaintDensityRatio: 0,
+ },
+ useGpu: false,
+ };
+
+ const pts: Point[] = [];
+ for (let i = 0; i <= 14; i++) {
+ pts.push({ x: 120, y: 30 + i * 10, pressure: 0.75, width: 115 });
+ }
+ // Reverse micro-hook at pointer-up should NOT spin the flat blade
+ pts.push({ x: 120.4, y: 169.3, pressure: 0.75, width: 115 });
+
+ renderCompleteStroke(
+ surface.ctx,
+ pts,
+ settings,
+ 'brush',
+ 'color',
+ false,
+ surface as unknown as HTMLCanvasElement,
+ false,
+ sampler
+ );
+
+ // Crisp start cap at y=38 (no dark lip, high coverage) and smooth monotonic Fade over 381px
+ const startCenter = (42 * 240 + 120) * 4;
+ expect(surface.buf[startCenter + 3]).toBeGreaterThan(210);
+
+ // Razor-sharp side edge at y=80: inside (x=72) is solid, outside (x=55) is completely clean transparent
+ const insideEdge = (80 * 240 + 72) * 4;
+ const outsideEdge = (80 * 240 + 55) * 4;
+ expect(surface.buf[insideEdge + 3]).toBeGreaterThan(200);
+ expect(surface.buf[outsideEdge + 3]).toBe(0);
+ });
+
+ it('produces monotonic tangent angles on circular arcs (no Catmull-Rom sawtooth wiggle) and smooth 381px Fade', () => {
+ const arcPts: Point[] = [];
+ for (let i = 0; i <= 12; i++) {
+ const a = (i / 12) * 1.2;
+ arcPts.push({ x: 100 + Math.cos(a) * 80, y: 100 + Math.sin(a) * 80, pressure: 0.8, width: 40 });
+ }
+ const { c1, c2 } = centripetalCatmullRomToBezier(arcPts[4], arcPts[5], arcPts[6], arcPts[7]);
+ const tab = buildCubicArcLengthTable(arcPts[5], c1, c2, arcPts[6]);
+ const s0 = getCubicPointAtArcLength(arcPts[5], c1, c2, arcPts[6], 0, tab);
+ const sMid = getCubicPointAtArcLength(arcPts[5], c1, c2, arcPts[6], tab.totalLength * 0.5, tab);
+ const s1 = getCubicPointAtArcLength(arcPts[5], c1, c2, arcPts[6], tab.totalLength, tab);
+ const a0 = Math.atan2(s0.dy, s0.dx);
+ const aMid = Math.atan2(sMid.dy, sMid.dx);
+ const a1 = Math.atan2(s1.dy, s1.dx);
+ expect(aMid).toBeGreaterThan(a0);
+ expect(a1).toBeGreaterThan(aMid);
+
+ // Verify 381px Specify-length ending taper stays solid over long continuous strokes (>500px)
+ // and smoothly fades out over the final ending tail (never killing strokes mid-way at 381px)
+ const surf = createSoftwareCanvas(120, 760);
+ const sampler = new LayerPixelSampler(surf as unknown as HTMLCanvasElement);
+ const pts: Point[] = [];
+ for (let i = 0; i <= 70; i++) {
+ pts.push({ x: 60, y: 20 + i * 10, pressure: 0.55, width: 60 });
+ }
+ renderCompleteStroke(
+ surf.ctx,
+ pts,
+ {
+ size: 60,
+ minSizeFactor: 0.55,
+ color: '#101010',
+ opacity: 1.0,
+ flow: 1.0,
+ adjustDensityByGap: false,
+ spacing: 0.003,
+ hardness: 1.0,
+ thickness: 0.17,
+ thicknessVertical: false,
+ customTipAngle: 90,
+ customTipAngleDynamics: 'direction',
+ antiAlias: 2,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 0,
+ densitySensor: { usePressure: true, pressureMin: 0 },
+ colorMixing: true,
+ perceptualMixing: false,
+ amountOfPaint: 0.62,
+ densityOfPaint: 0.74,
+ colorStretch: 0.82,
+ mixingMode: 'blend',
+ taper: {
+ useIn: true,
+ inLength: 20,
+ inRatio: 0.3,
+ useOut: true,
+ outLength: 381,
+ outRatio: 0.3,
+ inOutType: 2,
+ inOutBySpeed: true,
+ affectSize: true,
+ minSizeRatio: 0.53,
+ affectDensity: false,
+ minDensityRatio: 0,
+ affectOpacity: false,
+ affectAmountOfPaint: true,
+ minAmountRatio: 0,
+ affectDensityOfPaint: true,
+ minPaintDensityRatio: 0,
+ },
+ useGpu: false,
+ },
+ 'brush',
+ 'color',
+ false,
+ surf as unknown as HTMLCanvasElement,
+ false,
+ sampler,
+ false,
+ 1.1
+ );
+
+ // At y=400 (380px into a 700px stroke — past 381px!), stroke MUST still be rich solid oil (not dead!)
+ const aPast381 = surf.buf[(400 * 120 + 60) * 4 + 3];
+ // Near the ending tail (y=620 and y=695), stroke smoothly tapers toward transparent
+ const aMidTail = surf.buf[(620 * 120 + 60) * 4 + 3];
+ const aEndTail = surf.buf[(705 * 120 + 60) * 4 + 3];
+ expect(aPast381).toBeGreaterThan(220);
+ expect(aMidTail).toBeLessThan(aPast381 - 15);
+ expect(aEndTail).toBeLessThan(aMidTail - 40);
+ });
+});
diff --git a/src/utils/colorMixingEngine.ts b/src/utils/colorMixingEngine.ts
index 8c2f27a..c468920 100644
--- a/src/utils/colorMixingEngine.ts
+++ b/src/utils/colorMixingEngine.ts
@@ -699,6 +699,83 @@ export class LayerPixelSampler {
return out;
}
+ /**
+ * Zero-allocation O(1) bilinear single-pixel sample for 2D SpatialTipMixer.
+ */
+ public sampleBilinearFast(cx: number, cy: number, out: RgbaColor): RgbaColor {
+ const w = this.width;
+ const h = this.height;
+ if (w <= 0 || h <= 0 || cx < -0.5 || cy < -0.5 || cx >= w - 0.5 || cy >= h - 0.5) {
+ out.r = 255;
+ out.g = 255;
+ out.b = 255;
+ out.a = 0;
+ return out;
+ }
+
+ const x0 = Math.max(0, Math.min(w - 1, Math.floor(cx)));
+ const y0 = Math.max(0, Math.min(h - 1, Math.floor(cy)));
+ const x1 = Math.min(w - 1, x0 + 1);
+ const y1 = Math.min(h - 1, y0 + 1);
+ const fx = Math.max(0, Math.min(1, cx - x0));
+ const fy = Math.max(0, Math.min(1, cy - y0));
+
+ const w00 = (1 - fx) * (1 - fy);
+ const w10 = fx * (1 - fy);
+ const w01 = (1 - fx) * fy;
+ const w11 = fx * fy;
+
+ let sumR = 0;
+ let sumG = 0;
+ let sumB = 0;
+ let sumA = 0;
+
+ const accum = (px: number, py: number, wt: number) => {
+ if (wt <= 1e-4) return;
+ let tr: number, tg: number, tb: number, ta: number;
+ if (this.useLazyTiles) {
+ const tile = this.getOrLoadTile(px >> 8, py >> 8);
+ const idx = (((py & 255) << 8) + (px & 255)) << 2;
+ tr = tile[idx];
+ tg = tile[idx + 1];
+ tb = tile[idx + 2];
+ ta = tile[idx + 3] / 255;
+ } else {
+ const idx = (py * w + px) << 2;
+ tr = this.data[idx];
+ tg = this.data[idx + 1];
+ tb = this.data[idx + 2];
+ ta = this.data[idx + 3] / 255;
+ }
+ if (ta > 0.002) {
+ const aw = wt * ta;
+ sumR += tr * aw;
+ sumG += tg * aw;
+ sumB += tb * aw;
+ sumA += aw;
+ }
+ };
+
+ accum(x0, y0, w00);
+ if (x1 !== x0) accum(x1, y0, w10);
+ if (y1 !== y0) accum(x0, y1, w01);
+ if (x1 !== x0 && y1 !== y0) accum(x1, y1, w11);
+
+ if (sumA > 0.002) {
+ const inv = 1 / sumA;
+ out.r = sumR * inv;
+ out.g = sumG * inv;
+ out.b = sumB * inv;
+ out.a = Math.min(1, sumA);
+ } else {
+ out.r = 255;
+ out.g = 255;
+ out.b = 255;
+ out.a = 0;
+ }
+ return out;
+ }
+
/**
* Lightweight per-bristle pixel deposit so overlapping turns immediately pick up
* freshly mixed multi-colored streaks laid down earlier in the same stroke.
@@ -843,6 +920,7 @@ export class PaintReservoir {
public isLoadedWithCanvasColor: boolean = false;
public cumulativeDistance: number = 0;
public smoothedAngle: number = 0;
+ public spatialMixer?: SpatialTipMixer;
constructor(initialColor: string) {
const rgb = parseColorToRgb(initialColor);
@@ -1479,3 +1557,673 @@ export class SpatialBristleReservoir {
return out;
}
}
+
+// -------------------------------------------------------------
+// 2D Spatial Per-Pixel Tip Mixer (Clip Studio Paint Blend / Running Color / Smear)
+// Maintains an oriented 2D RGBA pickup buffer across the brush tip footprint so
+// one edge of a flat brush picks up & drags underlying paint independently while
+// the rest of the brush lays down clean foreground color — matching CSP exactly.
+// -------------------------------------------------------------
+
+export interface SpatialTipStampParams {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ angleRad: number;
+ dirX: number;
+ dirY: number;
+ stepDist: number;
+ spacingRatio?: number;
+ adjustDensityByGap?: boolean;
+ dabSeq?: number;
+ hardness: number;
+ antiAlias: number;
+ flipX: number;
+ flipY: number;
+ flow: number;
+ pressure: number;
+ pressureAlreadyApplied: boolean;
+ amountOfPaint: number;
+ densityOfPaint: number;
+ colorStretch: number;
+ mixingMode: NaturalMixingMode;
+ perceptualMixing: boolean;
+ tipImage?: HTMLImageElement;
+ sampler?: LayerPixelSampler;
+ grainDensity?: number;
+ grainModulate?: (wx: number, wy: number, tipAlpha: number) => number;
+}
+
+interface CachedTipMask {
+ width: number;
+ height: number;
+ alpha: Uint8Array;
+}
+
+const tipAlphaMaskCache = new WeakMap<HTMLImageElement, CachedTipMask>();
+
+function getCachedTipAlphaMask(img: HTMLImageElement): CachedTipMask | null {
+ const cached = tipAlphaMaskCache.get(img);
+ if (cached) return cached;
+ if (typeof document === 'undefined') return null;
+ const w = img.naturalWidth || img.width;
+ const h = img.naturalHeight || img.height;
+ if (w <= 0 || h <= 0) return null;
+ const maxDim = 64;
+ const scale = Math.min(1, maxDim / Math.max(w, h));
+ const dw = Math.max(4, Math.round(w * scale));
+ const dh = Math.max(4, Math.round(h * scale));
+ const c = document.createElement('canvas');
+ c.width = dw;
+ c.height = dh;
+ const ctx = c.getContext('2d');
+ if (!ctx || typeof ctx.getImageData !== 'function') return null;
+ ctx.clearRect(0, 0, dw, dh);
+ ctx.drawImage(img, 0, 0, dw, dh);
+ const raw = ctx.getImageData(0, 0, dw, dh).data;
+ const alpha = new Uint8Array(dw * dh);
+ for (let i = 0; i < alpha.length; i++) {
+ alpha[i] = raw[i * 4 + 3];
+ }
+ const mask: CachedTipMask = { width: dw, height: dh, alpha };
+ tipAlphaMaskCache.set(img, mask);
+ return mask;
+}
+
+const MAX_SPATIAL_COLOR_DIM = 64;
+const MAX_SPATIAL_OUT_DIM = 256;
+
+export class SpatialTipMixer {
+ public readonly origR: number;
+ public readonly origG: number;
+ public readonly origB: number;
+
+ private gridW: number = 0;
+ private gridH: number = 0;
+ private initialized: boolean = false;
+ private readonly bufR = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
+ private readonly bufG = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
+ private readonly bufB = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
+ private readonly bufA = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
+ private readonly bufCarry = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
+ private readonly tmpR = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
+ private readonly tmpG = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
+ private readonly tmpB = new Float32Array(MAX_SPATIAL_COLOR_DIM * MAX_SPATIAL_COLOR_DIM);
+
+ private scratchCanvas: HTMLCanvasElement | null = null;
+ private scratchCtx: CanvasRenderingContext2D | null = null;
+ private scratchImgData: ImageData | null = null;
+ private scratchW: number = 0;
+ private scratchH: number = 0;
+
+ private readonly sampleScratch: RgbaColor = { r: 0, g: 0, b: 0, a: 0 };
+ private readonly c1Scratch: RgbColor = { r: 0, g: 0, b: 0 };
+ private readonly c2Scratch: RgbColor = { r: 0, g: 0, b: 0 };
+
+ constructor(initialColor: string) {
+ const rgb = parseColorToRgb(initialColor);
+ this.origR = rgb.r;
+ this.origG = rgb.g;
+ this.origB = rgb.b;
+ }
+
+ private ensureGrid(width: number, height: number): void {
+ if (this.initialized && this.gridW > 0 && this.gridH > 0) {
+ return;
+ }
+ const maxDim = Math.max(width, height, 1);
+ const scale = Math.min(1, MAX_SPATIAL_COLOR_DIM / maxDim);
+ this.gridW = Math.max(8, Math.min(MAX_SPATIAL_COLOR_DIM, Math.ceil(width * scale)));
+ this.gridH = Math.max(8, Math.min(MAX_SPATIAL_COLOR_DIM, Math.ceil(height * scale)));
+ }
+
+ private ensureScratchSurface(outW: number, outH: number): boolean {
+ if (typeof document === 'undefined') return false;
+ if (!this.scratchCanvas) {
+ this.scratchCanvas = document.createElement('canvas');
+ this.scratchCanvas.width = outW;
+ this.scratchCanvas.height = outH;
+ this.scratchCtx = this.scratchCanvas.getContext('2d');
+ this.scratchW = outW;
+ this.scratchH = outH;
+ } else if (this.scratchW !== outW || this.scratchH !== outH) {
+ this.scratchCanvas.width = outW;
+ this.scratchCanvas.height = outH;
+ this.scratchW = outW;
+ this.scratchH = outH;
+ this.scratchImgData = null;
+ }
+ if (!this.scratchCtx || typeof this.scratchCtx.createImageData !== 'function') return false;
+ if (!this.scratchImgData) {
+ this.scratchImgData = this.scratchCtx.createImageData(outW, outH);
+ }
+ return true;
+ }
+
+ /**
+ * Samples underlying canvas across the oriented 2D brush tip footprint, updates per-texel
+ * pickup buffer with CSP Blend / Running Color / Smear physics, and composites a crisp 1:1
+ * anti-aliased tip stamp (decoupled from the color-pickup grid so large brushes stay razor-sharp).
+ */
+ public stepAndBuildStamp(p: SpatialTipStampParams): {
+ canvas: HTMLCanvasElement;
+ srcW: number;
+ srcH: number;
+ drawW: number;
+ drawH: number;
+ hasVisiblePixels: boolean;
+ avgR: number;
+ avgG: number;
+ avgB: number;
+ avgA: number;
+ pickedUpCanvas: boolean;
+ } | null {
+ if (p.width < 0.25 || p.height < 0.25 || p.flow <= 0.002) return null;
+
+ this.ensureGrid(p.width, p.height);
+ const gw = this.gridW;
+ const gh = this.gridH;
+
+ // 1:1 output stamp dimensions (capped at 256px) with 1px transparent padding on each edge
+ // so Canvas2D bilinear filtering never blurs or clips sharp rotated chisel corners.
+ const maxAxis = Math.max(p.width, p.height);
+ const outScale = maxAxis > MAX_SPATIAL_OUT_DIM - 2 ? (MAX_SPATIAL_OUT_DIM - 2) / maxAxis : 1.0;
+ const innerW = Math.max(4, Math.ceil(p.width * outScale));
+ const innerH = Math.max(4, Math.ceil(p.height * outScale));
+ const outW = innerW + 2;
+ const outH = innerH + 2;
+
+ if (!this.ensureScratchSurface(outW, outH) || !this.scratchCtx || !this.scratchCanvas || !this.scratchImgData) {
+ return null;
+ }
+
+ const clampedAmount = Math.max(0, Math.min(1, p.amountOfPaint));
+ const clampedDensity = Math.max(0, Math.min(1, p.densityOfPaint));
+ const clampedStretch = Math.max(0, Math.min(1, p.colorStretch));
+ const isPureSmudge = clampedAmount <= 0.005 || p.mixingMode === 'smear';
+ const isFullFresh = !isPureSmudge && clampedAmount >= 0.995;
+ const isRunning = p.mixingMode === 'running_color';
+
+ const cosA = Math.cos(p.angleRad);
+ const sinA = Math.sin(p.angleRad);
+ const halfW = p.width * 0.5;
+ const halfH = p.height * 0.5;
+ const invGw = 1 / gw;
+ const invGh = 1 / gh;
+
+ const brushSpan = Math.max(6, Math.max(p.width, p.height));
+ const thinSpan = Math.max(1.5, Math.min(p.width, p.height));
+ const step = Math.max(0, p.stepDist);
+
+ // Effective ellipse diameter along the motion direction (for footprint-normalized alpha & pickup)
+ let diamAlongStroke = thinSpan;
+ if (p.dirX !== 0 || p.dirY !== 0) {
+ const localDirX = p.dirX * cosA + p.dirY * sinA;
+ const localDirY = -p.dirX * sinA + p.dirY * cosA;
+ const dDenom = Math.hypot(localDirX / Math.max(0.5, p.width), localDirY / Math.max(0.5, p.height));
+ if (dDenom > 1e-5) {
+ diamAlongStroke = 1.0 / dDenom;
+ }
+ }
+
+ // Fast canvas pickup on contact (~0.25..0.75x tip thickness along stroke);
+ // Color Stretch governs long carry persistence (even on small 15-35px brushes!).
+ const carryScale = Math.max(0.75, brushSpan / 36);
+ const pickupLen = Math.max(1.8, diamAlongStroke * (0.26 + 0.44 * clampedStretch));
+ const pickupRate = step > 0 ? 1.0 - Math.exp(-step / pickupLen) : 0.9;
+
+ const stretchDist = Math.max(16.0, (24 + clampedStretch * clampedStretch * 340) * carryScale);
+ const carryDecay = step > 0 ? 1.0 - Math.exp(-step / stretchDist) : 0.0;
+ const recoverLen = Math.max(
+ 18.0,
+ stretchDist / Math.max(0.18, clampedAmount)
+ );
+ const recoverRate = step > 0 ? 1.0 - Math.exp(-step / recoverLen) : 0.0;
+
+ const smudgeDecay = carryDecay;
+
+ const mixColorInto = (
+ r1: number,
+ g1: number,
+ b1: number,
+ r2: number,
+ g2: number,
+ b2: number,
+ w2: number
+ ): RgbColor => {
+ const w = w2 <= 0 ? 0 : w2 >= 1 ? 1 : w2;
+ if (w <= 0.0005) {
+ this.c1Scratch.r = r1;
+ this.c1Scratch.g = g1;
+ this.c1Scratch.b = b1;
+ return this.c1Scratch;
+ }
+ if (w >= 0.9995) {
+ this.c1Scratch.r = r2;
+ this.c1Scratch.g = g2;
+ this.c1Scratch.b = b2;
+ return this.c1Scratch;
+ }
+ if (p.perceptualMixing) {
+ this.c1Scratch.r = r1;
+ this.c1Scratch.g = g1;
+ this.c1Scratch.b = b1;
+ this.c2Scratch.r = r2;
+ this.c2Scratch.g = g2;
+ this.c2Scratch.b = b2;
+ return mixSubtractivePigments(this.c1Scratch, this.c2Scratch, w);
+ }
+ this.c1Scratch.r = r1 + (r2 - r1) * w;
+ this.c1Scratch.g = g1 + (g2 - g1) * w;
+ this.c1Scratch.b = b1 + (b2 - b1) * w;
+ return this.c1Scratch;
+ };
+
+ const sampler = p.sampler;
+ const firstTouch = !this.initialized;
+ let pickedUpCanvas = false;
+ let sumBufR = 0;
+ let sumBufG = 0;
+ let sumBufB = 0;
+ let sumBufA = 0;
+ const totalTexels = gw * gh;
+
+ // 1. Sample underlying canvas & update 2D oriented paint buffer
+ for (let gy = 0; gy < gh; gy++) {
+ const ny = ((gy + 0.5) * invGh - 0.5) * 2.0; // [-1, 1]
+ const ly = ny * halfH;
+ const rowOff = gy * gw;
+ for (let gx = 0; gx < gw; gx++) {
+ const nx = ((gx + 0.5) * invGw - 0.5) * 2.0; // [-1, 1]
+ const lx = nx * halfW;
+ const idx = rowOff + gx;
+
+ if (isFullFresh) {
+ this.bufR[idx] = this.origR;
+ this.bufG[idx] = this.origG;
+ this.bufB[idx] = this.origB;
+ this.bufA[idx] = 1.0;
+ this.bufCarry[idx] = 0.0;
+ sumBufR += this.origR;
+ sumBufG += this.origG;
+ sumBufB += this.origB;
+ sumBufA += 1.0;
+ continue;
+ }
+
+ const wx = p.x + lx * cosA - ly * sinA;
+ const wy = p.y + lx * sinA + ly * cosA;
+ const sampled = sampler
+ ? sampler.sampleBilinearFast(wx, wy, this.sampleScratch)
+ : ((this.sampleScratch.a = 0), this.sampleScratch);
+ const ca = sampled.a;
+ if (ca > 0.015) pickedUpCanvas = true;
+
+ // CSP Blend wet pickup: when crossing existing paint, load canvas pigment strongly into the
+ // carried tip buffer (proportional to (1 - amount) boosted by colorStretch) so overlapping
+ // colors smear visibly into blank canvas instead of snapping back to pure foreground.
+ const stretchPickupBoost = 1.0 + clampedStretch * (isRunning ? 1.45 : 1.15);
+
+ if (firstTouch) {
+ if (isPureSmudge) {
+ this.bufR[idx] = sampled.r;
+ this.bufG[idx] = sampled.g;
+ this.bufB[idx] = sampled.b;
+ this.bufA[idx] = ca;
+ this.bufCarry[idx] = ca;
+ } else if (ca > 0.015) {
+ const wCanvas = (1.0 - clampedAmount) * stretchPickupBoost * ca;
+ const wFresh = clampedAmount * (isRunning ? 0.75 : 0.9);
+ const eqFresh = wFresh / Math.max(1e-4, wFresh + wCanvas);
+ const m = mixColorInto(sampled.r, sampled.g, sampled.b, this.origR, this.origG, this.origB, eqFresh);
+ this.bufR[idx] = m.r;
+ this.bufG[idx] = m.g;
+ this.bufB[idx] = m.b;
+ this.bufA[idx] = 1.0;
+ this.bufCarry[idx] = Math.min(1.0, ca * (1.0 - eqFresh * 0.65));
+ } else {
+ this.bufR[idx] = this.origR;
+ this.bufG[idx] = this.origG;
+ this.bufB[idx] = this.origB;
+ this.bufA[idx] = 1.0;
+ this.bufCarry[idx] = 0.0;
+ }
+ } else if (ca > 0.015) {
+ if (isPureSmudge) {
+ const rate = Math.min(1.0, pickupRate * (0.45 + 0.55 * ca));
+ const curA = this.bufA[idx];
+ if (curA <= 0.01) {
+ this.bufR[idx] = sampled.r;
+ this.bufG[idx] = sampled.g;
+ this.bufB[idx] = sampled.b;
+ this.bufA[idx] = ca * rate;
+ } else {
+ const m = mixColorInto(this.bufR[idx], this.bufG[idx], this.bufB[idx], sampled.r, sampled.g, sampled.b, rate);
+ this.bufR[idx] = m.r;
+ this.bufG[idx] = m.g;
+ this.bufB[idx] = m.b;
+ this.bufA[idx] = curA + (ca - curA) * rate;
+ }
+ this.bufCarry[idx] = Math.min(1.0, this.bufCarry[idx] + (ca - this.bufCarry[idx]) * rate);
+ } else {
+ const wCanvas = (1.0 - clampedAmount) * stretchPickupBoost * ca;
+ const wFresh = clampedAmount * (isRunning ? 0.72 : 0.88);
+ const eqFresh = wFresh / Math.max(1e-4, wFresh + wCanvas);
+ const eq = mixColorInto(sampled.r, sampled.g, sampled.b, this.origR, this.origG, this.origB, eqFresh);
+ const eqR = eq.r;
+ const eqG = eq.g;
+ const eqB = eq.b;
+ const m = mixColorInto(this.bufR[idx], this.bufG[idx], this.bufB[idx], eqR, eqG, eqB, pickupRate);
+ this.bufR[idx] = m.r;
+ this.bufG[idx] = m.g;
+ this.bufB[idx] = m.b;
+ this.bufA[idx] = Math.min(1.0, this.bufA[idx] + (1.0 - this.bufA[idx]) * pickupRate);
+ const targetCarry = Math.min(1.0, ca * (1.0 - eqFresh * 0.55));
+ this.bufCarry[idx] = this.bufCarry[idx] + (targetCarry - this.bufCarry[idx]) * pickupRate;
+ }
+ } else if (step > 0) {
+ if (isPureSmudge) {
+ this.bufA[idx] = Math.max(0, this.bufA[idx] * (1.0 - smudgeDecay));
+ this.bufCarry[idx] = Math.max(0, this.bufCarry[idx] * (1.0 - carryDecay));
+ } else {
+ const m = mixColorInto(
+ this.bufR[idx],
+ this.bufG[idx],
+ this.bufB[idx],
+ this.origR,
+ this.origG,
+ this.origB,
+ recoverRate
+ );
+ this.bufR[idx] = m.r;
+ this.bufG[idx] = m.g;
+ this.bufB[idx] = m.b;
+ this.bufA[idx] = Math.min(1.0, this.bufA[idx] + (1.0 - this.bufA[idx]) * recoverRate);
+ this.bufCarry[idx] = Math.max(0, this.bufCarry[idx] * (1.0 - carryDecay));
+ }
+ }
+ sumBufR += this.bufR[idx];
+ sumBufG += this.bufG[idx];
+ sumBufB += this.bufB[idx];
+ sumBufA += this.bufA[idx];
+ }
+ }
+
+ this.initialized = true;
+
+ // 2. Gentle lateral diffusion (softens red-to-black cross-brush seam like real oil paint)
+ if (!isFullFresh && step > 0 && gw >= 4 && gh >= 4) {
+ const diff = (isRunning ? 0.095 : 0.045) * Math.min(1, step / Math.max(1, thinSpan * 0.28));
+ if (diff > 0.003) {
+ const centerW = 1.0 - 2.0 * diff;
+ const wideAlongX = p.width >= p.height;
+ if (wideAlongX) {
+ for (let gy = 0; gy < gh; gy++) {
+ const row = gy * gw;
+ this.tmpR[row] = this.bufR[row];
+ this.tmpG[row] = this.bufG[row];
+ this.tmpB[row] = this.bufB[row];
+ this.tmpR[row + gw - 1] = this.bufR[row + gw - 1];
+ this.tmpG[row + gw - 1] = this.bufG[row + gw - 1];
+ this.tmpB[row + gw - 1] = this.bufB[row + gw - 1];
+ for (let gx = 1; gx < gw - 1; gx++) {
+ const i = row + gx;
+ this.tmpR[i] = this.bufR[i - 1] * diff + this.bufR[i] * centerW + this.bufR[i + 1] * diff;
+ this.tmpG[i] = this.bufG[i - 1] * diff + this.bufG[i] * centerW + this.bufG[i + 1] * diff;
+ this.tmpB[i] = this.bufB[i - 1] * diff + this.bufB[i] * centerW + this.bufB[i + 1] * diff;
+ }
+ }
+ } else {
+ for (let gx = 0; gx < gw; gx++) {
+ this.tmpR[gx] = this.bufR[gx];
+ this.tmpG[gx] = this.bufG[gx];
+ this.tmpB[gx] = this.bufB[gx];
+ const last = (gh - 1) * gw + gx;
+ this.tmpR[last] = this.bufR[last];
+ this.tmpG[last] = this.bufG[last];
+ this.tmpB[last] = this.bufB[last];
+ }
+ for (let gy = 1; gy < gh - 1; gy++) {
+ const row = gy * gw;
+ for (let gx = 0; gx < gw; gx++) {
+ const i = row + gx;
+ this.tmpR[i] = this.bufR[i - gw] * diff + this.bufR[i] * centerW + this.bufR[i + gw] * diff;
+ this.tmpG[i] = this.bufG[i - gw] * diff + this.bufG[i] * centerW + this.bufG[i + gw] * diff;
+ this.tmpB[i] = this.bufB[i - gw] * diff + this.bufB[i] * centerW + this.bufB[i + gw] * diff;
+ }
+ }
+ }
+ const total = gw * gh;
+ for (let i = 0; i < total; i++) {
+ this.bufR[i] = this.tmpR[i];
+ this.bufG[i] = this.tmpG[i];
+ this.bufB[i] = this.tmpB[i];
+ }
+ }
+ }
+
+ // 3. Footprint-chord-normalized Beer-Lambert optical-depth model (exact CSP Blend + TextureForPlot):
+ // Dense fixed-interval CSP brushes (BrushAdjustFlowByInterval=0, spacing=0.3%) fill into rich
+ // velvety oil paint even at normal tablet pressure (p=0.45..0.85), while still glazing smoothly
+ // at light pressure and tapering cleanly to 0 at ending tails. When Density of Paint tapers to 0
+ // at the end of a stroke, carried pigment (bufCarry * colorStretch) keeps stretching smoothly!
+ const effPressure = Math.max(0.02, Math.min(1.0, p.pressure));
+ const pressureMod = p.pressureAlreadyApplied ? 1.0 : 0.35 + 0.65 * effPressure;
+ const flowFactor = Math.max(0, Math.min(1.0, p.flow * pressureMod));
+ const freshDensity = Math.max(0, Math.min(1.0, flowFactor * clampedDensity));
+ const spacingRatio = Math.max(0.003, Math.min(2.0, p.spacingRatio ?? 0.06));
+ const gapBoost = !p.adjustDensityByGap
+ ? 1.0 + 13.5 * Math.pow(Math.max(0, 1.0 - spacingRatio / 0.15), 2)
+ : 1.0;
+ const baseOpticalDepth =
+ freshDensity >= 0.995
+ ? 12.0
+ : gapBoost * Math.pow(freshDensity, 1.18);
+ const carriedOpticalScale = flowFactor * clampedStretch * 0.65;
+ const effectiveChord = Math.max(1.0, diamAlongStroke * 0.85);
+ const nominalStep = step > 0 ? Math.max(0.2, step) : Math.max(0.55, Math.min(1.05, thinSpan * 0.1));
+ const overlapHits = Math.max(1.0, effectiveChord / nominalStep);
+ const invOverlapHits = 1.0 / overlapHits;
+ const dabSalt = Math.imul((p.dabSeq ?? 0) + 1, 83492791);
+
+ // 4. Composite crisp 1:1 silhouette SDF + bilinear pigment grid + per-plot paper grain
+ const out = this.scratchImgData.data;
+ const tipMask = p.tipImage ? getCachedTipAlphaMask(p.tipImage) : null;
+ const hNorm = Math.max(0.02, Math.min(1.0, p.hardness));
+ const aaFeatherPx = p.antiAlias === 0 ? 0 : p.antiAlias === 1 ? 0.65 : p.antiAlias === 3 ? 1.65 : 1.0;
+ const hasGrain = Boolean(p.grainModulate && (p.grainDensity ?? 0) > 0.005);
+ const flipX = p.flipX < 0 ? -1 : 1;
+ const flipY = p.flipY < 0 ? -1 : 1;
+ const invInnerW = 1 / innerW;
+ const invInnerH = 1 / innerH;
+ const gwM1 = gw - 1;
+ const ghM1 = gh - 1;
+
+ let hasVisiblePixels = false;
+
+ for (let oy = 0; oy < outH; oy++) {
+ const rowOff = oy * outW;
+ // 1px transparent border ring
+ if (oy === 0 || oy === outH - 1) {
+ const start = rowOff << 2;
+ out.fill(0, start, start + (outW << 2));
+ continue;
+ }
+ const vNorm = (oy - 0.5) * invInnerH; // [0, 1] across exact tip height
+ const ny = (vNorm - 0.5) * 2.0; // [-1, 1]
+ const ly = ny * halfH;
+
+ const fy = Math.max(0, Math.min(ghM1, vNorm * gh - 0.5));
+ const gy0 = Math.floor(fy);
+ const gy1 = gy0 < ghM1 ? gy0 + 1 : ghM1;
+ const ty = fy - gy0;
+ const gRow0 = gy0 * gw;
+ const gRow1 = gy1 * gw;
+
+ for (let ox = 0; ox < outW; ox++) {
+ const pOff = (rowOff + ox) << 2;
+ if (ox === 0 || ox === outW - 1) {
+ out[pOff] = 0;
+ out[pOff + 1] = 0;
+ out[pOff + 2] = 0;
+ out[pOff + 3] = 0;
+ continue;
+ }
+
+ const uNorm = (ox - 0.5) * invInnerW; // [0, 1] across exact tip width
+ const nx = (uNorm - 0.5) * 2.0; // [-1, 1]
+
+ let tipAlpha = 0;
+ if (tipMask) {
+ const su = flipX < 0 ? 1.0 - uNorm : uNorm;
+ const sv = flipY < 0 ? 1.0 - vNorm : vNorm;
+ const tx = Math.max(0, Math.min(tipMask.width - 1, Math.floor(su * tipMask.width)));
+ const tyM = Math.max(0, Math.min(tipMask.height - 1, Math.floor(sv * tipMask.height)));
+ tipAlpha = tipMask.alpha[tyM * tipMask.width + tx] / 255;
+ } else {
+ const dist = Math.hypot(nx, ny);
+ if (dist < 1.0) {
+ if (p.antiAlias === 0) {
+ tipAlpha = 1.0;
+ } else if (hNorm >= 0.98) {
+ const gradLen = Math.hypot(nx / Math.max(0.5, halfW), ny / Math.max(0.5, halfH));
+ const edgePx = gradLen > 1e-5 ? (1.0 - dist) / gradLen : halfH;
+ const u = Math.max(0, Math.min(1, edgePx / Math.max(0.35, aaFeatherPx)));
+ tipAlpha = u * u * (3.0 - 2.0 * u);
+ } else if (dist <= hNorm) {
+ tipAlpha = 1.0;
+ } else {
+ const t = (dist - hNorm) / Math.max(1e-4, 1.0 - hNorm);
+ tipAlpha = hNorm <= 0.05 ? 0.5 * (1.0 + Math.cos(t * Math.PI)) : 1.0 - (3.0 * t * t - 2.0 * t * t * t);
+ }
+ }
+ }
+
+ if (tipAlpha <= 0.002) {
+ out[pOff] = 0;
+ out[pOff + 1] = 0;
+ out[pOff + 2] = 0;
+ out[pOff + 3] = 0;
+ continue;
+ }
+
+ let grainFactor = 1.0;
+ if (hasGrain && p.grainModulate) {
+ const lx = nx * halfW;
+ const wx = p.x + lx * cosA - ly * sinA;
+ const wy = p.y + lx * sinA + ly * cosA;
+ const rawGrain = p.grainModulate(wx, wy, 1.0);
+ // Wet oil paint fills paper valleys rather than punching static world-locked holes;
+ // blend grain depth softly so tooth shows delicately in fades while body stays creamy.
+ grainFactor = 0.62 + 0.38 * rawGrain;
+ if (grainFactor <= 0.002) {
+ out[pOff] = 0;
+ out[pOff + 1] = 0;
+ out[pOff + 2] = 0;
+ out[pOff + 3] = 0;
+ continue;
+ }
+ }
+
+ // Bilinear sample from color pickup buffer
+ const fx = Math.max(0, Math.min(gwM1, uNorm * gw - 0.5));
+ const gx0 = Math.floor(fx);
+ const gx1 = gx0 < gwM1 ? gx0 + 1 : gwM1;
+ const tx = fx - gx0;
+ const i00 = gRow0 + gx0;
+ const i10 = gRow0 + gx1;
+ const i01 = gRow1 + gx0;
+ const i11 = gRow1 + gx1;
+ const w00 = (1 - tx) * (1 - ty);
+ const w10 = tx * (1 - ty);
+ const w01 = (1 - tx) * ty;
+ const w11 = tx * ty;
+
+ const bA = this.bufA[i00] * w00 + this.bufA[i10] * w10 + this.bufA[i01] * w01 + this.bufA[i11] * w11;
+ const bCarry =
+ this.bufCarry[i00] * w00 +
+ this.bufCarry[i10] * w10 +
+ this.bufCarry[i01] * w01 +
+ this.bufCarry[i11] * w11;
+ const carriedDensity = bCarry * carriedOpticalScale;
+ const carriedTau = carriedDensity > 0.002 ? gapBoost * Math.pow(carriedDensity, 1.18) : 0;
+ const localTau = Math.max(baseOpticalDepth, carriedTau) * grainFactor * bA;
+ const perStampBody = localTau > 0.0005 ? 1.0 - Math.exp(-localTau * invOverlapHits) : 0;
+ const finalAlpha = Math.max(0, Math.min(1, tipAlpha * perStampBody));
+
+ if (finalAlpha <= 0.001) {
+ out[pOff] = 0;
+ out[pOff + 1] = 0;
+ out[pOff + 2] = 0;
+ out[pOff + 3] = 0;
+ continue;
+ }
+
+ const bR = this.bufR[i00] * w00 + this.bufR[i10] * w10 + this.bufR[i01] * w01 + this.bufR[i11] * w11;
+ const bG = this.bufG[i00] * w00 + this.bufG[i10] * w10 + this.bufG[i01] * w01 + this.bufG[i11] * w11;
+ const bB = this.bufB[i00] * w00 + this.bufB[i10] * w10 + this.bufB[i01] * w01 + this.bufB[i11] * w11;
+
+ // Deterministic sub-LSB alpha dither prevents 8-bit quantization banding across 15+ low-alpha Fade stamps
+ let h = (Math.imul(ox, 73856093) ^ Math.imul(oy, 19349663) ^ dabSalt) | 0;
+ h = Math.imul(h ^ (h >>> 16), 0x85ebca6b);
+ const dither = ((h ^ (h >>> 13)) >>> 0) / 4294967296 - 0.5;
+ const qAlpha = Math.max(0, Math.min(255, Math.floor(finalAlpha * 255 + 0.5 + dither * 0.95)));
+ if (qAlpha === 0) {
+ out[pOff] = 0;
+ out[pOff + 1] = 0;
+ out[pOff + 2] = 0;
+ out[pOff + 3] = 0;
+ continue;
+ }
+
+ out[pOff] = Math.max(0, Math.min(255, Math.round(bR)));
+ out[pOff + 1] = Math.max(0, Math.min(255, Math.round(bG)));
+ out[pOff + 2] = Math.max(0, Math.min(255, Math.round(bB)));
+ out[pOff + 3] = qAlpha;
+ hasVisiblePixels = true;
+ }
+ }
+
+ if (!hasVisiblePixels) return null;
+
+ this.scratchCtx.putImageData(this.scratchImgData, 0, 0);
+
+ // 5. Trailing self-pickup deposit into LayerPixelSampler strictly behind the trailing edge
+ // Dense across the full brush width so continuous back-and-forth scrubbing blends freshly laid strokes cleanly!
+ const depositBodyAlpha = baseOpticalDepth > 0.0005 ? 1.0 - Math.exp(-baseOpticalDepth * invOverlapHits) : 0;
+ if (sampler && step > 0 && (p.dirX !== 0 || p.dirY !== 0)) {
+ const trailDist = thinSpan * 0.6 + 1.25;
+ const targetSamples = Math.max(6, Math.min(gw, 18));
+ const sampleStride = Math.max(1, Math.floor(gw / targetSamples));
+ const midRow = (gh >> 1) * gw;
+ const depRad = Math.max(1, Math.min(6, Math.ceil((brushSpan / targetSamples) * 0.75)));
+ const depAlphaBoost = Math.min(0.85, Math.max(depositBodyAlpha * 2.1, Math.min(0.45, depositBodyAlpha * 1.4)));
+ for (let gx = 0; gx < gw; gx += sampleStride) {
+ const idx = midRow + gx;
+ const a = this.bufA[idx] * depAlphaBoost;
+ if (a <= 0.01) continue;
+ const nx = ((gx + 0.5) * invGw - 0.5) * 2.0;
+ const lx = nx * halfW;
+ const depX = p.x + lx * cosA - p.dirX * trailDist;
+ const depY = p.y + lx * sinA - p.dirY * trailDist;
+ sampler.depositPointFast(depX, depY, depRad, this.bufR[idx], this.bufG[idx], this.bufB[idx], a);
+ }
+ }
+
+ const invTotal = totalTexels > 0 ? 1 / totalTexels : 1;
+ return {
+ canvas: this.scratchCanvas,
+ srcW: outW,
+ srcH: outH,
+ drawW: p.width * (outW / innerW),
+ drawH: p.height * (outH / innerH),
+ hasVisiblePixels,
+ avgR: sumBufR * invTotal,
+ avgG: sumBufG * invTotal,
+ avgB: sumBufB * invTotal,
+ avgA: sumBufA * invTotal,
+ pickedUpCanvas,
+ };
+ }
+}
diff --git a/src/utils/inkbBrushFormat.ts b/src/utils/inkbBrushFormat.ts
index 1ea8f4e..e57c06b 100644
--- a/src/utils/inkbBrushFormat.ts
+++ b/src/utils/inkbBrushFormat.ts
@@ -258,7 +258,13 @@ function sanitizeTaper(val: unknown): CspTaperSettings | undefined {
affectSize: optBool(t.affectSize),
affectDensity: optBool(t.affectDensity),
affectOpacity: optBool(t.affectOpacity),
+ affectAmountOfPaint: optBool(t.affectAmountOfPaint),
+ minAmountRatio: optNum(t.minAmountRatio, 0, 1),
+ affectDensityOfPaint: optBool(t.affectDensityOfPaint),
+ minPaintDensityRatio: optNum(t.minPaintDensityRatio, 0, 1),
affectLoad: optBool(t.affectLoad),
+ minSizeRatio: optNum(t.minSizeRatio, 0, 1),
+ minDensityRatio: optNum(t.minDensityRatio, 0, 1),
};
}
diff --git a/src/utils/sutParser.ts b/src/utils/sutParser.ts
index 1561471..fcebd53 100644
--- a/src/utils/sutParser.ts
+++ b/src/utils/sutParser.ts
@@ -11,7 +11,7 @@ import {
CspTipFlipMode,
} from '../types/editor';
import { evaluateFastSpline } from '../engine/BrushEngine';
-import { isNativeRustAvailable, parseSutSqliteNative } from './nativeBackend';
+import { isNativeRustAvailable, NativeSutExtract, parseSutSqliteNative } from './nativeBackend';
const MAX_DECOMPRESSED_BLOB_BYTES = 64 * 1024 * 1024;
const MAX_COMPRESSED_BLOB_BYTES = 16 * 1024 * 1024;
@@ -231,6 +231,24 @@ export function isPng(buf: Uint8Array): boolean {
);
}
+/**
+ * Checks whether a MaterialFile TAR archive is tagged as a PaperTexture in icedata/layerData.xml.
+ */
+export function isMaterialPaperTexture(fileData: Uint8Array): boolean {
+ if (!fileData || fileData.length < 512) return false;
+ try {
+ const entries = extractTarEntries(fileData);
+ const xmlEntry = entries.find((e) => e.name.toLowerCase().endsWith('layerdata.xml'));
+ if (xmlEntry && xmlEntry.data.length > 0) {
+ const xml = new TextDecoder('utf-8', { fatal: false }).decode(xmlEntry.data);
+ return xml.includes('<data>PaperTexture</data>');
+ }
+ } catch {
+ // Ignore malformed TAR
+ }
+ return false;
+}
+
/**
* Extracts the primary raster image from a Clip Studio Paint MaterialFile BLOB.
*/
@@ -342,7 +360,11 @@ export function parseCspEffector(blob: Uint8Array | null | undefined): DecodedEf
const maxValue = rawMax > 0 ? Math.max(0, Math.min(1.0, rawMax / 100.0)) : 1.0;
const curves: [number, number][][] = [];
- let offset = 44;
+ const headerLen = view.getUint32(0, false);
+ let offset = headerLen >= 44 && headerLen <= blob.length ? headerLen : 48;
+ if (offset + 12 <= blob.length && view.getUint32(offset, false) !== 12 && blob.length >= 56 && view.getUint32(44, false) === 12) {
+ offset = 44;
+ }
while (offset + 12 <= blob.length) {
const magic = view.getUint32(offset, false);
@@ -596,14 +618,99 @@ function mapFlipMode(val: unknown): CspTipFlipMode {
return 'none';
}
+export interface DecodedInOutTarget {
+ affectSize: boolean;
+ minSizeRatio: number;
+ affectDensity: boolean;
+ minDensityRatio: number;
+ affectOpacity: boolean;
+ affectAmountOfPaint: boolean;
+ minAmountRatio: number;
+ affectDensityOfPaint: boolean;
+ minPaintDensityRatio: number;
+}
+
+/**
+ * Parses CSP Variant.BrushInOutTarget binary table:
+ * [header: magic(u32BE=12), count(u32BE), entrySize(u32BE=12)]
+ * followed by `count` entries of [paramId(u32BE), enabled(u32BE), minVal(u32BE)].
+ * Exact CSP param IDs (ordered by Sub Tool Detail -> Starting and Ending):
+ * - 0x03e9 (1001): Opacity
+ * - 0x03fd (1021): Brush Size (minVal in 0..100%)
+ * - 0x0411 (1041): Brush Density / Flow (minVal in 0..100%)
+ * - 0x043a (1082): Amount of Paint / BrushMixColor (minVal in 0..100%)
+ * - 0x043c (1084): Density of Paint / BrushMixAlpha (minVal in 0..100%)
+ */
+export function parseCspInOutTarget(blob: Uint8Array | null | undefined): DecodedInOutTarget | null {
+ if (!blob || blob.length < 12) return null;
+ const view = new DataView(blob.buffer, blob.byteOffset, blob.byteLength);
+ const magic = view.getUint32(0, false);
+ const count = view.getUint32(4, false);
+ const entrySize = view.getUint32(8, false);
+ if (magic !== 12 || entrySize !== 12 || count === 0 || 12 + count * 12 > blob.length) {
+ return null;
+ }
+
+ let affectSize = false;
+ let minSizeRatio = 0;
+ let affectDensity = false;
+ let minDensityRatio = 0;
+ let affectOpacity = false;
+ let affectAmountOfPaint = false;
+ let minAmountRatio = 0;
+ let affectDensityOfPaint = false;
+ let minPaintDensityRatio = 0;
+ let anyEnabled = false;
+
+ for (let i = 0; i < count; i++) {
+ const off = 12 + i * 12;
+ const paramId = view.getUint32(off, false);
+ const enabled = view.getUint32(off + 4, false) !== 0;
+ const val = view.getUint32(off + 8, false);
+ if (!enabled) continue;
+ anyEnabled = true;
+ const norm = Math.max(0, Math.min(1, val / 100));
+ if (paramId === 0x03fd) {
+ affectSize = true;
+ minSizeRatio = norm;
+ } else if (paramId === 0x03e9 || paramId === 0x03fc) {
+ affectOpacity = true;
+ } else if (paramId === 0x0411) {
+ affectDensity = true;
+ minDensityRatio = norm;
+ } else if (paramId === 0x043a) {
+ affectAmountOfPaint = true;
+ minAmountRatio = norm;
+ } else if (paramId === 0x043c) {
+ affectDensityOfPaint = true;
+ minPaintDensityRatio = norm;
+ }
+ }
+
+ if (!anyEnabled) return null;
+ return {
+ affectSize,
+ minSizeRatio,
+ affectDensity,
+ minDensityRatio,
+ affectOpacity,
+ affectAmountOfPaint,
+ minAmountRatio,
+ affectDensityOfPaint,
+ minPaintDensityRatio,
+ };
+}
+
function mapTextureMode(val: unknown): CspPaperTextureMode {
const n = Number(val);
- if (n === 1) return 'subtract';
- if (n === 2) return 'multiply';
- if (n === 3) return 'compare';
+ // CSP TextureCompositeMode: 0=Normal, 1=Multiply, 2=Subtract, 3=Compare density,
+ // 4=Overlay, 5=Color burn, 6=Linear burn, 7=Height, 8=Outline
+ if (n === 0 || n === 1 || n === 5 || n === 6) return 'multiply';
+ if (n === 2) return 'subtract';
+ if (n === 3 || n === 7) return 'compare';
if (n === 4) return 'overlay';
- if (n === 5) return 'outline';
- return 'subtract';
+ if (n === 8) return 'outline';
+ return 'multiply';
}
/**
@@ -619,7 +726,17 @@ export async function parseSutFile(
}
const extracted = await parseSutSqliteNative(rawBytes);
+ return parseSutExtractedData(extracted, fileName);
+}
+/**
+ * Pure mapper from extracted SQLite rows (Node/Variant/MaterialFile) to CspBrush.
+ * Exported directly for deterministic unit testing without Tauri IPC.
+ */
+export async function parseSutExtractedData(
+ extracted: NativeSutExtract,
+ fileName: string = 'Brush.sut'
+): Promise<CspBrush> {
let brushName = extracted.nodeName || fileName.replace(/\.sut$/i, '').trim();
let brushSize = 16;
@@ -650,6 +767,7 @@ export async function parseSutFile(
let opacitySensor: CspSensorConfig | undefined = undefined;
let densitySensor: CspSensorConfig | undefined = undefined;
let colorMixing = false;
+ let perceptualMixing = false;
let amountOfPaint = 0.7;
let densityOfPaint = 0.8;
let colorStretch = 0.6;
@@ -661,15 +779,17 @@ export async function parseSutFile(
let textureDensity = 0;
let paperTextureScale = 1.0;
let paperTextureRotate = 0;
- let paperTextureMode: CspPaperTextureMode = 'subtract';
+ let paperTextureMode: CspPaperTextureMode = 'multiply';
let paperTextureBrightness = 0;
let paperTextureContrast = 0;
+ let paperTextureApplyEachPlot = false;
let paperTextureInverted = false;
let spray: CspSpraySettings | undefined = undefined;
let taper: CspTaperSettings | undefined = undefined;
let isRibbon = false;
let dualBrush = false;
let dualBrushCompositeMode = 'multiply';
+ let usePatternImage: boolean | null = null;
let rawPatternArrayBlob: Uint8Array | null = null;
let rawTextureImageBlob: Uint8Array | null = null;
let rawDualPatternBlob: Uint8Array | null = null;
@@ -718,22 +838,29 @@ export async function parseSutFile(
const opacityEffBlob = getVal(['OpacityEffector', 'BrushOpacityEffector']);
if (opacityEffBlob instanceof Uint8Array) {
const eff = parseCspEffector(opacityEffBlob);
- if (eff) opacitySensor = effectorToSensorConfig(eff);
+ if (eff && (eff.usePressure || eff.useTilt || eff.useVelocity || eff.useRandom)) {
+ opacitySensor = effectorToSensorConfig(eff);
+ }
}
const densityEffBlob = getVal(['BrushDensityEffector', 'BrushFlowEffector', 'DensityEffector']);
if (densityEffBlob instanceof Uint8Array) {
const eff = parseCspEffector(densityEffBlob);
- if (eff) densitySensor = effectorToSensorConfig(eff);
+ if (eff && (eff.usePressure || eff.useTilt || eff.useVelocity || eff.useRandom)) {
+ densitySensor = effectorToSensorConfig(eff);
+ }
}
- // Spacing / Interval
+ // Spacing / Interval (CSP BrushAutoIntervalType: 0=Fixed %, 1=Wide, 2=Normal, 3=Narrow)
+ const rawAutoInterval = getVal(['BrushAutoIntervalType']);
const rawSpacing = getVal(['BrushInterval', 'Interval', 'Spacing', 'BrushSpacing']);
- if (typeof rawSpacing === 'number' && rawSpacing > 0) {
- spacing =
- rawSpacing > 1.0
- ? Math.max(0.01, Math.min(1.0, rawSpacing / 100))
- : Math.max(0.01, Math.min(1.0, rawSpacing));
+ if (typeof rawAutoInterval === 'number' && rawAutoInterval > 0) {
+ if (rawAutoInterval === 1) spacing = 0.25;
+ else if (rawAutoInterval === 2) spacing = 0.1;
+ else if (rawAutoInterval === 3) spacing = 0.04;
+ } else if (typeof rawSpacing === 'number' && rawSpacing > 0) {
+ // In CSP, BrushInterval in Fixed mode is ALWAYS a percentage (0.1%..200% -> 0.001..2.0)
+ spacing = Math.max(0.003, Math.min(2.0, rawSpacing / 100));
}
// Opacity (strictly stroke ceiling opacity, distinct from BrushDensity!)
@@ -748,7 +875,7 @@ export async function parseSutFile(
flow = rawFlow > 1.0 ? Math.min(1.0, rawFlow / 100) : rawFlow;
}
- const rawAdjustGap = getVal(['BrushAdjustDensityByGap', 'AdjustDensityByGap']);
+ const rawAdjustGap = getVal(['BrushAdjustFlowByInterval', 'BrushAdjustDensityByGap', 'AdjustDensityByGap']);
if (rawAdjustGap !== null) {
adjustDensityByGap = Boolean(rawAdjustGap);
}
@@ -777,12 +904,13 @@ export async function parseSutFile(
thicknessVertical = Boolean(rawVertThick);
}
- const rawFlipH = getVal(['BrushFlipX', 'FlipHorizontal']);
+ const rawFlipH = getVal(['BrushPatternReverseHorizontal', 'BrushFlipX', 'FlipHorizontal']);
if (rawFlipH !== null) flipH = mapFlipMode(rawFlipH);
- const rawFlipV = getVal(['BrushFlipY', 'FlipVertical']);
+ const rawFlipV = getVal(['BrushPatternReverseVertical', 'BrushFlipY', 'FlipVertical']);
if (rawFlipV !== null) flipV = mapFlipMode(rawFlipV);
// Rotation & Rotation Dynamics
+ // CSP BrushRotationEffector low nibble: 1=None, 2=Pen direction (tilt), 3=Direction of line, 4=Random, 5=Pen rotation (twist)
const rawAngle = getVal(['BrushRotation', 'Rotation', 'BrushAngle', 'Angle']);
if (typeof rawAngle === 'number') {
angle = ((rawAngle % 360) + 360) % 360;
@@ -790,7 +918,19 @@ export async function parseSutFile(
const rawRotEff = getVal(['BrushRotationEffector', 'RotationEffector', 'AngleDynamics']);
if (typeof rawRotEff === 'number') {
- if (rawRotEff & 0x80 || rawRotEff === 3 || rawRotEff === 67 || rawRotEff === 131) {
+ const rotMode = rawRotEff & 0x0f;
+ if (rotMode === 3) {
+ angleDynamics = 'direction';
+ } else if (rotMode === 2) {
+ angleDynamics = 'tilt';
+ useTilt = true;
+ } else if (rotMode === 4) {
+ angleDynamics = 'random';
+ } else if (rotMode === 5) {
+ angleDynamics = 'twist';
+ } else if (rotMode === 1) {
+ angleDynamics = 'none';
+ } else if (rawRotEff & 0x80) {
angleDynamics = 'direction';
} else if (rawRotEff & 0x20) {
angleDynamics = 'tilt';
@@ -798,12 +938,21 @@ export async function parseSutFile(
}
}
- const rawRandRot = getVal(['BrushRotationRandomScale', 'RotationRandomScale']);
- if (typeof rawRandRot === 'number' && rawRandRot > 0) {
- rotationRandomScale = Math.min(1.0, rawRandRot / 100);
- if (angleDynamics === 'none') {
- angleDynamics = 'random';
+ // CSP stores BrushRotationRandomScale=100 by default even when Random rotation is OFF!
+ // Only apply random scale when random rotation mode is explicitly enabled.
+ if (angleDynamics === 'random') {
+ const rawRandRot = getVal(['BrushRotationRandomScale', 'RotationRandomScale']);
+ if (typeof rawRandRot === 'number' && rawRandRot > 0) {
+ rotationRandomScale = Math.min(1.0, rawRandRot / 100);
}
+ } else {
+ rotationRandomScale = 0;
+ }
+
+ // CSP "Direction of line" aligns 12 o'clock (-Y) with the stroke tangent,
+ // whereas Ink Studio aligns 3 o'clock (+X) with atan2(dy, dx). Offset +90 deg to match CSP exactly.
+ if (angleDynamics === 'direction') {
+ angle = (angle + 90) % 360;
}
// Anti-Aliasing
@@ -813,15 +962,16 @@ export async function parseSutFile(
}
// Stabilization & Post-Correction
- const rawRev = getVal(['BrushRevision', 'Revision', 'FlickerReduction', 'BrushStabilization']);
+ const rawRev = getVal(['FlickerReduction', 'BrushStabilization']);
if (typeof rawRev === 'number' && rawRev >= 0) {
stabilization = Math.min(50, Math.max(0, Math.round(rawRev)));
}
- const rawPostCorr = getVal(['BrushPostCorrection', 'PostCorrection']);
- if (typeof rawPostCorr === 'number' && rawPostCorr >= 0) {
- postCorrection = Math.min(5, Math.max(0, Math.round(rawPostCorr)));
+ const rawUseRev = getVal(['BrushUseRevision']);
+ const rawPostCorr = getVal(['BrushRevision', 'BrushPostCorrection', 'PostCorrection']);
+ if (Boolean(rawUseRev) && typeof rawPostCorr === 'number' && rawPostCorr >= 0) {
+ postCorrection = Math.min(5, Math.max(0, Math.round(rawPostCorr / 2)));
}
- const rawSharp = getVal(['BrushSharpAngles', 'SharpAngles']);
+ const rawSharp = getVal(['BrushSharpenCorner', 'BrushSharpAngles', 'SharpAngles']);
if (rawSharp !== null) {
sharpCorners = Boolean(rawSharp);
}
@@ -863,17 +1013,21 @@ export async function parseSutFile(
colorStretch = rawMixExt > 1.0 ? Math.min(1.0, rawMixExt / 100) : rawMixExt;
}
- const rawMixMode = getVal(['BrushColorMixingMode', 'MixingMode']);
+ // CSP Variant.BrushWaterColor selects Mixing Mode: 0=Blend, 1=Running color, 2=Smear/Blur.
+ // CSP Variant.BrushColorMixingMode (CSP 2.0+) selects Color Space: 0=Standard, 1=Perceptual.
+ const rawMixMode = getVal(['BrushWaterColor', 'MixingMode']);
if (rawMixMode !== null) {
const m = Number(rawMixMode);
mixingMode = m === 2 ? 'smear' : m === 1 ? 'running_color' : 'blend';
}
+ const rawColorSpaceMode = getVal(['BrushColorMixingMode', 'PerceptualMixing']);
+ if (rawColorSpaceMode !== null) {
+ perceptualMixing = Number(rawColorSpaceMode) === 1;
+ }
- // Wet Edge
+ // Wet Edge (strictly gated on BrushUseWaterEdge!)
const rawWetEdge = getVal(['BrushUseWaterEdge', 'UseWaterEdge']);
- if (rawWetEdge !== null) {
- wetEdge = Boolean(rawWetEdge) ? 0.75 : 0;
- }
+ const wetEdgeEnabled = Boolean(rawWetEdge);
const rawWetRad = getVal(['BrushWaterEdgeRadius', 'WaterEdgeRadius']);
if (typeof rawWetRad === 'number' && rawWetRad > 0) {
wetEdgeRadius = rawWetRad;
@@ -881,12 +1035,14 @@ export async function parseSutFile(
const rawWetAlpha = getVal(['BrushWaterEdgeAlphaPower', 'WaterEdgeAlphaPower']);
if (typeof rawWetAlpha === 'number' && rawWetAlpha > 0) {
wetEdgeAlphaPower = rawWetAlpha;
- if (!rawWetEdge) wetEdge = Math.min(1.0, rawWetAlpha / 100);
}
const rawWetVal = getVal(['BrushWaterEdgeValuePower', 'WaterEdgeValuePower']);
if (typeof rawWetVal === 'number' && rawWetVal > 0) {
wetEdgeValuePower = rawWetVal;
}
+ wetEdge = wetEdgeEnabled
+ ? Math.max(0.15, Math.min(1.0, (wetEdgeAlphaPower || 75) / 100))
+ : 0;
// Paper Grain / Texture
const rawTexDensity = getVal(['TextureDensity', 'Grain', 'BrushTextureDensity']);
@@ -902,21 +1058,25 @@ export async function parseSutFile(
if (typeof rawTexRotate === 'number') {
paperTextureRotate = rawTexRotate;
}
- const rawTexMode = getVal(['TextureMode', 'BrushTextureMode']);
+ const rawTexMode = getVal(['TextureCompositeMode', 'TextureMode', 'BrushTextureMode']);
if (rawTexMode !== null) {
paperTextureMode = mapTextureMode(rawTexMode);
}
- const rawTexInvert = getVal(['TextureInvert', 'BrushTextureInvert']);
+ const rawTexInvert = getVal(['TextureReverseDensity', 'TextureInvert', 'BrushTextureInvert']);
if (rawTexInvert !== null) {
paperTextureInverted = Boolean(rawTexInvert);
}
+ const rawTexForPlot = getVal(['TextureForPlot']);
+ if (rawTexForPlot !== null) {
+ paperTextureApplyEachPlot = Boolean(rawTexForPlot);
+ }
const rawTexBright = getVal(['TextureBrightness']);
if (typeof rawTexBright === 'number') {
- paperTextureBrightness = Math.max(-1, Math.min(1, rawTexBright / 100));
+ paperTextureBrightness = Math.max(-100, Math.min(100, rawTexBright));
}
const rawTexContrast = getVal(['TextureContrast']);
if (typeof rawTexContrast === 'number') {
- paperTextureContrast = Math.max(-1, Math.min(1, rawTexContrast / 100));
+ paperTextureContrast = Math.max(-100, Math.min(100, rawTexContrast));
}
// Spray / Airbrush
@@ -939,19 +1099,22 @@ export async function parseSutFile(
};
}
- // Taper (In / Out)
+ // Taper (Starting and Ending)
const rawUseIn = getVal(['BrushUseIn']);
const rawUseOut = getVal(['BrushUseOut']);
const useIn = rawUseIn !== null ? Boolean(rawUseIn) : false;
const useOut = rawUseOut !== null ? Boolean(rawUseOut) : false;
const inLength = Number(getVal(['BrushInLength']) || 0);
- const inRatio = Number(getVal(['BrushInRatio']) || 0);
+ const rawInRatio = Number(getVal(['BrushInRatio']) || 0);
+ const inRatio = rawInRatio > 1 ? Math.min(1, rawInRatio / 100) : Math.max(0, rawInRatio);
const outLength = Number(getVal(['BrushOutLength']) || 0);
- const outRatio = Number(getVal(['BrushOutRatio']) || 0);
+ const rawOutRatio = Number(getVal(['BrushOutRatio']) || 0);
+ const outRatio = rawOutRatio > 1 ? Math.min(1, rawOutRatio / 100) : Math.max(0, rawOutRatio);
const inOutType = Number(getVal(['BrushInOutType']) || 0);
const inOutBySpeed = Boolean(getVal(['BrushInOutBySpeed']));
+ const decodedInOut = parseCspInOutTarget(getVal(['BrushInOutTarget']));
- if (useIn || useOut || inLength > 0 || outLength > 0 || inRatio > 0 || outRatio > 0) {
+ if ((useIn || useOut) && inOutType !== 0) {
taper = {
useIn,
inLength,
@@ -961,6 +1124,15 @@ export async function parseSutFile(
outRatio,
inOutType,
inOutBySpeed,
+ affectSize: decodedInOut ? decodedInOut.affectSize : true,
+ minSizeRatio: decodedInOut ? decodedInOut.minSizeRatio : 0,
+ affectDensity: decodedInOut ? decodedInOut.affectDensity : false,
+ minDensityRatio: decodedInOut ? decodedInOut.minDensityRatio : 0,
+ affectOpacity: decodedInOut ? decodedInOut.affectOpacity : false,
+ affectAmountOfPaint: decodedInOut ? decodedInOut.affectAmountOfPaint : false,
+ minAmountRatio: decodedInOut ? decodedInOut.minAmountRatio : 0,
+ affectDensityOfPaint: decodedInOut ? decodedInOut.affectDensityOfPaint : false,
+ minPaintDensityRatio: decodedInOut ? decodedInOut.minPaintDensityRatio : 0,
};
}
@@ -969,7 +1141,7 @@ export async function parseSutFile(
if (Boolean(rawDual)) {
dualBrush = true;
}
- const rawDualMode = getVal(['DualBrushMode', 'DualCompositeMode']);
+ const rawDualMode = getVal(['DualBrushCompositeMode', 'DualBrushMode', 'DualCompositeMode']);
if (rawDualMode !== null) {
const dm = Number(rawDualMode);
if (dm === 1) dualBrushCompositeMode = 'subtract';
@@ -978,6 +1150,10 @@ export async function parseSutFile(
else if (dm === 4) dualBrushCompositeMode = 'screen';
}
+ const rawUsePattern = getVal(['BrushUsePatternImage']);
+ if (rawUsePattern !== null) {
+ usePatternImage = Boolean(rawUsePattern);
+ }
rawPatternArrayBlob = getVal(['BrushPatternImageArray']);
rawTextureImageBlob = getVal(['TextureImage']);
rawDualPatternBlob = getVal(['DualPatternImageArray']);
@@ -988,8 +1164,15 @@ export async function parseSutFile(
}
// 4. MaterialFile extraction (from native Rust rusqlite rows)
- const materialMap = new Map<string, { mainPng: Uint8Array; width: number; height: number }>();
- const allMaterialsList: { mainPng: Uint8Array; catalogPath: string; width: number; height: number }[] = [];
+ interface ExtractedMaterial {
+ mainPng: Uint8Array;
+ catalogPath: string;
+ width: number;
+ height: number;
+ isPaperTexture: boolean;
+ }
+ const materialMap = new Map<string, ExtractedMaterial>();
+ const allMaterialsList: ExtractedMaterial[] = [];
for (const mat of extracted.materials) {
const fileData = mat.fileData;
@@ -1007,7 +1190,13 @@ export async function parseSutFile(
height = view.getUint32(20, false);
}
- const entry = { mainPng, width, height };
+ const entry: ExtractedMaterial = {
+ mainPng,
+ catalogPath: catPath,
+ width,
+ height,
+ isPaperTexture: isMaterialPaperTexture(fileData),
+ };
if (catPath) materialMap.set(catPath, entry);
materialMap.set(pwId, entry);
@@ -1018,14 +1207,14 @@ export async function parseSutFile(
materialMap.set(uuidMatch[0], entry);
}
- allMaterialsList.push({ mainPng, catalogPath: catPath, width, height });
+ allMaterialsList.push(entry);
}
}
}
// 5. Match Paper Texture
let paperTexture: string | undefined = undefined;
- let paperTextureEntry: { mainPng: Uint8Array } | null = null;
+ let paperTextureEntry: ExtractedMaterial | null = null;
if (rawTextureImageBlob) {
const texIds = extractCatalogIdsFromBlob(rawTextureImageBlob);
@@ -1037,37 +1226,49 @@ export async function parseSutFile(
}
}
}
+ if (!paperTexture) {
+ // CSP stores TextureDensity=50 even when no texture image is bound; avoid ghost grain.
+ textureDensity = 0;
+ }
- // 6. Match Brush Tip(s)
- const tipPngEntries: { mainPng: Uint8Array; width: number; height: number }[] = [];
-
- if (rawPatternArrayBlob) {
- const patternIds = extractCatalogIdsFromBlob(rawPatternArrayBlob);
- for (const pid of patternIds) {
- if (materialMap.has(pid)) {
- const entry = materialMap.get(pid)!;
- if (entry !== paperTextureEntry && !tipPngEntries.includes(entry)) {
- tipPngEntries.push(entry);
+ // 6. Match Brush Tip(s) — NEVER hijack a PaperTexture or ignore BrushUsePatternImage=0!
+ const tipPngEntries: ExtractedMaterial[] = [];
+
+ if (usePatternImage !== false) {
+ if (rawPatternArrayBlob) {
+ const patternIds = extractCatalogIdsFromBlob(rawPatternArrayBlob);
+ for (const pid of patternIds) {
+ if (materialMap.has(pid)) {
+ const entry = materialMap.get(pid)!;
+ if (entry !== paperTextureEntry && !tipPngEntries.includes(entry)) {
+ tipPngEntries.push(entry);
+ }
}
}
}
- }
- if (tipPngEntries.length === 0 && allMaterialsList.length > 0) {
- for (const m of allMaterialsList) {
- if (m !== paperTextureEntry && !tipPngEntries.some((e) => e.mainPng === m.mainPng)) {
- tipPngEntries.push(m);
+ if (tipPngEntries.length === 0 && allMaterialsList.length > 0 && usePatternImage === true) {
+ for (const m of allMaterialsList) {
+ if (
+ m !== paperTextureEntry &&
+ !m.isPaperTexture &&
+ !tipPngEntries.some((e) => e.mainPng === m.mainPng)
+ ) {
+ tipPngEntries.push(m);
+ }
}
}
}
- // 7. Process extracted tips or generate procedural tip
+ // 7. Process extracted custom tips; for Circle tips (BrushUsePatternImage=0), leave tipDataUrl undefined
+ // so BrushEngine renders its analytical/SDF circular/elliptical tip at native crisp resolution
+ // without double-applying thickness!
let tipDataUrl: string | undefined = undefined;
let tipWidth: number | undefined = undefined;
let tipHeight: number | undefined = undefined;
let isColorTip = false;
const subTips: CspSubTip[] = [];
- const fallbackProc = { hardness, thickness, antiAlias };
+ const fallbackProc = { hardness, thickness: 1.0, antiAlias };
if (tipPngEntries.length > 0) {
const primaryEntry = tipPngEntries[0];
@@ -1088,11 +1289,6 @@ export async function parseSutFile(
isColor: p.isColor,
});
}
- } else {
- const proc = generateProceduralTip(hardness, thickness, antiAlias);
- tipDataUrl = proc.dataUrl;
- tipWidth = proc.width;
- tipHeight = proc.height;
}
let secondaryTipDataUrl: string | undefined = undefined;
@@ -1120,7 +1316,7 @@ export async function parseSutFile(
id: uniqueId,
name: brushName,
badge: 'CSP',
- desc: tipPngEntries.length > 0 ? 'Clip Studio Paint Textured Brush' : 'Clip Studio Paint Inking Pen',
+ desc: tipPngEntries.length > 0 ? 'Clip Studio Paint Textured Brush' : 'Clip Studio Paint Brush',
tipDataUrl,
tipWidth,
tipHeight,
@@ -1158,6 +1354,7 @@ export async function parseSutFile(
pressureCurve,
velocityCurve,
colorMixing,
+ perceptualMixing,
amountOfPaint,
densityOfPaint,
colorStretch,
@@ -1173,6 +1370,7 @@ export async function parseSutFile(
paperTextureMode,
paperTextureBrightness,
paperTextureContrast,
+ paperTextureApplyEachPlot,
paperTextureInverted,
dualBrush,
dualBrushCompositeMode,