@ikijs/mcp 0.37.1 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fold-report.ts","../../engine/src/math.ts","../../engine/src/parameter-store.ts","../../engine/src/affine.ts","../../engine/src/warp.ts","../../engine/src/warp-grid.ts","../../engine/src/deform.ts","../../engine/src/occlusion.ts","../../engine/src/idle-motion.ts","../../engine/src/frame-clock.ts","../../engine/src/physics-motion.ts","../../engine/src/hair-chain-motion.ts","../../engine/src/iki-motion.ts","../../engine/src/clip-player.ts","../../engine/src/expression-player.ts","../../engine/src/folds.ts","../../engine/src/land.ts","../../engine/src/physics-check.ts","../../engine/src/physics-runs.ts","../src/probe.ts","../src/limits.ts","../src/node-images.ts","../src/custom-gate.ts","../src/sweep-report.ts","../src/sweep.ts","../src/render-poses.ts","../src/render-browser.ts","../src/tools.ts","../src/bake-report.ts","../src/measure-turn.ts","../src/measure.ts","../src/measure-arms.ts","../src/measure-hair-side.ts","../src/measure-forearm-pose.ts","../src/measure-lips.ts","../src/compose-lips.ts","../src/trim.ts","../src/compose.ts","../src/compose-arms.ts","../src/hair-side-report.ts","../src/physics-report.ts","../src/illustration-grid.ts","../src/illustration.ts","../src/illustration-cut.ts","../src/illustration-colour.ts","../src/illustration-context.ts","../src/illustration-labels.ts","../src/illustration-features.ts","../src/illustration-landmarks.ts","../src/server.ts"],"sourcesContent":["/**\n * The fold check `auto_rig_from_layers` and `render_poses` report: the\n * engine's `checkFolds` with the auto-rig's by-design closures set apart, and\n * the text lines both tools print it as.\n */\n\nimport { SHUT_BY } from \"@ikijs/editor\";\nimport {\n checkFolds,\n foldPoses,\n type FoldHit,\n type FoldPose,\n type FoldReport,\n type FoldTarget,\n} from \"@ikijs/engine\";\nimport type { IkiModel } from \"@ikijs/format\";\n\n/**\n * `checkFolds` over `foldPoses(model)` then one pose per `extraValues` set,\n * appended as given (a set equal to a default pose is checked twice), with\n * the auto-rig's by-design closures (`SHUT_BY`) kept out of `worst`.\n */\nexport function checkModelFolds(\n model: IkiModel,\n extraValues: Record<string, number>[] = [],\n): FoldReport {\n // An undeclared parameter reads 0 from the store, which is no closure.\n const declared = new Set(model.parameters.map((p) => p.id));\n return checkFolds(model, {\n poses: [...foldPoses(model), ...extraValues.map(foldPose)],\n // The effective value, not the pose's overrides: the auto-rig's mouth\n // rests shut at its default, so `rest` and the other parameters' singles\n // are shut-mouth poses too.\n expected: (target, _pose, value) => {\n if (target.kind !== \"part\") return false;\n const shutBy = SHUT_BY.get(target.id);\n return (\n shutBy !== undefined && declared.has(shutBy) && value(shutBy) === 0\n );\n },\n });\n}\n\n/**\n * `report` as text lines: one `FOLD` line per offender, worst first, or\n * `FOLDS: none over N poses`; then, when a by-design closure folds, one\n * `FOLDS expected:` line naming each such part, its ratio and the parameter\n * that shuts it. A `FOLD` line gives its rest point in model space and in\n * model px from the top-left of the model's `canvas` — the layer PNGs' own\n * pixels, the frame `RenderPlan.mouth` is in, not a render's.\n */\nexport function formatFoldReport(\n report: FoldReport,\n canvas: { width: number; height: number },\n): string[] {\n const lines =\n report.offenders.length === 0\n ? [`FOLDS: none over ${report.poses} poses`]\n : report.offenders.map((t) => offenderLine(t, t.worst!, canvas));\n\n // An expected hit that never came near folding is no closure to list.\n const closures = report.targets.flatMap((t) => {\n if (t.expected === undefined) return [];\n if (t.expected.ratio >= report.thresholds.collapse) return [];\n const shutBy = SHUT_BY.get(t.target.id);\n const at = shutBy === undefined ? \"\" : ` at ${shutBy}=0`;\n return [`${t.target.id} ${ratioText(t.expected.ratio)}${at}`];\n });\n if (closures.length > 0) {\n lines.push(\n `FOLDS expected: by-design closures, not findings — ${closures.join(\", \")}`,\n );\n }\n return lines;\n}\n\n/**\n * `values` named by the `FoldPose.name` contract, as the engine names its own\n * poses (its helper is not exported): sorted `id=value` pairs joined by one\n * space, `rest` when empty. Never a caller's PNG name, so a `FOLD` line keeps\n * settings a host can reproduce.\n */\nexport function foldPose(values: Record<string, number>): FoldPose {\n const ids = Object.keys(values).sort();\n const name =\n ids.length === 0\n ? \"rest\"\n : ids.map((id) => `${id}=${values[id]}`).join(\" \");\n return { name, values };\n}\n\nfunction offenderLine(\n t: FoldTarget,\n hit: FoldHit,\n canvas: { width: number; height: number },\n): string {\n const where =\n \"triangle\" in hit.where\n ? `triangle ${hit.where.triangle}`\n : `cell (${hit.where.col},${hit.where.row})`;\n const { x, y } = hit.rest;\n return (\n `FOLD ${t.kind} ${t.target.kind} ${t.target.id} ${where} ratio ${ratioText(hit.ratio)} ` +\n `pose [${hit.pose.name}] rest at (${x.toFixed(1)}, ${y.toFixed(1)}) model space, ` +\n `(${(canvas.width / 2 + x).toFixed(0)}, ${(canvas.height / 2 - y).toFixed(0)}) model px from the top-left`\n );\n}\n\n/** Two decimals, or two significant figures under 0.01, so a flip a hair\n * under 0 never reads `-0.00`. */\nfunction ratioText(ratio: number): string {\n if (ratio === 0) return \"0\";\n return Math.abs(ratio) < 0.01 ? ratio.toExponential(1) : ratio.toFixed(2);\n}\n","/**\n * Clamp `value` into `[min, max]`.\n *\n * NaN in, NaN out — `Math.max(min, Math.min(max, NaN))` is `NaN`, so this\n * cannot be used to sanitize external input. Anything taking values from a\n * host must reject non-finite input itself before clamping (see\n * {@link ParameterStore.set}).\n */\nexport function clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * Linear interpolation from `a` (at `t = 0`) to `b` (at `t = 1`). Exact at\n * `t = 0` and when `a === b`; at `t = 1` it can differ from `b` by rounding.\n */\nexport function lerp(a: number, b: number, t: number): number {\n return a + (b - a) * t;\n}\n\n/**\n * Smoothstep `x²(3 − 2x)` of `x` clamped to `[0, 1]`: 0 at 0, 1 at 1, with zero\n * slope at both ends, so a fade along it starts and lands without a kink.\n * Exact at 0, 1/2 and 1.\n */\nexport function smoothstep(x: number): number {\n const t = clamp(x, 0, 1);\n return t * t * (3 - 2 * t);\n}\n","import type { IkiParameter } from \"@ikijs/format\";\nimport { clamp } from \"./math\";\n\n/**\n * Holds the live value of every model parameter, clamped to its declared\n * range. This is the single surface a host drives (lip-sync, gaze, blink) and\n * the engine reads each frame to evaluate bindings.\n */\nexport class ParameterStore {\n private readonly params = new Map<string, IkiParameter>();\n private readonly values = new Map<string, number>();\n /**\n * Resting value per id: the declared default clamped into range, resolved\n * ONCE here so `reset()` is a straight copy and a malformed descriptor is\n * reported once rather than on every reset.\n */\n private readonly defaults = new Map<string, number>();\n\n constructor(parameters: IkiParameter[]) {\n for (const param of parameters) {\n this.params.set(param.id, param);\n // A non-finite default would survive `clamp` and poison every read, so it\n // falls back to the neutral in-range value — but say so rather than\n // repairing a broken descriptor silently. `parseIkiModel` requires a\n // finite default, so this only reaches a host that skipped the validator.\n if (!Number.isFinite(param.default)) {\n console.error(\n `Iki: parameter \"${param.id}\" has a non-finite default; resting at the neutral in-range value instead`,\n );\n }\n const base = Number.isFinite(param.default) ? param.default : 0;\n this.defaults.set(param.id, clamp(base, param.min, param.max));\n }\n for (const [id, value] of this.defaults) this.values.set(id, value);\n }\n\n /**\n * Set a parameter's value, clamped to its range. Unknown ids are ignored, as\n * are non-finite values: this is the boundary a host drives with live signals,\n * and `clamp` cannot filter NaN (`Math.max(min, Math.min(max, NaN))` is NaN),\n * so one bad lip-sync/gaze frame would otherwise poison every binding that\n * reads the parameter. A dropped write holds the last good pose.\n */\n set(id: string, value: number): void {\n const param = this.params.get(id);\n if (!param) return;\n if (!Number.isFinite(value)) return;\n this.values.set(id, clamp(value, param.min, param.max));\n }\n\n /** Current value, or 0 if the id is unknown. */\n get(id: string): number {\n return this.values.get(id) ?? 0;\n }\n\n /** Position of a parameter within its range, 0..1. */\n normalized(id: string): number {\n const param = this.params.get(id);\n if (!param || param.max === param.min) return 0;\n return (this.get(id) - param.min) / (param.max - param.min);\n }\n\n /** Reset every parameter to its resting value (see `defaults`). */\n reset(): void {\n for (const [id, value] of this.defaults) this.values.set(id, value);\n }\n\n list(): IkiParameter[] {\n return [...this.params.values()];\n }\n}\n","// --- 2D affine helpers ------------------------------------------------------\n// Affine stored as [a, b, c, d, e, f] => | a c e |\n// | b d f |\n// | 0 0 1 |\nexport type Affine = [number, number, number, number, number, number];\n\nexport function translate(tx: number, ty: number): Affine {\n return [1, 0, 0, 1, tx, ty];\n}\n\nexport function scale(sx: number, sy: number): Affine {\n return [sx, 0, 0, sy, 0, 0];\n}\n\nexport function rotate(degrees: number): Affine {\n const r = (degrees * Math.PI) / 180;\n const c = Math.cos(r);\n const s = Math.sin(r);\n return [c, s, -s, c, 0, 0];\n}\n\nexport function multiply(a: Affine, b: Affine): Affine {\n return [\n a[0] * b[0] + a[2] * b[1],\n a[1] * b[0] + a[3] * b[1],\n a[0] * b[2] + a[2] * b[3],\n a[1] * b[2] + a[3] * b[3],\n a[0] * b[4] + a[2] * b[5] + a[4],\n a[1] * b[4] + a[3] * b[5] + a[5],\n ];\n}\n\n/** Expand a 2D affine into a column-major mat3 for `uniformMatrix3fv`. */\nexport function toMat3(a: Affine): Float32Array {\n return new Float32Array([a[0], a[1], 0, a[2], a[3], 0, a[4], a[5], 1]);\n}\n","import type { IkiGrid2DKeyform, IkiWarp } from \"@ikijs/format\";\nimport type { ParameterStore } from \"./parameter-store\";\n\n/**\n * Accumulate one keyform set's interpolated offsets into `out` (out += ...).\n * Clamps `value` to [keyforms[0].value, keyforms[last].value] (no extrapolation),\n * linearly interpolates the bracketing pair, and adds. `out.length` must be >=\n * each keyform's `offsets.length`. Shared by part-local mesh warps and grid warps.\n */\nexport function accumulateKeyformOffsets(\n keyforms: { value: number; offsets: ArrayLike<number> }[],\n value: number,\n out: Float32Array,\n): void {\n const ks = keyforms;\n\n if (value <= ks[0].value) {\n // Clamp to first keyform.\n const { offsets } = ks[0];\n for (let i = 0; i < offsets.length; i++) {\n out[i] += offsets[i];\n }\n } else if (value >= ks[ks.length - 1].value) {\n // Clamp to last keyform.\n const { offsets } = ks[ks.length - 1];\n for (let i = 0; i < offsets.length; i++) {\n out[i] += offsets[i];\n }\n } else {\n // Find bracketing pair with a linear scan (keyforms are small in practice).\n let lo = ks[0];\n let hi = ks[1];\n for (let k = 1; k < ks.length - 1; k++) {\n if (ks[k].value <= value) {\n lo = ks[k];\n hi = ks[k + 1];\n }\n }\n const t = (value - lo.value) / (hi.value - lo.value);\n const loOff = lo.offsets;\n const hiOff = hi.offsets;\n for (let i = 0; i < loOff.length; i++) {\n out[i] += loOff[i] + (hiOff[i] - loOff[i]) * t;\n }\n }\n}\n\n/**\n * Accumulate a 2D keyform grid's bilinear-interpolated offsets into `out` (out += ...).\n *\n * This is PARAMETER bilinear interpolation driven by two live parameter values\n * (`vx` along `valuesX`, `vy` along `valuesY`). It is DISTINCT from\n * {@link sampleWarpGrid}'s spatial bilinear (which interpolates model-space\n * control-point positions). Name params `tx`/`ty` to avoid confusion with\n * the spatial `s`/`t` in sampleWarpGrid.\n *\n * Contract mirrors {@link accumulateKeyformOffsets}: `out += blended offsets`,\n * pure, deterministic, no allocation inside the function, O(points).\n *\n * Bracket rule (applied identically to X and Y; length ≥ 2 is validator-guaranteed):\n * - v <= values[0] → i = 0, t = 0\n * - v >= values[last] → i = length - 2, t = 1\n * - interior → i such that values[i] <= v < values[i+1], t = (v - values[i]) / (values[i+1] - values[i])\n * This keeps i ∈ [0, length-2] so i+1 is always in range.\n *\n * Corner index (row-major): k(i, j) = j * valuesX.length + i\n */\nexport function accumulate2DKeyformOffsets(\n valuesX: number[],\n valuesY: number[],\n keyforms2d: IkiGrid2DKeyform[],\n vx: number,\n vy: number,\n out: Float32Array,\n): void {\n const lastX = valuesX.length - 1;\n const lastY = valuesY.length - 1;\n\n // Per-axis bracket: clamp at both ends, interior normal scan.\n let ix: number;\n let tx: number;\n if (vx <= valuesX[0]) {\n ix = 0;\n tx = 0;\n } else if (vx >= valuesX[lastX]) {\n ix = lastX - 1;\n tx = 1;\n } else {\n ix = 0;\n for (let k = 0; k < lastX - 1; k++) {\n if (valuesX[k + 1] <= vx) ix = k + 1;\n }\n tx = (vx - valuesX[ix]) / (valuesX[ix + 1] - valuesX[ix]);\n }\n\n let iy: number;\n let ty: number;\n if (vy <= valuesY[0]) {\n iy = 0;\n ty = 0;\n } else if (vy >= valuesY[lastY]) {\n iy = lastY - 1;\n ty = 1;\n } else {\n iy = 0;\n for (let k = 0; k < lastY - 1; k++) {\n if (valuesY[k + 1] <= vy) iy = k + 1;\n }\n ty = (vy - valuesY[iy]) / (valuesY[iy + 1] - valuesY[iy]);\n }\n\n // Row-major corners: k(i, j) = j * valuesX.length + i.\n const W = valuesX.length;\n const c00 = keyforms2d[iy * W + ix];\n const c10 = keyforms2d[iy * W + ix + 1];\n const c01 = keyforms2d[(iy + 1) * W + ix];\n const c11 = keyforms2d[(iy + 1) * W + ix + 1];\n\n // Per-component bilinear: top/bot over tx, then ty into out.\n const o00 = c00.offsets;\n const o10 = c10.offsets;\n const o01 = c01.offsets;\n const o11 = c11.offsets;\n for (let n = 0; n < o00.length; n++) {\n const top = o00[n] + (o10[n] - o00[n]) * tx;\n const bot = o01[n] + (o11[n] - o01[n]) * tx;\n out[n] += top + (bot - top) * ty;\n }\n}\n\n/**\n * Apply all warps to `rest`, accumulating per-vertex offsets into `out`.\n *\n * - Copies `rest` into `out` first (out = rest).\n * - For each warp: looks up the live parameter value (REAL range, not\n * normalized), clamps to the keyform range (no extrapolation), linearly\n * interpolates the bracketing pair, and ADDS the result to `out`.\n * - No allocation: writes into the caller-supplied `out`. `rest` is never\n * mutated.\n * - `undefined` warps → identity copy (out equals rest).\n */\nexport function applyWarps(\n rest: Float32Array,\n warps: IkiWarp[] | undefined,\n params: ParameterStore,\n out: Float32Array,\n): void {\n out.set(rest);\n\n if (!warps || warps.length === 0) return;\n\n for (const warp of warps) {\n accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), out);\n }\n}\n","import type { IkiWarpDeformer, IkiWarpGrid } from \"@ikijs/format\";\nimport type { Affine } from \"./affine\";\nimport type { ParameterStore } from \"./parameter-store\";\nimport { clamp, lerp } from \"./math\";\nimport { accumulate2DKeyformOffsets, accumulateKeyformOffsets } from \"./warp\";\n\n/** A warp deformer's deformed control grid for one frame. */\nexport interface ResolvedWarpGrid {\n cols: number;\n rows: number;\n /** Deformed control points, MODEL space, length (cols+1)*(rows+1)*2. */\n points: Float32Array;\n}\n\n/**\n * A warp deformer's LOCAL deformed grid: its rest `grid.points` plus the\n * interpolated offsets of EVERY entry of `warps` (each clamped and lerped on\n * its own parameter, then added, so several 1D warps sum) or of `warp2d`, in\n * the deformer's own rest frame — no parent affine. Returns a new array; the\n * rest grid is never written.\n */\nexport function deformWarpGrid(\n d: IkiWarpDeformer,\n params: ParameterStore,\n): Float32Array {\n const points = Float32Array.from(d.grid.points);\n for (const warp of d.warps ?? []) {\n accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), points);\n }\n // 1D xor 2D is validator-enforced; at most one branch contributes per deformer.\n if (d.warp2d !== undefined) {\n accumulate2DKeyformOffsets(\n d.warp2d.valuesX,\n d.warp2d.valuesY,\n d.warp2d.keyforms2d,\n params.get(d.warp2d.parameter),\n params.get(d.warp2d.parameterY),\n points,\n );\n }\n return points;\n}\n\n/**\n * `affine` applied to every [x, y] of a flat point list, into `out` — a NEW\n * array unless one is given — so the input (a warp's local grid, which a\n * matrix child's rigid frame still reads) is left as is.\n */\nexport function transformGridPoints(\n points: ArrayLike<number>,\n affine: Affine,\n): Float32Array;\nexport function transformGridPoints<T extends Float32Array | Float64Array>(\n points: ArrayLike<number>,\n affine: Affine,\n out: T,\n): T;\nexport function transformGridPoints(\n points: ArrayLike<number>,\n affine: Affine,\n out: Float32Array | Float64Array = new Float32Array(points.length),\n): Float32Array | Float64Array {\n for (let i = 0; i < points.length; i += 2) {\n const x = points[i];\n const y = points[i + 1];\n out[i] = affine[0] * x + affine[2] * y + affine[4];\n out[i + 1] = affine[1] * x + affine[3] * y + affine[5];\n }\n return out;\n}\n\n/** A model-space point bound to a rest-grid cell with within-cell (s,t). */\nexport interface GridBinding {\n /** row*cols + col index of the containing cell. */\n cell: number;\n /** [0,1] within-cell horizontal, 0 at the left (smaller-x) edge. */\n s: number;\n /** [0,1] within-cell vertical, 0 at the TOP (larger-y) edge. */\n t: number;\n}\n\n/**\n * Bind a model-space point to the REST grid: computes the containing cell +\n * local (s,t) by linear mapping over the grid's actual column/row boundaries.\n * Out-of-bounds points clamp to an edge cell with s/t pinned to 0/1. Never\n * returns NaN. Do NOT call against a deformed grid.\n *\n * The rest grid is validated to be a regular axis-aligned lattice with EXACT\n * ordering, so boundaries are read DIRECTLY from `restGrid.points` (no sorting):\n * - row-major, +y up; row 0 = TOP (LARGEST y, y DECREASES with row index);\n * - column 0 = LEFT (smallest x, x INCREASES with column index).\n * Column x-boundaries are row 0's x values `points[col*2]`; row y-boundaries are\n * column 0's y values `points[(row*(cols+1))*2 + 1]`. Maps x left→right and y\n * top→bottom: `s = (x - xLeft)/(xRight - xLeft)`, `t = (yTop - y)/(yTop - yBottom)`\n * (numerator `yTop - y`, NOT `y - minY`, so rows are not vertically flipped).\n */\nexport function bindPointToRestGrid(\n x: number,\n y: number,\n restGrid: IkiWarpGrid,\n): GridBinding {\n const { cols, rows, points } = restGrid;\n const stride = cols + 1;\n\n // Column boundaries: row 0's x values, increasing with column index.\n let col = cols - 1;\n for (let c = 0; c < cols; c++) {\n const xRight = points[(c + 1) * 2];\n if (x < xRight) {\n col = c;\n break;\n }\n }\n const xLeft = points[col * 2];\n const xRight = points[(col + 1) * 2];\n const s = clamp((x - xLeft) / (xRight - xLeft), 0, 1);\n\n // Row boundaries: column 0's y values, decreasing with row index (top→bottom).\n let row = rows - 1;\n for (let r = 0; r < rows; r++) {\n const yBottom = points[(r + 1) * stride * 2 + 1];\n if (y > yBottom) {\n row = r;\n break;\n }\n }\n const yTop = points[row * stride * 2 + 1];\n const yBottom = points[(row + 1) * stride * 2 + 1];\n const t = clamp((yTop - y) / (yTop - yBottom), 0, 1);\n\n return { cell: row * cols + col, s, t };\n}\n\n/**\n * Compute model-space positions for a warp-deformer child's mesh vertices:\n * transform each LOCAL-space vertex by `partAffine`, rebind to the RAW rest\n * grid, and bilinear-sample the deformed grid. Writes `out` (length ===\n * localVerts.length). Affine layout [a,b,c,d,e,f]: x'=a*x+c*y+e, y'=b*x+d*y+f.\n */\nexport function applyWarpToChild(\n localVerts: Float32Array | number[],\n partAffine: Affine,\n restGrid: IkiWarpGrid,\n deformedGrid: ResolvedWarpGrid,\n out: Float32Array,\n): void {\n const n = localVerts.length / 2;\n for (let v = 0; v < n; v++) {\n const lx = localVerts[v * 2];\n const ly = localVerts[v * 2 + 1];\n const mx = partAffine[0] * lx + partAffine[2] * ly + partAffine[4];\n const my = partAffine[1] * lx + partAffine[3] * ly + partAffine[5];\n const binding = bindPointToRestGrid(mx, my, restGrid);\n const [sx, sy] = sampleWarpGrid(deformedGrid, binding);\n out[v * 2] = sx;\n out[v * 2 + 1] = sy;\n }\n}\n\n/**\n * Bilinear-sample a deformed grid at a binding, returning model-space [x, y].\n * Reads the 4 corner control points of `binding.cell` from `grid.points`, using\n * the SAME row/col convention as `bindPointToRestGrid` (s left→right between\n * col and col+1, t top→bottom between row and row+1).\n */\nexport function sampleWarpGrid(\n grid: ResolvedWarpGrid,\n binding: GridBinding,\n): [number, number] {\n const { cols, points } = grid;\n const stride = cols + 1;\n const row = Math.floor(binding.cell / cols);\n const col = binding.cell % cols;\n const { s, t } = binding;\n\n const i00 = (row * stride + col) * 2;\n const i10 = (row * stride + col + 1) * 2;\n const i01 = ((row + 1) * stride + col) * 2;\n const i11 = ((row + 1) * stride + col + 1) * 2;\n\n // Top edge: lerp p00→p10 by s; bottom edge: lerp p01→p11 by s.\n const topX = points[i00] + (points[i10] - points[i00]) * s;\n const topY = points[i00 + 1] + (points[i10 + 1] - points[i00 + 1]) * s;\n const botX = points[i01] + (points[i11] - points[i01]) * s;\n const botY = points[i01 + 1] + (points[i11 + 1] - points[i01 + 1]) * s;\n\n // Vertical: lerp top→bottom by t.\n return [topX + (botX - topX) * t, topY + (botY - topY) * t];\n}\n\n/**\n * Rigid frame of a matrix deformer hung from a warp: returns\n * `translate(p') · rotate(θ) · translate(−p)`, where `p` is `pivot` bound to the\n * RAW rest grid and `p'` is that binding sampled on `localPoints`, the warp's\n * LOCAL deformed grid (rest + keyform offsets, no ancestor affine — the caller\n * composes that on top). θ is the rotation part (polar decomposition) of the\n * bilinear cell's Jacobian at the binding, each tangent divided by the rest\n * cell's width/height so the rest grid gives θ = 0. The warp's scale and shear\n * are deliberately dropped: a narrowing torso warp moves the head but never\n * squashes it.\n */\nexport function warpRigidFrame(\n pivot: { x: number; y: number },\n restGrid: IkiWarpGrid,\n localPoints: Float32Array,\n): Affine {\n const { cols, rows } = restGrid;\n const binding = bindPointToRestGrid(pivot.x, pivot.y, restGrid);\n const [px, py] = sampleWarpGrid({ cols, rows, points: localPoints }, binding);\n\n const stride = cols + 1;\n const row = Math.floor(binding.cell / cols);\n const col = binding.cell % cols;\n const { s, t } = binding;\n const i00 = (row * stride + col) * 2;\n const i10 = (row * stride + col + 1) * 2;\n const i01 = ((row + 1) * stride + col) * 2;\n const i11 = ((row + 1) * stride + col + 1) * 2;\n\n const rest = restGrid.points;\n // Same boundaries as bindPointToRestGrid (row 0's x, column 0's y): the\n // validator tolerates 1e-6 of jitter elsewhere, which can zero a cell's own\n // corner difference.\n const cellWidth = rest[(col + 1) * 2] - rest[col * 2];\n const cellHeight =\n rest[row * stride * 2 + 1] - rest[(row + 1) * stride * 2 + 1];\n\n // Images of the rest x/y axes. t runs top→bottom, i.e. against +y, hence\n // the minus on ey.\n const q = localPoints;\n const exX = lerp(q[i10] - q[i00], q[i11] - q[i01], t) / cellWidth;\n const exY =\n lerp(q[i10 + 1] - q[i00 + 1], q[i11 + 1] - q[i01 + 1], t) / cellWidth;\n const eyX = -lerp(q[i01] - q[i00], q[i11] - q[i10], s) / cellHeight;\n const eyY =\n -lerp(q[i01 + 1] - q[i00 + 1], q[i11 + 1] - q[i10 + 1], s) / cellHeight;\n\n // A collapsed cell gives atan2(0, 0) = 0: the frame stays finite.\n const theta = Math.atan2(exY - eyX, exX + eyY);\n const c = Math.cos(theta);\n const sn = Math.sin(theta);\n return [\n c,\n sn,\n -sn,\n c,\n px - (c * pivot.x - sn * pivot.y),\n py - (sn * pivot.x + c * pivot.y),\n ];\n}\n","import type {\n IkiBinding,\n IkiDeformer,\n IkiDeformerBinding,\n IkiDeformerTransform,\n IkiMatrixDeformer,\n IkiTransform,\n IkiWarpDeformer,\n} from \"@ikijs/format\";\nimport { type Affine, multiply, rotate, scale, translate } from \"./affine\";\nimport type { ParameterStore } from \"./parameter-store\";\nimport {\n type ResolvedWarpGrid,\n deformWarpGrid,\n transformGridPoints,\n warpRigidFrame,\n} from \"./warp-grid\";\n\n/** Resolved TRS + opacity from a transform + bindings at current parameter values. */\nexport interface ResolvedTransform {\n x: number;\n y: number;\n rotation: number;\n scaleX: number;\n scaleY: number;\n opacity: number;\n}\n\nconst IDENTITY_TRANSFORM: Required<IkiTransform> = {\n x: 0,\n y: 0,\n rotation: 0,\n scaleX: 1,\n scaleY: 1,\n opacity: 1,\n};\n\n/**\n * Shared transform evaluator: resolves the effective TRS + opacity from a\n * (possibly absent) base transform plus bindings at current parameter values.\n *\n * - Part callers pass `IkiTransform` (which may include opacity) and use all 6\n * fields including `opacity`.\n * - Deformer callers pass `IkiDeformerTransform` (no opacity field) and\n * `IkiDeformerBinding[]` (no opacity channel); the returned `opacity` is\n * always 1 on the deformer path and should be ignored by the caller.\n */\nexport function evaluateTransform(\n transform: IkiTransform | IkiDeformerTransform | undefined,\n bindings: IkiBinding[] | IkiDeformerBinding[] | undefined,\n params: ParameterStore,\n): ResolvedTransform {\n const base = transform ?? IDENTITY_TRANSFORM;\n const result: ResolvedTransform = {\n x: base.x,\n y: base.y,\n rotation: base.rotation ?? 0,\n scaleX: base.scaleX ?? 1,\n scaleY: base.scaleY ?? 1,\n opacity: (base as IkiTransform).opacity ?? 1,\n };\n\n for (const binding of bindings ?? []) {\n const t = params.normalized(binding.parameter);\n const value = binding.from + (binding.to - binding.from) * t;\n switch (binding.channel) {\n case \"translateX\":\n result.x += value;\n break;\n case \"translateY\":\n result.y += value;\n break;\n case \"rotate\":\n result.rotation += value;\n break;\n case \"scaleX\":\n result.scaleX += value;\n break;\n case \"scaleY\":\n result.scaleY += value;\n break;\n case \"opacity\":\n result.opacity *= value;\n break;\n }\n }\n\n return result;\n}\n\n/**\n * Build the local deformer matrix about its pivot:\n * translate(pivot) · TRS · translate(-pivot)\n */\nfunction deformerLocalMatrix(\n d: IkiMatrixDeformer,\n params: ParameterStore,\n): Affine {\n const t = evaluateTransform(d.transform, d.bindings, params);\n const trs: Affine = multiply(\n multiply(translate(t.x, t.y), rotate(t.rotation)),\n scale(t.scaleX, t.scaleY),\n );\n return multiply(\n multiply(translate(d.pivot.x, d.pivot.y), trs),\n translate(-d.pivot.x, -d.pivot.y),\n );\n}\n\n/** Every deformer of a model resolved for one frame. */\nexport interface ResolvedDeformers {\n /** Matrix deformer id → world affine. */\n worlds: Map<string, Affine>;\n /** Warp deformer id → deformed control grid, model space. */\n grids: Map<string, ResolvedWarpGrid>;\n}\n\n/**\n * A warp's grid before its parent affine, and that affine (absent at a root)\n * — what a matrix child of the warp reads its rigid frame from.\n */\ninterface LocalWarp {\n localGrid: Float32Array;\n parentWorld: Affine | undefined;\n}\n\n/**\n * Resolve every deformer — matrix worlds and warp grids — in topological\n * order, regardless of array ordering.\n *\n * The validator guarantees the hierarchy is acyclic, that every `parent` id\n * exists and that no warp hangs from a warp; the engine resolves on-demand\n * with memoization so any valid array order is handled correctly.\n *\n * Throws a clear internal Error if a parent is unexpectedly absent or a warp\n * hangs from a warp (defense-in-depth — indicates an unvalidated model was\n * passed to the engine).\n */\nexport function resolveDeformers(\n deformers: IkiDeformer[],\n params: ParameterStore,\n): ResolvedDeformers {\n const byId = new Map<string, IkiDeformer>(deformers.map((d) => [d.id, d]));\n const worlds = new Map<string, Affine>();\n const grids = new Map<string, ResolvedWarpGrid>();\n const localWarps = new Map<string, LocalWarp>();\n\n function parentOf(d: IkiDeformer): IkiDeformer | undefined {\n if (d.parent === undefined) return undefined;\n const parent = byId.get(d.parent);\n if (!parent) {\n throw new Error(\n `unresolved deformer parent \"${d.parent}\" — model not validated?`,\n );\n }\n return parent;\n }\n\n function resolveWorld(d: IkiMatrixDeformer): Affine {\n const cached = worlds.get(d.id);\n if (cached) return cached;\n\n const local = deformerLocalMatrix(d, params);\n const parent = parentOf(d);\n let world: Affine;\n if (parent === undefined) {\n world = local;\n } else if (parent.kind === \"warp\") {\n // The frame comes off the warp's LOCAL grid and the warp's own parent\n // affine goes on top — the same order the grid itself is resolved in,\n // so a rest warp between two matrices changes nothing.\n const warp = resolveWarp(parent);\n const ridden = multiply(\n warpRigidFrame(d.pivot, parent.grid, warp.localGrid),\n local,\n );\n world = warp.parentWorld ? multiply(warp.parentWorld, ridden) : ridden;\n } else {\n world = multiply(resolveWorld(parent), local);\n }\n\n worlds.set(d.id, world);\n return world;\n }\n\n function resolveWarp(d: IkiWarpDeformer): LocalWarp {\n const cached = localWarps.get(d.id);\n if (cached) return cached;\n\n const parent = parentOf(d);\n if (parent?.kind === \"warp\") {\n throw new Error(\n `warp deformer \"${d.id}\" hangs from warp \"${parent.id}\" — model not validated?`,\n );\n }\n const parentWorld = parent && resolveWorld(parent);\n // ORDER IS CRITICAL: keyform offsets FIRST (curvature added in the rest\n // frame), parent affine SECOND — so the curvature rotates WITH the parent\n // head rather than staying pinned to world axes. The reversed order\n // (affine then offsets) pushes the bend along world-x even when the head\n // is turned (coordinate bug).\n const localGrid = deformWarpGrid(d, params);\n grids.set(d.id, {\n cols: d.grid.cols,\n rows: d.grid.rows,\n points: parentWorld\n ? transformGridPoints(localGrid, parentWorld)\n : localGrid,\n });\n\n const resolved = { localGrid, parentWorld };\n localWarps.set(d.id, resolved);\n return resolved;\n }\n\n for (const d of deformers) {\n if (d.kind === \"warp\") resolveWarp(d);\n else resolveWorld(d);\n }\n\n return { worlds, grids };\n}\n","import type { IkiOcclusion } from \"@ikijs/format\";\n\n/**\n * How far a part is hidden at the key parameter's `value`: linear between the\n * stops, held before the first and after the last (one stop is a constant).\n * The player and the rig gate both read it, so they cannot disagree. Exact at\n * every stop. Infinities read as the first or last stop; NaN reads as past the\n * last stop (no comparison with it holds), so the last stop's amount.\n */\nexport function occlusionAmount(\n occlusion: Pick<IkiOcclusion, \"stops\">,\n value: number,\n): number {\n const { stops } = occlusion;\n const first = stops[0];\n if (value <= first.value) return first.amount;\n for (let i = 1; i < stops.length; i++) {\n const hi = stops[i];\n if (value <= hi.value) {\n const lo = stops[i - 1];\n const t = (value - lo.value) / (hi.value - lo.value);\n return lo.amount * (1 - t) + hi.amount * t;\n }\n }\n return stops[stops.length - 1].amount;\n}\n","import { type IkiParameter, StandardParameter } from \"@ikijs/format\";\nimport { MAX_DT_MS } from \"./frame-clock\";\nimport { clamp, lerp, smoothstep } from \"./math\";\n\n// --- Module-internal timing/easing constants -----------------------------------\n// These are intentionally private; tests assert observable behavior, not config.\n\nconst BLINK_INTERVAL_MIN_MS = 1500;\nconst BLINK_INTERVAL_MAX_MS = 6000;\n// A blink closes fast and opens slower, with a moment shut in between. The\n// human blink-kinematics literature has the down-phase at roughly a third of\n// the whole and the up-phase decelerating into the open pose. These three are\n// a judgement inside the 150–180 ms range.\nconst BLINK_CLOSE_MS = 60;\nconst BLINK_HOLD_MS = 20;\nconst BLINK_OPEN_MS = 100;\nconst BLINK_DURATION_MS = BLINK_CLOSE_MS + BLINK_HOLD_MS + BLINK_OPEN_MS; // 180\n// Share of blinks followed by a second one, a short beat after the first\n// reopens. The second never draws the coin, so a pair never runs to three.\nconst DOUBLE_BLINK_P = 0.18;\nconst DOUBLE_BLINK_GAP_MS = 70;\n// How far the brows drop below their resting value (BrowLY/RY units) with the\n// lids fully shut; the dip scales with how closed each eye is.\nconst BROW_BLINK_DIP = 0.06;\n\n// A breath rises over the first 40 % of its cycle, falls by 88 %, and rests\n// at empty for the rest: inhaling is quicker than exhaling, with a pause\n// before the next. Each cycle draws its own length, so the rhythm never ticks.\nconst BREATH_IN_END = 0.4;\nconst BREATH_OUT_END = 0.88;\nconst BREATH_PERIOD_MIN_MS = 3200;\nconst BREATH_PERIOD_MAX_MS = 4600;\n// Degrees the head lifts (AngleY) at full breath.\nconst BREATH_PITCH_DEG = 1;\n\n// --- Tuning: gaze ----------------------------------------------------------------\n// The eyes hold a point, then jump: each retarget comes after a uniform wait.\nconst GAZE_RETARGET_MIN_MS = 800;\nconst GAZE_RETARGET_MAX_MS = 3300;\n// Share of retargets that come back to the viewer, (0, 0) exactly.\nconst GAZE_EYE_CONTACT_P = 0.4;\n// Half-widths of the uniform box the other retargets land in, gaze units.\nconst GAZE_X_MAX = 0.8;\nconst GAZE_Y_MAX = 0.5;\n// The eye springs: stiff, so a jump lands within ~0.3 s, and damped close to\n// critical so it barely overshoots.\nconst EYE_SPRING_OMEGA = 16;\nconst EYE_SPRING_ZETA = 0.9;\n// Degrees the head turns (X) and nods (Y) per unit of gaze target. The soft\n// head spring chases the same target as the stiff eye one, so the eyes lead\n// and the head follows. Same signs: + is the viewer's right and up for both.\nconst HEAD_FOLLOW_X_DEG = 10;\nconst HEAD_FOLLOW_Y_DEG = 10;\n\n// --- Tuning: the head idle -----------------------------------------------------\n// Retune these by eye. Each head axis is a soft spring chasing its own seeded\n// noise, so the head drifts, settles and pauses instead of tracing a sine.\n//\n// Peak noise in degrees per axis — small against the ±30° standard AngleX/Y/Z\n// range. Roll stays under the turn: a tilt reads much larger than a turn of\n// the same degrees. The spring can overshoot these by a few percent.\nconst HEAD_NOISE_AMP_X_DEG = 6;\nconst HEAD_NOISE_AMP_Y_DEG = 4;\nconst HEAD_NOISE_AMP_Z_DEG = 4;\n// Noise lattice points per second. Distinct rates so the axes never move in step.\nconst HEAD_NOISE_RATE_X_HZ = 0.18;\nconst HEAD_NOISE_RATE_Y_HZ = 0.15;\nconst HEAD_NOISE_RATE_Z_HZ = 0.12;\n// Angular frequency (rad/s) and damping ratio of the head springs: soft enough\n// to round off the noise, damped enough that a stop barely overshoots.\nconst HEAD_SPRING_OMEGA = 7.4;\nconst HEAD_SPRING_ZETA = 0.72;\n// The springs start at 0 but the noise rarely does; fading the targets in over\n// this long keeps the head from lurching to its first noise value on load.\n// Under ~4 s the fade outruns the noise's own steady speed on some seeds.\nconst HEAD_NOISE_EASE_IN_MS = 4000;\n// Longest spring integration slice. Semi-implicit Euler holds while ω·h stays\n// well under 2, so 8 ms keeps even a stiff ω = 16 stable at the 100 ms dt cap.\nconst SPRING_SUBSTEP_MS = 8;\n\n// Ambient sway: the drift hair physics follows in idle, where the head idle\n// alone barely moves it. Two near-coprime periods (29:43) inside 2.5–5 s; the\n// breath draws a new length each cycle, so the two never stay in step. The\n// amplitudes sum to exactly ±1, the parameter's range. Zero phase, so the resting pose writes 0\n// and it takes no rng draw (the blink and gaze schedules keep their sequence).\nconst AMBIENT_AMP_A = 0.6;\nconst AMBIENT_PERIOD_A_MS = 2900;\nconst AMBIENT_AMP_B = 0.4;\nconst AMBIENT_PERIOD_B_MS = 4300;\n\n// --- Small pure helpers -------------------------------------------------------\n\n/**\n * Eye-open value over one blink, `phase` ∈ [0, 1]: 1 at both ends, 0 across the\n * hold. Close is a smoothstep (soft start, soft landing on the lid); open is a\n * quadratic ease-out (the lid leaves the hold at speed and settles). Exported\n * for the shape tests; not part of the package entry.\n */\nexport function blinkEnvelope(phase: number): number {\n const ms = phase * BLINK_DURATION_MS;\n if (ms <= 0) return 1;\n if (ms < BLINK_CLOSE_MS) return 1 - smoothstep(ms / BLINK_CLOSE_MS);\n if (ms <= BLINK_CLOSE_MS + BLINK_HOLD_MS) return 0; // inclusive: the close point is exactly 0 for any retune\n if (ms < BLINK_DURATION_MS) {\n const t = (ms - BLINK_CLOSE_MS - BLINK_HOLD_MS) / BLINK_OPEN_MS;\n return 1 - (1 - t) * (1 - t);\n }\n return 1;\n}\n\n/**\n * Breath value over one cycle, `phase` ∈ [0, 1]: a smoothstep rise from 0 to 1\n * by BREATH_IN_END, a smoothstep fall back to 0 by BREATH_OUT_END, then 0.\n * Exported for the shape tests; not part of the package entry.\n */\nexport function breathEnvelope(phase: number): number {\n if (phase < BREATH_IN_END) return smoothstep(phase / BREATH_IN_END);\n return (\n 1 - smoothstep((phase - BREATH_IN_END) / (BREATH_OUT_END - BREATH_IN_END))\n );\n}\n\n/** Draw a 32-bit integer seed from a [0, 1) rng. */\nfunction drawSeed(rng: () => number): number {\n return Math.floor(rng() * 0x100000000) | 0;\n}\n\n/** Lattice value in [-1, 1) for integer `i`, a fixed integer mix of seed and index. */\nfunction latticeValue(seed: number, i: number): number {\n let h = Math.imul(i, 0x27d4eb2d) ^ seed;\n h = Math.imul(h ^ (h >>> 15), 0x2c1b3c6d);\n h = Math.imul(h ^ (h >>> 12), 0x297a2d39);\n h ^= h >>> 15;\n return (h >>> 0) / 0x80000000 - 1;\n}\n\n/**\n * 1D value noise in [-1, 1): lattice values eased with smoothstep, so the\n * slope is zero at every lattice point — the head eases into each one.\n */\nfunction valueNoise(seed: number, x: number): number {\n const i = Math.floor(x);\n return lerp(\n latticeValue(seed, i),\n latticeValue(seed, i + 1),\n smoothstep(x - i),\n );\n}\n\n/**\n * Two octaves of value noise, the second at double rate and half amplitude,\n * divided by the summed amplitudes so the result stays within ±1. Every\n * first-octave lattice point is also a second-octave one, so both slopes\n * vanish together there and the head comes to a real pause.\n */\nfunction fbm(seed: number, x: number): number {\n return (\n (valueNoise(seed, x) + 0.5 * valueNoise(seed ^ 0x5bd1e995, 2 * x)) / 1.5\n );\n}\n\n/** A damped spring chasing a moving target. */\nclass Spring {\n value = 0;\n velocity = 0;\n\n constructor(\n private readonly omega: number,\n private readonly zeta: number,\n ) {}\n\n /** Advance `dtMs` toward `target` by semi-implicit Euler in short slices. */\n step(target: number, dtMs: number): void {\n const slices = Math.ceil(dtMs / SPRING_SUBSTEP_MS);\n const h = dtMs / slices / 1000;\n for (let s = 0; s < slices; s++) {\n const accel =\n this.omega * this.omega * (target - this.value) -\n 2 * this.zeta * this.omega * this.velocity;\n this.velocity += accel * h;\n this.value += this.velocity * h;\n }\n }\n}\n\n// --- Public API ---------------------------------------------------------------\n\nexport interface IdleMotionOptions {\n /** Inject a deterministic rng for testing. Defaults to Math.random. */\n rng?: () => number;\n /**\n * The model's declared parameters. When they include BrowLeftY or\n * BrowRightY, that brow dips a little below its resting value (the default,\n * clamped into range) with each blink; otherwise idle writes no brow.\n */\n parameters?: readonly IkiParameter[];\n}\n\n/**\n * Pure-logic idle-animation driver: the \"life\" a model shows when nothing\n * else moves it. It writes, through the sink, the nine standard ids EyeOpen\n * L/R, Breath, EyeballX/Y, AngleX/Y/Z and AmbientSway, plus BrowLY/RY when\n * the model declares them (see {@link IdleMotionOptions.parameters});\n * `drivenParameterIds` lists them in write order.\n *\n * - Blink: both eyes together, at random intervals, some in quick pairs.\n * Each declared brow dips a little below its rest as the lids close. The\n * dip follows idle's blink, not the eye shown: under an expression that\n * holds the eyes shut, the brows still dip a little on each idle blink.\n * - Breath: rises faster than it falls, then rests at 0, each cycle drawing\n * its own length so the rhythm never ticks.\n * - Eyes lead, head follows: the gaze holds a point, then jumps to the next\n * (or back to the viewer) on stiff springs. The head is one soft spring\n * per axis chasing a seeded two-octave noise, so it drifts, settles and\n * pauses; on the turn and nod it also chases the gaze target, so it\n * arrives after the eyes. The nod lifts a little with each breath. That\n * lift and the follow are part of the head channel, so a declared `Idle`\n * motion group drops them with the rest of the head (see IkiMotion).\n * - AmbientSway: two slow sines for hair physics to follow in idle.\n *\n * A host holds the gaze on a point of its own (a pointer, a face tracker)\n * with {@link setGazeTarget}, which drives the eyes and the head follow as a\n * scheduled pick does; the scheduled jumps resume on {@link clearGazeTarget}.\n *\n * Everything runs on an internal clock that advances by the clamped frame\n * delta, so tab-backgrounding or irregular frame delivery can't produce\n * teleports or snap-close blinks. The blink and breath shapes, the head\n * noise (once seeded) and the ambient sway are pure functions of that clock.\n * The rng draws the first blink and gaze retarget, the three head noise\n * seeds and the first breath length in the constructor, then each blink\n * interval and double-blink coin, each gaze retarget (target and wait) and\n * each breath length as it runs. Host gaze calls draw nothing, so they leave\n * the sequence unchanged. The tuning constants (timings, amplitudes, spring\n * stiffness) are module-private, at the top of this file.\n *\n * Usage:\n * const idle = new IdleMotion(player.setParameter.bind(player), {\n * parameters: model.parameters, // for the brows' blink dip\n * });\n * // inside your rAF loop:\n * idle.update(performance.now());\n *\n * The host is responsible for scheduling; this class has no timers or rAF.\n */\nexport class IdleMotion {\n /**\n * Every parameter id {@link update} and `emitRestingPose` write, in write\n * order. Published so a host (or IkiMotion) can restore them after it\n * stops driving — keep in step with those two methods; the test suite\n * pins this list to the actual emissions.\n */\n readonly drivenParameterIds: readonly string[];\n private readonly sink: (id: string, value: number) => void;\n private readonly rng: () => number;\n /** The declared brow Y ids the blink dip writes, with their resting values. */\n private readonly brows: readonly { id: string; rest: number }[];\n\n // Internal clock: advances by clamped dt, NOT by raw wall-clock jumps.\n // This is the only clock blink/breath/gaze scheduling reads.\n private clockMs = 0;\n private prevNowMs: number | undefined = undefined;\n\n // Blink state\n private nextBlinkAtMs: number;\n private blinkStartMs = -1; // -1 means not currently blinking\n // Whether the blink scheduled (or running) is the second of a pair.\n private blinkIsSecond = false;\n\n // Gaze state: the scheduled pick starts at eye contact, (0, 0), until the\n // first retarget. A host target, while set, replaces the pick as what the\n // eyes and head chase; the schedule keeps picking underneath it.\n private readonly eyeX = new Spring(EYE_SPRING_OMEGA, EYE_SPRING_ZETA);\n private readonly eyeY = new Spring(EYE_SPRING_OMEGA, EYE_SPRING_ZETA);\n private gazeTargetX = 0;\n private gazeTargetY = 0;\n private nextGazeRetargetMs: number;\n private hostGaze: { x: number; y: number } | undefined = undefined;\n\n // Breath state: the current cycle's start and length on the internal clock.\n private breathStartMs = 0;\n private breathPeriodMs: number;\n\n // Head state: one noise seed and one spring per axis (X turn, Y nod, Z roll).\n private readonly headSeedX: number;\n private readonly headSeedY: number;\n private readonly headSeedZ: number;\n private readonly headX = new Spring(HEAD_SPRING_OMEGA, HEAD_SPRING_ZETA);\n private readonly headY = new Spring(HEAD_SPRING_OMEGA, HEAD_SPRING_ZETA);\n private readonly headZ = new Spring(HEAD_SPRING_OMEGA, HEAD_SPRING_ZETA);\n\n constructor(\n sink: (id: string, value: number) => void,\n options?: IdleMotionOptions,\n ) {\n this.sink = sink;\n // Math.random is the single allowed default reference; all other uses go\n // through this.rng so tests can inject a deterministic substitute.\n this.rng = options?.rng ?? Math.random;\n this.brows = [StandardParameter.BrowLeftY, StandardParameter.BrowRightY]\n .map((id) => options?.parameters?.find((p) => p.id === id))\n .filter((p) => p !== undefined)\n .map((p) => ({ id: p.id, rest: clamp(p.default, p.min, p.max) }));\n this.drivenParameterIds = [\n StandardParameter.EyeOpenLeft,\n StandardParameter.EyeOpenRight,\n ...this.brows.map((b) => b.id),\n StandardParameter.Breath,\n StandardParameter.EyeballX,\n StandardParameter.EyeballY,\n StandardParameter.AngleX,\n StandardParameter.AngleY,\n StandardParameter.AngleZ,\n StandardParameter.AmbientSway,\n ];\n\n // Schedule the first blink and gaze retarget relative to clock zero.\n this.nextBlinkAtMs = lerp(\n BLINK_INTERVAL_MIN_MS,\n BLINK_INTERVAL_MAX_MS,\n this.rng(),\n );\n this.nextGazeRetargetMs = lerp(\n GAZE_RETARGET_MIN_MS,\n GAZE_RETARGET_MAX_MS,\n this.rng(),\n );\n // Drawn after the blink and gaze schedules so those keep their draws.\n this.headSeedX = drawSeed(this.rng);\n this.headSeedY = drawSeed(this.rng);\n this.headSeedZ = drawSeed(this.rng);\n // Last, so every draw above keeps its place in the sequence.\n this.breathPeriodMs = this.drawBreathPeriod();\n }\n\n /**\n * Advance the idle animation to the given wall-clock timestamp (milliseconds).\n *\n * On the first call: record prevNowMs, emit the resting pose, and return —\n * no animation advance happens so there is no jump from time 0.\n *\n * On subsequent calls: compute dt = clamp(nowMs - prevNowMs, 0, MAX_DT_MS)\n * and advance the internal clock by dt. A non-monotonic nowMs produces a\n * negative raw delta that the clamp floors to 0 — no rewind.\n */\n update(nowMs: number): void {\n // Host-supplied timestamp, same boundary rule as FixedStepClock.advance and\n // ParameterStore.set: drop the frame, touch nothing. `clockMs += NaN` would\n // stick, and every blink/gaze schedule reads clockMs — the face would go\n // still permanently. A host driving from media time hands you NaN through an\n // ordinary path (`duration * pct` before metadata loads).\n if (!Number.isFinite(nowMs)) return;\n if (this.prevNowMs === undefined) {\n this.prevNowMs = nowMs;\n // Emit resting pose so the host mirror stays in sync from frame 1.\n this.emitRestingPose();\n return;\n }\n\n // Clamp dt so a backgrounded tab or long GC pause advances the internal\n // clock by at most MAX_DT_MS — blink can't snap shut, gaze can't teleport.\n const rawDt = nowMs - this.prevNowMs;\n const dt = clamp(rawDt, 0, MAX_DT_MS);\n this.prevNowMs = nowMs;\n this.clockMs += dt;\n\n // Both eyes always carry the identical value (unified blink).\n const eyeVal = this.advanceBlink();\n this.sink(StandardParameter.EyeOpenLeft, eyeVal);\n this.sink(StandardParameter.EyeOpenRight, eyeVal);\n // Each brow follows its own eye's openness; the unified blink makes the\n // two the same. Written as dip × (eye − 1) so an open eye adds +0.\n for (const { id, rest } of this.brows) {\n this.sink(id, rest + BROW_BLINK_DIP * (eyeVal - 1));\n }\n\n const breath = this.advanceBreath();\n this.advanceGaze(dt);\n\n this.sink(StandardParameter.Breath, breath);\n this.sink(StandardParameter.EyeballX, this.eyeX.value);\n this.sink(StandardParameter.EyeballY, this.eyeY.value);\n\n // The head idle keeps the character (and any hair physics reading\n // AngleX/Y/Z) from freezing solid between blinks. Models without these\n // parameters ignore the writes (ParameterStore drops unknown ids).\n this.advanceHead(dt, breath);\n this.sink(StandardParameter.AngleX, this.headX.value);\n this.sink(StandardParameter.AngleY, this.headY.value);\n this.sink(StandardParameter.AngleZ, this.headZ.value);\n this.sink(StandardParameter.AmbientSway, this.ambientSway());\n }\n\n /**\n * Hold the gaze on (`x`, `y`), in EyeballX/Y units (+ is the viewer's right\n * and up), until {@link clearGazeTarget}: the eyes chase it on their stiff\n * springs and the head follows it on the turn and nod, as it follows a\n * scheduled pick. Each value is clamped to [-1, 1], so the follow can reach\n * past the scheduled picks' ±0.8 / ±0.5 box. A pair with a non-finite value\n * is ignored and changes nothing, the same boundary rule as\n * ParameterStore.set.\n *\n * The scheduled retargets keep running and drawing from the rng while a host\n * target is set, so the rng sequence does not depend on host calls.\n */\n setGazeTarget(x: number, y: number): void {\n if (!Number.isFinite(x) || !Number.isFinite(y)) return;\n this.hostGaze = { x: clamp(x, -1, 1), y: clamp(y, -1, 1) };\n }\n\n /**\n * Drop the host target: the eyes and head turn back to the current\n * scheduled pick at once (a pointer leaving does not leave the eyes frozen\n * until the next retarget), and later picks drive them as before.\n */\n clearGazeTarget(): void {\n this.hostGaze = undefined;\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private emitRestingPose(): void {\n this.sink(StandardParameter.EyeOpenLeft, 1);\n this.sink(StandardParameter.EyeOpenRight, 1);\n for (const { id, rest } of this.brows) this.sink(id, rest);\n // Breath at phase 0: the start of an inhale, empty.\n this.sink(StandardParameter.Breath, 0);\n this.sink(StandardParameter.EyeballX, 0);\n this.sink(StandardParameter.EyeballY, 0);\n // The head springs start at rest at 0 — the head starts centered.\n this.sink(StandardParameter.AngleX, 0);\n this.sink(StandardParameter.AngleY, 0);\n this.sink(StandardParameter.AngleZ, 0);\n this.sink(StandardParameter.AmbientSway, 0);\n }\n\n /** Returns the current eye-open value (0..1) and advances blink state. */\n private advanceBlink(): number {\n const { clockMs } = this;\n\n // If a blink is in progress, evaluate the envelope.\n if (this.blinkStartMs >= 0) {\n const phase = (clockMs - this.blinkStartMs) / BLINK_DURATION_MS;\n if (phase >= 1) {\n // Blink finished — schedule the next one on the internal clock: the\n // second of a pair after a short beat, else after the usual interval.\n // Only a first blink draws the coin.\n this.blinkStartMs = -1;\n this.blinkIsSecond = !this.blinkIsSecond && this.rng() < DOUBLE_BLINK_P;\n this.nextBlinkAtMs =\n clockMs +\n (this.blinkIsSecond\n ? DOUBLE_BLINK_GAP_MS\n : lerp(BLINK_INTERVAL_MIN_MS, BLINK_INTERVAL_MAX_MS, this.rng()));\n return 1;\n }\n return blinkEnvelope(phase);\n }\n\n // Check if it is time to start a new blink.\n if (clockMs >= this.nextBlinkAtMs) {\n this.blinkStartMs = clockMs;\n // Return the first envelope sample (exactly 1 at phase 0).\n return blinkEnvelope(0);\n }\n\n // Between blinks: eyes fully open.\n return 1;\n }\n\n /**\n * Returns the breath value (0..1), starting the next cycle, with a freshly\n * drawn length, once the current one has run out. One clamped dt (≤ 100 ms)\n * is far shorter than any cycle, so a step crosses at most one boundary.\n */\n private advanceBreath(): number {\n if (this.clockMs - this.breathStartMs >= this.breathPeriodMs) {\n this.breathStartMs += this.breathPeriodMs;\n this.breathPeriodMs = this.drawBreathPeriod();\n }\n return breathEnvelope(\n (this.clockMs - this.breathStartMs) / this.breathPeriodMs,\n );\n }\n\n private drawBreathPeriod(): number {\n return lerp(BREATH_PERIOD_MIN_MS, BREATH_PERIOD_MAX_MS, this.rng());\n }\n\n /**\n * Step each head spring toward its axis noise at the internal clock, plus,\n * on the turn and nod, the gaze target scaled to degrees, and on the nod the\n * breath's lift. Only the noise fades in: the scheduled pick starts at\n * (0, 0), so it has no start value to lurch to, and its first jump is no\n * larger than any later one; the breath starts empty, at 0.\n */\n private advanceHead(dt: number, breath: number): void {\n const seconds = this.clockMs / 1000;\n const easeIn = smoothstep(this.clockMs / HEAD_NOISE_EASE_IN_MS);\n this.headX.step(\n easeIn *\n HEAD_NOISE_AMP_X_DEG *\n fbm(this.headSeedX, seconds * HEAD_NOISE_RATE_X_HZ) +\n HEAD_FOLLOW_X_DEG * (this.hostGaze?.x ?? this.gazeTargetX),\n dt,\n );\n this.headY.step(\n easeIn *\n HEAD_NOISE_AMP_Y_DEG *\n fbm(this.headSeedY, seconds * HEAD_NOISE_RATE_Y_HZ) +\n HEAD_FOLLOW_Y_DEG * (this.hostGaze?.y ?? this.gazeTargetY) +\n BREATH_PITCH_DEG * breath,\n dt,\n );\n this.headZ.step(\n easeIn *\n HEAD_NOISE_AMP_Z_DEG *\n fbm(this.headSeedZ, seconds * HEAD_NOISE_RATE_Z_HZ),\n dt,\n );\n }\n\n /** Ambient sway (-1..1), pure function of the internal clock. */\n private ambientSway(): number {\n const t = 2 * Math.PI * this.clockMs;\n return (\n AMBIENT_AMP_A * Math.sin(t / AMBIENT_PERIOD_A_MS) +\n AMBIENT_AMP_B * Math.sin(t / AMBIENT_PERIOD_B_MS)\n );\n }\n\n /**\n * Step the eye springs toward the gaze target, the host's while set, else\n * the scheduled pick; retarget on the internal clock either way.\n */\n private advanceGaze(dt: number): void {\n // Retarget check reads clockMs so a clamped pause can't skip retargets.\n if (this.clockMs >= this.nextGazeRetargetMs) {\n if (this.rng() < GAZE_EYE_CONTACT_P) {\n this.gazeTargetX = 0;\n this.gazeTargetY = 0;\n } else {\n this.gazeTargetX = lerp(-GAZE_X_MAX, GAZE_X_MAX, this.rng());\n this.gazeTargetY = lerp(-GAZE_Y_MAX, GAZE_Y_MAX, this.rng());\n }\n this.nextGazeRetargetMs =\n this.clockMs +\n lerp(GAZE_RETARGET_MIN_MS, GAZE_RETARGET_MAX_MS, this.rng());\n }\n this.eyeX.step(this.hostGaze?.x ?? this.gazeTargetX, dt);\n this.eyeY.step(this.hostGaze?.y ?? this.gazeTargetY, dt);\n }\n}\n","import { clamp } from \"./math\";\n\n/** Per-frame dt ceiling: a backgrounded tab or a long GC pause must not snap state. */\nexport const MAX_DT_MS = 100;\n/** Fixed integration sub-step, in SECONDS. */\nexport const FIXED_DT_S = 1 / 60;\n/** Catch-up cap per frame (spiral-of-death guard). */\nexport const MAX_SUBSTEPS = 6;\n\n/**\n * Fixed-timestep accumulator shared by the physics drivers, so a stability fix\n * lands in one place instead of one of two near-identical copies.\n *\n * A driver calls {@link advance} once per frame and runs its integration body\n * that many times. Leftover time carries to the next frame, which is what keeps\n * the simulation frame-rate independent; the dt clamp and the sub-step cap keep\n * a hitch from either snapping the rig or spiralling into catch-up work.\n */\nexport class FixedStepClock {\n private prevNowMs: number | undefined = undefined;\n private accumulatorS = 0;\n\n /**\n * True until the first {@link advance}. Drivers seed their rest pose on that\n * frame and integrate nothing, so a model loaded mid-motion does not kick.\n */\n get isSeedFrame(): boolean {\n return this.prevNowMs === undefined;\n }\n\n /**\n * Time carried in the accumulator, in seconds: how far the frame's timestamp is\n * past the last whole sub-step. Drivers extrapolate their state by it so what\n * they emit is the state at the frame's time, not at the last sub-step.\n */\n get remainderS(): number {\n return this.accumulatorS;\n }\n\n /**\n * Fold `nowMs` into the accumulator and return how many {@link FIXED_DT_S}\n * sub-steps to run this frame. On the seed frame it only records the\n * timestamp and returns 0. A non-monotonic `nowMs` floors to 0 — no rewind.\n */\n advance(nowMs: number): number {\n // Host-supplied timestamp, so the same rule as ParameterStore.set: reject\n // non-finite input at the boundary. `clamp(NaN, ...)` is NaN, which would\n // make the accumulator NaN and every `NaN >= FIXED_DT_S` false FOREVER —\n // the rig would freeze silently with no way back. Pre-existing; hardened\n // here so both host entry points behave the same way.\n if (!Number.isFinite(nowMs)) return 0;\n if (this.prevNowMs === undefined) {\n this.prevNowMs = nowMs;\n return 0;\n }\n const dtMs = clamp(nowMs - this.prevNowMs, 0, MAX_DT_MS);\n this.prevNowMs = nowMs;\n this.accumulatorS += dtMs / 1000; // boundary ms->s conversion\n\n let steps = 0;\n while (this.accumulatorS >= FIXED_DT_S && steps < MAX_SUBSTEPS) {\n this.accumulatorS -= FIXED_DT_S;\n steps++;\n }\n return steps;\n }\n}\n","import {\n type IkiParameter,\n type IkiPhysics,\n physicsInputs,\n} from \"@ikijs/format\";\nimport { FIXED_DT_S, FixedStepClock } from \"./frame-clock\";\nimport { clamp } from \"./math\";\n\n// --- Small pure helpers ------------------------------------------------------\n\n/**\n * Map a parameter value to [-1, 1] around its engine-effective default. Portable\n * across param ranges: the wider side (rest→max vs min→rest) sets the unit, so\n * ±1 lands at the farther extreme. Returns 0 for a zero-width range.\n *\n * The rest center is `clamp(default, min, max)` to match ParameterStore, which\n * clamps an out-of-range default — so the spring rests where the model actually\n * renders, not at a raw out-of-range default.\n */\nfunction signedNormalized(\n value: number,\n param: { min: number; max: number; default: number },\n): number {\n const rest = clamp(param.default, param.min, param.max);\n const den = Math.max(Math.abs(param.max - rest), Math.abs(rest - param.min));\n if (den === 0) return 0;\n return clamp((value - rest) / den, -1, 1);\n}\n\n// --- Public API --------------------------------------------------------------\n\ninterface RigState {\n x: number; // spring position (lagging, normalized-ish units)\n v: number; // spring velocity\n lag: number; // Σ wᵢ·nᵢ over the lag inputs, as the last finite frame read it\n}\n\n/** One input of a rig, resolved once so the frame loop never branches on shape. */\ninterface RigInput {\n parameter: string;\n weight: number;\n lag: boolean;\n}\n\n/**\n * Host-agnostic 1D spring-mass-damper secondary-motion driver — the physics\n * peer of {@link IdleMotion}. For each rig it reads every input parameter,\n * signed-normalizes it around its default × `weight`, sums those into one spring\n * target `T`, integrates a lagging spring position `x` with semi-implicit\n * (symplectic) Euler on a fixed 1/60s sub-step accumulator, and writes\n * `outputDefault + (x − L) * scale` (x carried forward by the clock's leftover time) onto the output parameter, `L` being the\n * lag inputs' share of `T` — so the output lags and overshoots the inputs\n * (hair/accessory sway).\n *\n * By superposition a follow input's held value stays in the output (the spring\n * settles at `T`), while a lag input's held value settles out, returning the\n * output to rest: it swings only while that input moves. A rig seeded with a\n * lag input already displaced emits rest, without a kick. Inputs are not\n * smoothed, so a one-frame step on a lag input snaps the output by\n * `−scale·weight·Δn` before the spring catches up — deferred until a captured\n * snap calls for a rate limit.\n *\n * Usage:\n * const physics = new PhysicsMotion(\n * model.physics ?? [],\n * model.parameters,\n * (id) => currentValue(id),\n * player.setParameter.bind(player),\n * );\n * // inside your rAF loop, right AFTER idle.update(now):\n * physics.update(performance.now());\n *\n * The host schedules updates; this class has no timers, rAF, DOM, or Date.now.\n * Writes go through the sink, exactly like IdleMotion; the player renders the\n * updated params on its own render loop (drivers and rendering are decoupled).\n */\nexport class PhysicsMotion {\n /** The output parameter of every rig, in rig order — what `emit` writes. */\n readonly drivenParameterIds: readonly string[];\n /**\n * Per rig: how many times the finiteness guard reset its state or `emit`\n * replaced its non-finite product. Up to two per frame, so guard activations,\n * not repaired frames. A diagnostic; emitted values are unchanged.\n */\n readonly resets: readonly number[];\n private readonly resetCounts: number[];\n private readonly rigs: readonly IkiPhysics[];\n private readonly inputs: readonly (readonly RigInput[])[];\n private readonly read: (id: string) => number;\n private readonly sink: (id: string, value: number) => void;\n private readonly params: Map<string, IkiParameter>;\n\n // Integrator state, owned here — never stored in a ParameterStore.\n private readonly state: RigState[];\n private readonly clock = new FixedStepClock();\n\n constructor(\n rigs: IkiPhysics[],\n params: IkiParameter[],\n read: (id: string) => number,\n sink: (id: string, value: number) => void,\n ) {\n this.rigs = rigs;\n this.inputs = rigs.map((rig) =>\n physicsInputs(rig).map(({ parameter, weight, mode }) => ({\n parameter,\n weight,\n lag: mode === \"lag\",\n })),\n );\n this.read = read;\n this.sink = sink;\n this.params = new Map(params.map((p) => [p.id, p]));\n this.state = rigs.map(() => ({ x: 0, v: 0, lag: 0 }));\n this.drivenParameterIds = rigs.map((rig) => rig.output.parameter);\n this.resetCounts = rigs.map(() => 0);\n this.resets = this.resetCounts;\n }\n\n /**\n * Advance every rig to the given wall-clock timestamp (milliseconds).\n *\n * First call: seed each spring to rest AT its current target (so a model\n * loaded with a nonzero input does not kick: a lag input emits rest, a follow\n * input its value), emit that output, and return without integrating —\n * mirroring IdleMotion's first-frame behavior.\n *\n * A non-finite `nowMs` after that is a dropped frame: every rig re-emits its\n * last output from its stored state without reading its inputs.\n *\n * Subsequent calls: {@link FixedStepClock} folds the clamped frame delta into\n * its accumulator and returns how many {@link FIXED_DT_S} sub-steps are due;\n * the spring advances that many semi-implicit Euler steps, then each rig emits\n * its output once. The clock's dt clamp and sub-step cap plus the symplectic\n * integrator are what keep it stable across hitches.\n */\n update(nowMs: number): void {\n if (this.clock.isSeedFrame) {\n this.clock.advance(nowMs);\n for (let i = 0; i < this.rigs.length; i++) {\n const st = this.state[i];\n const { target, lag } = this.targetFor(i);\n st.x = target;\n st.v = 0;\n st.lag = lag;\n this.emit(i, st);\n }\n return;\n }\n\n // A dropped frame (the clock rejects it as well). Re-emit from the stored\n // `L` rather than read the inputs, or a lag rig's output would move on it.\n if (!Number.isFinite(nowMs)) {\n for (let i = 0; i < this.rigs.length; i++) this.emit(i, this.state[i]);\n return;\n }\n\n const steps = this.clock.advance(nowMs);\n\n // update() is synchronous, so the inputs cannot change mid-loop — read each\n // rig's target ONCE per frame and reuse it across the sub-steps.\n const targets = this.rigs.map((_, i) => this.targetFor(i));\n\n for (let s = 0; s < steps; s++) {\n for (let i = 0; i < this.rigs.length; i++) {\n this.step(this.rigs[i], this.state[i], targets[i].target);\n }\n }\n\n // Always emit (even when zero sub-steps ran) so the sink stays in sync.\n for (let i = 0; i < this.rigs.length; i++) {\n const st = this.state[i];\n // The fixed 1/60s sub-step can diverge for an extreme-but-parse-valid rig\n // (tiny mass / huge stiffness push ω·dt past the explicit-integrator\n // stability limit). If state goes non-finite, snap back to rest at the\n // current target: the store DROPS a non-finite write, so an un-reset rig\n // would emit NaN every frame and silently freeze the part at its last\n // good pose instead of visibly diverging.\n const { target, lag } = targets[i];\n if (!Number.isFinite(st.x) || !Number.isFinite(st.v)) {\n st.x = Number.isFinite(target) ? target : 0;\n st.v = 0;\n this.resetCounts[i]++;\n }\n st.lag = lag;\n this.emit(i, st);\n }\n }\n\n /**\n * Rig `index`'s spring target `T` = Σ signed-normalized input value × weight,\n * and `L`, the lag inputs' share of it. Reads each input once.\n */\n private targetFor(index: number): { target: number; lag: number } {\n let target = 0;\n let lag = 0;\n for (const input of this.inputs[index]) {\n const param = this.params.get(input.parameter);\n const value = this.read(input.parameter);\n const share = (param ? signedNormalized(value, param) : 0) * input.weight;\n target += share;\n if (input.lag) lag += share;\n }\n return { target, lag };\n }\n\n /** One semi-implicit (symplectic) Euler sub-step of FIXED_DT_S seconds. */\n private step(rig: IkiPhysics, st: RigState, target: number): void {\n const accel =\n (rig.stiffness * (target - st.x) - rig.damping * st.v) / rig.mass;\n st.v += accel * FIXED_DT_S;\n st.x += st.v * FIXED_DT_S;\n }\n\n /** Write outputDefault + (x − L) * scale onto the output param via the sink. */\n private emit(index: number, st: RigState): void {\n const rig = this.rigs[index];\n const outParam = this.params.get(rig.output.parameter);\n // clamp to match ParameterStore's engine-effective default (see signedNormalized).\n const outDefault = outParam\n ? clamp(outParam.default, outParam.min, outParam.max)\n : 0;\n // `x` only moves in whole sub-steps while `lag` is this frame's, so emit x\n // carried forward by the time since its last sub-step: the output then\n // follows the frame's time, not how many sub-steps happened to be due.\n // Extrapolating (not interpolating from the previous state) adds no lag, and\n // at rest (v = 0) it changes nothing.\n const x = st.x + st.v * this.clock.remainderS;\n const value = outDefault + (x - st.lag) * rig.output.scale;\n // Final guard: even a finite-but-enormous `x` could overflow the product to\n // ±Infinity. Emit the rest pose rather than hand a non-finite value to the\n // sink, which would drop the write and leave the output stuck where it was.\n const finite = Number.isFinite(value);\n if (!finite) this.resetCounts[index]++;\n this.sink(rig.output.parameter, finite ? value : outDefault);\n }\n}\n","import type {\n IkiDeformer,\n IkiParameter,\n IkiPhysicsChain,\n IkiPhysicsChainSegment,\n} from \"@ikijs/format\";\nimport type { Affine } from \"./affine\";\nimport { resolveDeformers } from \"./deform\";\n// The two physics drivers stay independent of EACH OTHER; the timing primitives\n// they both need live in frame-clock.ts so a stability fix lands once.\nimport { FIXED_DT_S, FixedStepClock } from \"./frame-clock\";\nimport { clamp } from \"./math\";\nimport { ParameterStore } from \"./parameter-store\";\n\nconst DEG2RAD = Math.PI / 180;\nconst RAD2DEG = 180 / Math.PI;\n\n// --- Per-chain / per-segment state -------------------------------------------\n\n/** Integrator state for one segment. angle = θ displacement in RADIANS. */\ninterface SegmentState {\n angle: number; // θ_i in radians (displacement from rest)\n angularVelocity: number; // ω_i in radians/s\n}\n\n/** All precomputed per-chain data (rest angles already in radians). */\ninterface ChainData {\n chain: IkiPhysicsChain;\n restAnglesRad: number[]; // restAngle_j in radians; 0 when omitted\n state: SegmentState[]; // preallocated, length = segments.length\n}\n\n// --- Public API --------------------------------------------------------------\n\n/**\n * Host-agnostic multi-segment angular-pendulum-chain secondary-motion driver.\n * Peer of {@link PhysicsMotion} and {@link IdleMotion}.\n *\n * Each chain anchors to a matrix deformer in the model hierarchy. The driver\n * self-computes the anchor's world rotation via `resolveDeformers` (a\n * private `ParameterStore` is filled from `read` ONCE per frame) and integrates\n * a per-segment angular pendulum with semi-implicit Euler on a fixed 1/60s\n * sub-step accumulator. Each segment's angular displacement θ (in radians\n * internally) is emitted in DEGREES on its output parameter, so `rotate = 0`\n * when the chain is at its authored rest pose.\n *\n * Usage:\n * const chains = new HairChainMotion(\n * model.physicsChains ?? [],\n * model.parameters,\n * model.deformers ?? [],\n * (id) => currentValue(id),\n * player.setParameter.bind(player),\n * );\n * // inside your rAF loop, right AFTER physics.update(now):\n * chains.update(performance.now());\n *\n * The host schedules updates; this class has no timers, rAF, DOM, or Date.now.\n */\nexport class HairChainMotion {\n /** Every segment's output, chain by chain — what `emitSegment` writes. */\n readonly drivenParameterIds: readonly string[];\n /**\n * Per segment, in `drivenParameterIds` order: how many times the finiteness\n * guard reset its state or `emitSegment` replaced its non-finite product. Up\n * to two per frame, so guard activations, not repaired frames. A diagnostic;\n * emitted values are unchanged.\n */\n readonly resets: readonly number[];\n private readonly resetCounts: number[];\n private readonly chainData: ChainData[];\n private readonly params: Map<string, IkiParameter>;\n private readonly deformers: IkiDeformer[];\n private readonly store: ParameterStore;\n private readonly read: (id: string) => number;\n private readonly sink: (id: string, value: number) => void;\n\n private readonly clock = new FixedStepClock();\n\n constructor(\n chains: IkiPhysicsChain[],\n params: IkiParameter[],\n deformers: IkiDeformer[],\n read: (id: string) => number,\n sink: (id: string, value: number) => void,\n ) {\n this.params = new Map(params.map((p) => [p.id, p]));\n this.deformers = deformers;\n // Private ParameterStore reused every frame for anchor-world resolution.\n this.store = new ParameterStore(params);\n this.read = read;\n this.sink = sink;\n\n // Precompute rest angles in radians; preallocate segment state (no per-substep alloc).\n this.chainData = chains.map((chain) => ({\n chain,\n restAnglesRad: chain.segments.map((seg) =>\n seg.restAngle !== undefined ? seg.restAngle * DEG2RAD : 0,\n ),\n state: chain.segments.map(() => ({ angle: 0, angularVelocity: 0 })),\n }));\n this.drivenParameterIds = chains.flatMap((c) =>\n c.segments.map((s) => s.output.parameter),\n );\n this.resetCounts = this.drivenParameterIds.map(() => 0);\n this.resets = this.resetCounts;\n }\n\n /**\n * Advance every chain to the given wall-clock timestamp (milliseconds).\n *\n * First call: seed every segment to θ=0/ω=0 (rest), emit the rest output\n * (outDefault + 0), and return without integrating — mirrors PhysicsMotion's\n * first-frame behavior so a model loaded in motion does not kick.\n *\n * Subsequent calls: dt = clamp(nowMs - prevNowMs, 0, MAX_DT_MS) → seconds into\n * accumulator. The per-frame world snapshot (anchor world angles) is taken ONCE\n * per update() — NOT per chain — so all chains share a consistent frame snapshot.\n * Fixed FIXED_DT_S sub-steps are run root→tip, capped at MAX_SUBSTEPS; leftover\n * time is carried to the next frame. Segments emit after substeps (even on zero\n * substeps) with a non-finite guard.\n */\n update(nowMs: number): void {\n // IkiMotion steps this driver every frame even for a chainless model;\n // with nothing to integrate or emit, skip the per-frame deformer resolve.\n if (this.chainData.length === 0) return;\n if (this.clock.isSeedFrame) {\n // FIRST FRAME: seed rest, emit outDefault for every segment, NO integration.\n this.clock.advance(nowMs);\n let flat = 0;\n for (const cd of this.chainData) {\n for (let i = 0; i < cd.chain.segments.length; i++) {\n cd.state[i].angle = 0;\n cd.state[i].angularVelocity = 0;\n this.emitSegment(flat++, cd.chain.segments[i], cd.state[i]);\n }\n }\n return;\n }\n\n const steps = this.clock.advance(nowMs);\n\n // Take the per-frame world snapshot ONCE per update() — NOT per chain.\n // Fill the private store from read, then resolve every deformer (warp grids\n // too, though only the matrix worlds are read here).\n for (const param of this.params.values()) {\n this.store.set(param.id, this.read(param.id));\n }\n const worldMap = resolveDeformers(this.deformers, this.store).worlds;\n\n // Read each chain's anchor world angle ONCE per frame (consistent across substeps,\n // like physics-motion.ts:122 `targets`).\n const anchorAnglesRad = this.chainData.map((cd) =>\n this.anchorWorldAngleRad(worldMap, cd.chain.anchorDeformer),\n );\n\n for (let s = 0; s < steps; s++) {\n for (let c = 0; c < this.chainData.length; c++) {\n this.stepChain(this.chainData[c], anchorAnglesRad[c]);\n }\n }\n\n // Emit always (even on zero substeps) so the sink stays in sync.\n let flat = 0;\n for (const cd of this.chainData) {\n for (let i = 0; i < cd.chain.segments.length; i++) {\n const st = cd.state[i];\n // FINITENESS GUARD (mirror physics-motion.ts:141): a pathological rig\n // (tiny mass / huge stiffness) can push the fixed-substep integrator\n // past its explicit-stability limit. Snap the segment back to rest so\n // a validated model can never poison the sink with NaN/Infinity.\n if (\n !Number.isFinite(st.angle) ||\n !Number.isFinite(st.angularVelocity)\n ) {\n st.angle = 0;\n st.angularVelocity = 0;\n this.resetCounts[flat]++;\n }\n this.emitSegment(flat++, cd.chain.segments[i], st);\n }\n }\n }\n\n /**\n * Extract world rotation (radians) from the anchor's Affine tuple.\n * Affine = [a,b,c,d,e,f]; rotation column = (a,b) → atan2(b,a).\n *\n * If the anchor id is absent from the map, THROWS an internal Error — the\n * format validator guarantees the anchor exists, so absence is an invariant\n * break (mirrors resolveDeformers' throw on an unresolved parent).\n */\n private anchorWorldAngleRad(\n worldMap: Map<string, Affine>,\n anchorId: string,\n ): number {\n const world = worldMap.get(anchorId);\n if (!world) {\n throw new Error(\n `HairChainMotion: anchor deformer \"${anchorId}\" not found in resolved world map — model not validated?`,\n );\n }\n // Affine [a,b,c,d,e,f]: the first column (a,b) is the x-axis direction\n // after rotation, so atan2(b,a) gives the world rotation angle in radians.\n return Math.atan2(world[1], world[0]);\n }\n\n /**\n * One fixed sub-step of FIXED_DT_S seconds for all segments in a chain.\n *\n * Segments are integrated ROOT→TIP so each segment can read its upstream\n * neighbor's current-substep state when computing the world angle Φ_i.\n * (The chain is causal root-to-tip; reversing the order would use stale θ\n * values from the previous substep for Φ_i computation.)\n *\n * Per-segment semi-implicit (symplectic) Euler:\n * Φ_i = anchorWorldAngleRad + Σ_{j≤i}(restAngle_j + θ_j)\n * α_i = (−stiffness_i·θ_i − strength·sin(Φ_i − gravityAngle_rad) − damping_i·ω_i) / mass_i\n * ω_i += α_i · FIXED_DT_S (velocity updated FIRST = semi-implicit)\n * θ_i += ω_i · FIXED_DT_S (position updated from NEW velocity)\n *\n * The spring term is −stiffness·θ (restoring θ→0); restAngle does NOT appear\n * in the spring term, only in Φ_i for the gravity torque.\n */\n private stepChain(cd: ChainData, anchorAngleRad: number): void {\n const { chain, restAnglesRad, state } = cd;\n const gravityAngleRad = chain.gravity.angle * DEG2RAD;\n const strength = chain.gravity.strength;\n\n // Accumulate world angle root→tip as we go.\n let worldAngleAccumRad = anchorAngleRad;\n\n for (let i = 0; i < chain.segments.length; i++) {\n const seg: IkiPhysicsChainSegment = chain.segments[i];\n const st = state[i];\n\n // World angle of this segment: anchor + sum of all segments 0..i.\n worldAngleAccumRad += restAnglesRad[i] + st.angle;\n const phi = worldAngleAccumRad;\n\n const alpha =\n (-seg.stiffness * st.angle -\n strength * Math.sin(phi - gravityAngleRad) -\n seg.damping * st.angularVelocity) /\n seg.mass;\n\n // Semi-implicit Euler: update velocity first, then position with new velocity.\n st.angularVelocity += alpha * FIXED_DT_S;\n st.angle += st.angularVelocity * FIXED_DT_S;\n }\n }\n\n /** Emit outDefault + (θ_i · RAD2DEG) · scale for one segment. */\n private emitSegment(\n flat: number,\n seg: IkiPhysicsChainSegment,\n st: SegmentState,\n ): void {\n const outParam = this.params.get(seg.output.parameter);\n const outDefault = outParam\n ? clamp(outParam.default, outParam.min, outParam.max)\n : 0;\n const value = outDefault + st.angle * RAD2DEG * seg.output.scale;\n // Final guard: even a finite-but-enormous θ could overflow to ±Infinity.\n const finite = Number.isFinite(value);\n if (!finite) this.resetCounts[flat]++;\n this.sink(seg.output.parameter, finite ? value : outDefault);\n }\n}\n","import { type IkiModel, StandardParameter } from \"@ikijs/format\";\nimport { ClipPlayer } from \"./clip-player\";\nimport { ExpressionPlayer } from \"./expression-player\";\nimport { MAX_DT_MS } from \"./frame-clock\";\nimport { HairChainMotion } from \"./hair-chain-motion\";\nimport { IdleMotion } from \"./idle-motion\";\nimport { clamp } from \"./math\";\nimport { ParameterStore } from \"./parameter-store\";\nimport { PhysicsMotion } from \"./physics-motion\";\n\n/** IdleMotion's head and gaze: what a declared Idle group replaces. */\nconst HEAD_AND_GAZE: ReadonlySet<string> = new Set([\n StandardParameter.AngleX,\n StandardParameter.AngleY,\n StandardParameter.AngleZ,\n StandardParameter.EyeballX,\n StandardParameter.EyeballY,\n]);\n\n/**\n * Bundles the model's motion into the one loop every host otherwise\n * hand-builds: the procedural {@link IdleMotion}, the model's motion clips and\n * expressions, then {@link PhysicsMotion} and {@link HairChainMotion} — stepped\n * in the order physics and chains depend on, with a record of what they write.\n *\n * Usage:\n * const motion = new IkiMotion(\n * model,\n * (id) => player.getParameter(id),\n * (id, value) => player.setParameter(id, value),\n * );\n * motion.playExpression(\"smile\");\n * motion.playMotion(\"Nod\", 0);\n * // inside your rAF loop:\n * motion.update(performance.now());\n * // then the signals the host owns, e.g. lip-sync:\n * player.setParameter(StandardParameter.MouthOpen, mouth);\n *\n * The model is the catalog: a host lists what it can play from\n * `model.expressions` (ids) and `model.motions` (group names and clip\n * indices). There are no getters for them here.\n *\n * Clips and expressions compose over a base, never over the store's current\n * value: an id's base is the value an earlier stage put in this update's\n * frame (for the one-shot: the procedural idle and the `Idle` loop; for an\n * expression: those and the one-shot), else its resting value\n * `clamp(default, min, max)`. So an `add` on a brow cannot accumulate across\n * frames, and an expression composes with the blink and a clip-driven head.\n * When an expression's stop completes or a one-shot ends, the ids it drove\n * are written once more at base and then dropped; so are the ids only a\n * replaced clip or expression held, once the one replacing it finishes its\n * fade-in. A parameter nothing else writes therefore rests at its default.\n *\n * Idle replacement: when the model declares an `Idle` motion group, its clips\n * loop in place of the procedural head and gaze — IdleMotion's AngleX/Y/Z\n * and EyeballX/Y writes are dropped, and with the head its breath pitch and\n * its follow of the gaze, so {@link setGazeTarget} moves nothing. A head or\n * gaze parameter the Idle clips don't animate is left unwritten by idle and\n * rests where it is (a one-shot or an expression can still drive it). Blink\n * (EyeOpen L/R), Breath and the ambient sway stay procedural: the format\n * rejects an Idle curve on them. The brows' blink dip stays too, as part of\n * the blink; an Idle curve on a brow is written over it. Without an `Idle`\n * group the procedural idle runs whole.\n *\n * The host schedules; this class has no timers, rAF, DOM, or Date.now.\n *\n * Stopping is the host's too: stop calling update(). The drivers leave the\n * pose where it was — a host that wants it back writes its own resting values\n * to `drivenParameterIds`.\n */\nexport class IkiMotion {\n /**\n * Everything {@link update} may write, deduplicated, in this order: idle ids\n * (without head and gaze when the model declares an `Idle` group), the curve\n * parameters of every motion group, expression parameters, rig outputs,\n * then chain-segment outputs. May name ids the model lacks (idle writes the\n * standard ids regardless, and the player silently drops writes to unknown\n * ids) — intersect with the model's parameters if you mirror into your own\n * store.\n */\n readonly drivenParameterIds: readonly string[];\n private readonly sink: (id: string, value: number) => void;\n private readonly idle: IdleMotion;\n private readonly clips: ClipPlayer;\n private readonly expressions: ExpressionPlayer;\n private readonly physics: PhysicsMotion;\n private readonly chains: HairChainMotion;\n /** Resting value per id; 0 for an undeclared id. */\n private readonly rest: (id: string) => number;\n /** This update's idle, clip and expression writes, in first-write order. */\n private readonly frame = new Map<string, number>();\n /** Bound once: `Map.forEach` hands it each entry without a tuple per id. */\n private readonly flush = (value: number, id: string): void =>\n this.sink(id, value);\n private prevNowMs: number | undefined = undefined;\n\n constructor(\n model: IkiModel,\n read: (id: string) => number,\n sink: (id: string, value: number) => void,\n ) {\n const rigs = model.physics ?? [];\n const chains = model.physicsChains ?? [];\n // A store nobody writes holds every parameter at rest, resolved the way\n // the player's store resolves it (a non-finite default rests at 0,\n // clamped), and reads 0 for an undeclared id.\n const restPose = new ParameterStore(model.parameters);\n this.sink = sink;\n this.rest = (id) => restPose.get(id);\n this.clips = new ClipPlayer(model.motions, model.parameters);\n this.expressions = new ExpressionPlayer(\n model.expressions,\n model.parameters,\n );\n const idleKeeps: (id: string) => boolean = this.clips.hasIdleLoop\n ? (id) => !HEAD_AND_GAZE.has(id)\n : () => true;\n this.idle = new IdleMotion(\n (id, value) => {\n if (idleKeeps(id)) this.frame.set(id, value);\n },\n { parameters: model.parameters },\n );\n this.physics = new PhysicsMotion(rigs, model.parameters, read, sink);\n this.chains = new HairChainMotion(\n chains,\n model.parameters,\n model.deformers ?? [],\n read,\n sink,\n );\n this.drivenParameterIds = [\n ...new Set([\n ...this.idle.drivenParameterIds.filter(idleKeeps),\n ...this.clips.parameterIds,\n ...this.expressions.parameterIds,\n ...this.physics.drivenParameterIds,\n ...this.chains.drivenParameterIds,\n ]),\n ];\n }\n\n /**\n * Make expression `id` active, fading it in over its `fadeIn` from the\n * current pose: it replaces the active one and blends from that one's\n * current output, as {@link playMotion} does, so nothing dips toward base on\n * the way. Returns false, and changes nothing, for an id the model does not\n * declare. Playing the active id again changes nothing and returns true; an\n * expression never stacks on itself.\n */\n playExpression(id: string): boolean {\n return this.expressions.play(id);\n }\n\n /** Fade the active expression, if any, back to base over its `fadeOut`. */\n stopExpression(): void {\n this.expressions.stop();\n }\n\n /**\n * Start clip `index` of motion group `group` at once. A running one-shot\n * stops, and the new clip fades in from the old one's last pose. Returns\n * false, and changes nothing, for a group the model does not declare or an\n * index that is not an integer in range. Any group plays one-shot, `Idle`\n * included; there is no queue.\n */\n playMotion(group: string, index: number): boolean {\n return this.clips.play(group, index);\n }\n\n /**\n * Hold the idle gaze on (`x`, `y`) until {@link clearGazeTarget}: the eyes\n * go there and the head follows on the turn and nod, as\n * {@link IdleMotion.setGazeTarget} describes (clamped to [-1, 1]; a pair\n * with a non-finite value is ignored).\n *\n * Under a declared `Idle` motion group this moves nothing: idle's head and\n * gaze writes are dropped, so a host that wants the eyes on a point writes\n * EyeballX/Y itself after {@link update}.\n */\n setGazeTarget(x: number, y: number): void {\n this.idle.setGazeTarget(x, y);\n }\n\n /** Drop the host gaze target; the idle's own gaze resumes. */\n clearGazeTarget(): void {\n this.idle.clearGazeTarget();\n }\n\n /**\n * Advance everything to the same wall-clock timestamp (milliseconds), in\n * this order:\n *\n * 1. Idle writes blink, the declared brows' blink dip, breath, the ambient\n * sway (and head and gaze, unless replaced) into this update's frame.\n * 2. The clip stage writes the `Idle` loop, then the one-shot over it.\n * 3. The expression stage writes the active expression, fading in from the\n * pose it replaced, or a stop fading back to base.\n * 4. The frame goes to `sink`, each id exactly once, in the order its first\n * writer gave it: an expression on EyeOpenL is flushed in idle's slot.\n * 5. Physics, then chains. They read their inputs through `read`, so the\n * springs lag the head this update put on screen (idle sway or clips),\n * and a chain resolves its anchor from that same pose (which may include\n * a physics output). Physics outputs are physics-owned: a clip or\n * expression that writes one is overwritten here.\n *\n * The host writes the signals it owns (lip-sync MouthOpen, brows it drives\n * itself) AFTER update(); the last write wins. That is how lip-sync beats\n * an expression that opens the mouth, and how a host's brow beats idle's\n * blink dip. A host pointer goes through {@link setGazeTarget} instead, so\n * the head follows it; only on a model with an `Idle` group, where that\n * moves nothing, does the host write EyeballX/Y itself after update().\n *\n * The clips and expressions advance by `clamp(now − prev, 0, MAX_DT_MS)`,\n * 0 on the first update. A non-finite `nowMs` is a dropped frame: idle and\n * both players write nothing and do not advance (physics and chains re-emit\n * their outputs unchanged), and the next finite frame measures from the\n * last finite one, as IdleMotion does.\n */\n update(nowMs: number): void {\n this.frame.clear();\n this.idle.update(nowMs);\n if (Number.isFinite(nowMs)) {\n const dtS =\n this.prevNowMs === undefined\n ? 0\n : clamp(nowMs - this.prevNowMs, 0, MAX_DT_MS) / 1000;\n this.prevNowMs = nowMs;\n this.clips.apply(dtS, this.frame, this.rest);\n this.expressions.apply(dtS, this.frame, this.rest);\n }\n this.frame.forEach(this.flush);\n this.physics.update(nowMs);\n this.chains.update(nowMs);\n }\n}\n","import {\n DEFAULT_FADE_SECONDS,\n IDLE_MOTION_GROUP,\n type IkiMotionClip,\n type IkiMotionCurve,\n type IkiParameter,\n} from \"@ikijs/format\";\nimport { clamp, lerp, smoothstep } from \"./math\";\n\n// --- Small pure helpers ------------------------------------------------------\n\n/**\n * The slope at each key of a `\"smooth\"` curve, by Steffen's monotone cubic\n * (M. Steffen, \"A simple method for monotonic interpolation in one\n * dimension\", 1990): each inner key's slope is capped by the slopes of the two\n * lines either side, so no segment overshoots its keys, and it is zero where\n * those lines change direction or one is flat. Chosen over Fritsch–Carlson\n * because it is one closed form per key, with no second pass to rescale. The\n * first and last key get slope zero (not Steffen's own end rule) so the curve\n * meets the holds before and after it without a kink. Exported for the tests;\n * not part of the package entry.\n */\nexport function curveSlopes(keys: IkiMotionCurve[\"keys\"]): number[] {\n const slopes = keys.map(() => 0);\n for (let i = 1; i < keys.length - 1; i++) {\n const [t0, v0] = keys[i - 1];\n const [t1, v1] = keys[i];\n const [t2, v2] = keys[i + 1];\n const h0 = t1 - t0;\n const h1 = t2 - t1;\n const s0 = (v1 - v0) / h0;\n const s1 = (v2 - v1) / h1;\n // The slope at key i of the parabola through the three keys.\n const p = (s0 * h1 + s1 * h0) / (h0 + h1);\n slopes[i] =\n (Math.sign(s0) + Math.sign(s1)) *\n Math.min(Math.abs(s0), Math.abs(s1), Math.abs(p) / 2);\n }\n return slopes;\n}\n\n/**\n * A curve's value at `t` seconds, holding the first key's value before it and\n * the last key's value after it. Between two keys it is a straight line, or,\n * given the keys' `slopes` ({@link curveSlopes}), the cubic Hermite through\n * them. Exported for the tests; not part of the package entry.\n */\nexport function sampleCurve(\n keys: IkiMotionCurve[\"keys\"],\n t: number,\n slopes?: readonly number[],\n): number {\n const first = keys[0];\n if (t <= first[0]) return first[1];\n const last = keys[keys.length - 1];\n if (t >= last[0]) return last[1];\n // first[0] < t < last[0], so the scan stops on a key after `t`; `<=` puts a\n // `t` exactly on a key at the start of its segment, where both forms are\n // exact.\n let i = 1;\n while (keys[i][0] <= t) i++;\n const [t0, v0] = keys[i - 1];\n const [t1, v1] = keys[i];\n const h = t1 - t0;\n const u = (t - t0) / h;\n if (!slopes) return lerp(v0, v1, u);\n // The Hermite basis regrouped: the eased move between the two values, plus\n // each key's slope term, which vanishes at both ends of the segment.\n return (\n lerp(v0, v1, smoothstep(u)) +\n h * u * (1 - u) * (slopes[i - 1] * (1 - u) - slopes[i] * u)\n );\n}\n\n/**\n * The clip's fade-in and fade-out weights at `t` seconds into it, each easing\n * along {@link smoothstep} and clamped to `[0, 1]`. A zero fade gives 1 — no\n * fade on that side. An absent one lasts `DEFAULT_FADE_SECONDS`, capped at\n * half the clip's duration: two absent fades never overlap, so a short clip\n * still reaches full weight, and, like a declared fade, each fits inside the\n * clip: the fade-out never starts before t = 0, so a replacing clip's first\n * frame (wOut = 1) is still the old pose. Exported for the tests; not part of\n * the package entry.\n */\nexport function fadeWeights(\n clip: IkiMotionClip,\n t: number,\n): { wIn: number; wOut: number } {\n const fallback = Math.min(DEFAULT_FADE_SECONDS, clip.duration / 2);\n const fadeIn = clip.fadeIn ?? fallback;\n const fadeOut = clip.fadeOut ?? fallback;\n return {\n wIn: fadeIn > 0 ? smoothstep(t / fadeIn) : 1,\n wOut: fadeOut > 0 ? smoothstep((clip.duration - t) / fadeOut) : 1,\n };\n}\n\n// --- Clip player -------------------------------------------------------------\n\n/** The one-shot slot: one playing clip, no queue. */\ninterface Slot {\n clip: IkiMotionClip;\n /** Seconds since the clip started. */\n t: number;\n /** The pose the clip fades in from: the replaced clip's last output. */\n from: Map<string, number>;\n /**\n * What the slot wrote on its last apply, clamped to each parameter's range;\n * `from` until the first apply, since that is still what is on screen.\n */\n last: Map<string, number>;\n}\n\n/**\n * Plays a model's motion clips into a per-update frame map. Internal to\n * {@link IkiMotion}, which owns the frame: the base rule below only holds\n * inside that frame, so this is not exported from the package entry.\n *\n * Two layers, written in this order on every {@link apply}:\n * - the Idle loop, when the model declares {@link IDLE_MOTION_GROUP}: its clips\n * back-to-back at full weight, wrapping from the last to the first;\n * - the one-shot slot over it, started by {@link play}. A clip blends between\n * the frame's base value and its own curves with its fade-in and fade-out;\n * a new `play` replaces the running clip and fades in from its last output.\n *\n * IkiMotion steps it once per update; this class has no timers, rAF, DOM, or\n * Date.now.\n */\nexport class ClipPlayer {\n /** True when the model declares the {@link IDLE_MOTION_GROUP} group. */\n readonly hasIdleLoop: boolean;\n /** Every curve parameter across all groups, deduplicated, insertion-ordered. */\n readonly parameterIds: readonly string[];\n private readonly motions: Record<string, IkiMotionClip[]>;\n private readonly params: Map<string, IkiParameter>;\n /** Key slopes of every `\"smooth\"` curve; a linear curve has no entry. */\n private readonly slopes: Map<IkiMotionCurve, readonly number[]>;\n\n private readonly idleClips: readonly IkiMotionClip[];\n private readonly idleLength: number;\n private idleIndex = 0;\n /** Seconds into the current Idle clip. */\n private idleTime = 0;\n\n private slot: Slot | undefined = undefined;\n\n constructor(\n motions: Record<string, IkiMotionClip[]> | undefined,\n parameters: IkiParameter[],\n ) {\n this.motions = motions ?? {};\n this.params = new Map(parameters.map((p) => [p.id, p]));\n // Own-property checks throughout: a group named after an Object.prototype\n // member (\"toString\") is not declared.\n this.hasIdleLoop = Object.hasOwn(this.motions, IDLE_MOTION_GROUP);\n this.idleClips = this.hasIdleLoop ? this.motions[IDLE_MOTION_GROUP] : [];\n this.idleLength = this.idleClips.reduce((sum, c) => sum + c.duration, 0);\n const curves = Object.values(this.motions).flatMap((clips) =>\n clips.flatMap((c) => c.curves),\n );\n this.parameterIds = [...new Set(curves.map((curve) => curve.parameter))];\n // Worked out once here, so a frame only evaluates the cubic.\n this.slopes = new Map(\n curves\n .filter((curve) => curve.interpolation !== \"linear\")\n .map((curve) => [curve, curveSlopes(curve.keys)]),\n );\n }\n\n /**\n * Start clip `index` of `group` at once, replacing any running one-shot.\n * Returns false, and changes nothing, for a group the model does not declare\n * or an index that is not an integer in range. Any group plays one-shot,\n * Idle included.\n */\n play(group: string, index: number): boolean {\n if (!Object.hasOwn(this.motions, group)) return false;\n const clips = this.motions[group];\n if (!Number.isInteger(index) || index < 0 || index >= clips.length) {\n return false;\n }\n // The new clip fades in from what the old one last put on screen. Until\n // the new one's first apply the screen still shows `from`, so that is its\n // last output too: a second play before the next apply inherits the same\n // pose instead of dropping the ids the first one never got to write.\n const from = this.slot?.last ?? new Map<string, number>();\n this.slot = { clip: clips[index], t: 0, from, last: from };\n return true;\n }\n\n /**\n * Advance `dtS` seconds and write into `frame`: the Idle loop layer, then\n * the one-shot slot over it.\n *\n * `frame` holds what earlier stages wrote this update. An id's base is its\n * frame value, else `rest(id)` — the parameter's resting value,\n * `clamp(default, min, max)`. The base is never the store's current value,\n * so a clip cannot accumulate across frames.\n */\n apply(\n dtS: number,\n frame: Map<string, number>,\n rest: (id: string) => number,\n ): void {\n if (this.hasIdleLoop) this.applyIdle(dtS, frame);\n if (this.slot) this.applySlot(this.slot, dtS, frame, rest);\n }\n\n /**\n * The Idle clips play as one continuous loop, so their fades are ignored:\n * fading each clip at its seams would dip the pose toward rest on every\n * clip boundary.\n */\n private applyIdle(dtS: number, frame: Map<string, number>): void {\n const clips = this.idleClips;\n let clip = clips[this.idleIndex];\n this.idleTime += dtS;\n if (this.idleTime >= clip.duration) {\n // A frame can cross many clips shorter than a frame. Whole passes of the\n // group land back at this same clip, so dropping them first leaves at\n // most one pass to walk, whatever dt is. The cap on the walk guards\n // float rounding: summing the durations one by one need not match the\n // precomputed total exactly.\n this.idleTime %= this.idleLength;\n for (\n let step = 0;\n step < clips.length && this.idleTime >= clip.duration;\n step++\n ) {\n this.idleTime -= clip.duration;\n this.idleIndex = (this.idleIndex + 1) % clips.length;\n clip = clips[this.idleIndex];\n }\n }\n for (const curve of clip.curves) {\n frame.set(curve.parameter, this.sample(curve, this.idleTime));\n }\n }\n\n private applySlot(\n slot: Slot,\n dtS: number,\n frame: Map<string, number>,\n rest: (id: string) => number,\n ): void {\n const { clip, from } = slot;\n // What earlier stages (and the Idle layer) wrote this update, else rest.\n const base = (id: string): number => frame.get(id) ?? rest(id);\n slot.t += dtS;\n\n if (slot.t >= clip.duration) {\n // One last write at base for every id the slot drove, then the slot is\n // gone: a parameter nothing else writes settles at its default instead\n // of holding the clip's final value.\n const ids = new Set(clip.curves.map((curve) => curve.parameter));\n for (const id of from.keys()) ids.add(id);\n for (const id of ids) frame.set(id, base(id));\n this.slot = undefined;\n return;\n }\n\n // Fade-in moves from the old pose to the new sample; fade-out pulls the\n // result to base. With an empty `from` this is lerp(base, s, wIn * wOut).\n const { wIn, wOut } = fadeWeights(clip, slot.t);\n const last = new Map<string, number>();\n const write = (id: string, sample: number | undefined): void => {\n const b = base(id);\n const f = from.get(id) ?? b;\n const value = lerp(b, lerp(f, sample ?? b, wIn), wOut);\n frame.set(id, value);\n last.set(id, this.displayed(id, value));\n };\n for (const curve of clip.curves) {\n write(curve.parameter, this.sample(curve, slot.t));\n }\n for (const id of from.keys()) if (!last.has(id)) write(id, undefined);\n slot.last = last;\n\n // From here on every value equals the no-`from` value, to rounding, and an\n // id only `from` held was just written at base, to rounding: drop them so\n // they are not written again.\n if (wIn >= 1) from.clear();\n }\n\n /** The curve at `t`, smooth unless it is marked `\"linear\"`. */\n private sample(curve: IkiMotionCurve, t: number): number {\n return sampleCurve(curve.keys, t, this.slopes.get(curve));\n }\n\n /**\n * The clip stage's output for an id, clamped to the parameter's range as\n * the store clamps every write. A replacing clip fades in from this, not\n * the raw value — a curve past the max would otherwise sit still on screen\n * until the fade got back inside the range.\n */\n private displayed(id: string, value: number): number {\n const param = this.params.get(id);\n return param ? clamp(value, param.min, param.max) : value;\n }\n}\n","import {\n DEFAULT_FADE_SECONDS,\n type IkiExpression,\n type IkiExpressionParameter,\n type IkiParameter,\n} from \"@ikijs/format\";\nimport { clamp, lerp, smoothstep } from \"./math\";\n\n/**\n * A parameter's value as a line in its base: `scale · base + offset`. Every\n * blend is one (add c is 1·base + c, multiply c is c·base, overwrite c is\n * 0·base + c) and so is leaving a parameter alone (1·base); a lerp between two\n * lines is a line too. So whatever mix of expressions is on screen, however\n * many were cut off mid-fade, is one line per parameter, and it still follows\n * the live base: a multiply on EyeOpen keeps the blink.\n */\ninterface Line {\n scale: number;\n offset: number;\n}\n\n/** The line of a parameter an expression leaves alone: the base itself. */\nconst BASE: Line = { scale: 1, offset: 0 };\n\nfunction lineOf({ value, blend = \"add\" }: IkiExpressionParameter): Line {\n switch (blend) {\n case \"add\":\n return { scale: 1, offset: value };\n case \"multiply\":\n return { scale: value, offset: 0 };\n case \"overwrite\":\n return { scale: 0, offset: value };\n }\n}\n\n/** The line's value over `base`. */\nfunction at({ scale, offset }: Line, base: number): number {\n return scale * base + offset;\n}\n\n/**\n * {@link lerp}, but exactly `b` at `t = 1` (lerp is exact only at 0): a\n * finished fade lands on its target, and an id it lets go of on base itself.\n */\nfunction mix(a: number, b: number, t: number): number {\n return t === 1 ? b : lerp(a, b, t);\n}\n\n/** What the player can fade to: an expression, or the base itself. */\ninterface Pose {\n /** Undefined for {@link RELEASE}. */\n expression: IkiExpression | undefined;\n /** The parameters it drives, by id. */\n lines: ReadonlyMap<string, Line>;\n}\n\n/** The pose a stop fades to: it drives nothing, so every id goes to base. */\nconst RELEASE: Pose = { expression: undefined, lines: new Map() };\n\n/**\n * The fade in progress: toward `pose`, from the pose on screen when it began.\n */\ninterface Fade {\n pose: Pose;\n /** How long it lasts, in seconds. */\n seconds: number;\n /** Seconds since it began. */\n elapsed: number;\n}\n\n/**\n * The fade's weight, eased along {@link smoothstep} from 0 to 1 over its\n * seconds; at or past its end exactly 1. A zero fade is at 1 the moment it\n * begins, with no division by zero: an expression with a zero `fadeIn` is\n * fully on as soon as it is played, so a stop before the next apply fades it\n * out from full.\n */\nfunction weight({ seconds, elapsed }: Fade): number {\n return elapsed >= seconds ? 1 : smoothstep(elapsed / seconds);\n}\n\n/** An id the player writes on every apply. */\ninterface Held {\n id: string;\n /**\n * Its base on the last apply, where a fold matches the screen (see\n * {@link ExpressionPlayer.begin}); NaN before the first apply.\n */\n base: number;\n}\n\n/**\n * Plays a model's expressions into a per-update frame map. Internal to\n * {@link IkiMotion}, which owns the frame: the base rule below only holds\n * inside that frame, so this is not exported from the package entry.\n *\n * One fade runs at a time, from the pose on screen when it began to its\n * target. {@link play} fades an expression in over its `fadeIn`; {@link stop}\n * fades back to base over the playing expression's `fadeOut`. Either one\n * interrupting a fade starts from where that fade got to, as a replacing\n * motion clip does, so the screen never jumps or dips toward base; unlike a\n * clip's, that starting pose keeps following the live base (see {@link Line}),\n * save a part of it the screen showed held at a range limit, which stays there.\n * Each target is taken over the base, never over what is on screen, so an\n * `add` never stacks on itself however often it is replayed.\n *\n * IkiMotion steps it once per update; this class has no timers, rAF, DOM, or\n * Date.now.\n */\nexport class ExpressionPlayer {\n /** Every expression parameter, deduplicated, insertion-ordered. */\n readonly parameterIds: readonly string[];\n private readonly poses: Map<string, Pose & { expression: IkiExpression }>;\n private readonly params: Map<string, IkiParameter>;\n\n /** Undefined while nothing is held. */\n private fade: Fade | undefined = undefined;\n /**\n * The pose on screen when {@link fade} began, a line per id; empty once the\n * fade has finished, since the screen is then its target alone.\n */\n private from = new Map<string, Line>();\n /** Every id `from` or the fade drives: what each apply writes. */\n private held: Held[] = [];\n\n constructor(\n expressions: IkiExpression[] | undefined,\n parameters: IkiParameter[],\n ) {\n const list = expressions ?? [];\n this.params = new Map(parameters.map((p) => [p.id, p]));\n this.poses = new Map(\n list.map((expression) => [\n expression.id,\n {\n expression,\n lines: new Map(\n expression.parameters.map((p) => [p.parameter, lineOf(p)]),\n ),\n },\n ]),\n );\n this.parameterIds = [\n ...new Set(list.flatMap((e) => e.parameters.map((p) => p.parameter))),\n ];\n }\n\n /**\n * Fade expression `id` in over its `fadeIn`, from what is on screen: the\n * base, or the output of the expression it replaces, or of a stop still\n * fading out. Returns false, and changes nothing, for an expression id the\n * model does not declare; playing the expression already fading in or held\n * changes nothing and returns true.\n */\n play(id: string): boolean {\n const pose = this.poses.get(id);\n if (!pose) return false;\n if (this.fade?.pose === pose) return true;\n this.begin(pose, pose.expression.fadeIn ?? DEFAULT_FADE_SECONDS);\n return true;\n }\n\n /**\n * Fade back to base over the playing expression's `fadeOut`, from what is\n * on screen. Does nothing when nothing is playing or a stop is already\n * fading out.\n */\n stop(): void {\n const playing = this.fade?.pose.expression;\n if (!playing) return;\n this.begin(RELEASE, playing.fadeOut ?? DEFAULT_FADE_SECONDS);\n }\n\n /**\n * Freeze what is on screen into {@link from}, at the weight the current\n * fade has reached, and start a fade from it toward `pose`. Folding keeps\n * this to one `from` and one fade however fast the plays come.\n *\n * {@link apply} clamps each end before it mixes, so each end folds in as\n * the screen showed it at the last apply's base ({@link pinned}): the new\n * fade starts on what was on screen, an end held at a range limit stays\n * there as the base moves, and the rest still follow the live base. Should\n * the base move so far that the old pose would have left the limit, the\n * start holds it instead: a little off, but continuous, and it fades out.\n */\n private begin(pose: Pose, seconds: number): void {\n if (this.fade) {\n const { lines } = this.fade.pose;\n const w = weight(this.fade);\n const from = new Map<string, Line>();\n for (const { id, base } of this.held) {\n const a = this.pinned(id, this.from.get(id) ?? BASE, base);\n const b = this.pinned(id, lines.get(id) ?? BASE, base);\n from.set(id, {\n scale: mix(a.scale, b.scale, w),\n offset: mix(a.offset, b.offset, w),\n });\n }\n this.from = from;\n }\n this.fade = { pose, seconds, elapsed: 0 };\n this.held = [...new Set([...this.from.keys(), ...pose.lines.keys()])].map(\n (id) => ({ id, base: NaN }),\n );\n }\n\n /**\n * Advance `dtS` seconds and write every held id into `frame`: the pose on\n * screen when the fade began, lerped toward the fade's target by its\n * weight, each end clamped to the parameter's range. An id the target does\n * not drive goes to base.\n *\n * `frame` holds what earlier stages wrote this update. A parameter id's base\n * is its frame value, else `rest(id)` — the parameter's resting value,\n * `clamp(default, min, max)`. The base is never the store's current value,\n * so an `add` cannot accumulate across frames.\n */\n apply(\n dtS: number,\n frame: Map<string, number>,\n rest: (id: string) => number,\n ): void {\n // IkiMotion calls this every frame for every model; most hold nothing.\n const fade = this.fade;\n if (!fade) return;\n fade.elapsed += dtS;\n const w = weight(fade);\n const { lines } = fade.pose;\n for (const held of this.held) {\n const { id } = held;\n const base = frame.get(id) ?? rest(id);\n held.base = base;\n const start = this.displayed(id, at(this.from.get(id) ?? BASE, base));\n const end = this.displayed(id, at(lines.get(id) ?? BASE, base));\n frame.set(id, mix(start, end, w));\n }\n if (w < 1) return;\n // The fade is done and the screen is its target alone. An id only `from`\n // drove was just written at base, exactly; dropping it now makes that its\n // last write, so a parameter nothing else writes rests at its default\n // instead of being held. A finished stop drives nothing, so it goes too.\n if (!fade.pose.expression) {\n this.fade = undefined;\n this.from.clear();\n this.held = [];\n } else if (this.from.size > 0) {\n this.from.clear();\n // Kept entries carry their last base into the next fold.\n this.held = this.held.filter(({ id }) => lines.has(id));\n }\n }\n\n /**\n * A value as the screen shows it: clamped to the parameter's range, as the\n * store clamps every write; an id the model does not declare as is. A fade\n * mixes these, so it leaves a value held past the max from the max at once\n * instead of sitting there until the mix gets back inside the range.\n */\n private displayed(id: string, value: number): number {\n const param = this.params.get(id);\n return param ? clamp(value, param.min, param.max) : value;\n }\n\n /**\n * `line`, or, where its value at `base` is past the parameter's range, the\n * constant line at the limit it crossed: the line as the screen shows it\n * there. An id the model does not declare pins nothing, and nor does a NaN\n * base (no apply yet), which compares false both ways.\n */\n private pinned(id: string, line: Line, base: number): Line {\n const param = this.params.get(id);\n if (!param) return line;\n const value = at(line, base);\n if (value > param.max) return { scale: 0, offset: param.max };\n if (value < param.min) return { scale: 0, offset: param.min };\n return line;\n }\n}\n","import {\n type IkiDeformer,\n type IkiMesh,\n type IkiModel,\n type IkiParameter,\n type IkiPart,\n type IkiWarpDeformer,\n StandardParameter as P,\n} from \"@ikijs/format\";\nimport type { Affine } from \"./affine\";\nimport { resolveDeformers } from \"./deform\";\nimport { type LandedPart, landPart, landedPart, staticDeformers } from \"./land\";\nimport { ParameterStore } from \"./parameter-store\";\nimport { deformWarpGrid } from \"./warp-grid\";\n\n/** A parameter setting to check the rig at; every other parameter rests at its default. */\nexport interface FoldPose {\n /** Its sorted `id=value` pairs joined by one space; `rest` when empty. */\n name: string;\n values: Record<string, number>;\n}\n\n/** Where and when a target comes nearest to folding over one class of poses. */\nexport interface FoldHit {\n /** Doubled signed area at the pose over the same at rest. */\n ratio: number;\n /** The warp grid's cell, or the part mesh's triangle (its index into `mesh.indices` / 3). */\n where: { col: number; row: number } | { triangle: number };\n pose: FoldPose;\n /** Where it sits at rest, model space, through the static matrix chain. */\n rest: { x: number; y: number };\n}\n\nexport interface FoldTarget {\n target: { kind: \"deformer\" | \"part\"; id: string };\n /** Read off `worst` alone; `ok` when it is absent. */\n kind: \"flip\" | \"collapse\" | \"ok\";\n /** Least ratio over the poses `expected` rejects (every pose without it). */\n worst?: FoldHit;\n /** Least ratio over the poses `expected` accepts. */\n expected?: FoldHit;\n}\n\nexport interface FoldOptions {\n /** The poses to check; `foldPoses(model)` when absent. */\n poses?: FoldPose[];\n /**\n * Whether `target` closes by design at `pose` (a mouth shut), which keeps a\n * fold there out of `worst`. `value(id)` is the parameter's effective value\n * at the pose: its override, else the clamped default — a pose carries only\n * overrides, so a closure at a default shows only through `value`.\n */\n expected?: (\n target: FoldTarget[\"target\"],\n pose: FoldPose,\n value: (id: string) => number,\n ) => boolean;\n}\n\nexport interface FoldReport {\n /** How many poses were checked. */\n poses: number;\n thresholds: { flip: 0; collapse: 0.1 };\n /** One per warp deformer, then one per mesh part, each in model order. */\n targets: FoldTarget[];\n /** The targets that are not `ok`, worst first. */\n offenders: FoldTarget[];\n}\n\nconst FLIP = 0;\nconst COLLAPSE = 0.1;\n\nconst ANGLES = [\n P.AngleX,\n P.AngleY,\n P.AngleZ,\n P.BodyAngleX,\n P.BodyAngleY,\n P.BodyAngleZ,\n];\n\n/** Crossed with every angle corner, each group's parameters at min then at max together. */\nconst CROSSES = [\n [P.EyeOpenLeft],\n [P.EyeOpenRight],\n [P.MouthOpen],\n [P.ArmLeft, P.ArmRight],\n [P.ElbowLeft, P.ElbowRight],\n];\n\n/**\n * The poses `checkFolds` checks by default: `rest`; every movable parameter\n * alone at its min and at its max; and, on a model declaring any head or body\n * angle, every min/max corner of those angles alone, then crossed with each\n * eye on its own, the mouth, the arms and the elbows (the last two paired)\n * shut/open — 2⁶ + 2⁶ · 2⁵ = 2112 corner poses at most — where moves no single extreme\n * shows stack up. Deduplicated by `name`.\n */\nexport function foldPoses(model: IkiModel): FoldPose[] {\n const byId = new Map(\n model.parameters.filter((p) => p.min !== p.max).map((p) => [p.id, p]),\n );\n const declared = (ids: string[]) => ids.flatMap((id) => byId.get(id) ?? []);\n\n const poses: FoldPose[] = [];\n const names = new Set<string>();\n const add = (values: Record<string, number>) => {\n const name = poseName(values);\n if (names.has(name)) return;\n names.add(name);\n poses.push({ name, values });\n };\n\n add({});\n for (const p of byId.values()) {\n add({ [p.id]: p.min });\n add({ [p.id]: p.max });\n }\n\n const angles = declared(ANGLES);\n if (angles.length === 0) return poses;\n const expand = (\n corners: Record<string, number>[],\n groups: IkiParameter[][],\n ) => {\n for (const group of groups) {\n corners = corners.flatMap((values) =>\n ([\"min\", \"max\"] as const).map((end) => {\n const next = { ...values };\n for (const p of group) next[p.id] = p[end];\n return next;\n }),\n );\n }\n return corners;\n };\n // The angle corners alone come first: the other parameters rest at their\n // defaults there, which no min/max cross reaches.\n const angleCorners = expand(\n [{}],\n angles.map((p) => [p]),\n );\n for (const values of angleCorners) add(values);\n const crosses = CROSSES.map(declared).filter((g) => g.length > 0);\n for (const values of expand(angleCorners, crosses)) add(values);\n return poses;\n}\n\nfunction poseName(values: Record<string, number>): string {\n const ids = Object.keys(values).sort();\n if (ids.length === 0) return \"rest\";\n return ids.map((id) => `${id}=${values[id]}`).join(\" \");\n}\n\n/**\n * Doubled signed area of each cell's four corner triangles — the corner, then\n * its two neighbours counter-clockwise (y up), as the auto-rig's body fold\n * refusal takes them — at index `cell * 4 + k`. Positive on a rest lattice.\n */\nfunction cornerAreas(\n points: ArrayLike<number>,\n cols: number,\n rows: number,\n): Float64Array {\n const stride = cols + 1;\n const out = new Float64Array(cols * rows * 4);\n for (let r = 0; r < rows; r++) {\n for (let c = 0; c < cols; c++) {\n const tl = r * stride + c;\n const [tr, bl, br] = [tl + 1, tl + stride, tl + stride + 1];\n const i = (r * cols + c) * 4;\n out[i] = doubledArea(points, bl, br, tl);\n out[i + 1] = doubledArea(points, br, tr, bl);\n out[i + 2] = doubledArea(points, tr, tl, br);\n out[i + 3] = doubledArea(points, tl, bl, tr);\n }\n }\n return out;\n}\n\nfunction doubledArea(\n points: ArrayLike<number>,\n p: number,\n q: number,\n s: number,\n): number {\n const ax = points[q * 2] - points[p * 2];\n const ay = points[q * 2 + 1] - points[p * 2 + 1];\n const bx = points[s * 2] - points[p * 2];\n const by = points[s * 2 + 1] - points[p * 2 + 1];\n return ax * by - ay * bx;\n}\n\n/** Doubled signed area of each of a mesh's triangles, at its triangle index. */\nfunction triangleAreas(\n points: ArrayLike<number>,\n indices: number[],\n): Float64Array {\n const out = new Float64Array(indices.length / 3);\n for (let t = 0; t < out.length; t++) {\n const i = t * 3;\n out[t] = doubledArea(points, indices[i], indices[i + 1], indices[i + 2]);\n }\n return out;\n}\n\n/** A target's least ratio so far over one class of poses. */\ninterface Least {\n ratio: number;\n /** Its index into the target's areas: `cell * 4 + corner`, or the triangle. */\n at: number;\n pose: FoldPose;\n}\n\n/** What a target keeps across the poses. */\ninterface Sweep {\n target: FoldTarget[\"target\"];\n restAreas: Float64Array;\n /** Rest areas below this have no ratio. */\n tiny: number;\n worst?: Least;\n expected?: Least;\n}\n\ninterface GridSweep extends Sweep {\n deformer: IkiWarpDeformer;\n}\n\ninterface PartSweep extends Sweep, LandedPart {\n indices: number[];\n}\n\n/**\n * Merges one pose's `areas` into `sweep`: each ratio to its rest area goes to\n * the class `expected` puts the pose in, which keeps its least.\n */\nfunction keepLeast(\n sweep: Sweep,\n areas: Float64Array,\n pose: FoldPose,\n expected: (target: FoldTarget[\"target\"]) => boolean,\n): void {\n const slot = expected(sweep.target) ? \"expected\" : \"worst\";\n for (let i = 0; i < areas.length; i++) {\n const rest = sweep.restAreas[i];\n if (Math.abs(rest) < sweep.tiny) continue;\n const ratio = areas[i] / rest;\n if (ratio < (sweep[slot]?.ratio ?? Infinity)) {\n sweep[slot] = { ratio, at: i, pose };\n }\n }\n}\n\n/** A mesh part's sweep: its landing, with the triangles' rest areas measured on its baseline. */\nfunction partSweep(\n part: IkiPart,\n mesh: IkiMesh,\n deformers: IkiDeformer[],\n worlds: Map<string, Affine>,\n store: ParameterStore,\n): PartSweep {\n const landing = landedPart(part, mesh.vertices, deformers, worlds, store);\n return {\n ...landing,\n target: { kind: \"part\", id: part.id },\n restAreas: triangleAreas(landing.restPoints, mesh.indices),\n tiny: 1e-9 * part.width * part.height,\n indices: mesh.indices,\n };\n}\n\n/**\n * Checks every warp deformer's grid cells and every mesh part's triangles for\n * folds over `options.poses` (`foldPoses(model)` by default) and reports, per\n * target, the least ratio of a triangle's doubled signed area at a pose to\n * the same at rest: `<= 0` a flip, `< 0.1` a collapse. Cells are measured on\n * the deformer's LOCAL grid, so a parent matrix's scale, which multiplies\n * every area alike, never reads as a fold. A part's triangles land as\n * drawPart lands them — its keyforms, its live transform, then its warp's\n * resolved grid or its matrix deformer's world — against its authored mesh on\n * the static matrix chain: a static scale or reflection cancels, a bound one\n * counts, and a vertex its warp grid pins to the edge shows already at\n * `rest` (a triangle wholly past the edge flattens, one across it thins).\n * Report-only: nothing is refused.\n */\nexport function checkFolds(\n model: IkiModel,\n options: FoldOptions = {},\n): FoldReport {\n const poses = options.poses ?? foldPoses(model);\n const deformers = model.deformers ?? [];\n const restStore = new ParameterStore(model.parameters);\n const { worlds } = resolveDeformers(staticDeformers(model), restStore);\n\n const gridSweeps: GridSweep[] = [];\n for (const d of deformers) {\n if (d.kind !== \"warp\") continue;\n const { cols, rows, points } = d.grid;\n // Row 0's x and column 0's y bound the lattice (the validator's own read).\n const width = points[cols * 2] - points[0];\n const height = points[1] - points[rows * (cols + 1) * 2 + 1];\n gridSweeps.push({\n deformer: d,\n target: { kind: \"deformer\", id: d.id },\n restAreas: cornerAreas(points, cols, rows),\n // The validator tolerates 1e-6 of jitter, which can zero a corner's area.\n tiny: 1e-9 * width * height,\n });\n }\n const partSweeps = model.parts.flatMap((part) =>\n part.mesh ? [partSweep(part, part.mesh, deformers, worlds, restStore)] : [],\n );\n\n for (const pose of poses) {\n const store = new ParameterStore(model.parameters);\n for (const [id, v] of Object.entries(pose.values)) store.set(id, v);\n const value = (id: string) => store.get(id);\n const expected = (target: FoldTarget[\"target\"]) =>\n options.expected?.(target, pose, value) === true;\n for (const sweep of gridSweeps) {\n const { cols, rows } = sweep.deformer.grid;\n const areas = cornerAreas(\n deformWarpGrid(sweep.deformer, store),\n cols,\n rows,\n );\n keepLeast(sweep, areas, pose, expected);\n }\n const resolved = resolveDeformers(deformers, store);\n for (const sweep of partSweeps) {\n const areas = triangleAreas(\n landPart(sweep, store, resolved),\n sweep.indices,\n );\n keepLeast(sweep, areas, pose, expected);\n }\n }\n\n const targets = [\n ...gridSweeps.map((sweep) => {\n const { parent } = sweep.deformer;\n const world = parent === undefined ? undefined : worlds.get(parent);\n return foldTarget(sweep, (least) =>\n cellHit(sweep.deformer, least, world),\n );\n }),\n ...partSweeps.map((sweep) =>\n foldTarget(sweep, (least) => triangleHit(sweep, least)),\n ),\n ];\n const offenders = targets\n .filter((t) => t.kind !== \"ok\")\n .sort((a, b) => a.worst!.ratio - b.worst!.ratio);\n return {\n poses: poses.length,\n thresholds: { flip: FLIP, collapse: COLLAPSE },\n targets,\n offenders,\n };\n}\n\n/** A sweep's two minima, each located by `hit`, and the kind they make. */\nfunction foldTarget(sweep: Sweep, hit: (least: Least) => FoldHit): FoldTarget {\n const worst = sweep.worst && hit(sweep.worst);\n const expected = sweep.expected && hit(sweep.expected);\n return { target: sweep.target, kind: classify(worst), worst, expected };\n}\n\n/** `least` located: its cell and that cell's rest centre through `parent`. */\nfunction cellHit(\n d: IkiWarpDeformer,\n least: Least,\n parent: Affine | undefined,\n): FoldHit {\n const { cols, points } = d.grid;\n const cell = Math.floor(least.at / 4);\n const col = cell % cols;\n const row = Math.floor(cell / cols);\n const stride = cols + 1;\n let x = 0;\n let y = 0;\n for (const i of [\n row * stride + col,\n row * stride + col + 1,\n (row + 1) * stride + col,\n (row + 1) * stride + col + 1,\n ]) {\n x += points[i * 2] / 4;\n y += points[i * 2 + 1] / 4;\n }\n const rest = parent\n ? {\n x: parent[0] * x + parent[2] * y + parent[4],\n y: parent[1] * x + parent[3] * y + parent[5],\n }\n : { x, y };\n return { ratio: least.ratio, where: { col, row }, pose: least.pose, rest };\n}\n\n/** `least` located: its triangle and that triangle's centroid on the static chain. */\nfunction triangleHit(sweep: PartSweep, least: Least): FoldHit {\n const { indices, restPoints } = sweep;\n let x = 0;\n let y = 0;\n for (let k = 0; k < 3; k++) {\n const i = indices[least.at * 3 + k];\n x += restPoints[i * 2] / 3;\n y += restPoints[i * 2 + 1] / 3;\n }\n return {\n ratio: least.ratio,\n where: { triangle: least.at },\n pose: least.pose,\n rest: { x, y },\n };\n}\n\nfunction classify(worst: FoldHit | undefined): FoldTarget[\"kind\"] {\n if (worst === undefined) return \"ok\";\n if (worst.ratio <= FLIP) return \"flip\";\n if (worst.ratio < COLLAPSE) return \"collapse\";\n return \"ok\";\n}\n","import type {\n IkiDeformer,\n IkiModel,\n IkiPart,\n IkiWarpDeformer,\n} from \"@ikijs/format\";\nimport { type Affine, multiply, rotate, scale, translate } from \"./affine\";\nimport {\n type ResolvedDeformers,\n type ResolvedTransform,\n evaluateTransform,\n resolveDeformers,\n} from \"./deform\";\nimport { ParameterStore } from \"./parameter-store\";\nimport { applyWarps } from \"./warp\";\nimport { applyWarpToChild, transformGridPoints } from \"./warp-grid\";\n\n/** The corners `createUnitQuad` uploads, which a part without a mesh draws. */\nexport const UNIT_QUAD = [-0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5];\n\n/**\n * The model's deformers with every binding and keyform removed: the rig no\n * parameter moves. Its matrix worlds place a rest location, and a part's\n * baseline, in model space.\n */\nexport function staticDeformers(model: IkiModel): IkiDeformer[] {\n return (model.deformers ?? []).map((d) =>\n d.kind === \"warp\"\n ? { ...d, warps: undefined, warp2d: undefined }\n : { ...d, bindings: undefined },\n );\n}\n\n/** A part's placement as `player.ts` drawPart builds it: translate · rotate · scale(size). */\nexport function placement(part: IkiPart, t: ResolvedTransform): Affine {\n return multiply(\n multiply(translate(t.x, t.y), rotate(t.rotation)),\n scale(part.width * t.scaleX, part.height * t.scaleY),\n );\n}\n\n/** A part's points set up to land at any pose, and their baseline. */\nexport interface LandedPart {\n part: IkiPart;\n /** The warp deformer it hangs from, which lands it instead of a matrix. */\n warpDeformer?: IkiWarpDeformer;\n /** The points as the renderer holds them: part-local, float32. */\n vertices: Float32Array;\n /** Per-pose scratch: the points after the part's keyforms, then where they land. */\n local: Float32Array;\n landed: Float32Array;\n /**\n * The baseline's points: `vertices` on the STATIC chain, model space — for\n * folds, the authored mesh. Not the rendered rest pose, which is `landPart`\n * at a resting store.\n */\n restPoints: Float64Array;\n}\n\n/**\n * A part's landing, its baseline set once: `vertices` (its mesh's, or any\n * part-local points) through the part's base transform and the static world\n * it hangs from — its matrix deformer's, or its warp's PARENT's (identity at\n * a root). The grid never enters it, so a vertex the grid pins to its edge is\n * measured, not cancelled.\n */\nexport function landedPart(\n part: IkiPart,\n vertices: number[],\n deformers: IkiDeformer[],\n worlds: Map<string, Affine>,\n store: ParameterStore,\n): LandedPart {\n // Found as drawPart finds it: a part hung from a warp is that warp's child.\n const warpDeformer = deformers.find(\n (d): d is IkiWarpDeformer => d.kind === \"warp\" && d.id === part.deformer,\n );\n const frame = warpDeformer ? warpDeformer.parent : part.deformer;\n const placed = placement(\n part,\n evaluateTransform(part.transform, undefined, store),\n );\n // Float64: a triangle authored degenerate stays exactly so, under folds'\n // `tiny`.\n const restPoints = transformGridPoints(\n vertices,\n frame === undefined ? placed : multiply(worlds.get(frame)!, placed),\n new Float64Array(vertices.length),\n );\n return {\n part,\n warpDeformer,\n vertices: Float32Array.from(vertices),\n local: new Float32Array(vertices.length),\n landed: new Float32Array(vertices.length),\n restPoints,\n };\n}\n\n/**\n * Where `landing`'s part lands at a pose, model space, by drawPart's three\n * branches: a warp child bound to its RAW rest grid and sampled on the\n * resolved one, a matrix child through its deformer's world, a free part by\n * its placement alone. `resolved` is the live rig at `store`'s pose, not the\n * static chain's worlds.\n */\nexport function landPart(\n landing: LandedPart,\n store: ParameterStore,\n { worlds, grids }: ResolvedDeformers,\n): Float32Array {\n const { part, warpDeformer, local, landed } = landing;\n applyWarps(landing.vertices, part.warps, store, local);\n const placed = placement(\n part,\n evaluateTransform(part.transform, part.bindings, store),\n );\n if (warpDeformer) {\n const grid = grids.get(warpDeformer.id)!;\n applyWarpToChild(local, placed, warpDeformer.grid, grid, landed);\n } else if (part.deformer !== undefined) {\n const world = worlds.get(part.deformer)!;\n transformGridPoints(local, multiply(world, placed), landed);\n } else {\n transformGridPoints(local, placed, landed);\n }\n return landed;\n}\n\n/**\n * Where the named parts land with `values` set (every other parameter at its\n * default), model space (x right, y up): the points as drawPart lands them,\n * the path `checkFolds` and `checkPhysics` read. A part without a mesh lands\n * the unit quad's four corners. Each result is a copy, so two poses can be\n * held at once. An id the model lacks is absent from the map, and a value for\n * a parameter it lacks is dropped, as the store does.\n */\nexport function landParts(\n model: IkiModel,\n values: Record<string, number>,\n partIds: readonly string[],\n): Map<string, Float32Array> {\n const deformers = model.deformers ?? [];\n const restStore = new ParameterStore(model.parameters);\n const store = new ParameterStore(model.parameters);\n for (const [id, value] of Object.entries(values)) store.set(id, value);\n const { worlds } = resolveDeformers(staticDeformers(model), restStore);\n const resolved = resolveDeformers(deformers, store);\n const out = new Map<string, Float32Array>();\n for (const id of partIds) {\n const part = model.parts.find((p) => p.id === id);\n if (!part) continue;\n const landing = landedPart(\n part,\n part.mesh?.vertices ?? UNIT_QUAD,\n deformers,\n worlds,\n restStore,\n );\n out.set(id, Float32Array.from(landPart(landing, store, resolved)));\n }\n return out;\n}\n","import {\n type IkiDeformer,\n type IkiModel,\n type IkiParameter,\n type IkiPart,\n type IkiPhysics,\n physicsInputs,\n} from \"@ikijs/format\";\nimport { resolveDeformers } from \"./deform\";\nimport { FIXED_DT_S } from \"./frame-clock\";\nimport { UNIT_QUAD, landPart, landedPart, staticDeformers } from \"./land\";\nimport { ParameterStore } from \"./parameter-store\";\nimport {\n type Reading,\n anchorInputs,\n farEnd,\n idleRun,\n stepRun,\n} from \"./physics-runs\";\n\n/** How a driven output moves over one excitation window. */\nexport interface PhysicsResponse {\n /**\n * Its largest displacement from its resting value, as the store holds it\n * (clamped): signed in `step`, which has a direction; its size in `idle`,\n * whose sway goes both ways, so a sign there would carry nothing.\n */\n peak: number;\n /**\n * When it peaks, seconds into the window. Between two near-equal extremes\n * of the idle it may name either.\n */\n at: number;\n /**\n * The largest vertex move of any part, model px, with the output alone\n * (every other parameter resting) at the values the window reached.\n */\n displacementPx: number;\n}\n\n/** One output a physics rig drives: a spring's, or one chain segment's. */\nexport interface PhysicsTarget {\n rig:\n | { kind: \"spring\"; id: string }\n | { kind: \"chain\"; id: string; segment: number };\n /**\n * The spring's inputs, in rig order; for a chain, every parameter that turns\n * its anchor.\n */\n input: string[];\n /** The driven parameter. */\n output: string;\n /** What reads `output`: parts, then deformers, each in model order. */\n drives: { kind: \"part\" | \"deformer\"; id: string }[];\n kind: \"ok\" | \"frozen\" | \"unstable\";\n /** One phrase saying why, naming the window it came from; present when not `ok`. */\n why?: string;\n /**\n * An input stepped from rest to `values` and held: its displacement over\n * every value the run emitted, `final` the output at the window's end.\n */\n step: PhysicsResponse & { values: Record<string, number>; final: number };\n /** Every rig and chain together behind the procedural idle, displaced at every value it emitted. */\n idle: PhysicsResponse;\n}\n\nexport interface PhysicsReport {\n thresholds: { displacementPx: 1; pinnedFrames: 60 };\n /** One per `model.physics` rig, then one per chain segment, each in model order. */\n targets: PhysicsTarget[];\n /** The targets that are not `ok`, unstable first. */\n offenders: PhysicsTarget[];\n}\n\n/** Under 1 model px is sub-pixel in every render the loop looks at (0.51 render px each). */\nconst DISPLACEMENT_PX = 1;\n/** One second outside the range: longer than any transient overshoot clip. */\nconst PINNED_FRAMES = 60;\n/** Slack on the spring's stability limits. */\nconst TOLERANCE = 1e-9;\n\n/** A run's reading of one output, the window `why` names it by, and how far it moves the parts. */\ninterface Excitation {\n name: string;\n reading: Reading;\n displacementPx: number;\n}\n\n/** A step excitation and the setting it held. */\ninterface StepExcitation extends Excitation {\n values: Record<string, number>;\n}\n\n/**\n * Excites every physics rig through the real drivers (`PhysicsMotion`,\n * `HairChainMotion`, `IdleMotion`) on a synthetic 60 Hz clock, one FIXED_DT_S\n * sub-step per frame, and reports per driven output whether it moves the\n * parts (`ok`), cannot (`frozen`) or runs away (`unstable`).\n *\n * Step: a fresh store and a driver holding only that rig, seeded at rest,\n * then an input set to its far end — the end farther from its clamped\n * default, `max` on a tie — and held for 5 s. A spring steps each input that\n * has a range alone, in its own run. A chain steps each parameter that alone\n * turns its anchor (probed at its max, min and every warp keyform stop) in\n * its own run, at the probe value that turned it most. Either reports the run\n * moving the parts most among the runs that are not unstable. A lag input's\n * step peaks at once at the bound `−scale·weight` (less one sub-step) and its\n * `final` reads rest: the bound is what a one-frame step shows, a gradual\n * turn swings less. Idle: every rig and chain together behind `IdleMotion`\n * (seeded) for 30 s.\n *\n * `displacementPx` is the largest vertex move of any part with the output\n * alone at every distinct value the run emitted, step or idle, against the\n * parts landed at rest. `frozen` when nothing reads the output, no input of a\n * spring has a range, nothing turns a chain's anchor, or the step moves the\n * parts under 1 model px. `unstable`, before frozen, when a\n * spring's one-sub-step map has a spectral radius over 1 or sits on its\n * undamped boundary (springs only: a chain's update is nonlinear), when a\n * driver's finiteness guard fires, or when the raw output stays outside its\n * range for 60 consecutive frames, in any run. Deferred by the user: a chain\n * that grows yet stays finite and inside its range trips none of these and\n * is not flagged. Idle amplitude never flags. Report-only: nothing is refused.\n */\nexport function checkPhysics(model: IkiModel): PhysicsReport {\n const idle = idleRun(model);\n const displace = displacer(model);\n const idleExcitation = (output: IkiParameter): Excitation => {\n const reading = idle.get(output.id)!;\n return {\n name: \"the idle\",\n reading,\n displacementPx: displace(output, reading.values),\n };\n };\n const param = (id: string) => model.parameters.find((p) => p.id === id)!;\n\n const springs = (model.physics ?? []).map((rig) => {\n const inputs = physicsInputs(rig).map((i) => param(i.parameter));\n const ids = inputs.map((p) => p.id);\n const output = param(rig.output.parameter);\n const ranged = inputs.flatMap((input) => {\n const far = farEnd(input);\n return far === undefined ? [] : [{ [input.id]: far }];\n });\n // One unexcited run when nothing has a range, so mostMoving has a run.\n const settings = ranged.length === 0 ? [{}] : ranged;\n const steps = settings.map((values): StepExcitation => {\n const reading = stepRun(model, [rig], [], values).get(output.id)!;\n // A one-input rig has one run, so naming its setting would add nothing.\n const setting =\n inputs.length === 1\n ? []\n : Object.entries(values).map(([id, v]) => `${id}=${v}`);\n return {\n name: [\"the step\", ...setting].join(\" \"),\n reading,\n displacementPx: displace(output, reading.values),\n values,\n };\n });\n const atIdle = idleExcitation(output);\n const clean = steps.filter((s) => !unstableWhy(output, [s]));\n return target(model, {\n rig: { kind: \"spring\", id: rig.id },\n input: ids,\n output,\n step: mostMoving(clean.length > 0 ? clean : steps),\n idle: atIdle,\n unstable: springWhy(rig) ?? unstableWhy(output, [...steps, atIdle]),\n inert:\n ranged.length === 0\n ? `${ids.join(\", \")} ${ids.length === 1 ? \"has\" : \"have\"} no range`\n : undefined,\n });\n });\n\n const chains = (model.physicsChains ?? []).flatMap((chain) => {\n const candidates = anchorInputs(model, chain);\n const settings =\n candidates.length === 0\n ? [{}]\n : candidates.map((c) => ({ [c.parameter]: c.value }));\n const runs = settings.map((values) => ({\n values,\n readings: stepRun(model, [], [chain], values),\n }));\n return chain.segments.map((segment, i) => {\n const output = param(segment.output.parameter);\n const steps = runs.map(({ values, readings }): StepExcitation => {\n const reading = readings.get(output.id)!;\n const setting = Object.entries(values).map(([id, v]) => `${id}=${v}`);\n return {\n name: [\"the step\", ...setting].join(\" \"),\n reading,\n displacementPx: displace(output, reading.values),\n values,\n };\n });\n const atIdle = idleExcitation(output);\n const clean = steps.filter((s) => !unstableWhy(output, [s]));\n return target(model, {\n rig: { kind: \"chain\", id: chain.id, segment: i },\n input: candidates.map((c) => c.parameter),\n output,\n step: mostMoving(clean.length > 0 ? clean : steps),\n idle: atIdle,\n unstable: unstableWhy(output, [...steps, atIdle]),\n inert:\n candidates.length === 0\n ? `nothing turns anchor ${chain.anchorDeformer}`\n : undefined,\n });\n });\n });\n\n const targets = [...springs, ...chains];\n return {\n thresholds: {\n displacementPx: DISPLACEMENT_PX,\n pinnedFrames: PINNED_FRAMES,\n },\n targets,\n offenders: [\n ...targets.filter((t) => t.kind === \"unstable\"),\n ...targets.filter((t) => t.kind === \"frozen\"),\n ],\n };\n}\n\n/**\n * A target from its excitations: `unstable` with its reason, else `frozen`\n * when nothing reads the output, by the input-side reason `inert`, or under\n * 1 px.\n */\nfunction target(\n model: IkiModel,\n t: {\n rig: PhysicsTarget[\"rig\"];\n input: string[];\n output: IkiParameter;\n step: StepExcitation;\n idle: Excitation;\n unstable: string | undefined;\n inert: string | undefined;\n },\n): PhysicsTarget {\n const { step, idle, output } = t;\n const drives = drivesOf(model, output.id);\n // Floored, so a frozen 0.96 px never reads as 1.0.\n const px = Math.floor(step.displacementPx * 10) / 10;\n const still =\n step.displacementPx < DISPLACEMENT_PX\n ? `moves ${px.toFixed(1)} model px over ${step.name}`\n : undefined;\n const frozen = drives.length === 0 ? \"drives nothing\" : (t.inert ?? still);\n const { peak, at, final } = step.reading;\n return {\n rig: t.rig,\n input: t.input,\n output: output.id,\n drives,\n kind: t.unstable ? \"unstable\" : frozen ? \"frozen\" : \"ok\",\n why: t.unstable ?? frozen,\n step: {\n values: step.values,\n peak,\n at,\n final,\n displacementPx: step.displacementPx,\n },\n idle: {\n peak: Math.abs(idle.reading.peak),\n at: idle.reading.at,\n displacementPx: idle.displacementPx,\n },\n };\n}\n\n/** The excitation moving the parts most, ties by `|peak|`, the first on a full tie. */\nfunction mostMoving(steps: StepExcitation[]): StepExcitation {\n return steps.reduce((best, s) => {\n if (s.displacementPx !== best.displacementPx) {\n return s.displacementPx > best.displacementPx ? s : best;\n }\n return Math.abs(s.reading.peak) > Math.abs(best.reading.peak) ? s : best;\n });\n}\n\n/** The parts, then the deformers, that read `output`, each in model order. */\nfunction drivesOf(model: IkiModel, output: string): PhysicsTarget[\"drives\"] {\n const parts = model.parts.filter((p) =>\n [\n ...(p.bindings ?? []).map((b) => b.parameter),\n ...(p.warps ?? []).map((w) => w.parameter),\n ].includes(output),\n );\n const deformers = (model.deformers ?? []).filter((d) =>\n (d.kind === \"warp\"\n ? [\n ...(d.warps ?? []).map((w) => w.parameter),\n d.warp2d?.parameter,\n d.warp2d?.parameterY,\n ]\n : (d.bindings ?? []).map((b) => b.parameter)\n ).includes(output),\n );\n return [\n ...parts.map((p) => ({ kind: \"part\" as const, id: p.id })),\n ...deformers.map((d) => ({ kind: \"deformer\" as const, id: d.id })),\n ];\n}\n\n/**\n * The spectral radius of the map `PhysicsMotion.step` applies to the state\n * (x, v) each FIXED_DT_S sub-step — linear, constant coefficients:\n * `[[1 − h²k/m, h(1 − hc/m)], [−hk/m, 1 − hc/m]]` — by the closed form: a real\n * pair from trace and determinant, a complex pair's modulus `√det`. With it,\n * `k` = h²k/m, the term the undamped boundary reads.\n */\nfunction springStepRadius({ mass, stiffness, damping }: IkiPhysics): {\n radius: number;\n k: number;\n} {\n const k = (FIXED_DT_S * FIXED_DT_S * stiffness) / mass;\n const c = (FIXED_DT_S * damping) / mass;\n const trace = 2 - k - c;\n const det = 1 - c;\n const disc = trace * trace - 4 * det;\n const radius =\n disc >= 0 ? (Math.abs(trace) + Math.sqrt(disc)) / 2 : Math.sqrt(det);\n return { radius, k };\n}\n\n/**\n * Why a spring's constants make it unstable, if they do: a radius over 1, or\n * the undamped boundary `dt²k/m = 4`, where the radius is exactly 1 but the\n * matrix is defective (double eigenvalue −1) and the state grows linearly.\n */\nfunction springWhy(rig: IkiPhysics): string | undefined {\n const { radius, k } = springStepRadius(rig);\n if (radius > 1 + TOLERANCE) {\n // As many decimals as it takes to print the radius over 1.\n let digits = 2;\n while (Number(radius.toFixed(digits)) <= 1) digits++;\n return `spring step map radius ${radius.toFixed(digits)} over 1 at 1/60 s`;\n }\n if (rig.damping === 0 && k >= 4 - TOLERANCE) {\n return `spring on its undamped boundary, dt²k/m ${k.toFixed(2)}`;\n }\n return undefined;\n}\n\n/** Why `output` is unstable over `excitations`, if it is: a guard activation in any, else a pin. */\nfunction unstableWhy(\n output: IkiParameter,\n excitations: Excitation[],\n): string | undefined {\n for (const { name, reading } of excitations) {\n const n = reading.resets;\n if (n === 0) continue;\n return `finiteness guard reset it ${n} time${n === 1 ? \"\" : \"s\"} in ${name}`;\n }\n for (const { name, reading } of excitations) {\n const { frames, end } = reading.pinned;\n if (frames < PINNED_FRAMES) continue;\n return `pinned at ${output.id} ${end} ${output[end]} for ${frames} frames of ${name}`;\n }\n return undefined;\n}\n\n/**\n * The largest vertex move, model px, of any part with an output alone at\n * each of a list of values (every other parameter resting), against every\n * part landed at the resting store through the live deformers resolved at\n * rest — so a binding or keyform away from zero at rest is not motion. Every\n * part lands, so a deformer- or chain-driven part counts by the same path.\n */\nfunction displacer(\n model: IkiModel,\n): (output: IkiParameter, values: number[]) => number {\n const deformers = model.deformers ?? [];\n const store = new ParameterStore(model.parameters);\n // Only `landedPart`'s `restPoints` (folds' baseline) reads the static\n // worlds; this check lands its own baseline below.\n const { worlds } = resolveDeformers(staticDeformers(model), store);\n const landings = model.parts.map((part) =>\n landedPart(\n part,\n part.mesh?.vertices ?? UNIT_QUAD,\n deformers,\n worlds,\n store,\n ),\n );\n const atRest = resolveDeformers(deformers, store);\n // Copied out: landPart returns the landing's shared scratch.\n const baselines = landings.map((l) =>\n Float32Array.from(landPart(l, store, atRest)),\n );\n return (output, values) => {\n let most = 0;\n const affected = affectedParts(model, output.id);\n for (const value of values) {\n store.set(output.id, value);\n const resolved = resolveDeformers(deformers, store);\n landings.forEach((landing, i) => {\n if (!affected.has(landing.part)) return;\n const landed = landPart(landing, store, resolved);\n const base = baselines[i];\n for (let j = 0; j < landed.length; j += 2) {\n const dx = landed[j] - base[j];\n const dy = landed[j + 1] - base[j + 1];\n most = Math.max(most, dx * dx + dy * dy);\n }\n });\n }\n store.reset();\n return Math.sqrt(most);\n };\n}\n\n/**\n * The parts whose geometry can depend on `output`: those that read it\n * themselves, or hang from a deformer that reads it or has an ancestor that\n * does. The rest land exactly at rest, so landing them adds nothing.\n */\nfunction affectedParts(model: IkiModel, output: string): Set<IkiPart> {\n const deformers = new Map((model.deformers ?? []).map((d) => [d.id, d]));\n const reads = (d: IkiDeformer) =>\n (d.kind === \"warp\"\n ? [\n ...(d.warps ?? []).map((w) => w.parameter),\n d.warp2d?.parameter,\n d.warp2d?.parameterY,\n ]\n : (d.bindings ?? []).map((b) => b.parameter)\n ).includes(output);\n const hung = (id: string | undefined): boolean => {\n for (\n let d = id && deformers.get(id);\n d;\n d = d.parent && deformers.get(d.parent)\n ) {\n if (reads(d)) return true;\n }\n return false;\n };\n return new Set(\n model.parts.filter(\n (p) =>\n [\n ...(p.bindings ?? []).map((b) => b.parameter),\n ...(p.warps ?? []).map((w) => w.parameter),\n ].includes(output) || hung(p.deformer),\n ),\n );\n}\n","import type {\n IkiModel,\n IkiParameter,\n IkiPhysics,\n IkiPhysicsChain,\n} from \"@ikijs/format\";\nimport { resolveDeformers } from \"./deform\";\nimport { FIXED_DT_S } from \"./frame-clock\";\nimport { HairChainMotion } from \"./hair-chain-motion\";\nimport { IdleMotion } from \"./idle-motion\";\nimport { clamp } from \"./math\";\nimport { ParameterStore } from \"./parameter-store\";\nimport { PhysicsMotion } from \"./physics-motion\";\n\n// The excitation runs behind `checkPhysics`: the real drivers on a synthetic\n// 60 Hz clock, never a re-implemented integrator.\n\n/**\n * A hair over one sub-step: at exactly 1000/60 ms, float rounding leaves the\n * drivers' accumulator just short or just over, so about one frame in three\n * runs no sub-step (re-emitting the last value) and about as many run two\n * (emitting only the second) — and a skipped sub-step can be the peak.\n */\nconst FRAME_MS = FIXED_DT_S * 1000 * (1 + 1e-9);\n/** Frames after the seed frame: 5 s of step (the defaults settle in ~2 s), 30 s of idle. */\nconst STEP_FRAMES = 300;\nconst IDLE_FRAMES = 1800;\n/** Any constant keeps two checks equal. It shapes every rig's idle input: the head's noise is seeded from it, as are the blink and gaze schedules. */\nconst IDLE_SEED = 1;\n/** An anchor turn, or a lead over another, under this many radians is float noise (a uniform scale over a rotated anchor). */\nconst MIN_TURN = 1e-9;\n\n/** What a driver handed its sink for one output, read against the output's range and resting value. */\nexport interface Reading {\n /** The largest signed displacement of the clamped value from rest, and when, seconds in. */\n peak: number;\n at: number;\n /** The clamped value at the window's end. */\n final: number;\n /** Every distinct clamped value emitted except the resting one. */\n values: number[];\n /** The least and greatest clamped values emitted. */\n lo: number;\n hi: number;\n /** The longest run of frames with the raw value outside the range, and the bound it began past. */\n pinned: { frames: number; end: \"min\" | \"max\" };\n /** The driver's finiteness-guard activations for the output. */\n resets: number;\n}\n\n/**\n * Runs a `PhysicsMotion` over `rigs` and a `HairChainMotion` over `chains`,\n * both reading and writing `store`, for the seed frame and `frames` more —\n * one FIXED_DT_S sub-step each — calling `excite` ahead of them every frame;\n * reads what they hand the sink, per output.\n */\nfunction run(\n model: IkiModel,\n store: ParameterStore,\n rigs: IkiPhysics[],\n chains: IkiPhysicsChain[],\n frames: number,\n excite: (frame: number, nowMs: number) => void,\n): Map<string, Reading> {\n const raw = new Map<string, number[]>();\n const read = (id: string) => store.get(id);\n const sink = (id: string, value: number) => {\n let trace = raw.get(id);\n if (trace === undefined) raw.set(id, (trace = []));\n trace.push(value);\n store.set(id, value);\n };\n const { parameters } = model;\n const drivers = [\n new PhysicsMotion(rigs, parameters, read, sink),\n new HairChainMotion(chains, parameters, model.deformers ?? [], read, sink),\n ];\n for (let frame = 0; frame <= frames; frame++) {\n const nowMs = frame * FRAME_MS;\n excite(frame, nowMs);\n for (const driver of drivers) driver.update(nowMs);\n }\n const readings = new Map<string, Reading>();\n for (const driver of drivers) {\n driver.drivenParameterIds.forEach((id, i) => {\n const param = parameters.find((p) => p.id === id)!;\n readings.set(id, readTrace(raw.get(id)!, param, driver.resets[i]));\n });\n }\n return readings;\n}\n\n/** Reads `raw`, one sink value per frame from the seed frame on, against `param`. */\nfunction readTrace(\n raw: number[],\n param: IkiParameter,\n resets: number,\n): Reading {\n const rest = clamp(param.default, param.min, param.max);\n const reading: Reading = {\n peak: 0,\n at: 0,\n final: rest,\n values: [],\n lo: rest,\n hi: rest,\n pinned: { frames: 0, end: \"max\" },\n resets,\n };\n const seen = new Set([rest]);\n let outside = 0;\n let end: Reading[\"pinned\"][\"end\"] = \"max\";\n raw.forEach((value, frame) => {\n const held = clamp(value, param.min, param.max);\n if (Math.abs(held - rest) > Math.abs(reading.peak)) {\n reading.peak = held - rest;\n reading.at = frame * FIXED_DT_S;\n }\n if (!seen.has(held)) {\n seen.add(held);\n reading.values.push(held);\n }\n reading.lo = Math.min(reading.lo, held);\n reading.hi = Math.max(reading.hi, held);\n reading.final = held;\n if (value >= param.min && value <= param.max) {\n outside = 0;\n return;\n }\n const side = value < param.min ? \"min\" : \"max\";\n // Crossing to the other bound ends the run: a swing between the two is\n // not pinning.\n if (outside === 0 || side !== end) {\n outside = 0;\n end = side;\n }\n outside++;\n if (outside > reading.pinned.frames) {\n reading.pinned = { frames: outside, end };\n }\n });\n return reading;\n}\n\n/**\n * The end farther from the clamped default — the one `signedNormalized`\n * takes as its unit, `max` on a tie — or `undefined` for a zero-width range.\n */\nexport function farEnd(param: IkiParameter): number | undefined {\n if (param.min === param.max) return undefined;\n const rest = clamp(param.default, param.min, param.max);\n return param.max - rest >= rest - param.min ? param.max : param.min;\n}\n\n/**\n * The step run: `rigs` and `chains` from rest, `values` set after the seed\n * frame and held for the window, every other parameter resting.\n */\nexport function stepRun(\n model: IkiModel,\n rigs: IkiPhysics[],\n chains: IkiPhysicsChain[],\n values: Record<string, number>,\n): Map<string, Reading> {\n const store = new ParameterStore(model.parameters);\n return run(model, store, rigs, chains, STEP_FRAMES, (frame) => {\n if (frame !== 1) return;\n for (const [id, v] of Object.entries(values)) store.set(id, v);\n });\n}\n\n/**\n * The idle run: every rig and chain together behind the procedural\n * `IdleMotion` on a seeded rng, stepped idle → physics → chains each frame as\n * `IkiMotion` orders them. A declared `Idle` group is not played.\n */\nexport function idleRun(model: IkiModel): Map<string, Reading> {\n const store = new ParameterStore(model.parameters);\n const idle = new IdleMotion((id, v) => store.set(id, v), {\n rng: lcg(IDLE_SEED),\n parameters: model.parameters,\n });\n return run(\n model,\n store,\n model.physics ?? [],\n model.physicsChains ?? [],\n IDLE_FRAMES,\n (_, nowMs) => idle.update(nowMs),\n );\n}\n\n/** Numerical Recipes' 32-bit LCG, in [0, 1). */\nfunction lcg(seed: number): () => number {\n let state = seed >>> 0;\n return () => {\n state = (Math.imul(state, 1664525) + 1013904223) >>> 0;\n return state / 2 ** 32;\n };\n}\n\n/** A parameter that turns a chain's anchor, at the probe value that turns it most. */\nexport interface Candidate {\n parameter: string;\n value: number;\n}\n\n/**\n * Every parameter that alone changes `chain`'s anchor world rotation at one\n * of its probe values — its `max`, its `min` and every keyform stop of a warp\n * deformer keyed on it, all but the resting value — in model order. Both\n * ends and the stops, since a warp parent can turn the anchor at one end\n * alone or at an interior stop while its other end matches rest. A probe\n * turning it no more than `MIN_TURN` past an earlier one does not replace it,\n * so a symmetric rig steps to `max`, as `farEnd` does, and float noise never\n * decides a near-tie.\n */\nexport function anchorInputs(\n model: IkiModel,\n chain: IkiPhysicsChain,\n): Candidate[] {\n const store = new ParameterStore(model.parameters);\n const angle = () => {\n const { worlds } = resolveDeformers(model.deformers ?? [], store);\n const world = worlds.get(chain.anchorDeformer)!;\n return Math.atan2(world[1], world[0]);\n };\n const rest = angle();\n const found: Candidate[] = [];\n for (const p of model.parameters) {\n const probes = new Set(\n [p.max, p.min, ...stopsOf(model, p.id)].map((v) =>\n clamp(v, p.min, p.max),\n ),\n );\n probes.delete(store.get(p.id));\n let most = 0;\n let best: Candidate | undefined;\n for (const value of probes) {\n store.set(p.id, value);\n const d = angle() - rest;\n const turn = Math.abs(Math.atan2(Math.sin(d), Math.cos(d)));\n if (turn <= most + MIN_TURN) continue;\n [most, best] = [turn, { parameter: p.id, value }];\n }\n store.reset();\n if (best) found.push(best);\n }\n return found;\n}\n\n/** The sorted distinct keyform values of every deformer warp and `warp2d` axis keyed on `parameter`. */\nfunction stopsOf(model: IkiModel, parameter: string): number[] {\n const stops = new Set<number>();\n for (const d of model.deformers ?? []) {\n if (d.kind !== \"warp\") continue;\n for (const w of d.warps ?? []) {\n if (w.parameter !== parameter) continue;\n for (const k of w.keyforms) stops.add(k.value);\n }\n const { warp2d } = d;\n if (warp2d?.parameter === parameter) {\n for (const v of warp2d.valuesX) stops.add(v);\n }\n if (warp2d?.parameterY === parameter) {\n for (const v of warp2d.valuesY) stops.add(v);\n }\n }\n return [...stops].sort((a, b) => a - b);\n}\n","/**\n * `probe_rig`: measuring a rigged model without rendering it. Where a point of\n * a part lands in a pose, how far that is from where it rests, and the opaque\n * runs of a layer PNG — the numbers a rigging program (or an agent checking\n * a custom part) needs and a picture cannot give exactly.\n *\n * The landing is the engine's own `landParts`, so it is what the player draws.\n * Frame: canvas px, origin top-left, x right, y down — the frame of the layer\n * PNGs and of `describe_iki`'s boxes.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { IkiFormatError, loadIkiModel, type IkiModel } from \"@ikijs/format\";\nimport { landParts } from \"@ikijs/engine\";\nimport {\n AutoRigInputError,\n MAX_PROBE_POINTS,\n MAX_PROBE_QUERIES,\n confineToWorkingDirectory,\n resolveInputPath,\n resolveOutputPath,\n writeFileAtomic,\n} from \"./limits\";\nimport { decodePng, type DecodedPng } from \"./node-images\";\n\nexport type ProbePoint = [number, number];\n\nexport type ProbeQuery =\n | { op: \"paint\"; path: string }\n | {\n op: \"land\" | \"displacement\";\n part: string;\n points: ProbePoint[];\n pose?: Record<string, number>;\n };\n\nexport interface ProbeInput {\n /** The rigged `.iki` to measure (resolved against cwd, under it). */\n modelPath: string;\n queries: ProbeQuery[];\n /** A `.probe.json` under the working directory to write the results to. */\n outputPath?: string;\n}\n\n/**\n * The opaque (alpha >= 128) runs of a layer per canvas row. `rows[i]` holds\n * the `[x0, x1)` runs (`x1` exclusive) of canvas row `y0 + i`; a row inside the\n * painted range with none is `[]`. A layer with no opaque pixel gives\n * `{ y0: 0, rows: [] }`.\n */\nexport interface PaintRuns {\n y0: number;\n rows: [number, number][][];\n}\n\nexport type ProbeQueryResult =\n | ({ op: \"paint\" } & PaintRuns)\n | {\n op: \"land\" | \"displacement\";\n part: string;\n /** One per input point; `null` for a point outside the part's mesh. */\n points: (ProbePoint | null)[];\n };\n\nexport type ProbeResult =\n | { ok: true; results: ProbeQueryResult[] }\n | { ok: true; outputPath: string; lines: string[] }\n | { ok: false; error: string };\n\n/** What a probe's `outputPath` must end in: never a name another tool or a config file owns. */\nconst OUTPUT_SUFFIX = \".probe.json\";\n\n/** The threshold the auto-rig's own layer measure uses. */\nconst OPAQUE = 128;\n\n/** Opaque runs per canvas row of a decoded layer. */\nexport function paintRuns(png: DecodedPng): PaintRuns {\n const { width, height, rgba } = png;\n const rows: [number, number][][] = [];\n let y0 = -1;\n for (let y = 0; y < height; y++) {\n const runs: [number, number][] = [];\n let start = -1;\n for (let x = 0; x < width; x++) {\n const on = rgba[(y * width + x) * 4 + 3] >= OPAQUE;\n if (on && start < 0) start = x;\n if (!on && start >= 0) {\n runs.push([start, x]);\n start = -1;\n }\n }\n if (start >= 0) runs.push([start, width]);\n if (runs.length > 0 && y0 < 0) y0 = y;\n if (y0 >= 0) rows.push(runs);\n }\n while (rows.length > 0 && rows[rows.length - 1].length === 0) rows.pop();\n return rows.length === 0 ? { y0: 0, rows: [] } : { y0, rows };\n}\n\n/** Model space (x right, y up, origin at the canvas centre) to canvas px. */\nexport function toCanvas(model: IkiModel, pts: Float32Array): Float64Array {\n const hw = model.canvas.width / 2;\n const hh = model.canvas.height / 2;\n const out = new Float64Array(pts.length);\n for (let i = 0; i < pts.length; i += 2) {\n out[i] = hw + pts[i];\n out[i + 1] = hh - pts[i + 1];\n }\n return out;\n}\n\n/** A millipixel is far below what a render shows, and keeps the text short. `+ 0` drops a -0. */\nconst round = (v: number) => Math.round(v * 1000) / 1000 + 0;\n\n/** The barycentric weights of (x, y) in a triangle of `vertices` (canvas px, rest or posed), or null outside it. */\nexport function locate(\n vertices: Float64Array,\n tri: [number, number, number],\n x: number,\n y: number,\n): [number, number, number] | null {\n const [a, b, c] = tri;\n const ax = vertices[a * 2];\n const ay = vertices[a * 2 + 1];\n const bx = vertices[b * 2];\n const by = vertices[b * 2 + 1];\n const cx = vertices[c * 2];\n const cy = vertices[c * 2 + 1];\n const d = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy);\n if (Math.abs(d) < 1e-12) return null;\n const l1 = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / d;\n const l2 = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / d;\n const l3 = 1 - l1 - l2;\n const eps = 1e-9;\n return l1 >= -eps && l2 >= -eps && l3 >= -eps ? [l1, l2, l3] : null;\n}\n\n/** A part without a mesh draws its unit quad. */\nconst QUAD_INDICES = [0, 1, 2, 1, 3, 2];\n\n/** A part's rest triangles with their boxes, computed once per call. */\nexport interface RestMesh {\n indices: number[];\n rest: Float64Array;\n /** minX, minY, maxX, maxY per triangle. */\n boxes: Float64Array;\n}\n\nexport function restMesh(\n model: IkiModel,\n cache: Map<string, RestMesh>,\n partId: string,\n): RestMesh {\n let m = cache.get(partId);\n if (m) return m;\n const part = model.parts.find((p) => p.id === partId)!;\n const indices = part.mesh ? part.mesh.indices : QUAD_INDICES;\n const rest = toCanvas(model, landParts(model, {}, [partId]).get(partId)!);\n const boxes = new Float64Array((indices.length / 3) * 4);\n for (let t = 0; t < indices.length / 3; t++) {\n let x0 = Infinity;\n let y0 = Infinity;\n let x1 = -Infinity;\n let y1 = -Infinity;\n for (let k = 0; k < 3; k++) {\n const v = indices[t * 3 + k];\n x0 = Math.min(x0, rest[v * 2]);\n x1 = Math.max(x1, rest[v * 2]);\n y0 = Math.min(y0, rest[v * 2 + 1]);\n y1 = Math.max(y1, rest[v * 2 + 1]);\n }\n boxes.set([x0, y0, x1, y1], t * 4);\n }\n m = { indices, rest, boxes };\n cache.set(partId, m);\n return m;\n}\n\n/** Where a rest point sits in a part's mesh: a triangle and its weights. */\nexport interface Located {\n tri: [number, number, number];\n w: [number, number, number];\n}\n\n/** Each point's triangle at rest (the first that holds it), or null off the mesh. */\nexport function locatePoints(\n mesh: RestMesh,\n points: ProbePoint[],\n): (Located | null)[] {\n const { indices, rest, boxes } = mesh;\n // A little slack, so the box test does not reject a point sitting on a\n // triangle's edge. `locate`'s own tolerance is in barycentric weight and\n // reaches a few 1e-6 px past the outline of a very large triangle; a point\n // that far outside the mesh reads off it here, which is what it is.\n const slack = 1e-6;\n return points.map(([x, y]) => {\n for (let t = 0; t < indices.length / 3; t++) {\n const b = t * 4;\n if (\n x < boxes[b] - slack ||\n x > boxes[b + 2] + slack ||\n y < boxes[b + 1] - slack ||\n y > boxes[b + 3] + slack\n ) {\n continue;\n }\n const tri: [number, number, number] = [\n indices[t * 3],\n indices[t * 3 + 1],\n indices[t * 3 + 2],\n ];\n const w = locate(rest, tri, x, y);\n if (w) return { tri, w };\n }\n return null;\n });\n}\n\n/** A located point on a part's posed vertices (canvas px). */\nexport function landLocated(\n posed: Float64Array,\n at: Located | null,\n): ProbePoint | null {\n if (at === null) return null;\n let px = 0;\n let py = 0;\n for (let k = 0; k < 3; k++) {\n px += at.w[k] * posed[at.tri[k] * 2];\n py += at.w[k] * posed[at.tri[k] * 2 + 1];\n }\n return [px, py];\n}\n\nfunction landPoints(\n model: IkiModel,\n cache: Map<string, RestMesh>,\n partId: string,\n points: ProbePoint[],\n pose: Record<string, number>,\n): (ProbePoint | null)[] {\n const located = locatePoints(restMesh(model, cache, partId), points);\n const posed = toCanvas(model, landParts(model, pose, [partId]).get(partId)!);\n return located.map((at) => landLocated(posed, at));\n}\n\nfunction invalid(i: number, field: string, what: string): AutoRigInputError {\n return new AutoRigInputError(`queries[${i}].${field} ${what}`);\n}\n\nfunction checkPoints(i: number, points: unknown): ProbePoint[] {\n if (!Array.isArray(points) || points.length === 0) {\n throw invalid(i, \"points\", \"must be a non-empty list of [x, y]\");\n }\n if (points.length > MAX_PROBE_POINTS) {\n throw invalid(\n i,\n \"points\",\n `has ${points.length} points; at most ${MAX_PROBE_POINTS} per query`,\n );\n }\n points.forEach((pt, k) => {\n if (\n !Array.isArray(pt) ||\n pt.length !== 2 ||\n !pt.every((v) => Number.isFinite(v))\n ) {\n throw invalid(i, `points[${k}]`, \"must be [x, y] with finite numbers\");\n }\n });\n return points as ProbePoint[];\n}\n\nfunction checkPose(\n model: IkiModel,\n i: number,\n pose: Record<string, number> | undefined,\n): Record<string, number> {\n const declared = new Set(model.parameters.map((p) => p.id));\n for (const [id, v] of Object.entries(pose ?? {})) {\n if (!declared.has(id)) {\n throw invalid(i, `pose.${id}`, \"is not a parameter the model declares\");\n }\n if (typeof v !== \"number\" || !Number.isFinite(v)) {\n throw invalid(i, `pose.${id}`, \"must be a finite number\");\n }\n }\n return pose ?? {};\n}\n\n/** A query whose shape has been checked, ready to run. */\ntype CheckedQuery =\n | { op: \"paint\"; path: string }\n | {\n op: \"land\" | \"displacement\";\n part: string;\n points: ProbePoint[];\n pose: Record<string, number>;\n };\n\n/** Every refusal that needs no file: shape, op, part, points, pose. */\nfunction checkQuery(model: IkiModel, q: ProbeQuery, i: number): CheckedQuery {\n if (q.op === \"paint\") return { op: \"paint\", path: q.path };\n if (q.op !== \"land\" && q.op !== \"displacement\") {\n throw invalid(i, \"op\", `must be paint, land or displacement`);\n }\n if (!model.parts.some((p) => p.id === q.part)) {\n throw invalid(i, \"part\", `names no part of the model: ${String(q.part)}`);\n }\n return {\n op: q.op,\n part: q.part,\n points: checkPoints(i, q.points),\n pose: checkPose(model, i, q.pose),\n };\n}\n\nasync function runQuery(\n model: IkiModel,\n cache: Map<string, RestMesh>,\n q: CheckedQuery,\n i: number,\n): Promise<ProbeQueryResult> {\n if (q.op === \"paint\") {\n // Its message is already qualified by the noun it is given.\n const file = resolveInputPath(q.path, `queries[${i}].path`);\n let png: DecodedPng;\n try {\n png = await decodePng(file);\n } catch (e) {\n if (e instanceof AutoRigInputError) throw invalid(i, \"path\", e.message);\n throw e;\n }\n const { width, height } = model.canvas;\n if (png.width !== width || png.height !== height) {\n throw invalid(\n i,\n \"path\",\n `is ${png.width}x${png.height}, not the model's canvas ${width}x${height}: ${q.path}`,\n );\n }\n return { op: \"paint\", ...paintRuns(png) };\n }\n const { points } = q;\n const landed = landPoints(model, cache, q.part, points, q.pose);\n return {\n op: q.op,\n part: q.part,\n points: landed.map((l, k) =>\n l === null\n ? null\n : q.op === \"land\"\n ? [round(l[0]), round(l[1])]\n : [round(l[0] - points[k][0]), round(l[1] - points[k][1])],\n ),\n };\n}\n\n/** One line per query for the text a `outputPath` call returns. */\nfunction summarize(r: ProbeQueryResult, i: number): string {\n if (r.op === \"paint\") {\n return `${i} paint: ${r.rows.length} rows from y ${r.y0}`;\n }\n const off = r.points.filter((p) => p === null).length;\n return `${i} ${r.op} ${r.part}: ${r.points.length} points, ${off} off the mesh`;\n}\n\n/**\n * Measure the model. Only caller-input failures (`AutoRigInputError`,\n * `IkiFormatError`) come back as `{ ok: false, error }`. With `outputPath` the\n * results go to that file and the return carries a line per query instead.\n */\nexport async function probeRig(input: ProbeInput): Promise<ProbeResult> {\n try {\n // First, so a refused path costs nothing.\n const outFile =\n input.outputPath !== undefined\n ? resolveOutputPath(input.outputPath, OUTPUT_SUFFIX)\n : undefined;\n const modelFile = confineToWorkingDirectory(\n process.cwd(),\n resolveInputPath(input.modelPath, \"model\"),\n \"model path\",\n input.modelPath,\n );\n const model = loadIkiModel(readFileSync(modelFile, \"utf8\"));\n if (!Array.isArray(input.queries) || input.queries.length === 0) {\n throw new AutoRigInputError(\"queries must be a non-empty list\");\n }\n if (input.queries.length > MAX_PROBE_QUERIES) {\n throw new AutoRigInputError(\n `queries has ${input.queries.length} entries; at most ${MAX_PROBE_QUERIES} per call`,\n );\n }\n const checked = input.queries.map((q, i) => checkQuery(model, q, i));\n const cache = new Map<string, RestMesh>();\n const results: ProbeQueryResult[] = [];\n for (const [i, q] of checked.entries()) {\n results.push(await runQuery(model, cache, q, i));\n }\n if (outFile === undefined) return { ok: true, results };\n writeFileAtomic(outFile, JSON.stringify(results));\n return {\n ok: true,\n outputPath: outFile,\n lines: results.map(summarize),\n };\n } catch (e) {\n if (e instanceof AutoRigInputError || e instanceof IkiFormatError) {\n return { ok: false, error: e.message };\n }\n throw e;\n }\n}\n","/**\n * Resource guards + fail-fast path resolution and atomic writes for the Node\n * auto-rig tool.\n *\n * These constants bound an agent-supplied layer set so a malformed or oversized\n * request fails fast with a path-qualified message rather than exhausting memory\n * or producing a multi-MB MCP response. All guards REJECT (never downscale).\n *\n * `sharp` must stay confined to @ikijs/mcp — none of @ikijs/engine, @ikijs/editor,\n * or @ikijs/format may take a heavy Node image dependency.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\n/** Max number of input layers in one request. */\nexport const MAX_LAYERS = 64;\n/** Max per-side dimension (px) of any single input PNG. */\nexport const MAX_LAYER_DIM = 4096;\n/** Max per-side dimension (px) of the derived canvas. */\nexport const MAX_CANVAS_DIM = 4096;\n/** Max per-side length (px) of each packed atlas page. WebGL2 guarantees only\n * 2048, but 4096 or more is near-universal; the engine refuses a texture over\n * the device's own limit on either side and leaves its parts untextured. Both\n * sides within it also bound a page's area at 4096². */\nexport const MAX_ATLAS_SIDE = 4096;\n/** Decoded-pixel ceiling per input PNG, passed to sharp `limitInputPixels`. */\nexport const MAX_INPUT_PIXELS = 4096 * 4096;\n/** Aggregate decoded-pixel budget across ALL layers in one request. Layers\n * decode one at a time, so it bounds the request's total work, not its peak\n * memory. A full body's 21 layers at 1100 × 3650 decode 84.3 M px. */\nexport const MAX_TOTAL_PIXELS = 128 * 1024 * 1024;\n/** Max length (bytes) of the base64 atlas data URI embedded in the model,\n * summed over its pages. Sized for the loop's lossless re-rig of a full body:\n * measured on bob's layers, a lossless atlas costs 1.56 data-URI bytes per\n * crop px (1,677,898 B over 1,075,888 px), and a full body on a canvas up to\n * 4096 tall crops to at most ~5 M px, about 8 MB. */\nexport const MAX_OUTPUT_BYTES = 12 * 1024 * 1024;\n/** Max queries in one `probe_rig` call. */\nexport const MAX_PROBE_QUERIES = 64;\n/** Max points in one `probe_rig` land/displacement query. */\nexport const MAX_PROBE_POINTS = 5000;\n/** Max points in one illustration landmark list (a polygon, a line, seeds,\n * samples): the cutter rasterises each, so an outsized one would stall it. */\nexport const MAX_LANDMARK_POINTS = 2000;\n/** Max custom parts one illustration's landmarks cut out. */\nexport const MAX_LANDMARK_CUSTOM_PARTS = 16;\n/** Max colour sample points per set (hair, skin) in one illustration's\n * landmarks: each is a segment every distinct colour is measured against,\n * and a few per tone describe a set. */\nexport const MAX_LANDMARK_SAMPLES = 32;\n/** Max `bodyOnly` polygons in one illustration's landmarks. */\nexport const MAX_LANDMARK_BODY_ONLY = 16;\n\n/**\n * Expected, caller-input-caused failure. The tool catches ONLY this class and\n * returns `{ ok: false, error }`; any other thrown Error (TypeError, invariant\n * break, programmer bug) propagates so the SDK handler surfaces `isError: true`.\n */\nexport class AutoRigInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AutoRigInputError\";\n }\n}\n\n/**\n * Reject an empty/whitespace or URL-looking caller-supplied path, shared by\n * {@link resolveInputPath} and {@link resolveInputDir}. `noun` and `kind`\n * shape the thrown message so each caller reports in its own vocabulary\n * (e.g. a directory input was never supposed to look like \"a file path\").\n */\nfunction rejectEmptyOrUrl(inputPath: string, noun: string, kind: string): void {\n if (typeof inputPath !== \"string\" || inputPath.trim() === \"\") {\n throw new AutoRigInputError(`${noun} is empty`);\n }\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(inputPath)) {\n throw new AutoRigInputError(\n `${noun} must be a ${kind}, not a URL: ${inputPath}`,\n );\n }\n}\n\n/**\n * Resolve a caller-supplied input file path against the MCP process cwd and\n * confirm it points at a readable file. Throws AutoRigInputError (path-qualified)\n * for empty/URL-looking strings, a missing file, or a directory.\n * `what` names the input in those messages (\"layer\" -> \"layer file not found\").\n *\n * READS ARE DELIBERATELY NOT CONFINED to the working directory, unlike\n * {@link resolveOutputPath}. The asymmetry is intentional, not an oversight: a\n * stray write destroys data, while a read only surfaces a PNG the agent already\n * named and the user's own account can already open. Confining reads would also\n * break the documented generate-a-character flow, which reads its part PNGs\n * from wherever the image generator dropped them (a downloads folder, a scratch\n * dir) while everything it writes — the composed layers, the model — stays\n * under the working directory. Revisit only if this server ever runs with wider\n * privileges than the person driving it. The same reasoning covers\n * {@link resolveInputDir}, its directory counterpart.\n *\n * Param is named `inputPath` (not `path`) to avoid shadowing the node:path import.\n */\nexport function resolveInputPath(inputPath: string, what = \"layer\"): string {\n rejectEmptyOrUrl(inputPath, `${what} path`, \"file path\");\n const resolved = path.resolve(process.cwd(), inputPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`${what} file not found: ${resolved}`);\n }\n if (stat.isDirectory()) {\n throw new AutoRigInputError(\n `${what} path is a directory, not a file: ${resolved}`,\n );\n }\n return resolved;\n}\n\n/** Directory counterpart to {@link resolveInputPath} — see its doc comment. */\nexport function resolveInputDir(dirPath: string): string {\n rejectEmptyOrUrl(dirPath, \"layers dir\", \"directory path\");\n const resolved = path.resolve(process.cwd(), dirPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`layers dir not found: ${resolved}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`layers path is not a directory: ${resolved}`);\n }\n return resolved;\n}\n\n/**\n * Confine an already-verified-to-exist directory to the MCP process working\n * directory, comparing REAL paths (statSync/writeFileSync follow symlinks, so\n * a lexical startsWith check can be bypassed by a symlinked dir under cwd).\n * Shared by {@link resolveOutputPath} and {@link resolveOutputDir} — both are\n * write-side boundaries where an unrestricted target is an\n * arbitrary-file-overwrite surface — and by `render_poses` for its model file,\n * whose first bytes a parse error would otherwise echo back. `label` and `original` shape the thrown\n * message (path-qualified with the caller's original, unresolved string).\n */\nexport function confineToWorkingDirectory(\n root: string,\n dir: string,\n label: string,\n original: string,\n): string {\n const realRoot = fs.realpathSync(root);\n const realDir = fs.realpathSync(dir);\n if (realDir !== realRoot && !realDir.startsWith(realRoot + path.sep)) {\n throw new AutoRigInputError(\n `${label} escapes the working directory: ${original}`,\n );\n }\n return realDir;\n}\n\n/**\n * Resolve a caller-supplied output path against the MCP process cwd. Throws\n * AutoRigInputError (path-qualified) if the parent directory does not exist —\n * the tool never creates directories (fail-fast).\n *\n * Writes are confined to the MCP process working directory: the path must end\n * in `extension` (`.iki` unless a tool writes another kind; a tool whose output\n * is not a model names a suffix of its own, so it cannot replace a `package.json`)\n * AND resolve to a location under `process.cwd()`. The MCP server runs\n * with the user's own permissions on agent-supplied input, so an unrestricted\n * `outputPath` is an arbitrary-file-overwrite surface — absolute paths and `..`\n * traversal that escape the working directory are rejected. (Overwriting an\n * existing `.iki` UNDER the working directory is intentional: re-running the tool\n * regenerates the named model.)\n */\nexport function resolveOutputPath(\n outputPath: string,\n extension = \".iki\",\n): string {\n if (typeof outputPath !== \"string\" || outputPath.trim() === \"\") {\n throw new AutoRigInputError(\"output path is empty\");\n }\n if (!outputPath.toLowerCase().endsWith(extension)) {\n throw new AutoRigInputError(\n `output path must end in ${extension}: ${outputPath}`,\n );\n }\n const root = process.cwd();\n const resolved = path.resolve(root, outputPath);\n const dir = path.dirname(resolved);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(dir);\n } catch {\n throw new AutoRigInputError(`output directory does not exist: ${dir}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output parent is not a directory: ${dir}`);\n }\n const realDir = confineToWorkingDirectory(\n root,\n dir,\n \"output path\",\n outputPath,\n );\n return path.join(realDir, path.basename(resolved));\n}\n\n/**\n * Resolve a caller-supplied output DIRECTORY against the MCP process cwd.\n * Unlike {@link resolveOutputPath}, no filename is appended — the directory\n * itself must already exist (the tool never creates directories, fail-fast) —\n * and is confined via {@link confineToWorkingDirectory}. Returns the\n * realpath'd directory.\n */\nexport function resolveOutputDir(dirPath: string): string {\n if (typeof dirPath !== \"string\" || dirPath.trim() === \"\") {\n throw new AutoRigInputError(\"output dir is empty\");\n }\n const root = process.cwd();\n const resolved = path.resolve(root, dirPath);\n let stat: fs.Stats;\n try {\n stat = fs.statSync(resolved);\n } catch {\n throw new AutoRigInputError(`output dir not found: ${resolved}`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`output dir is not a directory: ${resolved}`);\n }\n return confineToWorkingDirectory(root, resolved, \"output dir\", dirPath);\n}\n\n/**\n * Write `data` to `outPath` atomically: write to a fresh temp file in the\n * same directory, then `renameSync` over the target. `rename` REPLACES the\n * destination directory entry rather than following it, so an existing\n * symlink at `outPath` cannot redirect the write outside the working tree.\n * Throws AutoRigInputError(\"write: …\") on failure.\n */\nexport function writeFileAtomic(\n outPath: string,\n data: string | Uint8Array,\n): void {\n const tmp = `${outPath}.${process.pid}.${Date.now()}.tmp`;\n try {\n fs.writeFileSync(tmp, data);\n try {\n fs.renameSync(tmp, outPath);\n } catch (e) {\n try {\n fs.rmSync(tmp, { force: true });\n } catch {\n // best-effort temp cleanup; surface the original rename error\n }\n throw e;\n }\n } catch (e) {\n throw new AutoRigInputError(\n `write: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n","/**\n * Node (sharp-backed) re-host of the browser-only pixel functions used by the\n * auto-rig import flow. Only the DECODE/ENCODE halves are re-hosted here — the\n * alpha-bbox scan itself is shared with the browser path via\n * @ikijs/editor, so the two cannot drift. Still a controlled duplicate of:\n * - crop ← examples/editor/src/auto-rig-image.ts\n * - atlas render + edge-extrude ← examples/editor/src/atlas-image.ts\n * The pure parts (packAtlas / uvRectFor / generateIkiFromLayerSet / role parsing\n * / bbox→model math) are reused from @ikijs/editor, not reimplemented here.\n *\n * `sharp` is a heavy native dependency and MUST stay confined to @ikijs/mcp — it\n * may never reach @ikijs/editor, @ikijs/engine, or @ikijs/format.\n */\n\nimport sharp from \"sharp\";\nimport type { AtlasLayout } from \"@ikijs/editor\";\nimport { detectAlphaBbox as scanAlphaBbox } from \"@ikijs/editor\";\nimport { AutoRigInputError, MAX_INPUT_PIXELS } from \"./limits\";\n\nexport interface DecodedPng {\n width: number;\n height: number;\n /** Straight-alpha RGBA bytes, stride-4 (parity with canvas getImageData). */\n rgba: Buffer;\n /** Whether the FILE carried an alpha channel, before `.ensureAlpha()` added\n * one. A generated part without it is opaque on a white background and needs\n * that white keyed out before it can layer (see ./compose). */\n hasAlpha: boolean;\n}\n\n/**\n * Decode a PNG file to straight-alpha RGBA bytes + dimensions.\n *\n * Decode is an input boundary: a missing/corrupt/unsupported file or a\n * limitInputPixels overflow surfaces as a path-qualified AutoRigInputError so\n * the tool returns { ok:false } rather than { isError:true }.\n *\n * `.ensureAlpha()` promotes RGB PNGs to RGBA so the alpha scan matches the\n * browser canvas getImageData path (which is always RGBA).\n */\nexport async function decodePng(filePath: string): Promise<DecodedPng> {\n try {\n const pipeline = sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS });\n const metadata = await pipeline.metadata();\n if (metadata.format !== \"png\") {\n throw new AutoRigInputError(\n `non-PNG image (${metadata.format ?? \"unknown\"}): ${filePath}`,\n );\n }\n const { data, info } = await pipeline\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return {\n width: info.width,\n height: info.height,\n rgba: data,\n hasAlpha: metadata.hasAlpha ?? false,\n };\n } catch (e) {\n if (e instanceof AutoRigInputError) throw e;\n const msg = e instanceof Error ? e.message : String(e);\n throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);\n }\n}\n\n/**\n * Node-side wrapper over the shared scan in @ikijs/editor: same bbox rule\n * as the browser path by construction, with this package's error type for an\n * empty layer.\n */\nexport function detectAlphaBbox(\n rgba: Buffer,\n width: number,\n height: number,\n): { x: number; y: number; w: number; h: number } {\n const bbox = scanAlphaBbox(rgba, width, height);\n if (bbox === null) {\n throw new AutoRigInputError(\"layer is empty after alpha threshold\");\n }\n return bbox;\n}\n\n/**\n * Crop the already-decoded RGBA to bbox, returning a PNG buffer. One decode per\n * file: the crop is taken from the raw RGBA, not a re-read of the file. Parity\n * with cropBitmap in examples/editor/src/auto-rig-image.ts.\n */\nexport function cropToBuffer(\n rgba: Buffer,\n width: number,\n height: number,\n bbox: { x: number; y: number; w: number; h: number },\n): Promise<Buffer> {\n return sharp(rgba, { raw: { width, height, channels: 4 } })\n .extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h })\n .png()\n .toBuffer();\n}\n\n/**\n * Draw `svg` over the image at `filePath` and return the composited PNG bytes.\n * The debug half of ./measure-turn: the measurement is only believable once the\n * boxes are seen sitting on the irises. The caller has already decoded the file\n * through {@link decodePng}, so a failure here is an encode/environment fault,\n * not caller input, and propagates as itself.\n */\nexport function encodeOverlayPng(\n filePath: string,\n svg: string,\n): Promise<Buffer> {\n return sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS })\n .composite([{ input: Buffer.from(svg) }])\n .png()\n .toBuffer();\n}\n\nexport interface AtlasCrop {\n id: string;\n buffer: Buffer;\n width: number;\n height: number;\n}\n\n/**\n * Composite packed crops onto a transparent page and return a base64 PNG data\n * URI. Each crop's right + bottom edge pixels are extruded across the padding\n * gutter (replicating renderAtlas's right/bottom/corner drawImage extrudes in\n * examples/editor/src/atlas-image.ts) so LINEAR sampling at the inset UV never\n * reads a transparent neighbor texel. packAtlas reserves padding on the RIGHT\n * and BOTTOM only, so a one-sided `extend` matches its layout exactly.\n *\n * Crops are looked up BY placement.id (packAtlas sorts placements by id).\n * ASSUMES a non-empty layout (the empty case is handled by the caller).\n *\n * `quantizeColors` palette-quantizes the page PNG (libimagequant via sharp).\n * Flat-shaded character art keeps its look at 256 colours while the atlas\n * drops to roughly a quarter of its lossless size — the hero demo went from\n * 3.5MB to 0.9MB at a mean channel delta of 1.5/255 — which is what makes a\n * generated model shippable on a page. Omitted = lossless, as before. Soft\n * alpha is where it fails: a shaded nose's feather rims in borrowed palette\n * entries, so the auto-rig renders the nose on its own page without it.\n * Splitting it off also changes how page 0 re-quantizes, so the size effect\n * is content-dependent — on the playground hero the split model came to\n * 1.28MB, about the same as the all-quantized 1.29MB and well under the\n * 3.18MB lossless model.\n */\nexport async function renderAtlasToDataUri(\n crops: AtlasCrop[],\n layout: AtlasLayout,\n quantizeColors?: number,\n): Promise<string> {\n const byId = new Map<string, AtlasCrop>();\n for (const crop of crops) byId.set(crop.id, crop);\n\n const pad = layout.padding;\n\n const composites = await Promise.all(\n layout.placements.map(async (placement) => {\n const crop = byId.get(placement.id);\n if (crop === undefined) {\n throw new AutoRigInputError(\n `no crop for atlas placement \"${placement.id}\"`,\n );\n }\n // Replicate the right + bottom (+ corner) edge pixels into the gutter.\n const input =\n pad > 0\n ? await sharp(crop.buffer)\n .extend({ right: pad, bottom: pad, extendWith: \"copy\" })\n .png()\n .toBuffer()\n : crop.buffer;\n return { input, left: placement.x, top: placement.y };\n }),\n );\n\n const page = await sharp({\n create: {\n width: layout.pageWidth,\n height: layout.pageHeight,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n })\n .composite(composites)\n .png(\n quantizeColors === undefined\n ? {}\n : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 },\n )\n .toBuffer();\n\n return `data:image/png;base64,${page.toString(\"base64\")}`;\n}\n","/**\n * The per-part gate for custom parts, reported by `auto_rig_from_layers` and\n * blocking the character loop's candidate: each custom part measured over a\n * pose set for whether it folds, stays tied where it hangs from its anchor,\n * keeps the art it hides hidden, and (rigid parts) does not bend.\n *\n * Every landing is the engine's own `landParts`, through `probe.ts`'s rest\n * triangles, so the numbers are what the player draws. Lengths are in face\n * widths (the `face` part's width), so nothing is tied to one canvas; the\n * values are experiment C's gate over twin's 402 px face. Frame: canvas px,\n * origin top-left, x right, y down.\n */\n\nimport { partIdsOfRole, rigidResidual } from \"@ikijs/editor\";\nimport {\n checkFolds,\n foldPoses,\n landParts,\n occlusionAmount,\n type FoldPose,\n} from \"@ikijs/engine\";\nimport { StandardParameter, type IkiModel } from \"@ikijs/format\";\nimport { foldPose } from \"./fold-report\";\nimport {\n landLocated,\n locate,\n locatePoints,\n restMesh,\n type Located,\n toCanvas,\n type PaintRuns,\n type ProbePoint,\n type RestMesh,\n} from \"./probe\";\n\n/** A custom part as the gate reads it. */\nexport interface CustomGatePart {\n id: string;\n /** The role the part is fixed against; its first part is the anchor. */\n anchor: string;\n /** Where the part meets the anchor, canvas px. */\n tie: [number, number];\n rigid?: boolean;\n /** The roles of the entry's `occlusion.by`, when it declares one. Their\n * paint gives the gate the cover it excuses a reading under; without it a\n * declared occlusion excuses nothing. */\n occludedBy?: string[];\n}\n\nexport interface CustomGateOptions {\n /** Replaces the default pose set (`RIGID` still adds its stop midpoints). */\n poses?: FoldPose[];\n}\n\n/**\n * In face widths (squared for `EXPOSED`). Each is experiment C's gate v2 over\n * twin's 402 px face, the only evidence there is, as a share of that face:\n * `tie` 2 px, `slide` 40 px, `onAnchor` 6 px, `exposed` 150 px², `rigid` 1 px.\n * The fold limit is the engine's own collapse threshold, read from its report.\n */\nexport const CUSTOM_GATE_LIMITS = {\n tie: 0.005,\n slide: 0.1,\n onAnchor: 0.015,\n exposed: 0.0009,\n rigid: 0.0025,\n} as const;\n\nexport type CustomGateLimits = typeof CUSTOM_GATE_LIMITS & { fold: number };\n\n/** One measure's worst reading. `value` is in face widths (squared for an\n * area), the limit's unit; null where the measure has no number (a tie off\n * the mesh). */\ninterface CustomGateReadingBase {\n value: number | null;\n pose: string;\n limit: number;\n pass: boolean;\n reason?: string;\n}\n\n/** A length: `px` is the same worst value in canvas px. */\nexport interface CustomGateReading extends CustomGateReadingBase {\n px: number | null;\n}\n\n/** An area (`EXPOSED`): `px2` is the same worst value in canvas px². */\nexport interface CustomGateAreaReading extends CustomGateReadingBase {\n px2: number | null;\n}\n\nexport interface CustomGateTip {\n param: string;\n /** The part's free end at the parameter's two ends, min then max. */\n ends: {\n value: number;\n /** Canvas px. */\n landed: ProbePoint | null;\n /** The same point with the part's warps removed (its deformer alone), canvas px. */\n bare: ProbePoint | null;\n /** Distance from `bare` to `landed`, canvas px. */\n fromBare: number | null;\n }[];\n /** Between the two landed positions, canvas px. */\n travel: number | null;\n}\n\nexport interface CustomGatePartReport {\n id: string;\n anchor: string;\n folds: {\n ratio: number;\n pose: string;\n limit: number;\n pass: boolean;\n reason?: string;\n };\n tie: CustomGateReading;\n slide: {\n slide: CustomGateReading;\n onAnchor: CustomGateReading;\n /** How many poses of the set turn the head; 0 leaves both at 0. */\n turningPoses: number;\n pass: boolean;\n };\n exposed: {\n /** Pixels both layers paint within 0.15 face widths of the tie. */\n hiddenPx: number;\n /** Where the head does not turn: limited. */\n noTurn: CustomGateAreaReading;\n /** Where it turns: reported, no limit. */\n turning: { value: number; px2: number; pose: string } | null;\n pass: boolean;\n };\n rigid?: CustomGateReading;\n tip: CustomGateTip[];\n /** Only for a part that declares occlusion. Reported, never failing. */\n hidden?: CustomGateHidden;\n ok: boolean;\n}\n\n/** Where the amount leaves its rest value and first reaches 1, on one side of\n * the key parameter's default; null where it never does. */\nexport interface CustomGateHiddenSide {\n leaves: number | null;\n full: number | null;\n}\n\nexport interface CustomGateHidden {\n /** Every occluder part id the model names. */\n by: string[];\n /** Those whose paint gives the gate cover; the rest fade (or are roles not\n * passed) and give none. */\n cover: string[];\n parameter: string;\n /** The parameter's default. */\n default: number;\n /** The amount with every parameter at its default. */\n atRest: number;\n below: CustomGateHiddenSide;\n above: CustomGateHiddenSide;\n /** Poses of the part's set that `TIE` and `SLIDE` left out, and how many of\n * them turn the head. */\n leftOut: number;\n leftOutTurning: number;\n /** Poses that do not turn the head and that `TIE` read. */\n readNoTurn: number;\n poses: number;\n}\n\nexport interface CustomGateReport {\n ok: boolean;\n faceWidth: number;\n limits: CustomGateLimits;\n poses: number;\n parts: CustomGatePartReport[];\n /** `<part> <LINE>` per limited line that failed, or `gate error: <message>`. */\n failed: string[];\n}\n\n/** The engine's collapse threshold, which it states on every fold report. */\nfunction foldLimit(model: IkiModel): number {\n return checkFolds(model, { poses: [] }).thresholds.collapse;\n}\n\n/** The report for a gate that threw: failed, naming the error, no parts. */\nexport function failedCustomGate(\n model: IkiModel,\n error: unknown,\n): CustomGateReport {\n const message = error instanceof Error ? error.message : String(error);\n return {\n ok: false,\n faceWidth: model.parts.find((p) => p.id === \"face\")?.width ?? 0,\n limits: { ...CUSTOM_GATE_LIMITS, fold: foldLimit(model) },\n poses: 0,\n parts: [],\n failed: [`gate error: ${message}`],\n };\n}\n\nfunction readingOf(\n faceWidth: number,\n amount: number | null,\n dimension: 1,\n pose: string,\n limit: number,\n reason: string,\n): CustomGateReading;\nfunction readingOf(\n faceWidth: number,\n amount: number | null,\n dimension: 2,\n pose: string,\n limit: number,\n reason: string,\n): CustomGateAreaReading;\n/** The one place a worst value in px (px² for an area) becomes face widths. */\nfunction readingOf(\n faceWidth: number,\n amount: number | null,\n dimension: 1 | 2,\n pose: string,\n limit: number,\n reason: string,\n): CustomGateReading | CustomGateAreaReading {\n const value = amount === null ? null : amount / faceWidth ** dimension;\n const pass = value !== null && value <= limit;\n return {\n value,\n ...(dimension === 1 ? { px: amount } : { px2: amount }),\n pose,\n limit,\n pass,\n ...(pass ? {} : { reason }),\n } as CustomGateReading | CustomGateAreaReading;\n}\n\n/** Experiment C's sampling, for a 402 px face. */\nconst TWIN_FACE = 402;\nconst RING_PX = 5;\nconst RING_DIAGONAL_PX = 4;\nconst SAMPLE_REACH_PX = 80;\nconst SAMPLE_STEP_PX = 4;\nconst TIP_INSET_PX = 6;\n/** Of the face width: the neighbourhood of the tie where hidden art is read. */\nconst EXPOSED_REACH = 0.15;\n\nconst runsAt = (paint: PaintRuns, y: number): [number, number][] =>\n paint.rows[y - paint.y0] ?? [];\n\n/** Whether the pixel holding canvas point (x, y) is opaque in `paint`. */\nfunction paintedAt(paint: PaintRuns, x: number, y: number): boolean {\n const px = Math.floor(x);\n return runsAt(paint, Math.floor(y)).some(([a, b]) => px >= a && px < b);\n}\n\n/** Most cells a grid has along one side, whatever the extent it covers. */\nconst GRID_CELLS = 64;\n\n/**\n * The triangles of a posed mesh bucketed by cell, to find the one over a\n * point, over `bounds` (the box of the points to be looked up) alone: a bake\n * is only checked to be finite, so the mesh itself may be arbitrarily large and\n * must not set the number of bins.\n */\nfunction triangleGrid(\n posed: Float64Array,\n indices: number[],\n bounds: { x0: number; y0: number; x1: number; y1: number },\n) {\n const cell = Math.max(\n 16,\n (bounds.x1 - bounds.x0) / GRID_CELLS,\n (bounds.y1 - bounds.y0) / GRID_CELLS,\n );\n const cols = Math.floor((bounds.x1 - bounds.x0) / cell) + 1;\n const rows = Math.floor((bounds.y1 - bounds.y0) / cell) + 1;\n const bins = new Map<number, number[]>();\n for (let t = 0; t < indices.length / 3; t++) {\n let x0 = Infinity;\n let y0 = Infinity;\n let x1 = -Infinity;\n let y1 = -Infinity;\n for (let k = 0; k < 3; k++) {\n const v = indices[t * 3 + k];\n x0 = Math.min(x0, posed[v * 2]);\n x1 = Math.max(x1, posed[v * 2]);\n y0 = Math.min(y0, posed[v * 2 + 1]);\n y1 = Math.max(y1, posed[v * 2 + 1]);\n }\n if (x1 < bounds.x0 || x0 > bounds.x1 || y1 < bounds.y0 || y0 > bounds.y1) {\n continue;\n }\n const cx0 = Math.max(0, Math.floor((x0 - bounds.x0) / cell));\n const cx1 = Math.min(cols - 1, Math.floor((x1 - bounds.x0) / cell));\n const cy0 = Math.max(0, Math.floor((y0 - bounds.y0) / cell));\n const cy1 = Math.min(rows - 1, Math.floor((y1 - bounds.y0) / cell));\n for (let cy = cy0; cy <= cy1; cy++) {\n for (let cx = cx0; cx <= cx1; cx++) {\n const k = cx + cy * cols;\n const bin = bins.get(k);\n if (bin) bin.push(t);\n else bins.set(k, [t]);\n }\n }\n }\n return (x: number, y: number): number[] =>\n x < bounds.x0 || y < bounds.y0 || x > bounds.x1 || y > bounds.y1\n ? []\n : (bins.get(\n Math.floor((x - bounds.x0) / cell) +\n Math.floor((y - bounds.y0) / cell) * cols,\n ) ?? []);\n}\n\n/** Whether each of `points` lies over a painted rest point of `mesh`, posed as\n * `posed`: the triangle holding the point gives the rest point it came from. */\nfunction paintedUnder(\n posed: Float64Array,\n mesh: RestMesh,\n paint: PaintRuns,\n points: ProbePoint[],\n): boolean[] {\n if (points.length === 0) return [];\n const bounds = { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity };\n for (const [x, y] of points) {\n bounds.x0 = Math.min(bounds.x0, x);\n bounds.y0 = Math.min(bounds.y0, y);\n bounds.x1 = Math.max(bounds.x1, x);\n bounds.y1 = Math.max(bounds.y1, y);\n }\n const find = triangleGrid(posed, mesh.indices, bounds);\n return points.map(([x, y]) => {\n for (const t of find(x, y)) {\n const tri: [number, number, number] = [\n mesh.indices[t * 3],\n mesh.indices[t * 3 + 1],\n mesh.indices[t * 3 + 2],\n ];\n const w = locate(posed, tri, x, y);\n if (!w) continue;\n let rx = 0;\n let ry = 0;\n for (let k = 0; k < 3; k++) {\n rx += w[k] * mesh.rest[tri[k] * 2];\n ry += w[k] * mesh.rest[tri[k] * 2 + 1];\n }\n return paintedAt(paint, rx, ry);\n }\n return false;\n });\n}\n\n/** One side of `from` along an occlusion's stops: where the amount leaves its\n * value at `from`, and where it first reaches 1. The amount is linear between\n * stops, so both are stops (or `from` itself). */\nfunction hiddenSide(\n occlusion: { stops: { value: number; amount: number }[] },\n from: number,\n direction: 1 | -1,\n): CustomGateHiddenSide {\n const at = (v: number) => occlusionAmount(occlusion, v);\n const rest = at(from);\n const marks = occlusion.stops\n .map((s) => s.value)\n .filter((v) => (v - from) * direction > 0)\n .sort((a, b) => (a - b) * direction);\n const run = [from, ...marks];\n let leaves: number | null = null;\n let full: number | null = rest === 1 ? from : null;\n for (let i = 0; i + 1 < run.length; i++) {\n if (leaves === null && at(run[i + 1]) !== rest) leaves = run[i];\n if (full === null && at(run[i + 1]) === 1) full = run[i + 1];\n }\n return { leaves, full };\n}\n\n/** The poses the gate reads for one part: the engine's fold poses, each of the\n * part's own stops alone, and every combination of two baked parameters'\n * stops. `baked` also carries the stops of the part's occlusion on its key\n * parameter (the interior ones too: the part's warps are piecewise linear and add,\n * so a pair's sum can be worst at a stop between the ends). */\nfunction posesOf(\n model: IkiModel,\n baked: Map<string, number[]>,\n base: FoldPose[],\n): FoldPose[] {\n const byName = new Map(base.map((p) => [p.name, p]));\n const add = (values: Record<string, number>) => {\n const pose = foldPose(values);\n if (!byName.has(pose.name)) byName.set(pose.name, pose);\n };\n const defaults = new Map(model.parameters.map((p) => [p.id, p.default]));\n for (const [param, stops] of baked) {\n for (const v of stops) if (v !== defaults.get(param)) add({ [param]: v });\n }\n const params = [...baked.keys()];\n for (let i = 0; i < params.length; i++) {\n for (let j = i + 1; j < params.length; j++) {\n for (const a of baked.get(params[i])!) {\n if (a === defaults.get(params[i])) continue;\n for (const b of baked.get(params[j])!) {\n if (b === defaults.get(params[j])) continue;\n add({ [params[i]]: a, [params[j]]: b });\n }\n }\n }\n }\n return [...byName.values()];\n}\n\n/** The part's free end: the centre of the widest run on its painted row\n * farthest from the tie, inset toward the tie. */\nfunction freeEnd(\n paint: PaintRuns,\n tie: [number, number],\n inset: number,\n): ProbePoint | null {\n if (paint.rows.length === 0) return null;\n const [top, bottom] = [paint.y0, paint.y0 + paint.rows.length - 1];\n const y = Math.abs(bottom - tie[1]) > Math.abs(top - tie[1]) ? bottom : top;\n const runs = runsAt(paint, y);\n if (runs.length === 0) return null;\n const widest = runs.reduce((a, b) => (b[1] - b[0] > a[1] - a[0] ? b : a));\n return [(widest[0] + widest[1]) / 2, y > tie[1] ? y - inset : y + inset];\n}\n\n/**\n * Measure every custom part of `model`. `paints` holds the opaque runs of each\n * anchor role's layer and of each custom layer, by id. Throws `Error` on an\n * inconsistent call (a part, anchor or paint the model or `paints` lacks):\n * `auto_rig_from_layers` has validated those by then.\n */\nexport function checkCustomGate(\n model: IkiModel,\n parts: CustomGatePart[],\n paints: ReadonlyMap<string, PaintRuns>,\n options: CustomGateOptions = {},\n): CustomGateReport {\n const face = model.parts.find((p) => p.id === \"face\");\n if (face === undefined) throw new Error(\"custom gate: the model has no face\");\n const faceWidth = face.width;\n const limits: CustomGateLimits = {\n ...CUSTOM_GATE_LIMITS,\n fold: foldLimit(model),\n };\n if (parts.length === 0) {\n return {\n ok: true,\n faceWidth,\n limits,\n poses: 0,\n parts: [],\n failed: [],\n };\n }\n const scale = faceWidth / TWIN_FACE;\n const px = (twin: number) => Math.max(1, Math.round(twin * scale));\n const cache = new Map<string, RestMesh>();\n const turnParam = model.parameters.find(\n (p) => p.id === StandardParameter.AngleX,\n );\n const turns = (pose: FoldPose) =>\n turnParam !== undefined &&\n (pose.values[StandardParameter.AngleX] ?? turnParam.default) !==\n turnParam.default;\n\n const bakedOf = (id: string): Map<string, number[]> => {\n const part = model.parts.find((p) => p.id === id)!;\n return new Map(\n (part.warps ?? []).map((w) => [\n w.parameter,\n w.keyforms.map((k) => k.value),\n ]),\n );\n };\n const base = options.poses ?? foldPoses(model);\n const poseSets = parts.map((part) => {\n if (!model.parts.some((p) => p.id === part.id)) {\n throw new Error(`custom gate: the model has no part \"${part.id}\"`);\n }\n if (options.poses) return options.poses;\n const sampledOf = bakedOf(part.id);\n const occ = model.parts.find((p) => p.id === part.id)!.occlusion;\n if (occ !== undefined) {\n // The amount is piecewise linear in its stops, so they are breakpoints\n // of what is drawn: sample them like the part's own bake stops.\n const at = sampledOf.get(occ.parameter) ?? [];\n sampledOf.set(occ.parameter, [\n ...new Set([...at, ...occ.stops.map((s) => s.value)]),\n ]);\n }\n return posesOf(model, sampledOf, base);\n });\n const all = new Map(poseSets.flat().map((p) => [p.name, p]));\n\n const reports = parts.map((part, n): CustomGatePartReport => {\n const poses = poseSets[n];\n // A role may yield several parts (an arm's elbow): the anchor is the one\n // whose rest mesh holds the tie, the first when none does. Only pixels on\n // its mesh count as hidden art below, the layer's paint being the whole role.\n const roleParts = partIdsOfRole(part.anchor).filter((id) =>\n model.parts.some((p) => p.id === id),\n );\n const anchorId =\n roleParts.find(\n (id) =>\n locatePoints(restMesh(model, cache, id), [part.tie])[0] !== null,\n ) ?? roleParts[0];\n // Each part's worst ratio is read over its own pose set only.\n const folds = checkFolds(model, { poses });\n const anchorPart = model.parts.find((p) => p.id === anchorId);\n if (anchorPart === undefined) {\n throw new Error(`custom gate: the model has no part \"${anchorId}\"`);\n }\n const ownPaint = paints.get(part.id);\n const anchorPaint = paints.get(part.anchor);\n if (ownPaint === undefined || anchorPaint === undefined) {\n throw new Error(\n `custom gate: no paint for \"${ownPaint === undefined ? part.id : part.anchor}\"`,\n );\n }\n const partMesh = restMesh(model, cache, part.id);\n const anchorMesh = restMesh(model, cache, anchorId);\n const length = (\n amount: number | null,\n pose: string,\n limit: number,\n reason: string,\n ) => readingOf(faceWidth, amount, 1, pose, limit, reason);\n\n // TIE: the ring around the tie, on both meshes at rest.\n const ring = (\n [\n [0, 0],\n [px(RING_PX), 0],\n [-px(RING_PX), 0],\n [0, px(RING_PX)],\n [0, -px(RING_PX)],\n [px(RING_DIAGONAL_PX), px(RING_DIAGONAL_PX)],\n [-px(RING_DIAGONAL_PX), px(RING_DIAGONAL_PX)],\n [px(RING_DIAGONAL_PX), -px(RING_DIAGONAL_PX)],\n [-px(RING_DIAGONAL_PX), -px(RING_DIAGONAL_PX)],\n ] as [number, number][]\n ).map(([dx, dy]): ProbePoint => [part.tie[0] + dx, part.tie[1] + dy]);\n const onPart = locatePoints(partMesh, ring);\n const onAnchor = locatePoints(anchorMesh, ring);\n const shared = ring.flatMap((_, i) =>\n onPart[i] && onAnchor[i] ? [i] : [],\n );\n\n // SLIDE: the anchor's paint around the tie, sampled.\n const reach = px(SAMPLE_REACH_PX);\n const step = px(SAMPLE_STEP_PX);\n const samples: ProbePoint[] = [];\n const cx = Math.round(part.tie[0]);\n const cy = Math.round(part.tie[1]);\n for (let y = cy - reach; y <= cy + reach; y += step) {\n const runs = runsAt(anchorPaint, y);\n for (let x = cx - reach; x <= cx + reach; x += step) {\n if (runs.some(([a, b]) => x >= a && x < b))\n samples.push([x + 0.5, y + 0.5]);\n }\n }\n const samplesOn = locatePoints(anchorMesh, samples).filter(\n (l): l is NonNullable<Located> => l !== null,\n );\n const [tieOnPart] = locatePoints(partMesh, [part.tie]);\n\n // EXPOSED: the pixels both layers paint near the tie; the lower part's art\n // the upper one hides at rest.\n const partIndex = model.parts.findIndex((p) => p.id === part.id);\n const anchorIndex = model.parts.indexOf(anchorPart);\n const ownPart = model.parts[partIndex];\n const partLower =\n ownPart.order < anchorPart.order ||\n (ownPart.order === anchorPart.order && partIndex < anchorIndex);\n const [lowerId, upperId] = partLower\n ? [part.id, anchorId]\n : [anchorId, part.id];\n const [lowerMesh, upperMesh] = [\n restMesh(model, cache, lowerId),\n restMesh(model, cache, upperId),\n ];\n const upperPaint = partLower ? anchorPaint : ownPaint;\n const exposedReach = Math.round(EXPOSED_REACH * faceWidth);\n const hidden: ProbePoint[] = [];\n for (\n let y = Math.floor(part.tie[1]) - exposedReach;\n y <= Math.ceil(part.tie[1]) + exposedReach;\n y++\n ) {\n for (const [a0, a1] of runsAt(ownPaint, y)) {\n for (const [b0, b1] of runsAt(anchorPaint, y)) {\n for (let x = Math.max(a0, b0); x < Math.min(a1, b1); x++) {\n if (\n Math.hypot(x + 0.5 - part.tie[0], y + 0.5 - part.tie[1]) <=\n exposedReach\n ) {\n hidden.push([x + 0.5, y + 0.5]);\n }\n }\n }\n }\n }\n const onAnchorMesh = locatePoints(anchorMesh, hidden);\n const hiddenOn = locatePoints(lowerMesh, hidden).filter(\n (l, i): l is NonNullable<Located> =>\n l !== null && onAnchorMesh[i] !== null,\n );\n\n // Cover: the occluders the player draws at full alpha in every pose, with\n // the paint they were drawn from. A fading one gives none, whatever the\n // player does with it (`mouth_open`, a blush and a pose forearm fade).\n const occlusion = ownPart.occlusion;\n const coverParts: { id: string; mesh: RestMesh; paint: PaintRuns }[] = [];\n if (occlusion !== undefined) {\n for (const role of part.occludedBy ?? []) {\n for (const id of partIdsOfRole(role)) {\n const o = model.parts.find((p) => p.id === id);\n if (o === undefined || !occlusion.by.includes(id)) continue;\n const steady =\n o.color[3] === 1 &&\n (o.transform.opacity ?? 1) >= 1 &&\n !(o.bindings ?? []).some((b) => b.channel === \"opacity\");\n if (!steady) continue;\n const paint = paints.get(role);\n if (paint === undefined) {\n throw new Error(`custom gate: no paint for \"${role}\"`);\n }\n coverParts.push({ id, mesh: restMesh(model, cache, id), paint });\n }\n }\n }\n const coverIds = new Set(coverParts.map((c) => c.id));\n const keyParam =\n occlusion === undefined\n ? undefined\n : model.parameters.find((p) => p.id === occlusion.parameter)!;\n // The key value as the player reads it: inside the parameter's range.\n const keyOf = (values: Record<string, number>): number =>\n Math.min(\n keyParam!.max,\n Math.max(keyParam!.min, values[keyParam!.id] ?? keyParam!.default),\n );\n // The values of the key parameter this part's poses sample (its bake\n // stops and its occlusion's stops, both in the pose set). A reading in\n // a stretch between two samples is bounded by the readings at its two\n // ends, and none is taken between them, so a pose is left out only when\n // nothing is drawn in either stretch it bounds: the amount is 1 from the\n // sample below to the sample above.\n const sampled =\n keyParam === undefined\n ? []\n : [\n ...new Set([\n keyParam.default,\n ...poses.map((p) => keyOf(p.values)),\n ]),\n ].sort((a, b) => a - b);\n const fullyHidden = (lo: number, hi: number): boolean =>\n occlusion!.stops.every(\n (st) => st.value <= lo || st.value >= hi || st.amount === 1,\n ) &&\n occlusionAmount(occlusion!, lo) === 1 &&\n occlusionAmount(occlusion!, hi) === 1;\n const hiddenAt = (v: number): boolean =>\n fullyHidden(\n sampled.filter((x) => x < v).at(-1) ?? v,\n sampled.find((x) => x > v) ?? v,\n );\n let leftOut = 0;\n let leftOutTurning = 0;\n let readNoTurn = 0;\n\n const stops = bakedOf(part.id);\n // Worst values, in px (px² for the exposed ones); `readingOf` converts.\n const worstOf = {\n tie: { v: -1, pose: \"rest\" },\n slide: { v: -1, pose: \"rest\" },\n onAnchor: { v: -1, pose: \"rest\" },\n exposed: { v: -1, pose: \"rest\" },\n exposedTurn: { v: -1, pose: \"rest\" },\n rigid: { v: -1, pose: \"rest\" },\n };\n const keep = (\n w: { v: number; pose: string },\n v: number,\n pose: string,\n ): void => {\n if (v > w.v) {\n w.v = v;\n w.pose = pose;\n }\n };\n let onAnchorNull: string | null = null;\n let turningPoses = 0;\n const rest = partMesh.rest;\n const restPoints: ProbePoint[] = [];\n for (let i = 0; i < rest.length; i += 2)\n restPoints.push([rest[i], rest[i + 1]]);\n\n const measureRigid = (pose: FoldPose, posed: Float64Array) => {\n const moved: ProbePoint[] = [];\n for (let i = 0; i < posed.length; i += 2)\n moved.push([posed[i], posed[i + 1]]);\n keep(worstOf.rigid, rigidResidual(restPoints, moved), pose.name);\n };\n\n for (const pose of poses) {\n // The player hides the part wholly over the stretch this pose stands\n // for; only then are the occluders landed, for the spots the readings\n // below ask about.\n const hiding = occlusion !== undefined && hiddenAt(keyOf(pose.values));\n const landed = landParts(model, pose.values, [\n ...new Set([\n part.id,\n anchorId,\n ...(hiding && coverIds.size > 0 ? coverIds : []),\n ]),\n ]);\n const partPosed = toCanvas(model, landed.get(part.id)!);\n const anchorPosed = toCanvas(model, landed.get(anchorId)!);\n const canvasOf = new Map<string, Float64Array>();\n const underCover = (points: ProbePoint[], skip?: string): boolean[] => {\n const covered = points.map(() => false);\n if (!hiding) return covered;\n for (const c of coverParts) {\n if (c.id === skip) continue;\n let posed = canvasOf.get(c.id);\n if (posed === undefined) {\n posed = toCanvas(model, landed.get(c.id)!);\n canvasOf.set(c.id, posed);\n }\n const under = paintedUnder(posed, c.mesh, c.paint, points);\n under.forEach((u, i) => {\n if (u) covered[i] = true;\n });\n }\n return covered;\n };\n const turning = turns(pose);\n\n // TIE and SLIDE measure the ring, so a pose where the player hides the\n // part and all of the ring is under cover has nothing to measure.\n const ringLands = onPart.map((l) =>\n l === null ? null : landLocated(partPosed, l)!,\n );\n const ringHidden =\n hiding &&\n ringLands.every((p) => p !== null) &&\n underCover(ringLands as ProbePoint[]).every(Boolean);\n if (ringHidden) {\n leftOut++;\n if (turning) leftOutTurning++;\n } else if (turning) turningPoses++;\n else readNoTurn++;\n\n let gap = 0;\n for (const i of shared) {\n const a = landLocated(partPosed, onPart[i])!;\n const b = landLocated(anchorPosed, onAnchor[i])!;\n // The part's displacement less the anchor's, both from the same rest\n // point: the rest point drops out.\n gap = Math.max(gap, Math.hypot(a[0] - b[0], a[1] - b[1]));\n }\n if (shared.length > 0 && !ringHidden) {\n keep(turning ? worstOf.slide : worstOf.tie, gap, pose.name);\n }\n\n if (turning && !ringHidden) {\n const at = landLocated(partPosed, tieOnPart);\n let nearest: number | null = null;\n if (at !== null) {\n for (const l of samplesOn) {\n const q = landLocated(anchorPosed, l)!;\n const d = Math.hypot(q[0] - at[0], q[1] - at[1]);\n if (nearest === null || d < nearest) nearest = d;\n }\n }\n if (nearest === null) onAnchorNull ??= pose.name;\n else keep(worstOf.onAnchor, nearest, pose.name);\n }\n\n if (hiddenOn.length > 0) {\n const lowerPosed = lowerId === part.id ? partPosed : anchorPosed;\n const upperPosed = upperId === part.id ? partPosed : anchorPosed;\n const lands = hiddenOn.map((l) => landLocated(lowerPosed, l)!);\n const underUpper = paintedUnder(\n upperPosed,\n upperMesh,\n upperPaint,\n lands,\n );\n // Hidden by declaration where an occluder covers the spot. The lower\n // part's own art is under its cover by construction.\n const underHider = coverIds.has(lowerId)\n ? lands.map(() => hiding)\n : underCover(lands, upperId);\n let showing = 0;\n lands.forEach((_, i) => {\n if (!underUpper[i] && !underHider[i]) showing++;\n });\n keep(\n turning ? worstOf.exposedTurn : worstOf.exposed,\n showing,\n pose.name,\n );\n }\n\n if (part.rigid) measureRigid(pose, partPosed);\n }\n\n if (part.rigid) {\n for (const [param, values] of stops) {\n const def = model.parameters.find((p) => p.id === param)!.default;\n const sorted = [...new Set([...values, def])].sort((a, b) => a - b);\n for (let i = 0; i + 1 < sorted.length; i++) {\n const mid = foldPose({ [param]: (sorted[i] + sorted[i + 1]) / 2 });\n const posed = landParts(model, mid.values, [part.id]).get(part.id)!;\n measureRigid(mid, toCanvas(model, posed));\n }\n }\n }\n\n const tieReading =\n shared.length === 0\n ? length(\n null,\n \"rest\",\n limits.tie,\n `no point of the ring around the tie lies on both ${part.id} and ${anchorId}`,\n )\n : length(\n Math.max(0, worstOf.tie.v),\n worstOf.tie.pose,\n limits.tie,\n \"the tie comes apart\",\n );\n const slideReading = length(\n Math.max(0, worstOf.slide.v),\n worstOf.slide.pose,\n limits.slide,\n \"the tie slides too far\",\n );\n const onAnchorReading =\n onAnchorNull !== null\n ? length(\n null,\n onAnchorNull,\n limits.onAnchor,\n `the tie lands off ${part.id}'s mesh, or no painted point of ${anchorId} near it is on its mesh`,\n )\n : length(\n Math.max(0, worstOf.onAnchor.v),\n worstOf.onAnchor.pose,\n limits.onAnchor,\n `the tie leaves ${anchorId}'s paint`,\n );\n const exposedReading = readingOf(\n faceWidth,\n Math.max(0, worstOf.exposed.v),\n 2,\n worstOf.exposed.pose,\n limits.exposed,\n \"hidden art shows\",\n );\n const ratioHit = folds.targets.find(\n (t) => t.target.kind === \"part\" && t.target.id === part.id,\n )?.worst;\n const ratio = ratioHit?.ratio ?? 1;\n const foldsPass = ratio >= limits.fold;\n\n const rigidReading = part.rigid\n ? length(\n Math.max(0, worstOf.rigid.v),\n worstOf.rigid.pose,\n limits.rigid,\n \"the part bends\",\n )\n : undefined;\n\n // TIP: the free end at each baked parameter's ends. Reported, no limit.\n const tipAt = freeEnd(ownPaint, part.tie, px(TIP_INSET_PX));\n const [tipLoc] = tipAt === null ? [null] : locatePoints(partMesh, [tipAt]);\n const bareModel =\n stops.size === 0\n ? model\n : {\n ...model,\n parts: model.parts.map((p) =>\n p.id === part.id ? { ...p, warps: undefined } : p,\n ),\n };\n const tip = [...stops.keys()].map((param): CustomGateTip => {\n const def = model.parameters.find((p) => p.id === param)!;\n const ends = [def.min, def.max].map((value) => {\n const at = (m: IkiModel) =>\n landLocated(\n toCanvas(\n m,\n landParts(m, { [param]: value }, [part.id]).get(part.id)!,\n ),\n tipLoc ?? null,\n );\n const landed = at(model);\n const bare = at(bareModel);\n return {\n value,\n landed,\n bare,\n fromBare:\n landed && bare\n ? Math.hypot(landed[0] - bare[0], landed[1] - bare[1])\n : null,\n };\n });\n const [a, b] = ends;\n return {\n param,\n ends,\n travel:\n a.landed && b.landed\n ? Math.hypot(b.landed[0] - a.landed[0], b.landed[1] - a.landed[1])\n : null,\n };\n });\n\n const turningExposed =\n worstOf.exposedTurn.v < 0\n ? null\n : (({ value, px2, pose }) => ({ value: value!, px2: px2!, pose }))(\n readingOf(\n faceWidth,\n worstOf.exposedTurn.v,\n 2,\n worstOf.exposedTurn.pose,\n Infinity,\n \"\",\n ),\n );\n const slidePass = slideReading.pass && onAnchorReading.pass;\n const ok =\n foldsPass &&\n tieReading.pass &&\n slidePass &&\n exposedReading.pass &&\n (rigidReading?.pass ?? true);\n return {\n id: part.id,\n anchor: part.anchor,\n folds: {\n ratio,\n pose: ratioHit?.pose.name ?? \"rest\",\n limit: limits.fold,\n pass: foldsPass,\n ...(foldsPass ? {} : { reason: ratio <= 0 ? \"a flip\" : \"a collapse\" }),\n },\n tie: tieReading,\n slide: {\n slide: slideReading,\n onAnchor: onAnchorReading,\n turningPoses,\n pass: slidePass,\n },\n exposed: {\n hiddenPx: hiddenOn.length,\n noTurn: exposedReading,\n turning: turningExposed,\n pass: exposedReading.pass,\n },\n ...(rigidReading === undefined ? {} : { rigid: rigidReading }),\n tip,\n ...(occlusion === undefined\n ? {}\n : {\n hidden: {\n by: occlusion.by,\n cover: [...coverIds],\n parameter: occlusion.parameter,\n default: keyParam!.default,\n atRest: occlusionAmount(occlusion, keyParam!.default),\n below: hiddenSide(occlusion, keyParam!.default, -1),\n above: hiddenSide(occlusion, keyParam!.default, 1),\n leftOut,\n leftOutTurning,\n readNoTurn,\n poses: poses.length,\n },\n }),\n ok,\n };\n });\n\n const failed = reports.flatMap((r) => [\n ...(r.folds.pass ? [] : [`${r.id} FOLDS`]),\n ...(r.tie.pass ? [] : [`${r.id} TIE`]),\n ...(r.slide.pass ? [] : [`${r.id} SLIDE`]),\n ...(r.exposed.pass ? [] : [`${r.id} EXPOSED`]),\n ...(r.rigid === undefined || r.rigid.pass ? [] : [`${r.id} RIGID`]),\n ]);\n return {\n ok: failed.length === 0,\n faceWidth,\n limits,\n poses: all.size,\n parts: reports,\n failed,\n };\n}\n\nconst both = (faceWidth: number, px: number | null, digits = 4): string =>\n px === null\n ? \"off the mesh\"\n : `${px.toFixed(1)} px (${(px / faceWidth).toFixed(digits)} face widths)`;\n\n/**\n * The gate as text: per part one `CUSTOM <id> <LINE>: …` line per measure\n * (value in px and face widths, the pose, `pass` or `FAIL: <reason>`), then\n * `CUSTOM GATE pass` or `CUSTOM GATE FAIL: <part LINE, …>`.\n */\nexport function formatCustomGate(report: CustomGateReport): string[] {\n const w = report.faceWidth;\n const verdict = (pass: boolean, reason?: string) =>\n pass ? \"pass\" : `FAIL: ${reason}`;\n /** A limit in face widths and in px. */\n const limit = (fw: number) => `${fw} face widths, ${(fw * w).toFixed(1)} px`;\n const lines: string[] = [];\n for (const r of report.parts) {\n const at = `CUSTOM ${r.id}`;\n lines.push(\n `${at} FOLDS: least triangle area ratio ${r.folds.ratio.toFixed(3)} at [${r.folds.pose}] (limit >= ${r.folds.limit}) ${verdict(r.folds.pass, r.folds.reason)}`,\n );\n const noTurnLeftOut =\n r.hidden !== undefined &&\n r.hidden.readNoTurn === 0 &&\n r.hidden.leftOut > r.hidden.leftOutTurning;\n lines.push(\n noTurnLeftOut\n ? `${at} TIE: every pose that does not turn the head is left out as hidden (see HIDDEN) ${verdict(r.tie.pass, r.tie.reason)}`\n : `${at} TIE: at the tie and the ring around it, ${r.id} against ${r.anchor}, poses that do not turn the head: max ${both(w, r.tie.px)} at [${r.tie.pose}] (limit <= ${limit(r.tie.limit)}) ${verdict(r.tie.pass, r.tie.reason)}`,\n );\n const s = r.slide;\n lines.push(\n s.turningPoses === 0\n ? r.hidden !== undefined && r.hidden.leftOutTurning > 0\n ? `${at} SLIDE: every pose that turns the head is left out as hidden (see HIDDEN) pass`\n : `${at} SLIDE: no pose turns the head pass`\n : `${at} SLIDE: poses that turn the head, the same length: max ${both(w, s.slide.px)} at [${s.slide.pose}] (limit <= ${limit(s.slide.limit)}); the tie's distance to the nearest painted point of ${r.anchor} as landed: max ${both(w, s.onAnchor.px)} at [${s.onAnchor.pose}] (limit <= ${limit(s.onAnchor.limit)}) ${verdict(s.pass, s.slide.pass ? s.onAnchor.reason : s.slide.reason)}`,\n );\n const e = r.exposed;\n const turnText =\n e.turning === null\n ? \"no pose turns the head\"\n : `max ${e.turning.px2.toFixed(0)} px² (${e.turning.value.toFixed(5)} face widths²) at [${e.turning.pose}] (reported, no limit)`;\n lines.push(\n `${at} EXPOSED: ${e.hiddenPx} px of art both ${r.id} and ${r.anchor} paint near the tie, the lower one's hidden at rest; showing where the head does not turn: max ${(e.noTurn.px2 ?? 0).toFixed(0)} px² (${(e.noTurn.value ?? 0).toFixed(5)} face widths²) at [${e.noTurn.pose}] (limit <= ${e.noTurn.limit} face widths², ${(e.noTurn.limit * w * w).toFixed(0)} px²) ${verdict(e.pass, e.noTurn.reason)}; where it turns: ${turnText}`,\n );\n if (r.hidden) {\n const h = r.hidden;\n const side = (name: string, s: CustomGateHiddenSide) =>\n h.atRest === 1\n ? `${name} ${h.default} the amount is 1 at rest and ${s.leaves === null ? \"stays 1\" : `leaves it at ${s.leaves}`}`\n : `${name} ${h.default} the amount ${s.leaves === null ? `never leaves ${h.atRest}` : `leaves ${h.atRest} at ${s.leaves}`} and ${s.full === null ? \"never reaches 1\" : `reaches 1 at ${s.full}`}`;\n lines.push(\n `${at} HIDDEN: hidden by ${h.by.join(\",\")} on ${h.parameter}, cover from ${h.cover.length === 0 ? \"none of them\" : h.cover.join(\",\")}${h.cover.length === h.by.length ? \"\" : \" (the rest fade or are roles not passed, and give none)\"}; amount ${h.atRest} at rest; ${side(\"below\", h.below)}; ${side(\"above\", h.above)}; left out of TIE and SLIDE: ${h.leftOut} of ${h.poses} poses (reported, no limit)`,\n );\n }\n if (r.rigid) {\n lines.push(\n `${at} RIGID: bend against rest: max ${both(w, r.rigid.px)} at [${r.rigid.pose}] (limit <= ${limit(r.rigid.limit)}) ${verdict(r.rigid.pass, r.rigid.reason)}`,\n );\n }\n for (const t of r.tip) {\n const ends = t.ends\n .map(\n (x) =>\n `${t.param}=${x.value} lands ${x.landed ? `(${x.landed.map((v) => v.toFixed(1)).join(\", \")})` : \"off the mesh\"}, ${x.fromBare === null ? \"-\" : both(w, x.fromBare)} from where its deformer alone lands it`,\n )\n .join(\"; \");\n lines.push(\n `${at} TIP ${t.param}: free end ${ends}; travel end to end ${t.travel === null ? \"-\" : both(w, t.travel)} (reported, no limit)`,\n );\n }\n }\n lines.push(\n report.ok\n ? \"CUSTOM GATE pass\"\n : `CUSTOM GATE FAIL: ${report.failed.join(\", \")}`,\n );\n return lines;\n}\n","/**\n * The turn sweep's `SWEEP` lines: geometry, not pixels. A `ParamAngleX` ladder\n * from −30 to +30 in 1° steps, every other parameter at its default and no\n * physics, landed through the engine's `landParts` — the report reads the\n * rig, the frames show the rig plus the hair. Report-only, like `FOLD` and\n * `PHYSICS`: nothing here is a threshold that makes a finding.\n *\n * Landmarks are found by role (`eye_L`, `eye_R`, `nose`, against the `face`\n * plate) — mcp's knowledge, never the engine's. Every landed coordinate is\n * divided by the face part's own width, `describe_iki`'s `faceWidth` and the\n * unit a patch's `by` is in, before any number below is formed.\n */\n\nimport { landParts } from \"@ikijs/engine\";\nimport type { IkiModel } from \"@ikijs/format\";\n\nexport interface SweepLandmark {\n id: string;\n /** x(+30) − x(−30), face widths: a frozen rig reads 0, however smooth. */\n amplitude: number;\n /** The slope change of x through θ = 0, 0..1; null when both slopes are ~0. */\n xKink: number | null;\n /** The same for the landed width; null for a landmark without one, or when both slopes are ~0. */\n widthKink: number | null;\n /** How far the landmark has moved beyond the local face plate, at −30 and +30, face widths. */\n lead: { m30: number; p30: number };\n /** The largest second difference of x away from θ = 0, over the mean step; null when x never moves. */\n pop: number | null;\n}\n\nexport type SweepReport =\n | {\n preset: \"turn\";\n unit: \"fw\";\n faceWidth: number;\n /** The face plate's own x(+30) − x(−30) at the eye row, face widths. */\n plateAmplitude: number;\n landmarks: SweepLandmark[];\n }\n | { preset: \"turn\"; unavailable: string };\n\nconst LADDER_MIN = -30;\nconst LADDER_MAX = 30;\n/** The ladder index of θ = 0. */\nconst ZERO = -LADDER_MIN;\n/** A ten-thousandth of the face width per degree: sub-pixel on the renders. */\nconst FLAT_SLOPE = 1e-4;\nconst PARTS = [\"face\", \"eye_L\", \"eye_R\", \"nose\"];\n\ninterface Box {\n x: number;\n width: number;\n y: number;\n}\n\nfunction box(pts: Float32Array, fw: number): Box {\n let x0 = Infinity;\n let x1 = -Infinity;\n let y0 = Infinity;\n let y1 = -Infinity;\n for (let i = 0; i < pts.length; i += 2) {\n x0 = Math.min(x0, pts[i]);\n x1 = Math.max(x1, pts[i]);\n y0 = Math.min(y0, pts[i + 1]);\n y1 = Math.max(y1, pts[i + 1]);\n }\n return {\n x: (x0 + x1) / 2 / fw,\n width: (x1 - x0) / fw,\n y: (y0 + y1) / 2 / fw,\n };\n}\n\n/** Index of the face vertex nearest (x, y), all in face widths. */\nfunction nearestVertex(face: Float32Array, fw: number, x: number, y: number) {\n let best = 0;\n let bestD = Infinity;\n for (let i = 0; i < face.length; i += 2) {\n const d = (face[i] / fw - x) ** 2 + (face[i + 1] / fw - y) ** 2;\n if (d < bestD) {\n bestD = d;\n best = i / 2;\n }\n }\n return best;\n}\n\n/** |s₊ − s₋| / max(|s₊|, |s₋|) of the slopes at θ = ∓5; null when both are flat. */\nfunction kink(v: number[]): number | null {\n const sMinus = (v[ZERO] - v[ZERO - 5]) / 5;\n const sPlus = (v[ZERO + 5] - v[ZERO]) / 5;\n const big = Math.max(Math.abs(sMinus), Math.abs(sPlus));\n if (big < FLAT_SLOPE) return null;\n return Math.abs(sPlus - sMinus) / big;\n}\n\n/** Largest |second difference| over the 1° ladder, the steps touching θ = 0 excluded, over the mean |Δ|. */\nfunction pop(v: number[]): number | null {\n let steps = 0;\n for (let i = 0; i + 1 < v.length; i++) steps += Math.abs(v[i + 1] - v[i]);\n const mean = steps / (v.length - 1);\n // Float32 landings of an unmoved part are bit-identical: exactly \"never moves\".\n if (mean < 1e-9) return null;\n let most = 0;\n for (let i = 1; i + 1 < v.length; i++) {\n if (Math.abs(i - ZERO) <= 1) continue;\n most = Math.max(most, Math.abs(v[i + 1] - 2 * v[i] + v[i - 1]));\n }\n return most / mean;\n}\n\n/** A pair gap or a width, face widths: the range along the nod at each turn. */\nexport interface NodRange {\n id: \"eyes\" | \"irises\" | \"mouth\";\n range: { m30: number; zero: number; p30: number };\n}\n\n/** The additivity residual of a landmark at the four corners; first letter AngleX, second AngleY. */\nexport interface CornerResidual {\n id: string;\n residual: { mm: number; mp: number; pm: number; pp: number };\n}\n\nexport type NodReport =\n | {\n unit: \"fw\";\n faceWidth: number;\n nod: NodRange[];\n corner: CornerResidual[];\n }\n | { unavailable: string };\n\nconst NOD_TURNS = [-30, 0, 30];\nconst NOD_PARTS = [\n \"face\",\n \"eye_L\",\n \"eye_R\",\n \"iris_L\",\n \"iris_R\",\n \"nose\",\n \"lip_upper\",\n \"mouth\",\n];\n/** The ladder indices of AngleY −30, 0 and +30. */\nconst NOD_ENDS = [0, -LADDER_MIN, LADDER_MAX - LADDER_MIN];\n\n/**\n * The nod at three turns: `ParamAngleY` −30 … +30 in 1° steps at `ParamAngleX`\n * −30, 0 and +30, no physics. `nod` is how far a pair gap (or the mouth's\n * width) moves along each ladder; `corner` is the AngleX × AngleY additivity\n * residual per landmark, the rest term included, so a rig whose parts add the\n * turn and the nod reads 0. Both are read against each other and against the\n * corpus's zeros, never against a bound.\n */\nexport function checkNod(model: IkiModel): NodReport {\n const face = model.parts.find((p) => p.id === \"face\");\n if (!face) return { unavailable: \"no face part\" };\n const hasEyes = [\"eye_L\", \"eye_R\"].every((id) =>\n model.parts.some((p) => p.id === id),\n );\n if (!hasEyes) return { unavailable: \"no eye_L and eye_R parts\" };\n const fw = face.width;\n const ladders = NOD_TURNS.map((x) =>\n Array.from({ length: LADDER_MAX - LADDER_MIN + 1 }, (_, i) =>\n landParts(\n model,\n { ParamAngleX: x, ParamAngleY: LADDER_MIN + i },\n NOD_PARTS,\n ),\n ),\n );\n const has = (id: string) => ladders[0][0].has(id);\n const boxes = (id: string) =>\n ladders.map((ladder) => ladder.map((l) => box(l.get(id)!, fw)));\n const spread = (v: number[]) => Math.max(...v) - Math.min(...v);\n const ranges = (values: (b: number, i: number) => number) => {\n const [m30, zero, p30] = NOD_TURNS.map((_, b) =>\n spread(\n Array.from({ length: LADDER_MAX - LADDER_MIN + 1 }, (_, i) =>\n values(b, i),\n ),\n ),\n );\n return { m30, zero, p30 };\n };\n\n const gap = (l: string, r: string): NodRange[\"range\"] => {\n const bl = boxes(l);\n const br = boxes(r);\n return ranges((b, i) => br[b][i].x - bl[b][i].x);\n };\n const nod: NodRange[] = [{ id: \"eyes\", range: gap(\"eye_L\", \"eye_R\") }];\n if (has(\"iris_L\") && has(\"iris_R\")) {\n nod.push({ id: \"irises\", range: gap(\"iris_L\", \"iris_R\") });\n }\n const mouthId = has(\"lip_upper\")\n ? \"lip_upper\"\n : has(\"mouth\")\n ? \"mouth\"\n : null;\n if (mouthId) {\n const bm = boxes(mouthId);\n nod.push({ id: \"mouth\", range: ranges((b, i) => bm[b][i].width) });\n }\n\n const corner = [\"eye_L\", \"eye_R\", \"nose\"]\n .filter(has)\n .map((id): CornerResidual => {\n const b = boxes(id);\n // The ladder of turn t, the pose at AngleY index j.\n const at = (t: number, j: number) => b[t][NOD_ENDS[j]];\n const residual = (t: number, j: number) => {\n const r = (axis: \"x\" | \"y\") =>\n at(t, j)[axis] - at(t, 1)[axis] - at(1, j)[axis] + at(1, 1)[axis];\n return Math.max(Math.abs(r(\"x\")), Math.abs(r(\"y\")));\n };\n return {\n id,\n residual: {\n mm: residual(0, 0),\n mp: residual(0, 2),\n pm: residual(2, 0),\n pp: residual(2, 2),\n },\n };\n });\n return { unit: \"fw\", faceWidth: fw, nod, corner };\n}\n\nexport function checkSweep(model: IkiModel): SweepReport {\n const face = model.parts.find((p) => p.id === \"face\");\n if (!face) return { preset: \"turn\", unavailable: \"no face part\" };\n const hasEyes = [\"eye_L\", \"eye_R\"].every((id) =>\n model.parts.some((p) => p.id === id),\n );\n if (!hasEyes) {\n return { preset: \"turn\", unavailable: \"no eye_L and eye_R parts\" };\n }\n const fw = face.width;\n const ladder = Array.from({ length: LADDER_MAX - LADDER_MIN + 1 }, (_, i) =>\n landParts(model, { ParamAngleX: LADDER_MIN + i }, PARTS),\n );\n const at = (id: string, i: number) => ladder[i].get(id)!;\n const ids = [\"eye_L\", \"eye_R\", ...(ladder[0].has(\"nose\") ? [\"nose\"] : [])];\n\n const landmarks = ids.map((id): SweepLandmark => {\n const boxes = ladder.map((_, i) => box(at(id, i), fw));\n const xs = boxes.map((b) => b.x);\n const plateIndex = nearestVertex(\n at(\"face\", ZERO),\n fw,\n boxes[ZERO].x,\n boxes[ZERO].y,\n );\n const plate = ladder.map((_, i) => at(\"face\", i)[plateIndex * 2] / fw);\n const lead = (i: number) => xs[i] - plate[i] - (xs[ZERO] - plate[ZERO]);\n return {\n id,\n amplitude: xs[xs.length - 1] - xs[0],\n xKink: kink(xs),\n widthKink: id === \"nose\" ? null : kink(boxes.map((b) => b.width)),\n lead: { m30: lead(0), p30: lead(xs.length - 1) },\n pop: pop(xs),\n };\n });\n\n const eyes = [\"eye_L\", \"eye_R\"].map((id) => box(at(id, ZERO), fw));\n const plateIndex = nearestVertex(\n at(\"face\", ZERO),\n fw,\n (eyes[0].x + eyes[1].x) / 2,\n (eyes[0].y + eyes[1].y) / 2,\n );\n const plateX = (i: number) => at(\"face\", i)[plateIndex * 2] / fw;\n return {\n preset: \"turn\",\n unit: \"fw\",\n faceWidth: fw,\n plateAmplitude: plateX(ladder.length - 1) - plateX(0),\n landmarks,\n };\n}\n\nconst fw3 = (v: number) => {\n const s = v.toFixed(3);\n return s === \"-0.000\" ? \"0.000\" : s;\n};\nconst signed = (v: number) => (fw3(v).startsWith(\"-\") ? fw3(v) : `+${fw3(v)}`);\nconst two = (v: number | null) => (v === null ? \"n/a\" : v.toFixed(2));\n\n/** One `SWEEP` line per landmark and one for the plate, or the one `unavailable` line. */\nexport function formatSweepReport(report: SweepReport): string[] {\n if (\"unavailable\" in report) {\n return [`SWEEP: unavailable — ${report.unavailable}`];\n }\n return [\n ...report.landmarks.map(\n (l) =>\n `SWEEP turn ${l.id}: amplitude ${fw3(l.amplitude)} fw, x kink ${two(l.xKink)}, width kink ${two(l.widthKink)}, lead -30 ${signed(l.lead.m30)} fw / +30 ${signed(l.lead.p30)} fw, pop ${two(l.pop)}`,\n ),\n `SWEEP turn plate: amplitude ${fw3(report.plateAmplitude)} fw`,\n ];\n}\n\n/** The `SWEEP nod` and `SWEEP corner` lines, or the one `unavailable` line. */\nexport function formatNodReport(report: NodReport): string[] {\n if (\"unavailable\" in report) {\n return [`SWEEP nod: unavailable — ${report.unavailable}`];\n }\n return [\n ...report.nod.map(\n ({ id, range: r }) =>\n `SWEEP nod ${id}: ${id === \"mouth\" ? \"width\" : \"gap\"} range X -30 ${fw3(r.m30)} / 0 ${fw3(r.zero)} / +30 ${fw3(r.p30)} fw`,\n ),\n ...report.corner.map(\n ({ id, residual: r }) =>\n `SWEEP corner ${id}: residual (-30,-30) ${fw3(r.mm)} / (-30,+30) ${fw3(r.mp)} / (+30,-30) ${fw3(r.pm)} / (+30,+30) ${fw3(r.pp)} fw`,\n ),\n ];\n}\n","/**\n * The sweeps `render_poses` renders on request: an eased ±30 `ParamAngleX`\n * turn, the same curve on `ParamAngleZ` (`roll`), or the `turn-nod` box through\n * every `ParamAngleX` × `ParamAngleY` stop, with the hair physics running. This\n * file is their pure pieces — the schedules, the sheet picks, the kymograph\n * row, the flipbook template and the output directory — all decided in Node;\n * the page only draws what the {@link SweepSpec} says. The page script imports\n * this file for TYPES only (it is bundled as a browser IIFE and must never pull\n * in `node:fs`).\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { landParts } from \"@ikijs/engine\";\nimport type { IkiModel } from \"@ikijs/format\";\nimport { AutoRigInputError, confineToWorkingDirectory } from \"./limits\";\nimport { BUST_SIZE, bustPadY, type RenderCrop } from \"./render-poses\";\n\n/** The physics clock, and the rate the frames are captured at (every second step). */\nexport const SWEEP_CLOCK_HZ = 60;\nexport const SWEEP_FPS = 30;\nexport const SWEEP_DURATION_S = 3;\nexport const BOX_DURATION_S = 6;\nexport const SWEEP_PRESETS = [\"turn\", \"turn-nod\", \"roll\"] as const;\nexport type SweepPreset = (typeof SWEEP_PRESETS)[number];\n/** Steps at θ = 0 before step 0, so the hair starts settled. A choice of this sweep. */\nexport const SWEEP_WARMUP_S = 0.5;\n/**\n * A hair over one 60 Hz sub-step, the clock `physics-runs.ts` runs\n * `checkPhysics` on: at exactly 1000/60 ms, float rounding leaves the drivers'\n * accumulator just short or just over, so about one frame in three would run no\n * sub-step and about as many two.\n */\nexport const SWEEP_FRAME_MS = (1000 / SWEEP_CLOCK_HZ) * (1 + 1e-9);\n/** The sheet's frames: those nearest each θ, on the −30 → +30 leg. */\nexport const SHEET_THETAS = [-30, -20, -10, -5, 0, 5, 10, 20, 30];\n/** Vision limit when a request carries more than 20 images. */\nexport const SHEET_MAX_SIDE = 2000;\nexport const SHEET_MARGIN = 8;\nexport const SHEET_LABEL_BAND = 24;\n/** Rows of the eye row's neighbourhood each frame contributes to the kymograph. */\nexport const KYMOGRAPH_BAND = 3;\n\nconst CAPTURE_EVERY = SWEEP_CLOCK_HZ / SWEEP_FPS;\n/** The sheet's leg: 0.75 s is θ = −30, 2.25 s is +30. */\nconst LEG_FROM_S = 0.75;\nconst LEG_TO_S = 2.25;\nconst AMPLITUDE_DEG = 30;\n/** The box's corners, in order; each leg runs at BOX_SPEED_DEG_S over its longer axis. */\nconst BOX_CORNERS: [number, number][] = [\n [0, 0],\n [0, -30],\n [-30, -30],\n [-30, 30],\n [30, 30],\n [30, -30],\n [0, -30],\n [0, 0],\n];\nconst BOX_SPEED_DEG_S = 50;\n/** The box sheet's cells, row-major by angle: columns X −30/0/+30, rows Y +30/0/−30. */\nconst BOX_SHEET_STOPS: [number, number][] = [\n [-30, 30],\n [0, 30],\n [30, 30],\n [-30, 0],\n [0, 0],\n [30, 0],\n [-30, -30],\n [0, -30],\n [30, -30],\n];\n\n/** What the caller asks for. */\nexport interface RequestedSweep {\n /** Becomes the directory `<outDir>/<name>/`. */\n name: string;\n preset: SweepPreset;\n /** Model px from the top-left, as a pose's crop; absent = the standard shot. */\n crop?: { x: number; y: number; w: number; h: number };\n}\n\n/** `manifest.json`. */\nexport interface SweepManifest {\n version: 2;\n preset: SweepPreset;\n parameters: string[];\n fps: number;\n clockHz: number;\n warmupS: number;\n durationS: number;\n crop: { x: number; y: number; w: number; h: number } | null;\n frame: { width: number; height: number };\n kymographRow: { row: number; at: \"eye row\" | \"middle\" } | null;\n sheet: { frames: number[]; cell: { w: number; h: number } };\n physicsOutputs: string[];\n frames: {\n i: number;\n file: string;\n t: number;\n /** Every scripted id and every physics output, read off the player after step 2i. */\n values: Record<string, number>;\n }[];\n}\n\n/** Everything the page needs, as values: it defines no sweep constant of its own. */\nexport interface SweepSpec {\n /** The ids `steps` script. */\n parameters: string[];\n frameMs: number;\n /** Clock steps run holding `steps[0]` before step 0. */\n warmup: number;\n /** One record per clock step, the ids in `parameters`. */\n steps: Record<string, number>[];\n /** Frame k shows the pose after clock step `captureEvery · k`. */\n captureEvery: number;\n /** Frames captured. */\n frames: number;\n frame: { width: number; height: number };\n /** The only ids the page lets the motion write. */\n physicsOutputs: string[];\n sheet: {\n /** Frame indices in cell order, row-major. */\n frames: number[];\n cell: { w: number; h: number };\n margin: number;\n labelBand: number;\n labels: string[];\n };\n /** Absent when the preset has none. */\n kymograph?: { row: number; band: number; at: \"eye row\" | \"middle\" };\n crop?: RenderCrop;\n}\n\n/** The turn: 0 → −30 at 0.75 s → 0 at 1.5 s → +30 at 2.25 s → 0 at 3 s. */\nexport function turnTheta(t: number): number {\n return -AMPLITUDE_DEG * Math.sin((2 * Math.PI * t) / SWEEP_DURATION_S);\n}\n\n/** The box: each leg eased by a half-cosine; a stop is approached and left at rest. */\nexport function boxAngles(t: number): { x: number; y: number } {\n let start = 0;\n for (let i = 0; i + 1 < BOX_CORNERS.length; i++) {\n const [fx, fy] = BOX_CORNERS[i];\n const [tx, ty] = BOX_CORNERS[i + 1];\n const len = Math.max(Math.abs(tx - fx), Math.abs(ty - fy));\n const dur = len / BOX_SPEED_DEG_S;\n if (t < start + dur) {\n const u = (t - start) / dur;\n const e = (1 - Math.cos(Math.PI * u)) / 2;\n return { x: fx + (tx - fx) * e, y: fy + (ty - fy) * e };\n }\n start += dur;\n }\n return { x: 0, y: 0 };\n}\n\n/**\n * What differs between presets, in one place: the angles scripted at time t,\n * how the sheet's frames are picked, how a cell is labelled, and whether the\n * eye row is drawn as a kymograph (the turn only: it moves on the others).\n */\ninterface PresetShape {\n durationS: number;\n angles: (t: number) => Record<string, number>;\n sheetFrames: (steps: Record<string, number>[], frames: number) => number[];\n label: (step: Record<string, number>) => string;\n kymograph: boolean;\n}\n\nconst legSheet = (id: string) => (steps: Record<string, number>[], n: number) =>\n turnSheetFrames(steps, n, id);\n\nconst SHAPES: Record<SweepPreset, PresetShape> = {\n turn: {\n durationS: SWEEP_DURATION_S,\n angles: (t) => ({ ParamAngleX: turnTheta(t) }),\n sheetFrames: legSheet(\"ParamAngleX\"),\n label: (s) => `θ ${signedDeg(s.ParamAngleX)}°`,\n kymograph: true,\n },\n // The roll rides the turn's own curve, so its frames sit at the angles the\n // turn sheet's do.\n roll: {\n durationS: SWEEP_DURATION_S,\n angles: (t) => ({ ParamAngleZ: turnTheta(t) }),\n sheetFrames: legSheet(\"ParamAngleZ\"),\n label: (s) => `Z ${signedDeg(s.ParamAngleZ)}°`,\n kymograph: false,\n },\n \"turn-nod\": {\n durationS: BOX_DURATION_S,\n angles: (t) => {\n const { x, y } = boxAngles(t);\n return { ParamAngleX: x, ParamAngleY: y };\n },\n sheetFrames: boxSheetFrames,\n label: (s) =>\n `X ${signedDeg(s.ParamAngleX)}° Y ${signedDeg(s.ParamAngleY)}°`,\n kymograph: false,\n },\n};\n\nexport function sweepDurationS(preset: SweepPreset): number {\n return SHAPES[preset].durationS;\n}\n\n/**\n * The eye row, model px from the top: the mean of the two eye parts' landed\n * bbox centres at rest. Undefined without both.\n */\nexport function eyeRowModelPx(model: IkiModel): number | undefined {\n const landed = landParts(model, {}, [\"eye_L\", \"eye_R\"]);\n const l = landed.get(\"eye_L\");\n const r = landed.get(\"eye_R\");\n if (!l || !r) return undefined;\n const centreY = (pts: Float32Array) => {\n let lo = Infinity;\n let hi = -Infinity;\n for (let i = 1; i < pts.length; i += 2) {\n lo = Math.min(lo, pts[i]);\n hi = Math.max(hi, pts[i]);\n }\n return (lo + hi) / 2;\n };\n return model.canvas.height / 2 - (centreY(l) + centreY(r)) / 2;\n}\n\nfunction physicsOutputIds(model: IkiModel): string[] {\n const ids = new Set<string>();\n for (const rig of model.physics ?? []) ids.add(rig.output.parameter);\n for (const chain of model.physicsChains ?? []) {\n for (const seg of chain.segments) ids.add(seg.output.parameter);\n }\n return [...ids];\n}\n\n/** Captured frames on the −30 → +30 leg, the one nearest each of SHEET_THETAS, chronological. */\nfunction turnSheetFrames(\n steps: Record<string, number>[],\n frames: number,\n id: string,\n) {\n const onLeg: number[] = [];\n for (let k = 0; k < frames; k++) {\n const t = k / SWEEP_FPS;\n if (t >= LEG_FROM_S && t <= LEG_TO_S) onLeg.push(k);\n }\n const x = (k: number) => steps[CAPTURE_EVERY * k][id];\n const picked: number[] = [];\n for (const target of SHEET_THETAS) {\n let best = onLeg[0];\n for (const k of onLeg) {\n // Strict, so a tie keeps the earlier frame.\n if (Math.abs(x(k) - target) < Math.abs(x(best) - target)) best = k;\n }\n if (!picked.includes(best)) picked.push(best);\n }\n return picked.sort((a, b) => a - b);\n}\n\n/** One captured frame per box stop, in BOX_SHEET_STOPS order (not sorted). */\nfunction boxSheetFrames(steps: Record<string, number>[], frames: number) {\n return BOX_SHEET_STOPS.map(([sx, sy]) => {\n const miss = (k: number) => {\n const s = steps[CAPTURE_EVERY * k];\n return Math.abs(s.ParamAngleX - sx) + Math.abs(s.ParamAngleY - sy);\n };\n let best = 0;\n for (let k = 1; k < frames; k++) {\n // Strict, so a tie keeps the earlier frame.\n if (miss(k) < miss(best)) best = k;\n }\n return best;\n });\n}\n\nfunction signedDeg(angle: number): string {\n // Rounded first, so a hair under zero never prints as \"−0.0\".\n const rounded = Math.round(angle * 10) / 10 + 0;\n const deg = rounded.toFixed(1);\n return rounded > 0 ? `+${deg}` : deg.replace(\"-\", \"−\");\n}\n\n/** The schedule and layout the page draws, from the model and the framing. */\nexport function sweepSpec(\n model: IkiModel,\n preset: SweepPreset,\n crop?: RenderCrop,\n): SweepSpec {\n const shape = SHAPES[preset];\n const { durationS } = shape;\n const steps = Array.from({ length: SWEEP_CLOCK_HZ * durationS }, (_, j) =>\n shape.angles(j / SWEEP_CLOCK_HZ),\n );\n const parameters = Object.keys(steps[0]);\n const frameCount = durationS * SWEEP_FPS;\n const dw = crop ? crop.dw : BUST_SIZE;\n const dh = crop ? crop.dh : BUST_SIZE;\n\n const m = SHEET_MARGIN;\n const b = SHEET_LABEL_BAND;\n const scale = Math.min(\n 1,\n (SHEET_MAX_SIDE - 2 * m) / (3 * dw),\n (SHEET_MAX_SIDE - 2 * m - 3 * b) / (3 * dh),\n );\n const frames = shape.sheetFrames(steps, frameCount);\n const labelOf = (k: number): string =>\n `${shape.label(steps[CAPTURE_EVERY * k])} t ${(k / SWEEP_FPS).toFixed(2)} s`;\n\n const { width: W, height: H } = model.canvas;\n let kymograph: SweepSpec[\"kymograph\"];\n if (shape.kymograph) {\n const yModel = eyeRowModelPx(model);\n let row = Math.round(dh / 2);\n let at: \"eye row\" | \"middle\" = \"middle\";\n if (yModel !== undefined) {\n const y0 = bustPadY(W, H);\n const s = BUST_SIZE / W;\n const eyeRow = Math.round(\n crop\n ? ((y0 + yModel * s - crop.sy) * crop.dh) / crop.sh\n : y0 + yModel * s,\n );\n if (eyeRow >= 1 && eyeRow <= dh - 2) {\n row = eyeRow;\n at = \"eye row\";\n }\n }\n kymograph = { row, band: KYMOGRAPH_BAND, at };\n }\n\n return {\n parameters,\n frameMs: SWEEP_FRAME_MS,\n warmup: SWEEP_WARMUP_S * SWEEP_CLOCK_HZ,\n steps,\n captureEvery: CAPTURE_EVERY,\n frames: frameCount,\n frame: { width: dw, height: dh },\n physicsOutputs: physicsOutputIds(model),\n sheet: {\n frames,\n cell: {\n w: Math.max(1, Math.floor(dw * scale)),\n h: Math.max(1, Math.floor(dh * scale)),\n },\n margin: m,\n labelBand: b,\n labels: frames.map(labelOf),\n },\n kymograph,\n crop,\n };\n}\n\n/**\n * `index.html`: the sweep's frames played from disk. The manifest is inlined\n * (a `file://` page cannot fetch a sibling JSON). `?b=<relative dir>` shows\n * another sweep of the same preset beside it in lockstep, by frame name.\n */\nexport function flipbookHtml(manifest: SweepManifest): string {\n // `<` escaped so no model-derived id can close the script element.\n const json = JSON.stringify(manifest).replace(/</g, \"\\\\u003c\");\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>${manifest.preset} sweep</title>\n<style>\nbody { font: 14px system-ui, sans-serif; margin: 16px; background: #222; color: #eee; }\n.row { display: flex; gap: 16px; align-items: flex-start; }\nimg { max-width: 48vw; height: auto; background: #444; }\n#b { display: none; }\n#controls { margin: 12px 0; display: flex; gap: 12px; align-items: center; }\n#scrub { flex: 1; max-width: 640px; }\n</style>\n</head>\n<body>\n<div class=\"row\"><img id=\"a\" alt=\"A\"><img id=\"b\" alt=\"B\"></div>\n<div id=\"controls\">\n<button id=\"play\" type=\"button\">pause</button>\n<input id=\"scrub\" type=\"range\" min=\"0\" value=\"0\" step=\"1\">\n<span id=\"readout\"></span>\n</div>\n<p>Add <code>?b=&lt;relative dir&gt;</code> to the address to show another sweep beside this one; it must be a sweep of the same preset, since frames are matched by file name.</p>\n<script id=\"manifest\" type=\"application/json\">${json}</script>\n<script>\n(function () {\n var m = JSON.parse(document.getElementById(\"manifest\").textContent);\n var b = new URLSearchParams(location.search).get(\"b\");\n var a = document.getElementById(\"a\");\n var bi = document.getElementById(\"b\");\n var scrub = document.getElementById(\"scrub\");\n var readout = document.getElementById(\"readout\");\n var play = document.getElementById(\"play\");\n var n = m.frames.length;\n var i = 0;\n var playing = true;\n scrub.max = String(n - 1);\n if (b) { bi.style.display = \"block\"; }\n function short(id) {\n return id === \"ParamAngleX\" ? \"X\" : id === \"ParamAngleY\" ? \"Y\" : id === \"ParamAngleZ\" ? \"Z\" : id;\n }\n function show(k) {\n i = k;\n var f = m.frames[k];\n a.src = f.file;\n if (b) { bi.src = b.replace(/\\\\/$/, \"\") + \"/\" + f.file; }\n scrub.value = String(k);\n readout.textContent = \"frame \" + k + m.parameters.map(function (id) {\n return \" \" + short(id) + \" \" + f.values[id].toFixed(1) + \"\\\\u00b0\";\n }).join(\"\") + \" t \" + f.t.toFixed(2) + \" s\";\n }\n play.addEventListener(\"click\", function () {\n playing = !playing;\n play.textContent = playing ? \"pause\" : \"play\";\n });\n scrub.addEventListener(\"input\", function () {\n playing = false;\n play.textContent = \"play\";\n show(Number(scrub.value));\n });\n setInterval(function () { if (playing) { show((i + 1) % n); } }, 1000 / m.fps);\n show(0);\n})();\n</script>\n</body>\n</html>\n`;\n}\n\nconst STALE_FILE = /^f\\d{3}\\.png$/;\nconst STALE_NAMES = [\n \"kymograph.png\",\n \"sheet.png\",\n \"manifest.json\",\n \"index.html\",\n];\n\n/**\n * Makes `<outDir>/<name>/` (an existing directory is fine), refuses a symbolic\n * link or a non-directory planted there — it would redirect every frame write\n * — and confines it to the working directory. `outDir` is the realpath'd dir\n * `resolveOutputDir` returned and `name`\n * is already checked by `planRenders`; `label` names the input in a refusal\n * (\"sweep\" or `sweeps[i]`). Call only once the browser was found. Returns the\n * real directory; it clears nothing — call `clearSweepDir` once every dir has\n * passed, so a refusal on a later one deletes nothing.\n */\nexport function prepareSweepDir(\n outDir: string,\n name: string,\n label: string,\n): string {\n const dir = path.join(outDir, name);\n try {\n fs.mkdirSync(dir);\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== \"EEXIST\") {\n throw new AutoRigInputError(`sweep dir: ${(e as Error).message}`);\n }\n }\n const stat = fs.lstatSync(dir);\n if (stat.isSymbolicLink()) {\n throw new AutoRigInputError(`${label}.name names ${dir}, a symbolic link`);\n }\n if (!stat.isDirectory()) {\n throw new AutoRigInputError(`${label}.name names ${dir}, not a directory`);\n }\n return confineToWorkingDirectory(process.cwd(), dir, \"sweep dir\", name);\n}\n\n/** Removes the earlier run's files from a dir `prepareSweepDir` returned. */\nexport function clearSweepDir(real: string): void {\n // A re-run under the same name must leave nothing of another run for a reader\n // of the whole dir, even when this one throws midway.\n for (const entry of fs.readdirSync(real)) {\n if (STALE_FILE.test(entry) || STALE_NAMES.includes(entry)) {\n fs.rmSync(path.join(real, entry));\n }\n }\n}\n","/**\n * The pose plan `render_poses` captures: the canvas framing, the crops and the\n * pose list, all decided from the model. It is the iki-character-loop's\n * render recipe, minus the page that ran it.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n IkiFormatError,\n StandardParameter,\n loadIkiModel,\n type IkiModel,\n} from \"@ikijs/format\";\nimport {\n checkPhysics,\n type FoldReport,\n type PhysicsReport,\n} from \"@ikijs/engine\";\nimport { checkModelFolds } from \"./fold-report\";\nimport {\n AutoRigInputError,\n confineToWorkingDirectory,\n resolveInputPath,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\nimport {\n NO_BROWSER_MESSAGE,\n findBrowser,\n withBrowser,\n type Evaluate,\n} from \"./render-browser\";\nimport {\n checkNod,\n checkSweep,\n type NodReport,\n type SweepReport,\n} from \"./sweep-report\";\nimport {\n SWEEP_CLOCK_HZ,\n SWEEP_FPS,\n SWEEP_WARMUP_S,\n flipbookHtml,\n clearSweepDir,\n prepareSweepDir,\n sweepDurationS,\n sweepSpec,\n type RequestedSweep,\n type SweepManifest,\n type SweepPreset,\n} from \"./sweep\";\n\nexport interface RenderCrop {\n sx: number;\n sy: number;\n sw: number;\n sh: number;\n dw: number;\n dh: number;\n}\n\nexport interface RenderPose {\n name: string;\n values: Record<string, number>;\n /** Canvas px source and output size; absent = the whole canvas. */\n crop?: RenderCrop;\n}\n\nexport interface RenderPlan {\n canvas: { width: number; height: number };\n /** The player's view; absent = the model's own canvas. */\n view?: { x: number; y: number; width: number; height: number };\n fullBody: boolean;\n /** The mouth's centre in model px from the top-left. */\n mouth?: { cx: number; cy: number };\n poses: RenderPose[];\n /** The sweep's fixed framing; absent when no sweep was asked for. */\n sweepCrop?: RenderCrop;\n /** The same for each `sweeps` entry, aligned with it; absent without `sweeps`. */\n sweepsCrops?: (RenderCrop | undefined)[];\n}\n\n/** A pose the caller names, rendered in place of the model's own set. */\nexport interface RequestedPose {\n /** Written as `<outDir>/<name>.png`. */\n name: string;\n values: Record<string, number>;\n /** Model px from the top-left; absent = framed as the standard shots. */\n crop?: { x: number; y: number; w: number; h: number };\n}\n\n// The playground's view width for a full body, in model widths.\nconst FULL_BODY_VIEW_WIDTH = 2.5;\n// The model's square is drawn this many px wide, in the whole shot or a crop.\nexport const BUST_SIZE = 560;\n// A requested crop is drawn this many px wide, at its own aspect, and at\n// most this many tall: the page sizes a canvas to it.\nconst CROP_WIDTH = 720;\nconst CROP_MAX_HEIGHT = 8192;\n// The name becomes a file in outDir: no separator can climb out of it.\nconst POSE_NAME = /^[A-Za-z0-9_.-]+$/;\n// The name becomes a DIRECTORY in outDir: a leading alphanumeric keeps `.` and\n// `..` out, which POSE_NAME accepts as harmless parts of a file name.\nconst SWEEP_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;\n\n/**\n * Bust-render px of vertical padding above a landscape model: the renderer\n * fits it into the square canvas and centres it. Zero for square and tall ones.\n */\nexport function bustPadY(width: number, height: number): number {\n return Math.max(0, (BUST_SIZE - (BUST_SIZE * height) / width) / 2);\n}\n\n/**\n * The model's own pose set, or `requested` alone when given. Throws\n * `AutoRigInputError` for a request it cannot render.\n */\nexport function planRenders(\n model: IkiModel,\n requested?: RequestedPose[],\n sweep?: RequestedSweep,\n sweeps?: RequestedSweep[],\n): RenderPlan {\n const { width: W, height: H } = model.canvas;\n const fullBody = H > W;\n const canvas = fullBody\n ? {\n width: FULL_BODY_VIEW_WIDTH * BUST_SIZE,\n height: Math.ceil((BUST_SIZE * H) / W),\n }\n : { width: BUST_SIZE, height: BUST_SIZE };\n const view = fullBody\n ? { x: 0, y: 0, width: FULL_BODY_VIEW_WIDTH * W, height: H }\n : undefined;\n\n // The model's square sits in the middle of the canvas.\n const x0 = (canvas.width - BUST_SIZE) / 2;\n const s = BUST_SIZE / W;\n const y0 = bustPadY(W, H);\n\n // The auto-rigger writes world-space part transforms and its deformers carry\n // no base transform, so the rest transform alone places the part.\n const mouthPart =\n model.parts.find((p) => p.id === \"mouth_inner\") ??\n model.parts.find((p) => p.id === \"mouth\");\n const mouth = mouthPart\n ? { cx: W / 2 + mouthPart.transform.x, cy: H / 2 - mouthPart.transform.y }\n : undefined;\n\n const squareCrop: RenderCrop | undefined = fullBody\n ? {\n sx: x0,\n sy: 0,\n sw: BUST_SIZE,\n sh: BUST_SIZE,\n dw: BUST_SIZE,\n dh: BUST_SIZE,\n }\n : undefined;\n const square = (name: string, values: Record<string, number> = {}) => ({\n name,\n values,\n crop: squareCrop,\n });\n const whole = (name: string, values: Record<string, number> = {}) => ({\n name,\n values,\n });\n\n // Clamped to the canvas first, so a box grown past an edge still renders.\n const toRenderCrop = (\n crop: NonNullable<RequestedPose[\"crop\"]>,\n label: string,\n ): RenderCrop => {\n const left = Math.max(crop.x, 0);\n const top = Math.max(crop.y, 0);\n const w = Math.min(crop.x + crop.w, W) - left;\n const h = Math.min(crop.y + crop.h, H) - top;\n // Negated so a NaN corner is refused too.\n if (!(w > 0 && h > 0)) {\n throw new AutoRigInputError(\n `${label} does not overlap the model's ${W}x${H} canvas`,\n );\n }\n // Refused here, not by the page after earlier poses were written.\n const dh = Math.round((CROP_WIDTH * h) / w);\n if (dh < 1 || dh > CROP_MAX_HEIGHT) {\n throw new AutoRigInputError(\n `${label} meets the canvas in ${w}x${h} model px, which ${CROP_WIDTH} px wide draws ${dh} px tall, outside 1..${CROP_MAX_HEIGHT}`,\n );\n }\n return {\n sx: x0 + left * s,\n sy: y0 + top * s,\n sw: w * s,\n sh: h * s,\n dw: CROP_WIDTH,\n dh,\n };\n };\n if (sweeps && sweeps.length === 0) {\n throw new AutoRigInputError(\"sweeps is empty\");\n }\n // `sweep` first, then `sweeps` in order: names are directories, presets are\n // frames, and neither may repeat across the lot.\n const asked = [\n ...(sweep ? [{ label: \"sweep\", entry: sweep }] : []),\n ...(sweeps ?? []).map((entry, i) => ({ label: `sweeps[${i}]`, entry })),\n ];\n asked.forEach(({ label, entry }, i) => {\n if (!SWEEP_NAME.test(entry.name)) {\n throw new AutoRigInputError(\n `${label}.name must match ${SWEEP_NAME.source} (it names <outDir>/<name>/): ${JSON.stringify(entry.name)}`,\n );\n }\n const sameName = asked.findIndex(\n (a) => a.entry.name.toLowerCase() === entry.name.toLowerCase(),\n );\n if (sameName < i) {\n throw new AutoRigInputError(\n `${label}.name ${JSON.stringify(entry.name)} repeats ${asked[sameName].label}.name ${JSON.stringify(asked[sameName].entry.name)} (ignoring case: one directory on a case-insensitive disk)`,\n );\n }\n const samePreset = asked.findIndex((a) => a.entry.preset === entry.preset);\n if (samePreset < i) {\n throw new AutoRigInputError(\n `${label}.preset ${JSON.stringify(entry.preset)} repeats ${asked[samePreset].label}.preset (the same frames twice)`,\n );\n }\n });\n const cropOf = (entry: RequestedSweep, label: string) =>\n entry.crop ? toRenderCrop(entry.crop, `${label}.crop`) : squareCrop;\n const sweepCrop = sweep ? cropOf(sweep, \"sweep\") : undefined;\n const sweepsCrops = sweeps?.map((entry, i) => cropOf(entry, `sweeps[${i}]`));\n\n if (requested) {\n if (requested.length === 0) throw new AutoRigInputError(\"poses is empty\");\n const poses = requested.map((pose, i): RenderPose => {\n checkRequest(requested, i);\n if (!pose.crop) return square(pose.name, pose.values);\n return {\n name: pose.name,\n values: pose.values,\n crop: toRenderCrop(pose.crop, `poses[${i}].crop`),\n };\n });\n return { canvas, view, fullBody, mouth, poses, sweepCrop, sweepsCrops };\n }\n\n // The engine ignores an undeclared id, so this only keeps `stress` from\n // naming settings the rig lacks: every loop rig declares its other ids (the\n // composer requires brows), but the body angles only with a `body` layer.\n const bodyAngles = Object.fromEntries(\n [\n StandardParameter.BodyAngleX,\n StandardParameter.BodyAngleY,\n StandardParameter.BodyAngleZ,\n ]\n .filter((id) => model.parameters.some((p) => p.id === id))\n .map((id) => [id, -10]),\n );\n\n const poses: RenderPose[] = [\n square(\"rest\"),\n square(\"turn-m30\", { ParamAngleX: -30 }),\n square(\"turn-p30\", { ParamAngleX: 30 }),\n square(\"turn-15\", { ParamAngleX: 15 }),\n square(\"nod-15\", { ParamAngleY: 15 }),\n square(\"blink\", { ParamEyeLOpen: 0 }),\n square(\"blink-half\", { ParamEyeLOpen: 0.5 }),\n square(\"gaze\", { ParamEyeBallX: 1 }),\n square(\"combined\", { ParamAngleX: 30, ParamAngleY: 30, ParamAngleZ: 30 }),\n // Every head angle at its other extreme with the face moving too, where\n // moves that each look fine alone stack up into a fold.\n square(\"stress\", {\n ParamAngleX: -30,\n ParamAngleY: -30,\n ParamAngleZ: -30,\n ParamMouthOpenY: 1,\n ParamEyeLOpen: 0.5,\n ParamEyeROpen: 0.5,\n ParamBrowLY: -1,\n ParamBrowRY: 1,\n ParamBrowLAngle: 1,\n ParamBrowRAngle: -1,\n ...bodyAngles,\n }),\n ];\n\n if (mouth) {\n // 180 x 120 model px centred on the mouth, drawn x4 onto 720 x 480: a\n // small mouth is unreadable in the whole shot.\n const crop = {\n sx: x0 + (mouth.cx - 90) * s,\n sy: y0 + (mouth.cy - 60) * s,\n sw: 180 * s,\n sh: 120 * s,\n dw: 720,\n dh: 480,\n };\n for (const open of [0, 0.3, 0.6, 1]) {\n for (const [name, form] of [\n [\"m1\", -1],\n [\"0\", 0],\n [\"p1\", 1],\n ] as const) {\n poses.push({\n name: `mouth-open-${open}-form-${name}`,\n values: { ParamMouthOpenY: open, ParamMouthForm: form },\n crop,\n });\n }\n }\n poses.push(\n {\n name: \"mouth-laugh\",\n values: { ParamMouthOpenY: 0.8, ParamMouthForm: 1 },\n crop,\n },\n { name: \"mouth-surprised\", values: { ParamMouthOpenY: 0.9 }, crop },\n {\n name: \"mouth-turn-p30-half\",\n values: { ParamAngleX: 30, ParamMouthOpenY: 0.5 },\n crop,\n },\n );\n }\n\n if (fullBody) {\n poses.push(\n whole(\"full-rest\"),\n whole(\"full-turn-p30\", { ParamAngleX: 30 }),\n whole(\"full-body-x-m10\", { ParamBodyAngleX: -10 }),\n whole(\"full-body-x-p10\", { ParamBodyAngleX: 10 }),\n whole(\"full-body-y-m10\", { ParamBodyAngleY: -10 }),\n whole(\"full-body-y-p10\", { ParamBodyAngleY: 10 }),\n whole(\"full-body-z-m10\", { ParamBodyAngleZ: -10 }),\n whole(\"full-body-z-p10\", { ParamBodyAngleZ: 10 }),\n whole(\"full-arm-l-16\", { ParamArmL: 16 }),\n whole(\"full-arm-l-32\", { ParamArmL: 32 }),\n whole(\"full-arm-r-16\", { ParamArmR: 16 }),\n whole(\"full-arm-r-32\", { ParamArmR: 32 }),\n whole(\"full-elbow-l-m10\", { ParamElbowL: -10 }),\n whole(\"full-elbow-l-45\", { ParamElbowL: 45 }),\n whole(\"full-elbow-l-90\", { ParamElbowL: 90 }),\n whole(\"full-elbow-r-m10\", { ParamElbowR: -10 }),\n whole(\"full-elbow-r-45\", { ParamElbowR: 45 }),\n whole(\"full-elbow-r-90\", { ParamElbowR: 90 }),\n );\n if (model.parameters.some((p) => p.id === StandardParameter.ArmPoseRight)) {\n poses.push(\n whole(\"full-pose-l\", { ParamArmPoseL: 1 }),\n whole(\"full-pose-r\", { ParamArmPoseR: 1 }),\n whole(\"full-pose-r-angle-m15\", {\n ParamArmPoseR: 1,\n ParamArmPoseAngleR: -15,\n }),\n whole(\"full-pose-r-angle-p15\", {\n ParamArmPoseR: 1,\n ParamArmPoseAngleR: 15,\n }),\n whole(\"full-pose-r-half\", { ParamArmPoseR: 0.5 }),\n );\n }\n }\n\n return { canvas, view, fullBody, mouth, poses, sweepCrop, sweepsCrops };\n}\n\n/** `requested[i]`'s name and values, as `planRenders` takes them. */\nfunction checkRequest(requested: RequestedPose[], i: number): void {\n const { name, values } = requested[i];\n if (!POSE_NAME.test(name)) {\n throw new AutoRigInputError(\n `poses[${i}].name must match ${POSE_NAME.source} (it names <outDir>/<name>.png): ${JSON.stringify(name)}`,\n );\n }\n const first = requested.findIndex(\n (p) => p.name.toLowerCase() === name.toLowerCase(),\n );\n if (first < i) {\n throw new AutoRigInputError(\n `poses[${i}].name ${JSON.stringify(name)} repeats poses[${first}].name ${JSON.stringify(requested[first].name)} (ignoring case: one file on a case-insensitive disk)`,\n );\n }\n for (const [id, value] of Object.entries(values)) {\n if (!Number.isFinite(value)) {\n throw new AutoRigInputError(\n `poses[${i}].values.${id} must be a finite number, got ${value}`,\n );\n }\n }\n}\n\nexport interface RenderPosesInput {\n /** The rigged `.iki` to render (resolved against cwd). */\n modelPath: string;\n /** Existing directory under cwd the pose PNGs are written into. */\n outDir: string;\n /** Rendered in place of the model's own set; each is also fold-checked. */\n poses?: RequestedPose[];\n /** A turn sweep rendered in addition to the poses, into `<outDir>/<name>/`. */\n sweep?: RequestedSweep;\n /** More sweeps, rendered after `sweep`, each into its own `<outDir>/<name>/`. */\n sweeps?: RequestedSweep[];\n /**\n * Part ids left out of the drawn frames of this call, poses and sweeps alike.\n * The reports still read the whole model.\n */\n hideParts?: string[];\n}\n\n/**\n * `model` without the parts `hideParts` names, for the page to draw. Throws\n * `AutoRigInputError` for an id the model lacks, or one a part that stays is\n * clipped to (its mask would vanish and the part would draw unclipped) or\n * occluded by (it would show whole where its occluder hid it).\n */\nfunction withoutParts(model: IkiModel, hideParts: string[]): IkiModel {\n const hidden = new Set(hideParts);\n hideParts.forEach((id, i) => {\n if (!model.parts.some((p) => p.id === id)) {\n throw new AutoRigInputError(\n `hideParts[${i}] ${JSON.stringify(id)} is not a part of the model`,\n );\n }\n const kept = model.parts.find(\n (p) => !hidden.has(p.id) && p.clip?.masks.includes(id),\n );\n if (kept) {\n throw new AutoRigInputError(\n `hideParts[${i}] ${JSON.stringify(id)} masks ${JSON.stringify(kept.id)}, which stays; hide ${JSON.stringify(kept.id)} too`,\n );\n }\n const occluded = model.parts.find(\n (p) => !hidden.has(p.id) && p.occlusion?.by.includes(id),\n );\n if (occluded) {\n throw new AutoRigInputError(\n `hideParts[${i}] ${JSON.stringify(id)} occludes ${JSON.stringify(occluded.id)}, which stays; hide ${JSON.stringify(occluded.id)} too`,\n );\n }\n });\n return { ...model, parts: model.parts.filter((p) => !hidden.has(p.id)) };\n}\n\nexport interface SweepOutput {\n name: string;\n preset: SweepPreset;\n dir: string;\n fps: number;\n frames: number;\n manifest: string;\n sheet: string;\n /** Absent for a preset without one (`turn-nod`). */\n kymograph?: string;\n flipbook: string;\n report: SweepReport;\n nod: NodReport;\n}\n\nexport type RenderPosesResult =\n | {\n ok: true;\n outDir: string;\n canvas: RenderPlan[\"canvas\"];\n fullBody: boolean;\n mouth?: RenderPlan[\"mouth\"];\n /** Texture indices the engine could not load; the renders lack them. */\n failedTextures: number[];\n poses: { name: string; path: string }[];\n /** The model's own canvas, which `folds`' rest points are placed on in\n * the text (`canvas` is the render's). */\n modelCanvas: IkiModel[\"canvas\"];\n /** The model's folds, as `auto_rig_from_layers` reports them.\n * Report-only: a fold never fails the render. */\n folds: FoldReport;\n /** The model's own physics rigs (`poses` do not enter it), as\n * `auto_rig_from_layers` reports them. Report-only: it never fails\n * the render. */\n physics: PhysicsReport;\n /** Present whenever `sweep` was asked for; absent only from a server\n * before 0.31.0, which strips the input. */\n sweep?: SweepOutput;\n /** In request order; present whenever `sweeps` was asked for, absent\n * from a server before 0.32.0, which strips the input. */\n sweeps?: SweepOutput[];\n }\n | { ok: false; error: string };\n\nconst PNG_PREFIX = \"data:image/png;base64,\";\nconst PAGE_SCRIPT_MS = 10_000;\nconst LOAD_MS = 60_000;\nconst CAPTURE_MS = 15_000;\n\nfunction readPageScript(): string {\n // Resolves from both src/ (vitest) and dist/: each sits one level under the package.\n const url = new URL(\"../dist/render-page.global.js\", import.meta.url);\n try {\n return readFileSync(url, \"utf8\");\n } catch (cause) {\n // A broken build or install, not caller input: it surfaces as a tool error.\n throw new Error(\n \"could not read the render page script; run `pnpm build` in packages/mcp\",\n { cause },\n );\n }\n}\n\n/** Runs the sweep in the loaded page and writes its files into `dir`. */\nasync function captureSweep(\n evaluate: Evaluate,\n model: IkiModel,\n requested: RequestedSweep,\n crop: RenderCrop | undefined,\n dir: string,\n report: SweepReport,\n nod: NodReport,\n): Promise<SweepOutput> {\n const spec = sweepSpec(model, requested.preset, crop);\n await evaluate(\n `window.__ikiRender.sweepBegin(${JSON.stringify(spec)})`,\n CAPTURE_MS,\n );\n const frames: SweepManifest[\"frames\"] = [];\n for (let k = 0; k < spec.frames; k++) {\n const { png, values } = (await evaluate(\n \"window.__ikiRender.sweepFrame()\",\n CAPTURE_MS,\n )) as { png: string; values: Record<string, number> };\n if (typeof png !== \"string\" || !png.startsWith(PNG_PREFIX)) {\n throw new Error(\n `sweep ${requested.name} frame ${k}: the page returned no PNG`,\n );\n }\n const file = `f${String(k).padStart(3, \"0\")}.png`;\n writeFileAtomic(\n path.join(dir, file),\n Buffer.from(png.slice(PNG_PREFIX.length), \"base64\"),\n );\n frames.push({\n i: k,\n file,\n t: k / SWEEP_FPS,\n values,\n });\n }\n const end = (await evaluate(\"window.__ikiRender.sweepEnd()\", CAPTURE_MS)) as {\n sheet: string;\n kymograph?: string;\n };\n for (const [what, url] of Object.entries(end)) {\n // Absent for a preset without a kymograph.\n if (url === undefined) continue;\n if (typeof url !== \"string\" || !url.startsWith(PNG_PREFIX)) {\n throw new Error(\n `sweep ${requested.name} ${what}: the page returned no PNG`,\n );\n }\n }\n const sheet = path.join(dir, \"sheet.png\");\n writeFileAtomic(\n sheet,\n Buffer.from(end.sheet.slice(PNG_PREFIX.length), \"base64\"),\n );\n let kymograph: string | undefined;\n if (end.kymograph !== undefined) {\n kymograph = path.join(dir, \"kymograph.png\");\n writeFileAtomic(\n kymograph,\n Buffer.from(end.kymograph.slice(PNG_PREFIX.length), \"base64\"),\n );\n }\n const manifest: SweepManifest = {\n version: 2,\n preset: requested.preset,\n parameters: spec.parameters,\n fps: SWEEP_FPS,\n clockHz: SWEEP_CLOCK_HZ,\n warmupS: SWEEP_WARMUP_S,\n durationS: sweepDurationS(requested.preset),\n crop: requested.crop ?? null,\n frame: spec.frame,\n kymographRow: spec.kymograph\n ? { row: spec.kymograph.row, at: spec.kymograph.at }\n : null,\n sheet: { frames: spec.sheet.frames, cell: spec.sheet.cell },\n physicsOutputs: spec.physicsOutputs,\n frames,\n };\n const manifestPath = path.join(dir, \"manifest.json\");\n const flipbook = path.join(dir, \"index.html\");\n writeFileAtomic(manifestPath, JSON.stringify(manifest, null, 2) + \"\\n\");\n writeFileAtomic(flipbook, flipbookHtml(manifest));\n return {\n name: requested.name,\n preset: requested.preset,\n dir,\n fps: SWEEP_FPS,\n frames: spec.frames,\n manifest: manifestPath,\n sheet,\n ...(kymograph ? { kymograph } : {}),\n flipbook,\n report,\n nod,\n };\n}\n\n/**\n * Render the model's pose set into `outDir`. Only caller-input failures\n * (`AutoRigInputError`, `IkiFormatError`, and no installed browser) come back as\n * `{ ok: false, error }`; a browser or page failure throws.\n */\nexport async function renderPoses(\n input: RenderPosesInput,\n): Promise<RenderPosesResult> {\n try {\n const modelFile = confineToWorkingDirectory(\n process.cwd(),\n resolveInputPath(input.modelPath, \"model\"),\n \"model path\",\n input.modelPath,\n );\n const outDir = resolveOutputDir(input.outDir);\n const model = loadIkiModel(readFileSync(modelFile, \"utf8\"));\n const plan = planRenders(model, input.poses, input.sweep, input.sweeps);\n const drawn = input.hideParts\n ? withoutParts(model, input.hideParts)\n : model;\n const browser = findBrowser();\n if (!browser) return { ok: false, error: NO_BROWSER_MESSAGE };\n const pageScript = readPageScript();\n const folds = checkModelFolds(\n model,\n input.poses?.map((p) => p.values),\n );\n const physics = checkPhysics(model);\n // Only now: a call refused for its input or for a missing browser\n // creates and deletes nothing.\n const sweepDir = input.sweep\n ? prepareSweepDir(outDir, input.sweep.name, \"sweep\")\n : undefined;\n const sweepsDirs = input.sweeps?.map((s, i) =>\n prepareSweepDir(outDir, s.name, `sweeps[${i}]`),\n );\n // Only once every dir passed: a refusal above deletes nothing.\n for (const d of [sweepDir, ...(sweepsDirs ?? [])]) {\n if (d) clearSweepDir(d);\n }\n const sweepReport =\n input.sweep || input.sweeps ? checkSweep(model) : undefined;\n const nodReport = input.sweep || input.sweeps ? checkNod(model) : undefined;\n\n const { failedTextures, poses, sweep, sweeps } = await withBrowser(\n browser,\n async (evaluate) => {\n await evaluate(pageScript, PAGE_SCRIPT_MS);\n const loaded = (await evaluate(\n `window.__ikiRender.load(${JSON.stringify(drawn)}, ${JSON.stringify({ canvas: plan.canvas, view: plan.view })})`,\n LOAD_MS,\n )) as { failedTextures: number[] };\n const written: { name: string; path: string }[] = [];\n for (const pose of plan.poses) {\n const url = await evaluate(\n `window.__ikiRender.capture(${JSON.stringify(pose.values)}, ${JSON.stringify(pose.crop)})`,\n CAPTURE_MS,\n );\n if (typeof url !== \"string\" || !url.startsWith(PNG_PREFIX)) {\n throw new Error(`pose ${pose.name}: the page returned no PNG`);\n }\n const file = path.join(outDir, `${pose.name}.png`);\n writeFileAtomic(\n file,\n Buffer.from(url.slice(PNG_PREFIX.length), \"base64\"),\n );\n written.push({ name: pose.name, path: file });\n }\n const sweep =\n input.sweep && sweepDir && sweepReport && nodReport\n ? await captureSweep(\n evaluate,\n model,\n input.sweep,\n plan.sweepCrop,\n sweepDir,\n sweepReport,\n nodReport,\n )\n : undefined;\n let sweeps: SweepOutput[] | undefined;\n if (input.sweeps && sweepsDirs && sweepReport && nodReport) {\n sweeps = [];\n for (const [i, requested] of input.sweeps.entries()) {\n sweeps.push(\n await captureSweep(\n evaluate,\n model,\n requested,\n plan.sweepsCrops?.[i],\n sweepsDirs[i],\n sweepReport,\n nodReport,\n ),\n );\n }\n }\n return {\n failedTextures: loaded.failedTextures,\n poses: written,\n sweep,\n sweeps,\n };\n },\n );\n return {\n ok: true,\n outDir,\n canvas: plan.canvas,\n fullBody: plan.fullBody,\n mouth: plan.mouth,\n failedTextures,\n poses,\n modelCanvas: model.canvas,\n folds,\n physics,\n sweep,\n sweeps,\n };\n } catch (error) {\n if (error instanceof AutoRigInputError || error instanceof IkiFormatError) {\n return { ok: false, error: error.message };\n }\n throw error;\n }\n}\n","/**\n * Browser discovery and a headless DevTools driver for `render_poses`: find a\n * system Chrome/Edge/Chromium, launch it, and evaluate scripts over the\n * DevTools protocol on Node's global `WebSocket`. No Playwright, no dependency.\n */\n\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { AutoRigInputError } from \"./limits\";\n\nexport const NO_BROWSER_MESSAGE =\n \"render_poses needs a Chromium-based browser and found none. Install Google Chrome, Microsoft Edge or Chromium, or set CHROME_PATH to its executable.\";\n\nconst DARWIN_CANDIDATES = [\n \"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\",\n \"/Applications/Chromium.app/Contents/MacOS/Chromium\",\n \"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge\",\n];\nconst LINUX_CANDIDATES = [\n \"/usr/bin/google-chrome\",\n \"/usr/bin/google-chrome-stable\",\n \"/usr/bin/chromium\",\n \"/usr/bin/chromium-browser\",\n \"/usr/bin/microsoft-edge\",\n \"/snap/bin/chromium\",\n];\nconst WIN32_ROOTS = [\"PROGRAMFILES\", \"PROGRAMFILES(X86)\", \"LOCALAPPDATA\"];\nconst WIN32_SUFFIXES = [\n [\"Google\", \"Chrome\", \"Application\", \"chrome.exe\"],\n [\"Microsoft\", \"Edge\", \"Application\", \"msedge.exe\"],\n];\n\nconst CLOSE_GRACE_MS = 2000;\nconst DEFAULT_TIMEOUT_MS = 30000;\nconst BROWSER_CLOSE_MS = 1000;\n\nfunction isExecutableFile(file: string): boolean {\n try {\n if (!fs.statSync(file).isFile()) return false;\n fs.accessSync(file, fs.constants.X_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nexport interface FindBrowserOptions {\n env: NodeJS.ProcessEnv;\n platform: NodeJS.Platform;\n isExecutable: (file: string) => boolean;\n}\n\n/** The browser to drive, or `undefined` when none is installed. */\nexport function findBrowser({\n env = process.env,\n platform = process.platform,\n isExecutable = isExecutableFile,\n}: Partial<FindBrowserOptions> = {}): string | undefined {\n const override = env.CHROME_PATH;\n if (override) {\n // A bad override must not fall through to spawn, where it fails obscurely.\n if (!isExecutable(override)) {\n throw new AutoRigInputError(\n `CHROME_PATH is not an executable file: ${override}`,\n );\n }\n return override;\n }\n let candidates: string[];\n if (platform === \"darwin\") candidates = DARWIN_CANDIDATES;\n else if (platform === \"win32\") {\n candidates = [];\n for (const suffix of WIN32_SUFFIXES) {\n for (const root of WIN32_ROOTS) {\n const base = env[root];\n if (base) candidates.push(path.win32.join(base, ...suffix));\n }\n }\n } else candidates = LINUX_CANDIDATES;\n return candidates.find((file) => isExecutable(file));\n}\n\nexport type Evaluate = (\n expression: string,\n timeoutMs: number,\n) => Promise<unknown>;\n\nexport interface Browser {\n openPage(): Promise<Evaluate>;\n close(): Promise<void>;\n}\n\ninterface RuntimeEvaluate {\n result: { value?: unknown };\n exceptionDetails?: {\n text: string;\n exception?: { description?: string; value?: unknown };\n };\n}\n\n/**\n * Race `promise` against a timer, clearing the timer either way. `detail`\n * adds context to the timeout message, read only when it fires.\n */\nfunction within<T>(\n promise: Promise<T>,\n ms: number,\n what: string,\n detail?: () => string,\n): Promise<T> {\n let timer: NodeJS.Timeout;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new Error(\n `${what} timed out after ${ms} ms${detail ? `: ${detail()}` : \"\"}`,\n ),\n ),\n ms,\n );\n });\n return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));\n}\n\ninterface CdpClient {\n send<T = unknown>(\n method: string,\n timeoutMs: number,\n params?: object,\n sessionId?: string,\n ): Promise<T>;\n}\n\nfunction connectCdp(url: string, timeoutMs: number): Promise<CdpClient> {\n const socket = new WebSocket(url);\n let nextId = 0;\n let socketClosed = false;\n const pending = new Map<\n number,\n { resolve: (v: unknown) => void; reject: (e: Error) => void }\n >();\n socket.addEventListener(\"message\", (event) => {\n const message = JSON.parse(String(event.data));\n const entry = pending.get(message.id);\n if (!entry) return; // a protocol event, not a reply\n pending.delete(message.id);\n if (message.error) {\n entry.reject(\n new Error(`${message.error.message} (${message.error.code})`),\n );\n } else entry.resolve(message.result);\n });\n socket.addEventListener(\"close\", () => {\n socketClosed = true;\n for (const entry of pending.values()) {\n entry.reject(new Error(\"DevTools connection closed\"));\n }\n pending.clear();\n });\n const opened = new Promise<CdpClient>((resolve, reject) => {\n socket.addEventListener(\"error\", () =>\n reject(new Error(\"DevTools connection failed\")),\n );\n socket.addEventListener(\"open\", () =>\n resolve({\n send<T>(\n method: string,\n callTimeoutMs: number,\n params?: object,\n sessionId?: string,\n ) {\n // send() on a closed socket is silent; fail now, not at the timeout.\n if (socketClosed) {\n return Promise.reject(new Error(\"DevTools connection closed\"));\n }\n const id = ++nextId;\n const reply = new Promise<T>((res, rej) => {\n pending.set(id, {\n resolve: res as (v: unknown) => void,\n reject: rej,\n });\n });\n socket.send(JSON.stringify({ id, method, params, sessionId }));\n return within(reply, callTimeoutMs, method).finally(() =>\n pending.delete(id),\n );\n },\n }),\n );\n });\n // Closing the socket on failure lets a hung connect not outlive the launch.\n return within(opened, timeoutMs, \"DevTools connection\").catch((error) => {\n socket.close();\n throw error;\n });\n}\n\nfunction startError(executable: string, error: NodeJS.ErrnoException): Error {\n return new Error(\n `could not start ${executable}: ${error.code ?? error.message}`,\n );\n}\n\n/** The DevTools websocket URL Chrome prints on stderr once it is ready. */\nfunction waitForDevTools(\n child: ChildProcess,\n closed: Promise<void>,\n getSpawnError: () => NodeJS.ErrnoException | undefined,\n executable: string,\n timeoutMs: number,\n): Promise<string> {\n let tail = \"\";\n return within(\n new Promise<string>((resolve, reject) => {\n // Keeps draining after the match so Chrome never blocks on a full pipe.\n child.stderr!.on(\"data\", (chunk) => {\n tail = (tail + chunk).slice(-2000);\n const match = /DevTools listening on (ws:\\/\\/\\S+)/.exec(tail);\n if (match) resolve(match[1]);\n });\n void closed.then(() => {\n const spawnError = getSpawnError();\n reject(\n spawnError\n ? startError(executable, spawnError)\n : new Error(\n `${executable} exited before DevTools was ready: ${tail.trim()}`,\n ),\n );\n });\n }),\n timeoutMs,\n \"browser startup\",\n () => tail.trim() || \"no output\",\n );\n}\n\nasync function openPage(cdp: CdpClient, timeoutMs: number): Promise<Evaluate> {\n const { targetId } = await cdp.send<{ targetId: string }>(\n \"Target.createTarget\",\n timeoutMs,\n { url: \"about:blank\" },\n );\n const { sessionId } = await cdp.send<{ sessionId: string }>(\n \"Target.attachToTarget\",\n timeoutMs,\n { targetId, flatten: true },\n );\n return async (expression, evalTimeoutMs) => {\n const { result, exceptionDetails } = await cdp.send<RuntimeEvaluate>(\n \"Runtime.evaluate\",\n evalTimeoutMs,\n { expression, awaitPromise: true, returnByValue: true },\n sessionId,\n );\n if (exceptionDetails) {\n // A thrown non-Error has no description; its value beats \"Uncaught\".\n const thrown = exceptionDetails.exception;\n throw new Error(\n thrown?.description ??\n (thrown && \"value\" in thrown\n ? String(thrown.value)\n : exceptionDetails.text),\n );\n }\n return result.value;\n };\n}\n\n/** Cleanup must not replace the result of a render that already finished. */\nfunction removeProfile(profile: string): void {\n try {\n fs.rmSync(profile, {\n recursive: true,\n force: true,\n maxRetries: 5,\n retryDelay: 100,\n });\n } catch (error) {\n console.error(`could not remove browser profile ${profile}:`, error);\n }\n}\n\n/**\n * Start `executable` headless and connect to it. `timeoutMs` bounds startup\n * and every DevTools call `openPage` makes; each evaluate has its own.\n */\nexport async function launchBrowser(\n executable: string,\n timeoutMs: number,\n): Promise<Browser> {\n if (typeof globalThis.WebSocket === \"undefined\") {\n throw new AutoRigInputError(\n \"render_poses needs Node 22 or newer (the global WebSocket is missing).\",\n );\n }\n const profile = fs.mkdtempSync(path.join(os.tmpdir(), \"iki-render-\"));\n let child: ChildProcess;\n try {\n child = spawn(\n executable,\n [\n \"--headless=new\",\n \"--remote-debugging-port=0\",\n `--user-data-dir=${profile}`,\n \"--no-first-run\",\n \"--no-default-browser-check\",\n // Output pixel sizes must equal the plan's, whatever the display.\n \"--force-device-scale-factor=1\",\n // WebGL without a GPU; recent Chrome no longer falls back by itself.\n \"--enable-unsafe-swiftshader\",\n \"about:blank\",\n ],\n { stdio: [\"ignore\", \"ignore\", \"pipe\"] },\n );\n } catch (error) {\n // Some failures (ENOEXEC, EINVAL on Windows) throw instead of emitting.\n fs.rmSync(profile, { recursive: true, force: true });\n throw startError(executable, error as NodeJS.ErrnoException);\n }\n // Both in the spawn tick: a failed spawn is an `error` event, not a throw,\n // and `close` fires even when no `exit` does.\n let spawnError: NodeJS.ErrnoException | undefined;\n child.on(\"error\", (error) => {\n spawnError = error;\n });\n let exited = false;\n const closed = new Promise<void>((resolve) => {\n child.on(\"close\", () => {\n exited = true;\n resolve();\n });\n });\n const settle = (ms: number) =>\n within(closed, ms, \"browser close\").catch(() => {});\n\n // The server can die mid-render (SIGTERM, host gone); 'exit' handlers run\n // synchronously, so the browser and its profile do not outlive it.\n const onProcessExit = () => {\n child.kill(\"SIGKILL\");\n removeProfile(profile);\n };\n process.once(\"exit\", onProcessExit);\n\n let shutdownPromise: Promise<void> | undefined;\n const shutdown = () =>\n (shutdownPromise ??= (async () => {\n if (!exited) {\n child.kill();\n await settle(CLOSE_GRACE_MS);\n if (!exited) {\n child.kill(\"SIGKILL\");\n await settle(CLOSE_GRACE_MS);\n }\n }\n process.removeListener(\"exit\", onProcessExit);\n removeProfile(profile);\n })());\n\n let cdp: CdpClient;\n try {\n const endpoint = await waitForDevTools(\n child,\n closed,\n () => spawnError,\n executable,\n timeoutMs,\n );\n cdp = await connectCdp(endpoint, timeoutMs);\n } catch (error) {\n await shutdown();\n throw error;\n }\n\n return {\n openPage: () => openPage(cdp, timeoutMs),\n async close() {\n if (!exited) {\n // Best effort: a polite close lets Chrome flush; kill follows anyway.\n await cdp.send(\"Browser.close\", BROWSER_CLOSE_MS).catch(() => {});\n }\n await shutdown();\n },\n };\n}\n\n/** Launch, open a page, run `fn`, and always close the browser. */\nexport async function withBrowser<T>(\n executable: string,\n fn: (evaluate: Evaluate) => Promise<T>,\n): Promise<T> {\n const browser = await launchBrowser(executable, DEFAULT_TIMEOUT_MS);\n try {\n return await fn(await browser.openPage());\n } finally {\n await browser.close();\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n parseIkiModel,\n loadIkiModel,\n IkiFormatError,\n StandardParameter,\n type IkiModel,\n type IkiDeformer,\n type IkiOcclusion,\n} from \"@ikijs/format\";\nimport {\n EditorDocument,\n packAtlas,\n uvRectFor,\n createLayerSetMeasurer,\n detectAlphaBbox,\n generateIkiFromLayerSet,\n parseLayerRoles,\n partIdsOfRole,\n BakeError,\n CustomPartError,\n LayerGeometryError,\n PatchError,\n RigPlanError,\n RIG_PLAN_FIELDS,\n styleRemovedMessage,\n TurnTargetError,\n type IrisStrand,\n type LayerSetMeasurer,\n type AtlasAssignment,\n type AtlasLayout,\n type BakeReport,\n type CustomPart,\n type RigBakes,\n type PatchReport,\n type RigPatch,\n type RigPlan,\n type RigPlanField,\n type RigPlanReport,\n type TurnTargets,\n type TurnSolveReport,\n} from \"@ikijs/editor\";\nimport {\n checkPhysics,\n type FoldReport,\n type PhysicsReport,\n} from \"@ikijs/engine\";\nimport { checkBakes, type BakeCheck } from \"./bake-report\";\nimport {\n checkCustomGate,\n failedCustomGate,\n type CustomGateReport,\n} from \"./custom-gate\";\nimport { checkModelFolds } from \"./fold-report\";\nimport { paintRuns, type PaintRuns } from \"./probe\";\nimport { BUST_SIZE, bustPadY } from \"./render-poses\";\nimport {\n decodePng,\n cropToBuffer,\n renderAtlasToDataUri,\n type AtlasCrop,\n} from \"./node-images\";\nimport {\n AutoRigInputError,\n MAX_LAYERS,\n MAX_LAYER_DIM,\n MAX_CANVAS_DIM,\n MAX_ATLAS_SIDE,\n MAX_TOTAL_PIXELS,\n MAX_OUTPUT_BYTES,\n resolveInputPath,\n confineToWorkingDirectory,\n resolveOutputPath,\n writeFileAtomic,\n} from \"./limits\";\n\nexport type ValidateResult = { ok: true } | { ok: false; error: string };\n\nexport interface IkiSummary {\n name: string;\n canvas: { width: number; height: number };\n parameters: { id: string; min: number; max: number; default: number }[];\n parts: PartSummary[];\n deformers: DeformerSummary[];\n /** The `face` part's width in model px: the unit a rig patch op's `by` and `falloff` are measured in. */\n faceWidth?: number;\n /** Bust-render px per model px (`BUST_SIZE / canvas.width`). */\n bustScale: number;\n /** Each expression's id and the description a host picks it by. */\n expressions: { id: string; description: string }[];\n /** Each motion group's clip descriptions, by clip index. */\n motions: Record<string, string[]>;\n}\n\nexport interface PartSummary {\n id: string;\n order: number;\n deformer?: string;\n /** Rest box in model px from the canvas top-left, y down; the frame of the fold lines and `layout.json`. */\n box: { x: number; y: number; w: number; h: number };\n /** The same box in bust-render px, including the padding above a landscape model. */\n bustBox: { x: number; y: number; w: number; h: number };\n /** The part's own warps: parameter and the keyform stop values. */\n warps?: { parameter: string; stops: number[] }[];\n}\n\nexport interface DeformerSummary {\n id: string;\n kind: \"matrix\" | \"warp\";\n parent?: string;\n warp?:\n | { mode: \"1d\"; parameters: string[] }\n | {\n mode: \"2d\";\n parameterX: string;\n parameterY: string;\n gridX: number;\n gridY: number;\n stopsX: number[];\n stopsY: number[];\n };\n}\n\nexport type DescribeResult =\n | { ok: true; summary: IkiSummary }\n | { ok: false; error: string };\n\nexport interface StandardParameterInfo {\n id: string;\n description: string;\n}\n\nfunction coerceModel(\n model: unknown,\n): { ok: true; model: IkiModel } | { ok: false; error: string } {\n try {\n const parsed =\n typeof model === \"string\" ? loadIkiModel(model) : parseIkiModel(model);\n return { ok: true, model: parsed };\n } catch (e) {\n if (e instanceof IkiFormatError) return { ok: false, error: e.message };\n throw e;\n }\n}\n\nexport function validateIki(model: unknown): ValidateResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n return { ok: true };\n}\n\nexport function describeIki(model: unknown): DescribeResult {\n const result = coerceModel(model);\n if (!result.ok) return { ok: false, error: result.error };\n\n const m = result.model;\n\n const parameters = m.parameters.map((p) => ({\n id: p.id,\n min: p.min,\n max: p.max,\n default: p.default,\n }));\n\n const W = m.canvas.width;\n const H = m.canvas.height;\n const bustScale = BUST_SIZE / W;\n const padY = bustPadY(W, H);\n const tenth = (n: number) => Math.round(n * 10) / 10;\n const parts = m.parts.map((p): PartSummary => {\n // The auto-rig's deformers carry no rest transform, so the part's own\n // transform places it.\n const box = {\n x: W / 2 + p.transform.x - p.width / 2,\n y: H / 2 - p.transform.y - p.height / 2,\n w: p.width,\n h: p.height,\n };\n const entry: PartSummary = {\n id: p.id,\n order: p.order,\n box,\n bustBox: {\n x: tenth(box.x * bustScale),\n y: tenth(padY + box.y * bustScale),\n w: tenth(box.w * bustScale),\n h: tenth(box.h * bustScale),\n },\n };\n if (p.deformer !== undefined) entry.deformer = p.deformer;\n if (p.warps !== undefined && p.warps.length > 0) {\n entry.warps = p.warps.map((w) => ({\n parameter: w.parameter,\n stops: w.keyforms.map((k) => k.value),\n }));\n }\n return entry;\n });\n\n const deformers = (m.deformers ?? []).map(\n (d: IkiDeformer): DeformerSummary => {\n const kind = d.kind === \"warp\" ? \"warp\" : \"matrix\";\n const entry: DeformerSummary = { id: d.id, kind };\n if (d.parent !== undefined) entry.parent = d.parent;\n\n if (d.kind === \"warp\") {\n if (d.warp2d !== undefined) {\n entry.warp = {\n mode: \"2d\",\n parameterX: d.warp2d.parameter,\n parameterY: d.warp2d.parameterY,\n gridX: d.grid.cols,\n gridY: d.grid.rows,\n stopsX: d.warp2d.valuesX,\n stopsY: d.warp2d.valuesY,\n };\n } else if (d.warps !== undefined && d.warps.length > 0) {\n entry.warp = {\n mode: \"1d\",\n parameters: d.warps.map((w) => w.parameter),\n };\n }\n }\n\n return entry;\n },\n );\n\n const expressions = (m.expressions ?? []).map((e) => ({\n id: e.id,\n description: e.description,\n }));\n\n const motions = Object.fromEntries(\n Object.entries(m.motions ?? {}).map(([group, clips]) => [\n group,\n clips.map((c) => c.description),\n ]),\n );\n\n const summary: IkiSummary = {\n name: m.name,\n canvas: { width: m.canvas.width, height: m.canvas.height },\n parameters,\n parts,\n deformers,\n expressions,\n motions,\n bustScale,\n };\n const face = m.parts.find((p) => p.id === \"face\");\n if (face !== undefined) summary.faceWidth = face.width;\n\n return { ok: true, summary };\n}\n\n/**\n * `describeIki` on a written model, read from `modelPath` (confined to the\n * working directory like `renderPoses`), so a large model never crosses an\n * agent's context inline.\n */\nexport function describeIkiAt(modelPath: string): DescribeResult {\n try {\n const modelFile = confineToWorkingDirectory(\n process.cwd(),\n resolveInputPath(modelPath, \"model\"),\n \"model path\",\n modelPath,\n );\n return describeIki(readFileSync(modelFile, \"utf8\"));\n } catch (e) {\n if (e instanceof AutoRigInputError) return { ok: false, error: e.message };\n throw e;\n }\n}\n\n// Static map of standard parameter ids to human-readable descriptions,\n// sourced from JSDoc comments in parameters.ts (including range hints).\nconst STANDARD_PARAMETER_INFO: StandardParameterInfo[] = [\n {\n id: StandardParameter.MouthOpen,\n description: \"Mouth open amount for lip-sync (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.MouthForm,\n description: \"Mouth form / smile (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeOpenLeft,\n description:\n \"Left eye open (0 closed .. 1 open). Drive with the right eye for a blink.\",\n },\n {\n id: StandardParameter.EyeOpenRight,\n description: \"Right eye open (0 closed .. 1 open).\",\n },\n {\n id: StandardParameter.EyeballX,\n description: \"Eyeball gaze, horizontal (-1 .. 1).\",\n },\n {\n id: StandardParameter.EyeballY,\n description: \"Eyeball gaze, vertical (-1 .. 1).\",\n },\n {\n id: StandardParameter.AngleX,\n description: \"Head angle, horizontal degrees.\",\n },\n {\n id: StandardParameter.AngleY,\n description: \"Head angle, vertical degrees.\",\n },\n {\n id: StandardParameter.AngleZ,\n description:\n \"Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D.\",\n },\n {\n id: StandardParameter.BodyAngleX,\n description:\n \"Body turn, degrees (-10 .. 10); positive turns the body toward the viewer's right, as AngleX does the head.\",\n },\n {\n id: StandardParameter.BodyAngleY,\n description:\n \"Body lean, degrees (-10 .. 10); positive moves the upper body up, negative bows.\",\n },\n {\n id: StandardParameter.BodyAngleZ,\n description:\n \"Body tilt, degrees (-10 .. 10); positive tilts the top toward the viewer's right (clockwise), as AngleZ does the head.\",\n },\n {\n id: StandardParameter.Breath,\n description: \"Idle breath (0 .. 1), cycled by the host.\",\n },\n {\n id: StandardParameter.AmbientSway,\n description:\n \"Ambient sway (-1 .. 1): a slow zero-mean drift the idle writes for physics rigs to follow (the auto-rig's hair in idle). Not a wind: no bias. Stays procedural under a declared Idle group, as Breath does.\",\n },\n {\n id: StandardParameter.BrowLeftY,\n description: \"Left brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightY,\n description: \"Right brow raise/lower (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowLeftAngle,\n description: \"Left brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.BrowRightAngle,\n description: \"Right brow tilt/angle (-1 .. 1).\",\n },\n {\n id: StandardParameter.Cheek,\n description: \"Cheek blush strength (0 .. 1), raised by an expression.\",\n },\n {\n id: StandardParameter.HairSwayX,\n description:\n \"Front hair's horizontal sway driver. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n {\n id: StandardParameter.HairSwayZ,\n description:\n \"Front hair's sway driver behind a head tilt. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n {\n id: StandardParameter.HairBackSway,\n description:\n \"Back hair's sway driver behind the head turn, tilt and ambient drift, one spring slower than the front hair's so the two swing out of phase. Physics OUTPUT — driven by the spring, hosts should not set it directly.\",\n },\n {\n id: StandardParameter.ArmLeft,\n description:\n \"Left shoulder, degrees; positive raises the arm outward (mirrored on the right).\",\n },\n {\n id: StandardParameter.ArmRight,\n description:\n \"Right shoulder, degrees; positive raises the arm outward (mirrored on the left).\",\n },\n {\n id: StandardParameter.ElbowLeft,\n description:\n \"Left elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the right).\",\n },\n {\n id: StandardParameter.ElbowRight,\n description:\n \"Right elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the left).\",\n },\n {\n id: StandardParameter.ArmPoseLeft,\n description:\n \"Left pose-forearm switch, 0..1; 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm.\",\n },\n {\n id: StandardParameter.ArmPoseRight,\n description:\n \"Right pose-forearm switch, 0..1; 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm.\",\n },\n {\n id: StandardParameter.ArmPoseAngleLeft,\n description:\n \"Left pose forearm's own small rotation about the elbow, degrees; positive tips the raised hand outward, away from the body (mirrored on the right).\",\n },\n {\n id: StandardParameter.ArmPoseAngleRight,\n description:\n \"Right pose forearm's own small rotation about the elbow, degrees; positive tips the raised hand outward, away from the body (mirrored on the left).\",\n },\n];\n\nexport function listStandardParameters(): StandardParameterInfo[] {\n return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));\n}\n\n/** The rig plan's field catalog: the one source of the fields' defaults,\n * ranges, recommended spans, steps and poses. */\nexport function describeRigPlan(): { fields: RigPlanField[] } {\n return { fields: [...RIG_PLAN_FIELDS] };\n}\n\n/** The `RIGPLAN:` line: every field's effective value, with the requested one\n * and the bound when the art's room cut it, or the cue that fitted it. */\nexport function formatRigPlanReport(r: RigPlanReport): string {\n const fields = RIG_PLAN_FIELDS.map((f) => {\n const value = `${f.path}=${r.effective[f.path]}`;\n const clamp = r.clamped.find((c) => c.field === f.path);\n if (clamp !== undefined) {\n const asked =\n (r.requested as Record<string, Record<string, number>>)[f.group]?.[\n f.key\n ] ?? f.default;\n return `${value} (requested ${asked}, clamped at ${clamp.bound})`;\n }\n const cue = r.overriddenBy[f.path];\n return cue === undefined ? value : `${value} (fitted by ${cue})`;\n });\n return `RIGPLAN: ${fields.join(\" \")}`;\n}\n\n// ── auto_rig_from_layers ──────────────────────────────────────────────────────\n\n/** One role-named PNG layer; role is derived from `fileName ?? basename(path)`. */\nexport interface AutoRigLayerInput {\n fileName?: string;\n path: string;\n}\n\nexport interface AutoRigInput {\n layers: AutoRigLayerInput[];\n /** Output `.iki` path (relative paths resolve against the process cwd). */\n outputPath?: string;\n /** Palette-quantize the atlas PNG to this many colours (integer, 2..256).\n * Omitted = lossless. See renderAtlasToDataUri for the size/quality trade.\n * A `nose` layer is left out of the quantized page, on a second, lossless\n * page of its own, because the palette rims a soft-shaded nose's feather. */\n quantizeColors?: number;\n /** Head-turn cues to fit the rig to, as `measure_turn_reference` reports\n * them. */\n turnTargets?: AutoRigTurnTargets;\n /** Per-character tuning from the profile's defaults, validated against\n * `RIG_PLAN_FIELDS` (see @ikijs/editor's `RigPlan`; `describe_rig_plan`\n * lists the fields). */\n rigPlan?: RigPlan;\n /** Removed in 0.30.0: any value is refused with the field map. */\n style?: unknown;\n /** Displacements added to existing keyform stops of the freshly generated\n * rig, replayed on every rig of these inputs (see @ikijs/editor's\n * `RigPatch`). */\n patches?: RigPatch[];\n /** Parts the auto-rigger has no role for (a twin tail, a hairpin), each from\n * a canvas-sized PNG of its own, put in the model unrigged on `headDeformer`\n * (see @ikijs/editor's `CustomPart`). Their pixels never reach the role\n * parse or the measurements the head's width and turn are fitted to. */\n customParts?: AutoRigCustomPartInput[];\n /** Lattices that move the custom parts when a parameter does (see\n * @ikijs/editor's `RigBakes`); needs `customParts`. The written model is\n * landed through the engine and refused (`BAKE ERROR`, nothing written) when\n * a stop is off by 0.1 px or more. */\n bakes?: RigBakes;\n}\n\n/** One `customParts` entry: a `CustomPart` whose `layer` is read off `path`\n * (a PNG the size of the role layers) instead of given. */\nexport interface AutoRigCustomPartInput extends Omit<CustomPart, \"layer\"> {\n path: string;\n}\n\n/** The turn cues a caller may pass, which is every one but `headHalfWidth`:\n * the pixels the shift fractions are fractions of are measured off the layers\n * themselves, not accepted from the caller. */\nexport type AutoRigTurnTargets = Omit<TurnTargets, \"headHalfWidth\">;\n\nexport type AutoRigResult =\n | {\n ok: true;\n path: string;\n canvas: { width: number; height: number };\n partCount: number;\n /** The atlas's embedded size: its data URI's length, summed over\n * every page: the nose's own under `quantizeColors`, and the custom\n * parts' page. */\n atlasBytes: number;\n /** The head's half-width at the eye row, measured off the layers.\n * Absent when the opaque (alpha >= 128) union has no span there — a\n * layer set painted translucent below that threshold — in which case\n * the face plate stands in for it, same as a span that measures\n * narrower than the plate. */\n headHalfWidth?: number;\n /** Whether the measured value was handed to the generator; the\n * face-half fallback applies otherwise, which is what happens when it\n * is no wider than the face plate, or absent entirely. */\n headHalfWidthApplied: boolean;\n /** Every role with an opaque pixel in the same eye-row band as\n * `headHalfWidth`, per side, each with its own rest x there (canvas px)\n * — present only when `headHalfWidthApplied` is true, since the\n * fallback path has no measured edge to report at all. Passed to the\n * generator so it can land each candidate through its OWN motion\n * (hair_front's silhouette hold, a turn group's grid for the face and\n * its features, a side lock's own shear, the body's own turn\n * translate; `hair_back` holds the outline and lands where it rests,\n * and a role outside that table is refused) and take the outermost\n * LANDING, not just the outermost REST pixel. */\n headEdges?: {\n left: { role: string; x: number }[];\n right: { role: string; x: number }[];\n };\n /** Each side's iris and the `hair_front` run it would slide under on\n * the turn, as pixel edges on the row holding that iris's centre, in\n * model coordinates (`IrisStrand`: canvas x minus half the canvas\n * width) — measured whenever the layer set has `hair_front`, `iris_L`\n * and `iris_R`, and passed to the generator as `options.strandEdges`.\n * A run narrower than half that iris's painted width on the row is\n * hair detail, not a strand, and is skipped as if clear. A side is\n * absent only when its iris has no opaque pixel on that row, or when no\n * run it keeps covers the pixel on that side of the iris's centre or\n * lies outward of it; the whole field only when neither side has one. */\n strandEdges?: { left?: IrisStrand; right?: IrisStrand };\n /** The nose's dense core, canvas px — its pixels at alpha >= 128, not\n * grown — the box handed to the generator as the nose layer's\n * `denseCore` and, there, its turn landmark. Absent without a `nose`\n * layer, when the nose has no pixel at that threshold (painted wholly\n * translucent), or when its core is a speck of its crop\n * (`isSpeckCore`: a lone nostril mark or highlight); the crop stands\n * in for it in both cases. */\n noseCore?: { x: number; y: number; w: number; h: number };\n /** What the turn solve settled on — the cues the rig reaches, the\n * targets it had to cut down (`clamped`) and, per side whose far iris\n * the bangs' run still covers at some far stop, how much of it\n * (`strandOverlap`) and, per side lock, how it keeps its room on the turn\n * (`hairSide`, report-only, printed as `HAIRSIDE` lines). Absent for a\n * layer set with no nose, which solves no turn at all. */\n turn?: TurnSolveReport;\n /** The written model's folds over the engine's pose set, its eyes and\n * mouth shutting on purpose set apart as `expected`. Report-only: a\n * fold never refuses the rig. */\n folds: FoldReport;\n /** The written model's physics rigs, each output excited through the\n * engine's real drivers — a step held at the input's far end and the\n * procedural idle — and read as ok, frozen or unstable with both\n * windows' amplitudes. Report-only: it never refuses the rig. */\n physics: PhysicsReport;\n /** What each of `input.patches` moved on this rig, in order — present\n * whenever `patches` was passed, `[]` included, so a caller can tell\n * this server from one that drops the field. */\n patches?: PatchReport[];\n /** What the rig built with next to what `input.rigPlan` asked, and the\n * fields the art's room cut or a `turnTargets` cue fitted instead.\n * Always present on a rigged model; absent only from a server before\n * 0.30.0. */\n rigPlan: RigPlanReport;\n /** Where each of `input.customParts` landed — present whenever\n * `customParts` was passed, `[]` included, so a caller can tell this\n * server from one that drops the field. `box` is the layer's alpha box\n * in canvas px; `page` is the atlas page, the last one. `bakes` is\n * present only when `bakes` was passed: one entry per baked part and\n * parameter, as the engine lands it. `gate` is the per-part gate over\n * the written model (`ok`, the limits, each part's measures); a failing\n * one blocks the character loop's candidate, the model is written\n * either way. Absent from a server before 0.34.0. */\n customParts?: {\n parts: CustomPartReport[];\n bakes?: BakeCheck[];\n gate: CustomGateReport;\n };\n }\n | { ok: false; error: string };\n\nexport interface CustomPartReport {\n id: string;\n box: { x: number; y: number; w: number; h: number };\n mesh: { vertices: number; triangles: number };\n order: number;\n page: number;\n /** What hides the part, as written on the model; only for a part that\n * declares it. */\n occlusion?: IkiOcclusion;\n}\n\nexport type { TurnSolveReport, BakeCheck, CustomGateReport };\n\n/**\n * Run a fallible input/environment-boundary call, re-tagging any throw as an\n * AutoRigInputError with context so the tool reports it as `{ ok:false }` rather\n * than an unexpected `isError`. Use ONLY around true caller-input / filesystem\n * boundaries — never around internal pipeline math (a throw there is a bug).\n */\nfunction expectInput<T>(label: string, fn: () => T): T {\n try {\n return fn();\n } catch (e) {\n throw new AutoRigInputError(\n `${label}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\n/**\n * The role that keeps a lossless atlas page of its own under `quantizeColors`.\n * At 256 colours a soft nose's feather took the hair edge's lavender palette\n * entries and drew a rim around the nose; changing the dither, the effort, the\n * alpha floor or the alpha curve did not fix it. A lossless page for the nose\n * alone did, and the hero's model came to about 1.28 MB, against 3.18 MB with\n * the whole atlas lossless.\n */\nconst LOSSLESS_PAGE_ROLE = \"nose\";\n\n/** Pack `crops` onto one atlas page and render it — palette-quantized to\n * `quantizeColors` when that is set. A page over MAX_ATLAS_SIDE on either side\n * is refused before rendering, naming its widest (or tallest) crop — after\n * every shelf attempt up to and including the max side overflowed. */\nasync function renderAtlasPage(\n crops: AtlasCrop[],\n quantizeColors: number | undefined,\n): Promise<{ crops: AtlasCrop[]; layout: AtlasLayout; dataUri: string }> {\n const layout = packAtlas(\n crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),\n undefined,\n MAX_ATLAS_SIDE,\n );\n const over =\n layout.pageWidth > MAX_ATLAS_SIDE\n ? ({ side: \"width\", crop: \"widest\" } as const)\n : layout.pageHeight > MAX_ATLAS_SIDE\n ? ({ side: \"height\", crop: \"tallest\" } as const)\n : undefined;\n if (over !== undefined) {\n const crop = layout.placements.reduce((a, b) =>\n b[over.side] > a[over.side] ? b : a,\n );\n throw new AutoRigInputError(\n `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max side ${MAX_ATLAS_SIDE} (its ${over.crop} crop: \"${crop.id}\" ${crop.width}x${crop.height})`,\n );\n }\n const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);\n return { crops, layout, dataUri };\n}\n\n/**\n * Decode role-named PNG file paths, auto-rig a model from them, atlas + embed\n * the textures (Node sharp), validate, and write the renderable `.iki` to disk.\n * Returns the output path + summary stats (the multi-MB model is never inlined).\n *\n * The head turn is fitted to `input.turnTargets`, on what @ikijs/editor's\n * `createLayerSetMeasurer` measures off the decoded layers (the head\n * half-width, `headEdges`, `strandEdges`, the face's `rowHalfWidths`, the face's\n * and hair layers' opaque runs and the nose's dense core, returned as\n * `noseCore`); what the solve settled on comes back in `turn`. Under\n * `quantizeColors` the nose is atlased alone on a second, lossless page, which\n * the palette would otherwise rim; `atlasBytes` sums every page, the custom\n * page included. The generator replays `input.patches` on the fresh rig before\n * it validates and reports the turn, and what each op moved comes back in\n * `patches`; a refused op writes nothing.\n *\n * Re-host of examples/editor/src/store.ts `importLayerSet` with the three DOM\n * pixel functions swapped for the sharp-backed ./node-images helpers; the pure\n * model math is reused from @ikijs/editor.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) → `{ ok:false }`;\n * any other throw (invariant break, programmer bug) propagates to `isError`.\n */\nexport async function autoRigFromLayers(\n input: AutoRigInput,\n): Promise<AutoRigResult> {\n try {\n const layers = input.layers;\n if (!Array.isArray(layers) || layers.length === 0) {\n throw new AutoRigInputError(\"layers must be a non-empty array\");\n }\n // Only the path is read here, by resolveInputPath below; every other field\n // of an entry is the generator's to check, after the layers.\n const customInputs: unknown = input.customParts;\n if (customInputs !== undefined && !Array.isArray(customInputs)) {\n throw new AutoRigInputError(\"customParts must be an array\");\n }\n const customEntries: AutoRigCustomPartInput[] = customInputs ?? [];\n customEntries.forEach((entry: unknown, i) => {\n const at = `customParts[${i}]`;\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n throw new AutoRigInputError(`${at} must be a plain object`);\n }\n });\n if (layers.length + customEntries.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers: ${layers.length + customEntries.length} > ${MAX_LAYERS}`,\n );\n }\n\n // Resolve the output path FIRST (fail-fast): reject a bad/escaping/non-.iki\n // target before spending the image-decode budget on a request that can't\n // be written anyway.\n const outPath = resolveOutputPath(\n input.outputPath ?? \"auto-rigged-model.iki\",\n );\n const quantizeColors = input.quantizeColors;\n if (\n quantizeColors !== undefined &&\n (!Number.isInteger(quantizeColors) ||\n quantizeColors < 2 ||\n quantizeColors > 256)\n ) {\n throw new AutoRigInputError(\n `quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`,\n );\n }\n // Removed with no alias: undeclared keys are stripped by the schema, so\n // the tool keeps a tombstone for it and refuses here, before decoding.\n if (input.style !== undefined) {\n throw new AutoRigInputError(styleRemovedMessage(\"style\"));\n }\n // Checked before the generator call spreads it: a spread turns null or an\n // array into {}, which would rig on the defaults instead of refusing.\n const turnTargets: unknown = input.turnTargets;\n if (turnTargets !== undefined) {\n if (\n typeof turnTargets !== \"object\" ||\n turnTargets === null ||\n Array.isArray(turnTargets)\n ) {\n throw new AutoRigInputError(\"turnTargets must be a plain object\");\n }\n // Excluded from AutoRigTurnTargets, but a JS caller can still pass one:\n // the half-width is measured off the layers below, so a caller's own is\n // refused rather than silently dropped.\n if ((turnTargets as TurnTargets).headHalfWidth !== undefined) {\n throw new AutoRigInputError(\n \"turnTargets.headHalfWidth is measured off the layers, not accepted as input\",\n );\n }\n }\n\n // Resolve paths + role-map up front (input boundary; no decode needed).\n // parseLayerRoles throws on unknown/duplicate/missing-required roles.\n const resolvedLayers = layers.map((layer) => {\n const resolved = resolveInputPath(layer.path);\n return { resolved, fileName: layer.fileName ?? path.basename(resolved) };\n });\n const customPaths = customEntries.map((entry, i) =>\n resolveInputPath(entry.path, `customParts[${i}].path`),\n );\n const rolePairs = expectInput(\"role parsing\", () =>\n parseLayerRoles(resolvedLayers.map((r) => r.fileName)),\n );\n const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));\n\n // Decode + alpha-bbox + crop SEQUENTIALLY: only ONE full-canvas RGBA buffer\n // is live at a time (a Promise.all over all layers would hold every decoded\n // buffer at once, allowing a multi-GB spike on inputs that each pass\n // MAX_LAYER_DIM). MAX_TOTAL_PIXELS bounds the aggregate work. Canvas size =\n // the first layer's full PNG dims (parity with buildLayerInputs in\n // examples/editor/src/auto-rig-image.ts); all layers must match it.\n let canvasW = 0;\n let canvasH = 0;\n let totalPixels = 0;\n // Measures each layer while its decoded pixels are live, keeping none of\n // them (see createLayerSetMeasurer). Created once the first layer gives the\n // canvas.\n let measurer: LayerSetMeasurer | undefined;\n const crops: AtlasCrop[] = [];\n // The opaque runs of each custom part's anchor layer and of each custom\n // layer, read while they are decoded, for the custom gate.\n const paints = new Map<string, PaintRuns>();\n // Anchor roles, and the roles that hide a custom part: the gate reads the\n // paint of both.\n const anchorRoles = new Set(\n customEntries.flatMap((e) => [e.anchor, ...(e.occlusion?.by ?? [])]),\n );\n for (let i = 0; i < resolvedLayers.length; i++) {\n const { resolved, fileName } = resolvedLayers[i];\n const png = await decodePng(resolved);\n if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {\n throw new AutoRigInputError(\n `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`,\n );\n }\n totalPixels += png.width * png.height;\n if (totalPixels > MAX_TOTAL_PIXELS) {\n throw new AutoRigInputError(\n `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`,\n );\n }\n if (i === 0) {\n canvasW = png.width;\n canvasH = png.height;\n if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {\n throw new AutoRigInputError(\n `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`,\n );\n }\n measurer = createLayerSetMeasurer({ width: canvasW, height: canvasH });\n } else if (png.width !== canvasW || png.height !== canvasH) {\n throw new AutoRigInputError(\n `layer \"${fileName}\" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`,\n );\n }\n\n const role = roleByFileName.get(fileName);\n if (role === undefined) {\n throw new AutoRigInputError(`no role resolved for \"${fileName}\"`);\n }\n // Created at i === 0 above.\n const layer = measurer!.add({ role, fileName, rgba: png.rgba });\n if (layer === null) {\n throw new AutoRigInputError(\n `role \"${role}\" file \"${fileName}\": layer is empty after alpha threshold`,\n );\n }\n const { bbox } = layer;\n if (anchorRoles.has(role)) paints.set(role, paintRuns(png));\n const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);\n // png.rgba (full-canvas) is dropped at the next iteration — GC reclaims it\n // before the next decode, so peak memory stays ~one canvas + the crops.\n crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });\n }\n\n // The custom layers come after the role layers, on the canvas they gave,\n // and never reach the role parse or the measurer: an unknown name would be\n // refused there, and a tail across the eye row would widen the head the\n // turn is fitted to.\n const customLayers: {\n fileName: string;\n bbox: { x: number; y: number; w: number; h: number };\n }[] = [];\n const customCrops: AtlasCrop[] = [];\n for (let i = 0; i < customEntries.length; i++) {\n const at = `customParts[${i}]`;\n const { id } = customEntries[i];\n const resolved = customPaths[i];\n const png = await decodePng(resolved);\n if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {\n throw new AutoRigInputError(\n `${at}.path ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`,\n );\n }\n totalPixels += png.width * png.height;\n if (totalPixels > MAX_TOTAL_PIXELS) {\n throw new AutoRigInputError(\n `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`,\n );\n }\n if (png.width !== canvasW || png.height !== canvasH) {\n throw new AutoRigInputError(\n `${at}.path size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`,\n );\n }\n const bbox = detectAlphaBbox(png.rgba, png.width, png.height);\n if (bbox === null) {\n throw new AutoRigInputError(\n `${at}.path \"${path.basename(resolved)}\": layer is empty after alpha threshold`,\n );\n }\n customLayers.push({ fileName: path.basename(resolved), bbox });\n paints.set(id, paintRuns(png));\n customCrops.push({\n id,\n buffer: await cropToBuffer(png.rgba, png.width, png.height, bbox),\n width: bbox.w,\n height: bbox.h,\n });\n }\n // `layers` is non-empty (checked above), so the loop created the measurer.\n const measurement = measurer!.finish();\n const { headHalfWidth, headHalfWidthApplied, turnOptions } = measurement;\n const { headEdges, strandEdges } = turnOptions;\n\n // The nose layer's own denseCore, for the result — undefined without a\n // `nose` layer, or when the measurer's denseCoreOf found no pixel at\n // ALPHA_OPAQUE or a speck of the crop.\n const noseCore = measurement.layers.find(\n (l) => l.role === \"nose\",\n )?.denseCore;\n\n // Internal pipeline — direct calls. By here roles + bboxes are validated, so\n // a throw is an invariant break / bug and must propagate to `isError` —\n // except for the generator's four input errors, each a fact about the\n // request, not a bug: the turn solve, which reads CALLER input, throws\n // TurnTargetError (a field that is not a number, a target this layer set\n // cannot reach); the patch replay, which reads the caller's `patches`,\n // throws PatchError (a malformed op, or one that misses this rig); the rig\n // plan, which reads the caller's `rigPlan`, throws RigPlanError; and\n // art geometry the rig cannot build on (a body's hips with no room under\n // its pivots, an arm too short for its pivots, a lip set whose\n // mouth_inner has no opaque pixel) throws LayerGeometryError.\n let turn: TurnSolveReport | undefined;\n let patches: PatchReport[] | undefined;\n let rigPlan: RigPlanReport | undefined;\n let bakeReports: BakeReport[] | undefined;\n let model: IkiModel;\n try {\n // The caller's fields cross as passed (a headHalfWidth was refused\n // above), so the generator refuses a misspelt one; the measured\n // headHalfWidth, when applied, is merged in after them.\n model = generateIkiFromLayerSet(\n measurement.layers,\n { width: canvasW, height: canvasH },\n {\n turnTargets: {\n ...input.turnTargets,\n ...turnOptions.turnTargets,\n },\n onTurnSolved: (report) => {\n turn = report;\n },\n ...(input.rigPlan === undefined ? {} : { rigPlan: input.rigPlan }),\n onRigPlanResolved: (report) => {\n rigPlan = report;\n },\n ...(input.patches === undefined\n ? {}\n : {\n patches: input.patches,\n onPatchesApplied: (reports: PatchReport[]) => {\n patches = reports;\n },\n }),\n ...(headEdges === undefined ? {} : { headEdges }),\n ...(strandEdges === undefined ? {} : { strandEdges }),\n ...(input.customParts === undefined\n ? {}\n : {\n customParts: customEntries.map(\n ({ path: _path, ...rest }, i) => ({\n ...rest,\n layer: customLayers[i],\n }),\n ),\n }),\n ...(input.bakes === undefined\n ? {}\n : {\n bakes: input.bakes,\n onBakesApplied: (reports: BakeReport[]) => {\n bakeReports = reports;\n },\n }),\n },\n );\n } catch (e) {\n if (\n !(\n e instanceof TurnTargetError ||\n e instanceof LayerGeometryError ||\n e instanceof PatchError ||\n e instanceof RigPlanError ||\n e instanceof CustomPartError ||\n e instanceof BakeError\n )\n ) {\n throw e;\n }\n throw new AutoRigInputError(e.message);\n }\n const doc = new EditorDocument(model);\n\n // Under quantizeColors the nose is page 1, alone and lossless (see\n // LOSSLESS_PAGE_ROLE), and page 0 every other crop; otherwise one page.\n const losslessCrop =\n quantizeColors === undefined\n ? undefined\n : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);\n const pages =\n losslessCrop === undefined\n ? [await renderAtlasPage(crops, quantizeColors)]\n : [\n await renderAtlasPage(\n crops.filter((c) => c !== losslessCrop),\n quantizeColors,\n ),\n await renderAtlasPage([losslessCrop], undefined),\n ];\n // The custom parts' page is the last, quantized on a palette of its own,\n // so adding one leaves the bytes of the pages above untouched.\n const customPage =\n customCrops.length === 0\n ? undefined\n : await renderAtlasPage(customCrops, quantizeColors);\n const allPages = customPage === undefined ? pages : [...pages, customPage];\n const atlasBytes = allPages.reduce((sum, p) => sum + p.dataUri.length, 0);\n if (atlasBytes > MAX_OUTPUT_BYTES) {\n throw new AutoRigInputError(\n `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`,\n );\n }\n\n // Each crop's uv is on its own page, normalised to that page's size.\n const partTextureAssignments: AtlasAssignment[] = pages.flatMap(\n ({ crops: pageCrops, layout }) =>\n pageCrops.flatMap((crop) => {\n const placement = layout.placements.find((p) => p.id === crop.id);\n if (placement === undefined) {\n throw new Error(`auto-rig: no atlas placement for \"${crop.id}\"`);\n }\n const uv = uvRectFor(placement, {\n width: layout.pageWidth,\n height: layout.pageHeight,\n });\n // Every part of a role samples its crop: a forearm shares its arm's.\n return partIdsOfRole(crop.id).map((partId) => ({ partId, uv }));\n }),\n );\n\n if (customPage !== undefined) {\n partTextureAssignments.push(\n ...customPage.crops.map((crop) => {\n const placement = customPage.layout.placements.find(\n (p) => p.id === crop.id,\n )!;\n return {\n partId: crop.id,\n uv: uvRectFor(placement, {\n width: customPage.layout.pageWidth,\n height: customPage.layout.pageHeight,\n }),\n };\n }),\n );\n }\n\n // applyAtlas takes a single page: it sets every part's index to 0 and\n // remaps each mesh's uvs into its rect, which for the nose is already in\n // page 1's space — so the nose only needs its index, set on a clone\n // because getModel() hands back the document's live model, read-only.\n doc.applyAtlas({\n textures: [{ source: pages[0].dataUri }],\n partTextureAssignments,\n });\n let patched = doc.getModel();\n if (losslessCrop !== undefined || customPage !== undefined) {\n patched = structuredClone(patched);\n patched.textures = allPages.map((p) => ({ source: p.dataUri }));\n if (losslessCrop !== undefined) {\n for (const partId of partIdsOfRole(losslessCrop.id)) {\n patched.parts.find((p) => p.id === partId)!.texture!.index = 1;\n }\n }\n for (const crop of customCrops) {\n patched.parts.find((p) => p.id === crop.id)!.texture!.index =\n pages.length;\n }\n }\n // Validate the patched model before writing — never persist an invalid model.\n const finalModel = parseIkiModel(patched);\n // Landed through the engine before the write: a bake the player does not\n // reproduce is refused, not shipped.\n const bakes =\n bakeReports === undefined\n ? undefined\n : checkBakes(finalModel, bakeReports);\n\n // Write to a fresh temp file in the verified directory, then atomically\n // rename over the target — see writeFileAtomic for why an existing `.iki`\n // symlink at outPath cannot redirect the write outside the working tree.\n writeFileAtomic(outPath, JSON.stringify(finalModel));\n\n // Report-only, and after the write so a throw here — an engine bug,\n // surfacing as a tool error, never an input refusal — keeps the rig.\n const folds = checkModelFolds(finalModel);\n const physics = checkPhysics(finalModel);\n // A throw here is an engine or gate bug after the file is on disk: report\n // it as a failed gate, keeping the path, rather than as a tool error.\n let gate: CustomGateReport | undefined;\n if (input.customParts !== undefined) {\n try {\n gate = checkCustomGate(\n finalModel,\n customEntries.map(({ id, anchor, tie, rigid, occlusion }) => ({\n id,\n anchor,\n tie,\n ...(rigid === undefined ? {} : { rigid }),\n ...(occlusion === undefined ? {} : { occludedBy: occlusion.by }),\n })),\n paints,\n );\n } catch (e) {\n gate = failedCustomGate(finalModel, e);\n }\n }\n\n return {\n ok: true,\n path: outPath,\n canvas: { width: canvasW, height: canvasH },\n partCount: finalModel.parts.length,\n atlasBytes,\n ...(headHalfWidth === undefined ? {} : { headHalfWidth }),\n headHalfWidthApplied,\n ...(headEdges === undefined ? {} : { headEdges }),\n ...(strandEdges === undefined ? {} : { strandEdges }),\n ...(noseCore === undefined ? {} : { noseCore }),\n ...(turn === undefined ? {} : { turn }),\n folds,\n physics,\n ...(patches === undefined ? {} : { patches }),\n rigPlan: rigPlan!,\n ...(input.customParts === undefined\n ? {}\n : {\n customParts: {\n parts: customCrops.map((crop, i): CustomPartReport => {\n const part = finalModel.parts.find((p) => p.id === crop.id)!;\n return {\n id: crop.id,\n box: customLayers[i].bbox,\n mesh: {\n vertices: part.mesh!.vertices.length / 2,\n triangles: part.mesh!.indices.length / 3,\n },\n order: part.order,\n page: part.texture!.index,\n ...(part.occlusion === undefined\n ? {}\n : { occlusion: part.occlusion }),\n };\n }),\n ...(bakes === undefined ? {} : { bakes }),\n gate: gate!,\n },\n }),\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n","/**\n * What `auto_rig_from_layers` checks of `bakes` before it writes the rig: each\n * baked custom part landed through the engine's own `landParts` at every stop\n * and at the parameter's range ends where it holds the outermost stop, against\n * the displacement the generator was asked for. The generator solves its\n * offsets in closed form, so this is the check that the closed form and the\n * player agree on the written model.\n */\n\nimport type { BakeReport } from \"@ikijs/editor\";\nimport { landParts } from \"@ikijs/engine\";\nimport type { IkiModel } from \"@ikijs/format\";\nimport { AutoRigInputError } from \"./limits\";\n\n/** A bake that lands this far from what it was asked for is refused. */\nconst BAKE_TOLERANCE_PX = 0.1;\n\n/** One baked part on one parameter, as the engine lands it. */\nexport interface BakeCheck {\n part: string;\n param: string;\n vertices: number;\n /** The stops written, ascending (rest, implicit, is not among them). */\n stops: number[];\n /** The largest gap, over the part's vertices and the stops, between the\n * displacement the bake asked for and the engine's, in canvas px. */\n errorPx: number;\n}\n\n/** What a `BAKE ERROR` ends with: the input was valid, so the fault is not the caller's. */\nconst BUG =\n \"the rig and the engine disagree; report this as a bug in the packages\";\n\n/**\n * Land every `reports` entry on `model` and measure the gap. The reference is\n * the part landed at rest (no parameter set); a stop's displacement is the\n * landing with `param` alone at the stop, less that. The wanted displacement\n * is in canvas px with y down; the landing is in model space, which is canvas\n * px centred on the canvas with y up, so only y changes sign.\n *\n * Throws `AutoRigInputError`, each message starting `BAKE ERROR`: for a part\n * the bake moves at rest by `BAKE_TOLERANCE_PX` or more (`<part> at rest`), and\n * for the first stop or range end that is off by as much (`<part> <param>=<value>`).\n */\nexport function checkBakes(\n model: IkiModel,\n reports: BakeReport[],\n): BakeCheck[] {\n // The part with its bake warps removed is where it was placed. A shift the\n // rest keyform and every stop carry alike would pass the stop checks below.\n const restOf = new Map<string, Float32Array>();\n for (const id of new Set(reports.map((r) => r.part))) {\n const rest = landParts(model, {}, [id]).get(id)!;\n const bare = landParts(\n {\n ...model,\n parts: model.parts.map((p) =>\n p.id === id ? { ...p, warps: undefined } : p,\n ),\n },\n {},\n [id],\n ).get(id)!;\n let restGap = 0;\n for (let i = 0; i < rest.length; i++) {\n restGap = Math.max(restGap, Math.abs(rest[i] - bare[i]));\n }\n if (restGap >= BAKE_TOLERANCE_PX) {\n throw new AutoRigInputError(\n `BAKE ERROR ${id} at rest: the part moved ${restGap.toFixed(3)} px, where the bake must leave it (limit ${BAKE_TOLERANCE_PX} px); ${BUG}`,\n );\n }\n restOf.set(id, rest);\n }\n return reports.map((r) => {\n const rest = restOf.get(r.part)!;\n let errorPx = 0;\n const asked = [\n ...r.stops.map((value, s) => ({ value, wanted: r.wanted[s] })),\n ...r.ends,\n ];\n asked.forEach(({ value, wanted }) => {\n const posed = landParts(model, { [r.param]: value }, [r.part]).get(\n r.part,\n )!;\n let worst = 0;\n let worstVertex = 0;\n for (let v = 0; v < r.vertexCount; v++) {\n const gap = Math.hypot(\n posed[v * 2] - rest[v * 2] - wanted[v * 2],\n -(posed[v * 2 + 1] - rest[v * 2 + 1]) - wanted[v * 2 + 1],\n );\n if (gap > worst) {\n worst = gap;\n worstVertex = v;\n }\n }\n if (worst >= BAKE_TOLERANCE_PX) {\n throw new AutoRigInputError(\n `BAKE ERROR ${r.part} ${r.param}=${value}: vertex ${worstVertex} lands ${worst.toFixed(3)} px from the displacement the bake asked for (limit ${BAKE_TOLERANCE_PX} px); ${BUG}`,\n );\n }\n errorPx = Math.max(errorPx, worst);\n });\n return {\n part: r.part,\n param: r.param,\n vertices: r.vertexCount,\n stops: r.stops,\n errorPx,\n };\n });\n}\n","/**\n * Measure the head-turn cues in a PAIR of images of the same character — one\n * facing front, one turned — and report them as three ratios. It is how a\n * rigged turn gets compared to a reference turn without either image being\n * registered to the other: every number below is a front→turned CHANGE,\n * divided by something measured in the same image. That cancels crop and\n * position, not SCALE: the head span is sampled over a FIXED ±HEAD_BAND row\n * band, so a pair at different resolutions — or a character redrawn larger or\n * smaller between the two shots — would read as a turn that never happened.\n * The pair MUST already share framing and head size; this only checks it, it\n * does not correct for it. The check is a yaw does not change iris HEIGHT, so\n * a front/turned pair whose mean iris height differs is refused rather than\n * measured (see `measureTurnReference`).\n *\n * farEyeRatio how much the far eye narrows, over what it already was at\n * rest (a resting asymmetry in the art is divided out)\n * eyeShift how far the eye pair slides across the head, in units of\n * the FRONT head half-width (hh); negative = toward the\n * image's left\n * silhouetteRatio how much the head narrows, turned over front\n *\n * Read-only over two files; it edits nothing. Ported from the measurement\n * script this repo's turn work ran by hand, so the numbers a rig is tuned\n * against come out of the server every agent already has.\n *\n * `sharp` must stay confined to @ikijs/mcp; the decode and the debug-overlay\n * encode both go through ./node-images, this package's single image boundary.\n */\n\nimport path from \"node:path\";\nimport {\n ALPHA_OPAQUE,\n HEAD_BAND,\n foregroundSpan,\n headHalfOf,\n} from \"@ikijs/editor\";\nimport { decodePng, encodeOverlayPng } from \"./node-images\";\nimport {\n AutoRigInputError,\n resolveInputPath,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\n\n// Re-exported so compose.ts, measure.ts and the tests keep their imports.\nexport {\n SPECK_CORE_FRACTION,\n denseCoreOf,\n headHalfOf,\n isSpeckCore,\n} from \"@ikijs/editor\";\n\n/**\n * Hue/saturation window that selects the iris. Anime irises are a saturated\n * colour on a face that is not, which is what makes them findable at all; the\n * default window is violet-to-blue because that is what the characters this was\n * tuned on have. A character with, say, amber eyes passes its own window.\n */\nexport interface IrisColor {\n /** Inclusive hue bounds in degrees (0..360). */\n hueMin: number;\n hueMax: number;\n /** Minimum HSV saturation (0..1) — separates the iris from the skin. */\n satMin: number;\n}\n\nconst DEFAULT_IRIS: IrisColor = { hueMin: 230, hueMax: 300, satMin: 0.22 };\n\n// Value window, NOT a parameter: it excludes the specular highlight (near\n// white) and the pupil/lash ink (near black) whatever the iris hue is, so the\n// blob that survives is the coloured ring itself.\nconst IRIS_V_MIN = 0.18;\nconst IRIS_V_MAX = 0.95;\n// A blob whose surviving pixels average darker than this is lash ink or a\n// shadow that crept through the hue window, not an iris.\nconst IRIS_MEAN_V_MIN = 0.32;\n// The pupil and the specular highlight split the coloured ring into pieces; a\n// morphological CLOSE (dilate, then erode by the same radius) welds them back\n// into one component WITHOUT moving the blob's edges. A bare dilate would do\n// the welding too, but it adds its radius to every width, and that bias does\n// not cancel in far/near — it pushes the ratio toward 1 by an amount that\n// depends on how many pixels wide the iris happens to be.\nconst CLOSE_RADIUS = 3;\n// ...at the size it was tuned on; a smaller image gets a proportionally smaller\n// radius (at least 1 px), the way the area floor below is scaled.\nconst CLOSE_RADIUS_REFERENCE_PX = 1254;\n// An iris is small. Anything wider or taller than this fraction of the image is\n// hair, a collar, or the face itself leaking through the hue window.\nconst BLOB_MAX_FRAC = 0.12;\n// A KEYED head span this wide is not a head: the hue/sat/value backdrop rule\n// found no background at all, so the whole frame reads as foreground — a\n// backdrop that is not the lavender-grey it keys on (a plain screenshot, a\n// different key colour), not a character that fills the canvas edge to edge.\nconst KEYED_SPAN_MAX_FRAC = 0.95;\n// Area floor, scaled from the 300 px it was tuned at on a 1254² reference so\n// the same physical blob survives on a smaller render.\nconst MIN_AREA_REFERENCE_PIXELS = 1254 * 1254;\nconst MIN_AREA = 300;\n// Two irises sit apart but level. Below the dx floor is one iris found twice\n// (highlight vs ring), above the ceiling is an iris paired with a hair clip.\nconst PAIR_DX_MIN_FRAC = 0.08;\nconst PAIR_DX_MAX_FRAC = 0.35;\nconst PAIR_DY_MAX_FRAC = 0.05;\n/** Blobs kept as pair candidates, largest first — the pair search is O(n²). */\nconst MAX_CANDIDATES = 12;\n\n// --- Foreground (silhouette) rule -----------------------------------------\n// Two modes, chosen per image, because the two kinds of image this compares\n// carry their background differently and neither rule works on both.\n//\n// \"alpha\" an ENGINE RENDER: transparent backdrop. Foreground is alpha alone\n// — and nothing else. Its character pixels include near-black hair\n// ink and pale lavender highlights, both of which the keyed rule\n// below would eat, and the head would come back narrower than it is.\n// It is also the rule to follow when measuring the same silhouette\n// from the layer PNGs' own alpha, so the two are comparable.\n// \"keyed\" a fully opaque REFERENCE: no alpha to read, so the flat\n// lavender-grey backdrop is keyed out by colour instead, along with\n// a near-black frame/letterbox border.\nconst BG_HUE_MIN = 220;\nconst BG_HUE_MAX = 260;\nconst BG_SAT_MAX = 0.2;\nconst BG_V_MIN = 0.55;\nconst BG_V_BLACK = 0.03;\n\n/** Connected blob of iris-coloured pixels, in image px. */\nexport interface IrisBlob {\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n w: number;\n h: number;\n area: number;\n cx: number;\n cy: number;\n}\n\n/** One image's measurement. `irisL`/`irisR` are ordered by x in the IMAGE. */\nexport interface TurnImageMeasure {\n file: string;\n width: number;\n height: number;\n maskMode: \"alpha\" | \"keyed\";\n irisL: IrisBlob;\n irisR: IrisBlob;\n /** Mean row of the two iris centres. */\n eyeRow: number;\n /** Head silhouette span at the eye row. */\n head: { left: number; right: number; cx: number; half: number };\n /** Mean column of the two iris centres. */\n pairCx: number;\n eyeGap: number;\n}\n\nexport interface TurnMeasurement {\n front: TurnImageMeasure;\n turned: TurnImageMeasure;\n /** Turned far/near iris width over the same ratio at rest. */\n farEyeRatio: number;\n /** Front→turned slide of the eye pair across the head, in FRONT hh units. */\n eyeShift: number;\n /** Head half-width, turned over front. */\n silhouetteRatio: number;\n /** -1 = the head turned toward the image's left, +1 = toward its right. */\n turnSign: -1 | 1;\n /** Debug overlays written, when `debugDir` was given. */\n debug?: string[];\n}\n\nexport type MeasureTurnResult =\n | ({ ok: true } & TurnMeasurement)\n | { ok: false; error: string };\n\nexport interface MeasureTurnInput {\n /** Front-facing image (relative paths resolve against cwd). */\n front: string;\n /** The same character turned. */\n turned: string;\n /** Iris colour window override, merged over the violet default. */\n iris?: Partial<IrisColor>;\n /** Existing directory to write `<name>.debug.png` overlays into. */\n debugDir?: string;\n}\n\n/** HSV of an 8-bit RGB triple: hue in degrees, saturation and value in 0..1. */\nfunction rgbToHsv(r: number, g: number, b: number): [number, number, number] {\n r /= 255;\n g /= 255;\n b /= 255;\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const d = max - min;\n let h = 0;\n if (d > 0) {\n if (max === r) h = ((g - b) / d) % 6;\n else if (max === g) h = (b - r) / d + 2;\n else h = (r - g) / d + 4;\n h *= 60;\n if (h < 0) h += 360;\n }\n return [h, max === 0 ? 0 : d / max, max];\n}\n\n/** Grow `mask` by `r` px in every direction (square kernel). */\nfunction dilate(\n mask: Uint8Array,\n width: number,\n height: number,\n r: number,\n): Uint8Array {\n const out = new Uint8Array(width * height);\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n if (!mask[y * width + x]) continue;\n for (let dy = -r; dy <= r; dy++) {\n for (let dx = -r; dx <= r; dx++) {\n const yy = y + dy;\n const xx = x + dx;\n if (yy >= 0 && yy < height && xx >= 0 && xx < width)\n out[yy * width + xx] = 1;\n }\n }\n }\n }\n return out;\n}\n\n/** Shrink `mask` by `r` px in every direction; outside the image counts as\n * background. Erosion only ever clears pixels, so set ones are all it visits. */\nfunction erode(\n mask: Uint8Array,\n width: number,\n height: number,\n r: number,\n): Uint8Array {\n const out = new Uint8Array(width * height);\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n if (!mask[y * width + x]) continue;\n let keep = true;\n for (let dy = -r; dy <= r && keep; dy++) {\n for (let dx = -r; dx <= r; dx++) {\n const yy = y + dy;\n const xx = x + dx;\n if (\n yy < 0 ||\n yy >= height ||\n xx < 0 ||\n xx >= width ||\n !mask[yy * width + xx]\n ) {\n keep = false;\n break;\n }\n }\n }\n if (keep) out[y * width + x] = 1;\n }\n }\n return out;\n}\n\n/** Morphological close: weld pieces up to 2r apart, leaving the outer edges\n * where they were (a closed set never spills past the original's bbox). */\nfunction closeMask(\n mask: Uint8Array,\n width: number,\n height: number,\n r: number,\n): Uint8Array {\n return erode(dilate(mask, width, height, r), width, height, r);\n}\n\n/** 4-connected components of `mask` with at least `minArea` px, largest first. */\nfunction components(\n mask: Uint8Array,\n width: number,\n height: number,\n minArea: number,\n): IrisBlob[] {\n const seen = new Uint8Array(width * height);\n const out: IrisBlob[] = [];\n for (let i = 0; i < width * height; i++) {\n if (!mask[i] || seen[i]) continue;\n const stack = [i];\n seen[i] = 1;\n let x0 = width;\n let x1 = 0;\n let y0 = height;\n let y1 = 0;\n let n = 0;\n let sx = 0;\n let sy = 0;\n while (stack.length) {\n const p = stack.pop() as number;\n const x = p % width;\n const y = (p / width) | 0;\n n++;\n sx += x;\n sy += y;\n if (x < x0) x0 = x;\n if (x > x1) x1 = x;\n if (y < y0) y0 = y;\n if (y > y1) y1 = y;\n const neighbours: number[] = [];\n if (x > 0) neighbours.push(p - 1);\n if (x < width - 1) neighbours.push(p + 1);\n if (y > 0) neighbours.push(p - width);\n if (y < height - 1) neighbours.push(p + width);\n for (const q of neighbours) {\n if (seen[q] || !mask[q]) continue;\n seen[q] = 1;\n stack.push(q);\n }\n }\n if (n >= minArea) {\n out.push({\n x0,\n x1,\n y0,\n y1,\n w: x1 - x0 + 1,\n h: y1 - y0 + 1,\n area: n,\n cx: sx / n,\n cy: sy / n,\n });\n }\n }\n return out.sort((a, b) => b.area - a.area);\n}\n\n/** Merge a caller's partial iris window over the default, rejecting nonsense. */\nfunction resolveIris(override: Partial<IrisColor> | undefined): IrisColor {\n const iris = { ...DEFAULT_IRIS, ...override };\n if (iris.hueMin < 0 || iris.hueMax > 360 || iris.hueMin >= iris.hueMax) {\n throw new AutoRigInputError(\n `iris hue window must be 0 <= hueMin < hueMax <= 360, got ${iris.hueMin}..${iris.hueMax}`,\n );\n }\n if (iris.satMin < 0 || iris.satMin > 1) {\n throw new AutoRigInputError(\n `iris satMin must be within 0..1, got ${iris.satMin}`,\n );\n }\n return iris;\n}\n\n/**\n * Find the iris pair and the head silhouette in one image.\n *\n * Throws a path-qualified AutoRigInputError when no pair survives the filters\n * (the candidate count says whether the hue window found nothing at all or\n * found too much) or when the eye-row band holds no foreground.\n */\nasync function measureTurnImage(\n filePath: string,\n iris: IrisColor,\n): Promise<TurnImageMeasure> {\n const { width, height, rgba, hasAlpha } = await decodePng(filePath);\n const n = width * height;\n\n // An RGBA file whose alpha is entirely opaque is a reference that merely\n // carries a channel, not a render with a cut-out backdrop — key it by colour.\n let transparent = false;\n if (hasAlpha) {\n for (let i = 0; i < n; i++) {\n if (rgba[i * 4 + 3] < ALPHA_OPAQUE) {\n transparent = true;\n break;\n }\n }\n }\n const maskMode: \"alpha\" | \"keyed\" =\n hasAlpha && transparent ? \"alpha\" : \"keyed\";\n\n const irisMask = new Uint8Array(n);\n const fg = new Uint8Array(n);\n const value = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n if (rgba[i * 4 + 3] < ALPHA_OPAQUE) continue; // transparent = background\n const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);\n if (maskMode === \"alpha\") {\n fg[i] = 1;\n } else {\n const isBg =\n (hue >= BG_HUE_MIN &&\n hue <= BG_HUE_MAX &&\n s < BG_SAT_MAX &&\n v > BG_V_MIN) ||\n v < BG_V_BLACK;\n if (!isBg) fg[i] = 1;\n }\n if (\n hue >= iris.hueMin &&\n hue <= iris.hueMax &&\n s > iris.satMin &&\n v > IRIS_V_MIN &&\n v < IRIS_V_MAX\n ) {\n irisMask[i] = 1;\n value[i] = v;\n }\n }\n\n const minArea = Math.max(\n 1,\n Math.round((MIN_AREA * n) / MIN_AREA_REFERENCE_PIXELS),\n );\n const closeRadius = Math.max(\n 1,\n Math.round(\n (CLOSE_RADIUS * Math.max(width, height)) / CLOSE_RADIUS_REFERENCE_PX,\n ),\n );\n const meanValue = (b: IrisBlob): number => {\n let count = 0;\n let total = 0;\n for (let y = b.y0; y <= b.y1; y++) {\n for (let x = b.x0; x <= b.x1; x++) {\n const i = y * width + x;\n if (!irisMask[i]) continue;\n count++;\n total += value[i];\n }\n }\n return count ? total / count : 0;\n };\n const candidates = components(\n closeMask(irisMask, width, height, closeRadius),\n width,\n height,\n minArea,\n )\n .filter((b) => b.w < width * BLOB_MAX_FRAC && b.h < height * BLOB_MAX_FRAC)\n .filter((b) => meanValue(b) > IRIS_MEAN_V_MIN)\n .slice(0, MAX_CANDIDATES);\n\n let best: { score: number; pair: [IrisBlob, IrisBlob] } | null = null;\n for (let i = 0; i < candidates.length; i++) {\n for (let j = i + 1; j < candidates.length; j++) {\n const a = candidates[i];\n const b = candidates[j];\n const dx = Math.abs(a.cx - b.cx);\n const dy = Math.abs(a.cy - b.cy);\n if (dx < width * PAIR_DX_MIN_FRAC || dx > width * PAIR_DX_MAX_FRAC)\n continue;\n if (dy > height * PAIR_DY_MAX_FRAC) continue;\n const score = a.area + b.area;\n if (best === null || score > best.score) {\n const pair: [IrisBlob, IrisBlob] = a.cx <= b.cx ? [a, b] : [b, a];\n best = { score, pair };\n }\n }\n }\n if (best === null) {\n throw new AutoRigInputError(\n `no iris pair found in ${filePath} among ${candidates.length} candidate blobs ` +\n `(iris hue ${iris.hueMin}..${iris.hueMax}, sat > ${iris.satMin})`,\n );\n }\n\n const [irisL, irisR] = best.pair;\n const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);\n const { left, right } = foregroundSpan(\n fg,\n width,\n height,\n eyeRow - HEAD_BAND,\n eyeRow + HEAD_BAND,\n );\n // Every ratio divides by this half-width, so a band that keyed down to\n // nothing (or to a single column) must fail rather than report Infinity.\n if (right <= left) {\n throw new AutoRigInputError(\n `no head span at the eye row (y=${eyeRow}) in ${filePath}: the ${maskMode} foreground mask is empty there`,\n );\n }\n if (maskMode === \"keyed\" && right - left + 1 > width * KEYED_SPAN_MAX_FRAC) {\n throw new AutoRigInputError(\n `head span at the eye row (y=${eyeRow}) in ${filePath} covers ${right - left + 1}/${width} px: background not keyed / not an engine render`,\n );\n }\n\n return {\n file: filePath,\n width,\n height,\n maskMode,\n irisL,\n irisR,\n eyeRow,\n head: {\n left,\n right,\n cx: (left + right) / 2,\n half: headHalfOf({ left, right }),\n },\n pairCx: (irisL.cx + irisR.cx) / 2,\n eyeGap: irisR.cx - irisL.cx,\n };\n}\n\n/**\n * Iris widths split into far and near. FAR = the eye on the side the pair moved\n * TOWARD, which is the one rotating away from the viewer; `turnSign` says which\n * side that is. The measurement and the report must split them the same way, so\n * they share this.\n */\nfunction farNearWidths(\n m: TurnImageMeasure,\n turnSign: -1 | 1,\n): { far: number; near: number } {\n return turnSign < 0\n ? { far: m.irisL.w, near: m.irisR.w }\n : { far: m.irisR.w, near: m.irisL.w };\n}\n\n/** The overlay: iris boxes, head edges, head centre, pair centre. */\nfunction overlaySvg(m: TurnImageMeasure): string {\n const box = (b: IrisBlob, stroke: string) =>\n `<rect x=\"${b.x0}\" y=\"${b.y0}\" width=\"${b.w}\" height=\"${b.h}\" fill=\"none\" stroke=\"${stroke}\" stroke-width=\"3\"/>`;\n const tick = (x: number, half: number, stroke: string) =>\n `<line x1=\"${x}\" y1=\"${m.eyeRow - half}\" x2=\"${x}\" y2=\"${m.eyeRow + half}\" stroke=\"${stroke}\" stroke-width=\"3\"/>`;\n return (\n `<svg width=\"${m.width}\" height=\"${m.height}\">` +\n box(m.irisL, \"#ff0000\") +\n box(m.irisR, \"#00c000\") +\n tick(m.head.left, 40, \"#0000ff\") +\n tick(m.head.right, 40, \"#0000ff\") +\n tick(m.head.cx, 60, \"#ff8800\") +\n tick(m.pairCx, 60, \"#ff00ff\") +\n \"</svg>\"\n );\n}\n\n/** `label` prefixes the file name: the two inputs often share a basename\n * (`renders/head.png` + `ref/head.png`), and one would overwrite the other. */\nasync function writeOverlay(\n debugDir: string,\n label: \"front\" | \"turned\",\n m: TurnImageMeasure,\n): Promise<string> {\n const outPath = path.join(\n debugDir,\n `${label}-${path.basename(m.file, \".png\")}.debug.png`,\n );\n writeFileAtomic(outPath, await encodeOverlayPng(m.file, overlaySvg(m)));\n return outPath;\n}\n\n/** How far the front/turned mean iris heights may differ before the pair is\n * refused as not being at the same scale. A yaw foreshortens iris WIDTH, never\n * its height, so any difference here is framing/scale, not turn — 10% is\n * comfortably above the paint/detection noise a same-scale pair shows (the\n * fixtures in measure-turn.test.ts read within a percent) and comfortably\n * below a deliberate rescale. */\nconst IRIS_HEIGHT_SCALE_TOLERANCE = 0.1;\n\n/**\n * Measure a front/turned image pair and report the three turn ratios plus both\n * raw per-image measurements.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) →\n * `{ ok:false }`, matching measureLayers; any other throw propagates.\n */\nexport async function measureTurnReference(\n input: MeasureTurnInput,\n): Promise<MeasureTurnResult> {\n try {\n const iris = resolveIris(input.iris);\n const frontPath = resolveInputPath(input.front);\n const turnedPath = resolveInputPath(input.turned);\n // Resolve the debug dir before measuring (fail-fast): a missing or escaping\n // target should not cost two full decodes first.\n const debugDir =\n input.debugDir === undefined ? null : resolveOutputDir(input.debugDir);\n\n const front = await measureTurnImage(frontPath, iris);\n const turned = await measureTurnImage(turnedPath, iris);\n\n // A yaw does not change iris HEIGHT — only width, via foreshortening — so\n // a front/turned pair whose mean iris height differs is not at the same\n // scale/framing, and every ratio below would be measuring that instead of\n // the turn. Refuse it rather than silently reporting a scale change as one.\n const frontIrisH = (front.irisL.h + front.irisR.h) / 2;\n const turnedIrisH = (turned.irisL.h + turned.irisR.h) / 2;\n if (\n Math.abs(turnedIrisH - frontIrisH) / frontIrisH >\n IRIS_HEIGHT_SCALE_TOLERANCE\n ) {\n throw new AutoRigInputError(\n `front and turned images are not at the same scale: mean iris height ${frontIrisH.toFixed(1)}px front vs ${turnedIrisH.toFixed(1)}px turned, more than ${(IRIS_HEIGHT_SCALE_TOLERANCE * 100).toFixed(0)}% apart — a yaw does not change iris height, so the pair must share the same framing and head size`,\n );\n }\n\n // Where the eye pair sits on the head, per image; the CHANGE is the turn.\n const frontShift = front.pairCx - front.head.cx;\n const turnedShift = turned.pairCx - turned.head.cx;\n const shift = turnedShift - frontShift;\n // A pair that did not move has no far side, so there is no third value the\n // far/near rule below could use: treat a zero shift as a right turn, where\n // the ratio reads ~1 from either assignment anyway.\n const turnSign: -1 | 1 = shift < 0 ? -1 : 1;\n // Dividing the turned far/near by the same ratio at rest cancels a resting\n // asymmetry in the art, so what is left is the turn alone.\n const f = farNearWidths(front, turnSign);\n const t = farNearWidths(turned, turnSign);\n\n const debug =\n debugDir === null\n ? undefined\n : [\n await writeOverlay(debugDir, \"front\", front),\n await writeOverlay(debugDir, \"turned\", turned),\n ];\n\n return {\n ok: true,\n front,\n turned,\n farEyeRatio: t.far / t.near / (f.far / f.near),\n eyeShift: shift / front.head.half,\n silhouetteRatio: turned.head.half / front.head.half,\n turnSign,\n ...(debug === undefined ? {} : { debug }),\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n\nconst n1 = (v: number) => v.toFixed(1);\nconst n3 = (v: number) => v.toFixed(3);\n\n/** One image's raw block: what the ratios above were computed from. */\nfunction imageBlock(label: string, m: TurnImageMeasure): string[] {\n return [\n `# ${label} ${m.file} ${m.width}x${m.height} mask: ${m.maskMode}`,\n `iris widths ${m.irisL.w} / ${m.irisR.w} px centres ${n1(m.irisL.cx)} / ${n1(m.irisR.cx)} ` +\n `eye row ${m.eyeRow} gap ${n1(m.eyeGap)}`,\n `head ${m.head.left}..${m.head.right} centre ${n1(m.head.cx)} half ${n1(m.head.half)} ` +\n `pair centre ${n1(m.pairCx)}`,\n ];\n}\n\n/** Render a measurement as plain text: the three ratios with the raw numbers\n * behind each, then one block per image. */\nexport function formatTurnReport(result: TurnMeasurement): string {\n const { front, turned } = result;\n const f = farNearWidths(front, result.turnSign);\n const t = farNearWidths(turned, result.turnSign);\n const lines = [\n `farEyeRatio ${n3(result.farEyeRatio)} far/near iris width ${t.far}/${t.near} turned ` +\n `over ${f.far}/${f.near} front`,\n `eyeShift ${n3(result.eyeShift)} pair-vs-head centre ${n1(turned.pairCx - turned.head.cx)} px turned, ` +\n `${n1(front.pairCx - front.head.cx)} px front, over front head half ${n1(front.head.half)} px (hh)`,\n `silhouetteRatio ${n3(result.silhouetteRatio)} head half ${n1(turned.head.half)} px turned over ` +\n `${n1(front.head.half)} px front`,\n `turnSign ${result.turnSign} (the head turned toward the image's ${\n result.turnSign < 0 ? \"left\" : \"right\"\n })`,\n \"\",\n ...imageBlock(\"front\", front),\n \"\",\n ...imageBlock(\"turned\", turned),\n ];\n if (result.debug !== undefined) {\n lines.push(\"\", ...result.debug.map((p) => `debug overlay ${p}`));\n }\n return lines.join(\"\\n\");\n}\n","/**\n * Measure composed Iki role layers and flag the failure modes that have\n * actually shipped broken characters. Read-only: it never edits anything.\n *\n * Ports the geometry checks that shipped as a script in the Claude Code plugin,\n * so a plugin user gets them from the MCP server instead of an ad-hoc `sharp`\n * install. They exist because \"the eyes look too big\" is not actionable but\n * \"the iris is 33% of the sclera width, target 0.45-0.72\" is. Every check below\n * is one that cost a real regeneration or re-tune round to find by eye.\n *\n * `sharp` must stay confined to @ikijs/mcp; the decode goes through\n * ./node-images, this package's single image-decode boundary.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { decodePng, detectAlphaBbox } from \"./node-images\";\nimport { AutoRigInputError, MAX_LAYERS, resolveInputDir } from \"./limits\";\nimport { ARM_ROLES, armWarnings } from \"./measure-arms\";\nimport { hairSideWarnings } from \"./measure-hair-side\";\nimport { POSE_ROLES, forearmPoseWarnings } from \"./measure-forearm-pose\";\nimport { isLipLayerRole, lipWarnings, type LipFacts } from \"./measure-lips\";\nimport { SPECK_CORE_FRACTION, denseCoreOf, isSpeckCore } from \"./measure-turn\";\n\n// Iris width as a fraction of sclera width. Below the floor the eye reads as a\n// bead floating in white — that is the failure this check was written for, and\n// it caught a model that shipped at 0.33. The ceiling was a guess and it was\n// too tight: measured on a real anime reference the iris runs about 0.70 of the\n// eye, with the white reduced to corner crescents, so 0.6 flagged the correct\n// value as a fault three rounds running.\nconst IRIS_RATIO_MIN = 0.45;\nconst IRIS_RATIO_MAX = 0.72;\n// A sclera flatter than this cannot hold a round iris: the iris overflows the\n// lids no matter how narrow it is.\nconst EYE_ASPECT_MIN = 0.5;\n// How far the iris centre may sit from the white's centre of mass. The two axes\n// are not the same problem. Sideways drift is always a fault — that is the bug\n// this check was written for, a lash that fell out of sync with its sclera by\n// 14px. Vertically the reference itself rides its iris HIGH, tucked under the\n// lash with roughly a sixth of the aperture showing as white below it, so a\n// deliberate lift of that order is correct and a 3px ceiling flagged it.\nconst IRIS_OFFSET_MAX_X = 3;\nconst IRIS_OFFSET_MAX_Y = 10;\n// A cropped part shows a long, nearly-continuous opaque run along one bbox edge,\n// and that straight seam appears the moment the head turns. A round part's edge\n// row is a short tangent run, so a fraction test alone flags every iris; both a\n// high fraction AND real length are required to separate the two. Observed:\n// genuine crops read 60-93%, circle tangents 8-14%.\nconst EDGE_SOLID_MAX = 0.5;\n/** Share of a lash's opaque pixels tolerated off its sclera. In sync there\n * are none — the sclera was recoloured from those very pixels. A real eye\n * measured 0 of 934 in sync, then 6-12 at a 1 px drift, 45-50 at 2 px and\n * 104-110 at 4 px, whichever way it drifted. */\nconst LASH_STRAY_TOL_FRAC = 0.02;\n/** How much further short of the outer corner than of the nose side an eye's\n * lash may stop, as a fraction of the eye width, before the eye reads as\n * drawn facing the other way. Three real eyewhites drawn reversed stopped\n * 4.0-6.1% further short there; one drawn the right way stops short at the\n * nose side instead, and one with a wing at each end at neither. */\nconst EYE_FACING_TOL_FRAC = 0.02;\nconst EDGE_RUN_MIN_PX = 40;\n// Longest straight \"art appears out of nothing\" run tolerated inside a part, as\n// a fraction of its width. A body generated with hair draped over the shoulders\n// had that hair cut flat by its own frame; the cut hid behind the head at rest\n// and opened into a seam on turn. Measured: that part ran 15% of its width,\n// a clean one 5%, so the boundary sits between them.\nconst FLAT_CUT_MAX_FRAC = 0.1;\n// ...and long in absolute terms. A mouth's upper lip is a naturally horizontal\n// run that clears the fraction test on a narrow part while being only ~15px.\nconst FLAT_CUT_MIN_PX = 40;\n// The cut is antialiased, so the transition is a soft cliff rather than\n// transparent-to-opaque; 8/200 finds nothing at all on real art.\nconst FLAT_CUT_ALPHA_ABOVE = 120;\nconst FLAT_CUT_ALPHA_BELOW = 140;\n\n/** Alpha-derived geometry of one layer, in canvas pixels. */\nexport interface LayerStats {\n w: number;\n h: number;\n /** Longest flat cut through the art, and the row it runs along (-1 if none). */\n flatCutRun: number;\n flatCutY: number;\n bboxCx: number;\n bboxCy: number;\n massCx: number;\n massCy: number;\n /** Distance from the layer's content to each canvas edge. */\n marginTop: number;\n marginBottom: number;\n marginLeft: number;\n marginRight: number;\n /** Fraction of each bbox edge that is opaque. */\n edgeTop: number;\n edgeBottom: number;\n edgeLeft: number;\n edgeRight: number;\n canvasW: number;\n canvasH: number;\n}\n\nexport interface MeasureReport {\n /** Measured stats by role (the layer's file name without `.png`). */\n layers: Record<string, LayerStats>;\n /** Roles whose PNG is fully transparent — nothing to measure. */\n empty: string[];\n warnings: string[];\n /**\n * The lip set's opening as the rig reads it, set whenever the three lip\n * layers are present and readable. The fold's dead zone `deadZone` is the\n * `MouthOpen` below which the slit between the lips has not opened, and\n * it varies with the drawing (0.03 on one opening, 0.26 on another), so a\n * half-open mouth that shows no slit is judged against it, not against a\n * fixed number.\n */\n lips?: LipFacts;\n}\n\nexport type MeasureResult =\n | ({ ok: true; layersDir: string; passed: boolean } & MeasureReport)\n | { ok: false; error: string };\n\nexport interface MeasureInput {\n /** Directory of role-named layer PNGs (relative paths resolve against cwd). */\n layersDir: string;\n}\n\n/**\n * Scan one layer PNG's alpha channel. Returns null for a fully transparent\n * layer. A decode failure surfaces as a path-qualified AutoRigInputError.\n */\nexport async function layerStats(filePath: string): Promise<LayerStats | null> {\n const { width: W, height: H, rgba } = await decodePng(filePath);\n const alpha = (x: number, y: number) => rgba[(y * W + x) * 4 + 3];\n\n let minX = W;\n let minY = H;\n let maxX = -1;\n let maxY = -1;\n let sumX = 0;\n let sumY = 0;\n let n = 0;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n if (alpha(x, y) > 8) {\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n sumX += x;\n sumY += y;\n n++;\n }\n }\n }\n if (maxX < 0) return null; // fully transparent\n\n const edge = (pts: number[]) =>\n pts.filter((v) => v > 200).length / pts.length;\n const top: number[] = [];\n const bottom: number[] = [];\n const left: number[] = [];\n const right: number[] = [];\n for (let x = minX; x <= maxX; x++) {\n top.push(alpha(x, minY));\n bottom.push(alpha(x, maxY));\n }\n for (let y = minY; y <= maxY; y++) {\n left.push(alpha(minX, y));\n right.push(alpha(maxX, y));\n }\n\n // Longest contiguous run of pixels where the art appears out of nothing along\n // one row — transparent above, opaque below. Organic art (hair, cloth) meets\n // its silhouette at an angle, so a long FLAT run like this means the source\n // image was cropped through the drawing. It is often interior to the bbox\n // (a hair strand cut short above a wider shoulder line), which is why the\n // bbox-edge test alone misses it, and it only becomes visible once the head\n // turns and uncovers the cut.\n let flatCutRun = 0;\n let flatCutY = -1;\n for (let y = minY + 1; y <= maxY; y++) {\n let run = 0;\n for (let x = minX; x <= maxX; x++) {\n if (\n alpha(x, y - 1) < FLAT_CUT_ALPHA_ABOVE &&\n alpha(x, y) > FLAT_CUT_ALPHA_BELOW\n ) {\n run++;\n if (run > flatCutRun) {\n flatCutRun = run;\n flatCutY = y;\n }\n } else {\n run = 0;\n }\n }\n }\n\n return {\n w: maxX - minX + 1,\n h: maxY - minY + 1,\n flatCutRun,\n flatCutY,\n bboxCx: (minX + maxX) / 2,\n bboxCy: (minY + maxY) / 2,\n massCx: sumX / n,\n massCy: sumY / n,\n marginTop: minY,\n marginBottom: H - 1 - maxY,\n marginLeft: minX,\n marginRight: W - 1 - maxX,\n edgeTop: edge(top),\n edgeBottom: edge(bottom),\n edgeLeft: edge(left),\n edgeRight: edge(right),\n canvasW: W,\n canvasH: H,\n };\n}\n\nconst pct = (v: number) => `${(v * 100).toFixed(0)}%`;\n\n/** An arm's seams show once it raises, every other part's on the head turn. A\n * pose forearm raises with its arm, and shows only once the switch is on. */\nconst isArm = (role: string) =>\n (ARM_ROLES as readonly string[]).includes(role) ||\n (POSE_ROLES as readonly string[]).includes(role);\n\n/** A nose's dense core that `isSpeckCore` judged a speck of its part, as sizes\n * in px: compose's verdict on the trimmed source part, or the composed\n * layer's against its crop. */\nexport interface NoseSpeck {\n core: { w: number; h: number };\n part: { w: number; h: number };\n}\n\n/**\n * The nose-speck warning. Each source says only what its own reader did:\n * `\"compose\"` judged the trimmed source part, before resampling, and composed\n * it whole; `\"layer\"` judged the layer file against its crop, which is what\n * `auto_rig_from_layers` reads. The remedy is the same either way.\n */\nfunction noseSpeckWarning(\n { core, part }: NoseSpeck,\n source: \"compose\" | \"layer\",\n): string {\n const [found, consequence] =\n source === \"compose\"\n ? [\n `the source part's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} trimmed part`,\n `compose_layers_from_parts sized and placed the whole part instead — layout.nose's w and h now size it, feather included`,\n ]\n : [\n `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,\n `auto_rig_from_layers turns and tilts the nose about its whole crop instead`,\n ];\n return (\n `nose: ${found} — under ${SPECK_CORE_FRACTION} of its width or height, a speck: a lone nostril ` +\n `mark or highlight at alpha >= 128, not the drawing, so ${consequence}. Regenerate the nose with ` +\n `its shading painted denser, so the drawing itself reaches alpha 128. Billed.`\n );\n}\n\n/**\n * Count the lash's opaque pixels, and those of them that land where its\n * sclera is transparent. Both are canvas-sized layers, so a pixel's position\n * is the same canvas point in each.\n */\nasync function lashOffSclera(\n eyePath: string,\n lashPath: string,\n): Promise<{ opaque: number; off: number }> {\n const eye = await decodePng(eyePath);\n const lash = await decodePng(lashPath);\n let opaque = 0;\n let off = 0;\n for (let y = 0; y < lash.height; y++) {\n for (let x = 0; x < lash.width; x++) {\n if (lash.rgba[(y * lash.width + x) * 4 + 3] < 128) continue;\n opaque++;\n const onEye = x < eye.width && y < eye.height;\n if (!onEye || eye.rgba[(y * eye.width + x) * 4 + 3] <= 8) off++;\n }\n }\n return { opaque, off };\n}\n\n/**\n * Measure every `*.png` in an already-resolved layers directory but the\n * `preview*.png` ones (`preview.png` is the composer's contact sheet, and a\n * caller's own previews sit beside it; none is a role) and run the geometry\n * checks.\n * `noseSpeck` is compose's own verdict on the nose's source part when that\n * part's core was a speck, and the nose check reports it as given. Left out —\n * compose found no speck, or `measure_layers` — that check judges the `nose`\n * layer file against its crop instead, as `auto_rig_from_layers` does.\n * `inPlace` is for layers cut in place out of one picture\n * (`cut_layers_from_illustration`): every part is as the picture draws it,\n * so each check whose only remedy is re-laying-out or regenerating a\n * generated part is left out (an edge or straight cut in the art, a sclera's\n * aspect, the iris's size and place, an eyewhite drawn facing the other way,\n * a speck nose, the lip set's art: see `lipWarnings`, and a hair_side.png\n * drawing two locks), and so are the arm and pose forearm checks, whose\n * roles a cut never writes, and the side lock's eye-corner check, which a\n * cut eye (stopping where the lock covers it) cannot feed: the cut checks\n * the lock against the declared eye box itself. What stays is what the rig\n * refuses (a lip set partial, mixed or on another canvas, a lash whose top\n * row is off its sclera's, a side lock without hair_front), the side locks'\n * root and lean checks, each naming the landmark to move, the missing\n * optional roles, and the lip set's opening facts.\n */\nexport async function measureDir(\n absDir: string,\n noseSpeck?: NoseSpeck,\n { inPlace = false }: { inPlace?: boolean } = {},\n): Promise<MeasureReport> {\n const files = fs\n .readdirSync(absDir)\n .filter((f) => f.endsWith(\".png\") && !f.startsWith(\"preview\"))\n .sort();\n if (files.length === 0) {\n throw new AutoRigInputError(`no role layers in ${absDir}`);\n }\n // Same agent-supplied-input surface autoRigFromLayers bounds: a `layersDir`\n // pointed at an asset folder would decode every PNG in it before reporting.\n if (files.length > MAX_LAYERS) {\n throw new AutoRigInputError(\n `too many layers in ${absDir}: ${files.length} > ${MAX_LAYERS}`,\n );\n }\n\n const layers: Record<string, LayerStats> = {};\n const empty: string[] = [];\n for (const f of files) {\n const role = path.basename(f, \".png\");\n const m = await layerStats(path.join(absDir, f));\n if (!m) {\n empty.push(role);\n continue;\n }\n layers[role] = m;\n }\n\n const warnings: string[] = [];\n\n // 1. Art running to its own edge → a straight seam appears on head turn.\n // Two very different faults look identical in the flattened layer, and the\n // remedies cost differently, so tell them apart before prescribing one: a\n // part the CANVAS clipped has no margin left on that side (retune, free),\n // while a part placed with room whose own drawing runs to its frame does\n // (regenerate, billed). A real run lost a regeneration to this: the source\n // kept 44 px of margin and the default layout pushed it 70 px off-canvas,\n // so redrawing it reproduced the clip exactly.\n for (const [role, m] of Object.entries(layers)) {\n // A lip layer's straight edges are the split's cuts, not the art's; the\n // lip checks read what the rig does with them. In place, an edge is the\n // picture's own.\n if (inPlace || isLipLayerRole(role)) continue;\n const edges: [string, number, number, number][] = [\n [\"top\", m.edgeTop, m.w, m.marginTop],\n [\"left\", m.edgeLeft, m.h, m.marginLeft],\n [\"right\", m.edgeRight, m.h, m.marginRight],\n ];\n // A bust's torso is meant to run off the bottom of a square canvas. A\n // full body stands on a taller one with its soles inside it, where two\n // soles' flat bottoms could trip the generic check, so a check of its own\n // replaces it: paint on the canvas's last row is feet cut off.\n if (role !== \"body\") {\n edges.push([\"bottom\", m.edgeBottom, m.w, m.marginBottom]);\n } else if (m.canvasH > m.canvasW && m.marginBottom === 0) {\n warnings.push(\n `body: its bottom row is the canvas's last — on a tall canvas that cuts the feet off. ` +\n `Free fix: raise canvasHeight (the canvas grows downward, nothing else moves) and ` +\n `remeasure; regenerate body.png only if the drawing itself stops short of the soles.`,\n );\n }\n for (const [side, v, span, margin] of edges) {\n if (v > EDGE_SOLID_MAX && v * span >= EDGE_RUN_MIN_PX) {\n const remedy =\n margin === 0\n ? // margin 0 is consistent with a clipped placement AND with art\n // already cropped flush that happens to sit on the boundary, and\n // the flattened layer cannot separate them — so name the free\n // move rather than the cause. If moving it inward leaves the\n // edge opaque, the drawing is the one at fault.\n `it sits flush against the canvas ${side}, which a clipped placement and already-cropped ` +\n `art both produce. Move it inward first — retune layout.${role}.cx/cy/w, free — and ` +\n `remeasure; regenerate only if the edge is still opaque with margin to spare.`\n : `its own drawing runs to the frame ${margin} px inside the canvas — regenerate that part ` +\n `with empty margin on that side. Billed.`;\n warnings.push(\n `${role}: ${pct(v)} of its ${side} edge is opaque — the art is cut off there, ` +\n `which shows as a straight seam ${isArm(role) ? \"once the arm raises\" : \"once the head turns\"}. ` +\n `Cause: ${remedy}`,\n );\n }\n }\n }\n\n // 1b. A straight cut through the drawing, wherever it falls in the bbox.\n for (const [role, m] of Object.entries(layers)) {\n // `body` bends as one drawing, so no pose opens a cut in it; its top is\n // deliberately cut flat where the jaw covers it, and stays under the jaw\n // because the head rides the body.\n if (inPlace || role === \"body\" || isLipLayerRole(role)) continue;\n if (\n m.flatCutRun > FLAT_CUT_MAX_FRAC * m.w &&\n m.flatCutRun >= FLAT_CUT_MIN_PX\n ) {\n warnings.push(\n `${role}: ${m.flatCutRun}px of straight flat edge at y=${m.flatCutY} ` +\n `(${pct(m.flatCutRun / m.w)} of its width) — the source art is cut through there. ` +\n (isArm(role)\n ? `It hides at rest and opens into a seam once the arm raises. `\n : `It hides while the head faces front and opens into a seam on turn. `) +\n `Regenerate this part with the whole subject inside the frame.`,\n );\n }\n }\n\n // 1c. The arms: each needs a body, and its shoulder cap the torso under it.\n if (!inPlace) warnings.push(...(await armWarnings(absDir, layers)));\n\n // 1d. The pose forearms: each needs its arm, and its elbow end the arm's elbow.\n if (!inPlace) warnings.push(...(await forearmPoseWarnings(absDir, layers)));\n\n // 1e. The lip set: the fold's contract per column, the opening's size, the\n // line's weight, key green left, an interior with holes.\n const lip = await lipWarnings(absDir, layers, inPlace);\n warnings.push(...lip.warnings);\n\n // 1f. The side locks: root under the bangs, off the eye corner, paint behind\n // the near lean, one lock drawn (not in place: see hairSideWarnings).\n warnings.push(...(await hairSideWarnings(absDir, layers, inPlace)));\n\n // 2/3/4. Eye stack geometry, per side.\n for (const side of [\"L\", \"R\"]) {\n const eye: LayerStats | undefined = layers[`eye_${side}`];\n const iris: LayerStats | undefined = layers[`iris_${side}`];\n const lash: LayerStats | undefined = layers[`lash_${side}`];\n if (!eye) continue;\n\n const aspect = eye.h / eye.w;\n if (!inPlace && aspect < EYE_ASPECT_MIN) {\n warnings.push(\n `eye_${side}: sclera aspect h/w=${aspect.toFixed(2)} is flatter than ${EYE_ASPECT_MIN} — ` +\n `a round iris cannot sit inside it. Free fix first: set layout.eye_${side}.h and ` +\n `layout.lash_${side}.h to ${Math.ceil(eye.w * EYE_ASPECT_MIN)} (both, or the fold tears) — ` +\n `stretching a flat white lens is invisible. Regenerate the eyewhite taller only if that ` +\n `distorts the lash.`,\n );\n }\n\n if (iris) {\n const ratio = iris.w / eye.w;\n if (!inPlace && (ratio < IRIS_RATIO_MIN || ratio > IRIS_RATIO_MAX)) {\n warnings.push(\n `iris_${side}: width is ${pct(ratio)} of the sclera (target ${IRIS_RATIO_MIN}-${IRIS_RATIO_MAX}) — ` +\n `retune layout.iris_${side}.w (keep it a fraction of the eye width), no regeneration needed.`,\n );\n }\n const dx = iris.bboxCx - eye.massCx;\n const dy = iris.bboxCy - eye.massCy;\n if (\n !inPlace &&\n (Math.abs(dx) > IRIS_OFFSET_MAX_X || Math.abs(dy) > IRIS_OFFSET_MAX_Y)\n ) {\n warnings.push(\n `iris_${side}: sits (${dx.toFixed(1)}, ${dy.toFixed(1)}) px from the white's centre of mass — ` +\n `retune layout.iris_${side}.cx/cy. The sclera's bbox centre is NOT its visual centre when the ` +\n `lash flick stretches the box.`,\n );\n }\n }\n\n // 5. The lash and the white are split from ONE source and pasted with the\n // same cx/cy/w, so their frames coincide even though the lash only inks the\n // upper part of it (its content sits higher — that is the fold working, not\n // a fault). In sync, the lash is ink the sclera was recoloured from, so\n // every opaque lash pixel lies on the sclera, and both ink the same top\n // row; a drift moves pixels off it, and a lash scaled down inside it (a w\n // or h out of sync) drops its top row — the seam the fold rides — either\n // way tearing the fold. Neither the ink centres nor the frame's sides can\n // stand in for that: a lash stops short of the tear duct (5b), so a\n // correctly composed eye's ink sits 3-5% of its width off the sclera's\n // centre, while a lash drifting in toward that bare end stays inside the\n // frame.\n //\n // 5b. Which way the eye was drawn. A lash runs out to the outer corner,\n // wing and all, and stops short of the tear duct at the inner one, so in\n // the frame it shares with the sclera it is the nose end that the lash\n // leaves bare. A lash that stops short of the OUTER end instead is an\n // eyewhite drawn facing the other way: the wings point in, and \"left eye\"\n // in a prompt cannot prevent it, since it reads as the viewer's left or\n // the character's. The ends are read, not the ink's centroid: a thin wing\n // widens the frame far more than it moves the centroid, which reads a\n // correctly drawn eye as reversed. Only a lash in sync is read — a drift\n // moves the ends too, and is check 5's to report, not the drawing's.\n if (lash) {\n const { opaque, off } = await lashOffSclera(\n path.join(absDir, `eye_${side}.png`),\n path.join(absDir, `lash_${side}.png`),\n );\n const dTop = lash.marginTop - eye.marginTop;\n const faults = [\n ...(off > opaque * LASH_STRAY_TOL_FRAC\n ? [`${off} of its ${opaque} opaque px lie off eye_${side}'s sclera`]\n : []),\n ...(Math.abs(dTop) > 0.5\n ? [`its top edge is ${dTop.toFixed(1)} px off the sclera's`]\n : []),\n ];\n if (faults.length > 0) {\n warnings.push(\n `lash_${side}: ${faults.join(\" and \")} — they are split from one source and MUST share ` +\n `cx/cy/w/h in layout, or the blink fold tears. Retune to match.`,\n );\n } else {\n // How far short of each side of the frame the lash stops.\n const bareLeft = lash.marginLeft - eye.marginLeft;\n const bareRight = lash.marginRight - eye.marginRight;\n // eye_R is the screen-left eye: its outer corner is its left end.\n const [bareOuter, bareInner] =\n side === \"R\" ? [bareLeft, bareRight] : [bareRight, bareLeft];\n if (!inPlace && (bareOuter - bareInner) / eye.w > EYE_FACING_TOL_FRAC) {\n warnings.push(\n `eye_${side}: its lash stops ${pct(bareOuter / eye.w)} of the eye width short of the outer corner ` +\n `and ${pct(bareInner / eye.w)} short of the nose side — the eyewhite is drawn facing the other way, ` +\n `lash wing at the inner corner. The composer reads eyewhite.png as the eye on the screen LEFT: lash ` +\n `wing at the image's left end, lash-free tear duct at its right. Free fix: compose again with ` +\n `mirrorParts: [\"eyewhite.png\"] — no regeneration.`,\n );\n }\n }\n }\n }\n\n // 6. A nose whose dense core is a speck of its part (`isSpeckCore`). A\n // speck compose found in the source part, before resampling, is reported\n // as given: a dot blurred under alpha 128 no longer shows in the file.\n // Otherwise the file is judged against its crop — what the rig reads —\n // which also catches a core that only resampling made a speck.\n if (noseSpeck !== undefined) {\n warnings.push(noseSpeckWarning(noseSpeck, \"compose\"));\n } else if (!inPlace && layers.nose !== undefined) {\n const nose = await decodePng(path.join(absDir, \"nose.png\"));\n const core = denseCoreOf(nose.rgba, nose.width, nose.height);\n if (core !== null) {\n const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);\n if (isSpeckCore(core, crop))\n warnings.push(noseSpeckWarning({ core, part: crop }, \"layer\"));\n }\n }\n\n // 7. Optional roles that change how finished the character reads.\n for (const [role, why] of [\n [\"body\", \"without it the character reads as a floating head on head-turn\"],\n [\"hair_back\", \"without it the silhouette is flat behind the face\"],\n [\n \"nose\",\n \"without it the head still turns on the default profile, but there is no nose to lead it, and no turn fit to the art (`turnTargets` is inert, no `turn` report)\",\n ],\n ]) {\n if (layers[role] === undefined) warnings.push(`${role}: missing — ${why}.`);\n }\n\n return {\n layers,\n empty,\n warnings,\n ...(lip.lips === undefined ? {} : { lips: lip.lips }),\n };\n}\n\n/**\n * Measure a caller-supplied layers directory.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) →\n * `{ ok:false }`, matching autoRigFromLayers; any other throw propagates.\n */\nexport async function measureLayers(\n input: MeasureInput,\n): Promise<MeasureResult> {\n try {\n const layersDir = resolveInputDir(input.layersDir);\n const report = await measureDir(layersDir);\n return {\n ok: true,\n layersDir,\n ...report,\n passed: report.warnings.length === 0,\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n\n/** The lip set's opening as one line of a report. */\nexport function formatLipFacts({ opening, deadZone }: LipFacts): string {\n return `lips: opening ${opening.width} px wide, ${opening.height} px tall at its centre under a ${opening.line} px line — no slit below MouthOpen ${deadZone.toFixed(2)}`;\n}\n\n/**\n * Render a measurement as plain text: the per-layer table first (numbers to\n * argue with), then the checks that fired. Takes the report itself rather than\n * a MeasureResult so a caller holding one inline (no `ok` to unwrap) can print\n * it too; a failed measurement has no report to render.\n */\nexport function formatMeasureReport(\n result: MeasureReport & { layersDir: string },\n): string {\n const lines = [\n `# layers (${result.layersDir})`,\n \"\",\n \"role size bbox-centre mass-centre margins t/b/l/r\",\n ];\n // Roles come off a sorted file listing, so sorting the two groups back\n // together restores that order.\n for (const role of [...Object.keys(result.layers), ...result.empty].sort()) {\n const m = result.layers[role];\n if (m === undefined) {\n lines.push(`${role.padEnd(13)} EMPTY (fully transparent)`);\n continue;\n }\n lines.push(\n `${role.padEnd(13)} ${`${m.w}x${m.h}`.padEnd(11)} ` +\n `${`${m.bboxCx.toFixed(0)},${m.bboxCy.toFixed(0)}`.padEnd(14)} ` +\n `${`${m.massCx.toFixed(0)},${m.massCy.toFixed(0)}`.padEnd(13)} ` +\n `${m.marginTop}/${m.marginBottom}/${m.marginLeft}/${m.marginRight}`,\n );\n }\n\n if (result.lips !== undefined) {\n lines.push(\"\", formatLipFacts(result.lips));\n }\n\n lines.push(\"\", \"# checks\", \"\");\n if (result.warnings.length === 0) {\n lines.push(\"all geometry checks passed\");\n } else {\n for (const w of result.warnings) lines.push(`- ${w}`);\n }\n return lines.join(\"\\n\");\n}\n","/**\n * The measure's arm checks. An arm hangs from the body's shoulder, and raising\n * it turns its shoulder cap about the rig's shoulder pivot, so the torso has\n * to reach under that cap or a gap opens beside the shoulder. The pivot is\n * the rig's own: `armGeometry`, run on the layer as `auto_rig_from_layers`\n * runs it, so the cap measured here is the one the rig turns.\n */\n\nimport path from \"node:path\";\nimport {\n LayerGeometryError,\n armGeometry,\n createLayerSetMeasurer,\n type ArmGeometry,\n type LayerInput,\n type LayerSetMeasurer,\n} from \"@ikijs/editor\";\nimport type { LayerStats } from \"./measure\";\nimport { decodePng } from \"./node-images\";\n\n/** The arm roles, screen right (`arm_L`) then screen left (`arm_R`). */\nexport const ARM_ROLES = [\"arm_L\", \"arm_R\"] as const;\n\n/** How far an arm's shoulder cap must reach under the torso's edge on the\n * shoulder pivot's row, as a share of its radius r_u. Our own value: a\n * raised arm turns its cap about the pivot, so a cap that barely meets the\n * torso's edge swings clear of it and bares the gap beside the shoulder. */\nexport const CAP_OVERLAP = 0.5;\n\n/** A px figure as the report prints it: pivots sit on half px. */\nexport const px = (v: number) => `${Number(v.toFixed(1))}`;\n\n/** Decode a role's layer in `absDir` and measure it on `measurer`. */\nexport async function measured(\n measurer: LayerSetMeasurer,\n absDir: string,\n role: string,\n): Promise<LayerInput> {\n const fileName = `${role}.png`;\n const { rgba } = await decodePng(path.join(absDir, fileName));\n // layerStats counts alpha > 8 and the measurer alpha >= 8, so a layer\n // measured non-empty is never empty here.\n return measurer.add({ role, fileName, rgba })!;\n}\n\n/**\n * Warn of an arm layer the rig refuses or would hang with a gap at the\n * shoulder: one without a body, one on another canvas than the body's, one\n * too short to place an elbow under its shoulder, and one whose shoulder cap\n * does not reach `CAP_OVERLAP` of its radius under the torso's edge.\n * `layers` holds the measured, non-empty layers of `absDir` by role.\n */\nexport async function armWarnings(\n absDir: string,\n layers: Record<string, LayerStats>,\n): Promise<string[]> {\n const warnings: string[] = [];\n const body = layers.body;\n // Opened for the first arm that reaches the overlap, so the body decodes once.\n let set: { measurer: LayerSetMeasurer; body: LayerInput } | undefined;\n\n for (const arm of ARM_ROLES) {\n const stats = layers[arm];\n if (stats === undefined) continue;\n if (body === undefined) {\n warnings.push(\n `${arm}: no body layer — an arm hangs from the body's shoulder, and auto_rig_from_layers refuses it.`,\n );\n continue;\n }\n // One measurer reads every buffer at one size, and a buffer of another\n // shape but the same area would pass its length check and be read with\n // the wrong stride.\n if (stats.canvasW !== body.canvasW || stats.canvasH !== body.canvasH) {\n warnings.push(\n `${arm}: its canvas ${stats.canvasW}x${stats.canvasH} differs from body's ` +\n `${body.canvasW}x${body.canvasH} — auto_rig_from_layers refuses layers of different ` +\n `sizes; recompose them together.`,\n );\n continue;\n }\n if (set === undefined) {\n const measurer = createLayerSetMeasurer({\n width: body.canvasW,\n height: body.canvasH,\n });\n set = { measurer, body: await measured(measurer, absDir, \"body\") };\n }\n\n let g: ArmGeometry;\n try {\n // The body box's centre, model x: the axis the rig reads an arm's side\n // off.\n g = armGeometry(\n await measured(set.measurer, absDir, arm),\n set.body.bbox.x + set.body.bbox.w / 2 - body.canvasW / 2,\n );\n } catch (err) {\n if (err instanceof LayerGeometryError) {\n warnings.push(\n `${arm}: ${err.message} — auto_rig_from_layers refuses it. Regenerate arm.png drawn ` +\n `hanging, shoulder at the top. Billed.`,\n );\n continue;\n }\n throw err;\n }\n const cap = capWarning(arm, g, set.body);\n if (cap !== undefined) warnings.push(cap);\n }\n return warnings;\n}\n\n/**\n * The shoulder cap against the torso's edge on the arm's side, on the canvas\n * row holding the shoulder pivot: the cap reaches r_u past the pivot, so it\n * overlaps the torso by r_u less the pivot's distance outside that edge.\n */\nfunction capWarning(\n arm: (typeof ARM_ROLES)[number],\n g: ArmGeometry,\n body: LayerInput,\n): string | undefined {\n // Model space is centred on the canvas, y up.\n const pivotX = g.shoulder.x + body.canvasW / 2;\n const row = Math.floor(body.canvasH / 2 - g.shoulder.y);\n const runs = body.rowRuns?.[row - body.bbox.y] ?? [];\n if (runs.length === 0) {\n return (\n `${arm}: the body has no paint on its shoulder pivot's row (y=${row}) — the torso shows a ` +\n `gap beside the shoulder once the arm raises. Retune layout.${arm}.cy onto the shoulder (free).`\n );\n }\n // The outermost run's end on the arm's side; a run's end column is exclusive.\n const edge = g.side === 1 ? runs[runs.length - 1] : runs[0];\n const overlap = g.shoulderRadius - g.side * (pivotX - edge);\n const need = CAP_OVERLAP * g.shoulderRadius;\n if (overlap >= need) return undefined;\n return (\n `${arm}: its shoulder cap reaches ${px(overlap)} px under the torso's edge on its pivot row ` +\n `(y=${row}), under half its radius (${px(need)} px) — a gap opens beside the shoulder once ` +\n `the arm raises. Move layout.${arm}.cx ${Math.ceil(need - overlap)} px toward the body (free).`\n );\n}\n","/**\n * The measure's side-lock checks. A front side lock hangs over the cheek's\n * edge beside the ear with its root hidden under the bangs; on the turn the\n * near lock follows the face plate inward and the far eye's outer tail slides\n * under the far one. Four ways a drawing or its placement breaks that, each\n * naming the free `layout` move, where one exists, before the billed\n * regenerate. A lock the rig refuses (no `hair_front`) is warned of alone.\n * On a cut picture (`inPlace`) each names the landmark to move instead; the\n * two-locks check, whose only remedy is redrawing `hair_side.png`, is left\n * out, and so is the eye-corner check, which a cut eye (stopping where the\n * lock covers it) cannot feed: the cut checks the lock against the declared\n * eye box itself.\n */\n\nimport {\n createLayerSetMeasurer,\n type LayerInput,\n type LayerSetMeasurer,\n} from \"@ikijs/editor\";\nimport { measured } from \"./measure-arms\";\nimport type { LayerStats } from \"./measure\";\n\n/** The lock roles, as the composer writes them from one `hair_side.png`:\n * `hair_side_R` is the drawing as is, `hair_side_L` its mirror. */\nconst LOCK_ROLES = [\"hair_side_R\", \"hair_side_L\"] as const;\ntype LockRole = (typeof LOCK_ROLES)[number];\n\n/** Rules 1 and 2: a stretch of the lock this wide past the bangs, or over\n * the eye's corner, shows at rest; 1-2 px is antialiasing the neighbouring\n * layer's edge hides. */\nexport const VISIBLE_MIN_PX = 3;\n\n/** Rule 3: how far the near lock leans inward at the turn's extreme, as a\n * share of the head unit (the eye row to the chin): the default profile's\n * face-plate slide at ±30 (`slide` in the auto-rig profile), at\n * `rigPlan.turn.amount` 1 — a larger amount scales the lean. The near lock's\n * body follows the plate. Restated, not imported: the measure reads layers,\n * not the rig's internals. */\nconst LEAN_HH = 0.12;\n\n/** Rule 4: a run of the lock's opaque columns that is a lock of its own, as a\n * share of the layer's width; a smaller one is a wisp or a strand tip. */\nconst TWO_LOCKS_RUN = 0.25;\n/** Rule 4: the gap between two such runs that makes them two locks, not one\n * lock's parting. */\nconst TWO_LOCKS_GAP = 0.1;\n\ntype Runs = number[];\n\n/** Does a row's run list (start, exclusive end, ...) hold column `x`? */\nfunction covers(runs: Runs, x: number): boolean {\n for (let i = 0; i + 1 < runs.length; i += 2) {\n if (x >= runs[i] && x < runs[i + 1]) return true;\n }\n return false;\n}\n\n/** A layer's runs on canvas row `y`; none outside its crop. */\nfunction runsAt(layer: LayerInput | undefined, y: number): Runs {\n return layer?.rowRuns?.[y - layer.bbox.y] ?? [];\n}\n\n/** The canvas rows of a layer's first and last row holding a run, or\n * `undefined` with none. A run needs alpha 128 while `bbox` takes alpha 8\n * and is grown a pixel each side, so its edge rows can hold no run, and a\n * layer painted wholly under alpha 128 holds none at all. */\nfunction opaqueRows(\n layer: LayerInput,\n): { top: number; bottom: number } | undefined {\n const runs = layer.rowRuns ?? [];\n const top = runs.findIndex((r) => r.length > 0);\n if (top < 0) return undefined;\n let bottom = runs.length - 1;\n while (runs[bottom].length === 0) bottom--;\n return { top: layer.bbox.y + top, bottom: layer.bbox.y + bottom };\n}\n\n/**\n * Warn of a side lock the rig refuses or that would show badly: one without\n * the `hair_front` its root hides under, one whose root shows past the bangs\n * at rest, one over the eye white's outer corner at rest, one whose near-turn\n * lean bares columns nothing is painted behind, and a `hair_side.png` that\n * draws two locks. `layers` holds the measured, non-empty layers of `absDir`\n * by role. `inPlace`: the layers were cut out of one picture, each lock from\n * `landmarks.sideHair.<side>` (see `measureDir`).\n */\nexport async function hairSideWarnings(\n absDir: string,\n layers: Record<string, LayerStats>,\n inPlace = false,\n): Promise<string[]> {\n const present = LOCK_ROLES.filter((r) => layers[r] !== undefined);\n if (present.length === 0) return [];\n\n const warnings: string[] = [];\n if (layers.hair_front === undefined) {\n for (const role of present) {\n warnings.push(\n `${role}: needs hair_front — the rig refuses a lock without the bangs its root hides ` +\n (inPlace\n ? `under. Put landmarks.frontHair round the bangs, or drop ${landmark(role)}.`\n : `under. Remove hair_side.png and recompose (free), or draw hair_front.png. Billed.`),\n );\n }\n return warnings;\n }\n\n // One measurer reads every buffer at one size, and a buffer of another\n // shape but the same area would be read with the wrong stride.\n const ref = layers.hair_front;\n let mismatched = false;\n for (const r of [...present, \"hair_back\", \"face\"]) {\n const stats = layers[r];\n if (stats === undefined) continue;\n if (stats.canvasW !== ref.canvasW || stats.canvasH !== ref.canvasH) {\n mismatched = true;\n warnings.push(\n `${r}: its canvas ${stats.canvasW}x${stats.canvasH} differs from hair_front's ` +\n `${ref.canvasW}x${ref.canvasH} — auto_rig_from_layers refuses layers of different ` +\n `sizes; recompose them together.`,\n );\n }\n }\n if (mismatched) return warnings;\n\n const measurer: LayerSetMeasurer = createLayerSetMeasurer({\n width: ref.canvasW,\n height: ref.canvasH,\n });\n const read = (role: string) =>\n layers[role] === undefined ? undefined : measured(measurer, absDir, role);\n const front = await read(\"hair_front\");\n const back = await read(\"hair_back\");\n const face = await read(\"face\");\n\n // Each lock's side comes from where it sits against the face's centre, not\n // from its name, so a swapped layout still reads the right edge.\n const axisX = face ? face.bbox.x + face.bbox.w / 2 : ref.canvasW / 2;\n\n const locks = new Map<LockRole, LayerInput>();\n for (const role of present) {\n const lock = await measured(measurer, absDir, role);\n locks.set(role, lock);\n const side = lock.bbox.x + lock.bbox.w / 2 < axisX ? -1 : 1;\n const eyeRole = ([\"eye_L\", \"eye_R\"] as const).find(\n (r) =>\n layers[r] !== undefined && (layers[r].bboxCx < axisX ? -1 : 1) === side,\n );\n const eye = eyeRole === undefined ? undefined : layers[eyeRole];\n\n const root = rootWarning(role, lock, front, inPlace);\n if (root !== undefined) warnings.push(root);\n // A cut eye stops where a lock covers it, so its corner reads clear\n // here: the cut checks the lock against the declared eye box instead\n // (`sideHair.<side>`).\n if (!inPlace && eyeRole !== undefined && eye !== undefined) {\n const w = eyeCornerWarning(role, lock, side, eyeRole, eye);\n if (w !== undefined) warnings.push(w);\n }\n // The lean needs only an eye row, so the other eye's serves.\n const rowEye = eye ?? layers.eye_L ?? layers.eye_R;\n if (face !== undefined && rowEye !== undefined) {\n const w = leanWarning(role, lock, side, face, back, rowEye, inPlace);\n if (w !== undefined) warnings.push(w);\n }\n }\n if (inPlace) return warnings;\n\n // The as-drawn copy: a mirror of two locks is two locks too, so one reading\n // is enough, and the composer's input is the one the message is about.\n if (drawsTwoLocks(locks.get(\"hair_side_R\") ?? locks.get(present[0])!)) {\n warnings.push(\n `hair_side.png draws two locks — draw ONE lock, the screen-left one; the composer ` +\n `mirrors it into hair_side_L. Billed.`,\n );\n }\n return warnings;\n}\n\n/** The landmark a cut lock comes from: `hair_side_L` from `sideHair.L`. */\nconst landmark = (role: string) => `landmarks.sideHair.${role.slice(-1)}`;\n\n/**\n * Rule 1. The lock's root hides under the bangs, so on its top row every run\n * of its columns must lie under `hair_front`'s runs on that row; a stretch of\n * `VISIBLE_MIN_PX` or more past them shows the root at rest. A jagged hem\n * makes \"too low\" and \"too far out\" hard to tell apart from the runs, so the\n * remedy names both free moves and leaves the pick to the preview.\n */\nfunction rootWarning(\n role: LockRole,\n lock: LayerInput,\n front: LayerInput | undefined,\n inPlace: boolean,\n): string | undefined {\n const y = opaqueRows(lock)?.top;\n if (y === undefined) return undefined;\n const frontRuns = runsAt(front, y);\n const lockRuns = runsAt(lock, y);\n let shown = 0;\n for (let i = 0; i + 1 < lockRuns.length; i += 2) {\n // The run's columns past the bangs, in stretches: only a stretch of\n // VISIBLE_MIN_PX or more counts.\n let stretch = 0;\n for (let x = lockRuns[i]; x <= lockRuns[i + 1]; x++) {\n if (x < lockRuns[i + 1] && !covers(frontRuns, x)) {\n stretch++;\n continue;\n }\n if (stretch >= VISIBLE_MIN_PX) shown += stretch;\n stretch = 0;\n }\n }\n if (shown === 0) return undefined;\n const lead =\n `${role}: its top row (canvas y ${y}) shows past hair_front on ${shown} px — the root is ` +\n `visible at rest. `;\n if (inPlace) {\n return (\n lead +\n `Move ${landmark(role)}'s top up into landmarks.frontHair, or extend landmarks.frontHair ` +\n `down over the lock's top.`\n );\n }\n return (\n lead +\n `Move it under the bangs — up (layout.${role}.cy) or toward the face ` +\n `(layout.${role}.cx) (free), or regenerate hair_side.png with a longer hidden root. Billed.`\n );\n}\n\n/**\n * Rule 2. The eye's outer tail may only slide under the lock on the turn, so\n * at rest the lock must not already cover the corner column of its side's eye\n * on the eye's centre row by `VISIBLE_MIN_PX` or more. The overlap is how far\n * the lock's run holding the corner reaches past it, toward the eye's centre;\n * moving the lock outward by that clears the corner.\n */\nfunction eyeCornerWarning(\n role: LockRole,\n lock: LayerInput,\n side: -1 | 1,\n eyeRole: string,\n eye: LayerStats,\n): string | undefined {\n const row = Math.floor(eye.bboxCy);\n const corner = side < 0 ? eye.marginLeft : eye.marginLeft + eye.w - 1;\n const runs = runsAt(lock, row);\n let overlap = 0;\n for (let i = 0; i + 1 < runs.length; i += 2) {\n if (corner < runs[i] || corner >= runs[i + 1]) continue;\n overlap = side < 0 ? runs[i + 1] - corner : corner - runs[i] + 1;\n }\n if (overlap < VISIBLE_MIN_PX) return undefined;\n const lead =\n `${role}: covers ${eyeRole}'s outer corner at rest (canvas x ${corner}, y ${row}) by ` +\n `${overlap} px — the eye's outer tail may only slide under it on the turn. `;\n const way = side < 0 ? \"left\" : \"right\";\n return (\n lead +\n `Move layout.${role}.cx ${overlap} px ${way}, outward (free), or regenerate it narrower. Billed.`\n );\n}\n\n/**\n * Rule 3. The face plate slides toward the far side, the side the head turns\n * toward. Turned away from a lock's side, that lock is the near one: its body\n * follows the plate, moving INWARD by about `LEAN_HH` of the head unit (the\n * eye row to the chin), and baring a strip that wide just inside its rest\n * outer edge. Behind that strip `hair_back` or the face (which carries the\n * ear) must be painted. The face's last opaque row stands for the chin; a\n * painted neck only widens the strip. Only the root blend's lower part leans\n * fully; the full width on every lock row from its top to the face's last row\n * is the conservative reading. Below that row the plate is the neck and is\n * not checked.\n */\nfunction leanWarning(\n role: LockRole,\n lock: LayerInput,\n side: -1 | 1,\n face: LayerInput,\n back: LayerInput | undefined,\n eye: LayerStats,\n inPlace: boolean,\n): string | undefined {\n const faceRows = opaqueRows(face);\n const lockRows = opaqueRows(lock);\n if (faceRows === undefined || lockRows === undefined) return undefined;\n const faceBottom = faceRows.bottom;\n const lean = Math.round(LEAN_HH * (faceBottom - Math.floor(eye.bboxCy)));\n if (lean < 1) return undefined;\n\n const bare = new Set<number>();\n const rows = new Set<number>();\n for (let y = lockRows.top; y <= Math.min(lockRows.bottom, faceBottom); y++) {\n const runs = runsAt(lock, y);\n if (runs.length === 0) continue;\n // The outermost run only: its outer end is the lock's edge on this row,\n // and a lock narrower than the lean vacates only its own width.\n const from = side < 0 ? runs[0] : runs[runs.length - 2];\n const to = side < 0 ? runs[1] : runs[runs.length - 1];\n const start = side < 0 ? from : Math.max(from, to - lean);\n const end = side < 0 ? Math.min(to, from + lean) : to;\n const faceRuns = runsAt(face, y);\n const backRuns = runsAt(back, y);\n for (let x = start; x < end; x++) {\n if (covers(faceRuns, x) || covers(backRuns, x)) continue;\n bare.add(x);\n rows.add(y);\n }\n }\n if (bare.size === 0) return undefined;\n const cols = [...bare].sort((a, b) => a - b);\n const ys = [...rows].sort((a, b) => a - b);\n const where =\n `leaves bare pixels spanning columns ${cols[0]}–${cols[cols.length - 1]}, ` +\n `rows ${ys[0]}–${ys[ys.length - 1]}`;\n const lead = `${role}: when the head turns away from it the lock leans inward about ${lean} px and ${where}, where`;\n if (inPlace) {\n // The cut fills the back hair under a lock down to shellLower, a\n // landmark; skin only where the lock crosses the face's own paint.\n return (\n `${lead} neither hair_back nor the face is painted — lower landmarks.shellLower ` +\n `under it, down to where the hair behind the lock ends (back hair is filled under ` +\n `the lock above it).`\n );\n }\n if (back === undefined) {\n // No layout move clears this: the strip is measured from the lock's own\n // edge, so it moves with the lock, and rows above the face are bare\n // whatever the lock's cx.\n return `${lead} the face is not painted — draw hair_back.png behind the locks. Billed.`;\n }\n return (\n `${lead} neither hair_back nor the face is painted — widen hair_back there ` +\n `(layout.hair_back.w) (free), or regenerate it fuller behind the locks. Billed.`\n );\n}\n\n/**\n * Rule 4. The opaque column projection of one lock is one run; two runs each\n * `TWO_LOCKS_RUN` of its width or more, apart by `TWO_LOCKS_GAP` of it, are\n * two locks drawn on one sheet.\n */\nfunction drawsTwoLocks(lock: LayerInput): boolean {\n const w = lock.bbox.w;\n const col = new Array<boolean>(w).fill(false);\n for (const runs of lock.rowRuns ?? []) {\n for (let i = 0; i + 1 < runs.length; i += 2) {\n for (let x = runs[i]; x < runs[i + 1]; x++) col[x - lock.bbox.x] = true;\n }\n }\n const big: [number, number][] = [];\n let start = -1;\n for (let x = 0; x <= w; x++) {\n if (x < w && col[x]) {\n if (start < 0) start = x;\n } else if (start >= 0) {\n if (x - start >= TWO_LOCKS_RUN * w) big.push([start, x]);\n start = -1;\n }\n }\n for (let i = 1; i < big.length; i++) {\n if (big[i][0] - big[i - 1][1] >= TWO_LOCKS_GAP * w) return true;\n }\n return false;\n}\n","/**\n * The measure's pose forearm checks. A pose forearm hangs from its arm's\n * elbow and is swapped in for the hanging forearm, so it has to meet the arm\n * where the rig turns it: the rig puts its pivot on the arm's elbow and\n * `forearm_pose.png` is composed so that its elbow end lands there, at the\n * arm's elbow width. The geometry is the rig's own: `armGeometry` on the arm\n * and `forearmPoseGeometry` on the pose forearm, run on one measurer as\n * `auto_rig_from_layers` runs them. A pose forearm too far off in any of\n * pivot, width or length shows a broken joint once the switch is on; the\n * canvas-edge check is the generic one in `measureDir`.\n */\n\nimport {\n LayerGeometryError,\n armGeometry,\n createLayerSetMeasurer,\n forearmPoseGeometry,\n type ArmGeometry,\n type ForearmPoseGeometry,\n type LayerInput,\n type LayerSetMeasurer,\n} from \"@ikijs/editor\";\nimport type { LayerStats } from \"./measure\";\nimport { measured, px } from \"./measure-arms\";\n\n/** The pose forearm roles, each with the arm it hangs from. */\nexport const POSE_ROLES = [\"forearm_pose_L\", \"forearm_pose_R\"] as const;\nconst ARM_OF: Record<(typeof POSE_ROLES)[number], \"arm_L\" | \"arm_R\"> = {\n forearm_pose_L: \"arm_L\",\n forearm_pose_R: \"arm_R\",\n};\n\n/** How far off the arm's elbow the pose forearm's pivot may be, px. Our own\n * value: the composer pins it to within a pixel, so more is a layout `cx` /\n * `cy` that moved it. */\nexport const POSE_PIVOT_TOLERANCE = 2;\n/** How far the pose forearm's elbow end may differ from the arm's elbow run,\n * as a share of the run. Our own value: past it the joint shows a step in\n * the sleeve. */\nexport const POSE_WIDTH_TOLERANCE = 0.1;\n/** How far the pose forearm's length (pivot to its top painted row) may\n * differ from the hanging arm's (elbow to its last painted row), as a\n * share of it. Our own value, looser than the width's: a raised hand is\n * not a hanging one, but one twice as long is another arm. */\nexport const POSE_LENGTH_TOLERANCE = 0.15;\n\n/** Model y of the last painted row of a layer, y up. */\nfunction bottomRowY(layer: LayerInput): number {\n const painted =\n layer.rowRuns?.flatMap((runs, k) => (runs.length > 0 ? [k] : [])) ?? [];\n const k = painted.at(-1) ?? layer.bbox.h - 1;\n return layer.canvasH / 2 - (layer.bbox.y + k + 0.5);\n}\n\n/**\n * Warn of a pose forearm the rig refuses or would hang off its arm's elbow:\n * one without its arm, one on another canvas than its arm's, and one whose\n * pivot, elbow-end width or length is off the arm's. Each names its free\n * retune (`layout.forearm_pose_*`) or, where only a new drawing helps, the\n * regeneration. `layers` holds the measured, non-empty layers of `absDir` by\n * role.\n */\nexport async function forearmPoseWarnings(\n absDir: string,\n layers: Record<string, LayerStats>,\n): Promise<string[]> {\n const warnings: string[] = [];\n for (const pose of POSE_ROLES) {\n const stats = layers[pose];\n if (stats === undefined) continue;\n const arm = ARM_OF[pose];\n const armStats = layers[arm];\n if (armStats === undefined) {\n warnings.push(\n `${pose}: no ${arm} layer — a pose forearm hangs from its arm's elbow, and auto_rig_from_layers refuses it.`,\n );\n continue;\n }\n if (\n stats.canvasW !== armStats.canvasW ||\n stats.canvasH !== armStats.canvasH\n ) {\n warnings.push(\n `${pose}: its canvas ${stats.canvasW}x${stats.canvasH} differs from ${arm}'s ` +\n `${armStats.canvasW}x${armStats.canvasH} — auto_rig_from_layers refuses layers of different ` +\n `sizes; recompose them together.`,\n );\n continue;\n }\n // Without a body the arm is already warned of (armWarnings).\n if (layers.body === undefined) continue;\n\n const measurer: LayerSetMeasurer = createLayerSetMeasurer({\n width: stats.canvasW,\n height: stats.canvasH,\n });\n let a: ArmGeometry;\n let armLayer: LayerInput;\n try {\n armLayer = await measured(measurer, absDir, arm);\n // Only the elbow and the seam run are read, none of which depends on\n // the side, so the body is not decoded: the axis is the role's own, as\n // the composer passes it.\n a = armGeometry(armLayer, arm === \"arm_R\" ? Infinity : -Infinity);\n } catch (err) {\n // The arm's own warning says it.\n if (err instanceof LayerGeometryError) continue;\n throw err;\n }\n const b = forearmPoseGeometry(await measured(measurer, absDir, pose));\n warnings.push(...jointWarnings(pose, arm, stats, a, armLayer, b));\n }\n return warnings;\n}\n\nfunction jointWarnings(\n pose: (typeof POSE_ROLES)[number],\n arm: string,\n stats: LayerStats,\n a: ArmGeometry,\n armLayer: LayerInput,\n b: ForearmPoseGeometry,\n): string[] {\n const warnings: string[] = [];\n const key = `layout.${pose}`;\n\n // Pivot: model x grows right, y up; the layout's cy grows down. A layout\n // centre is the box's: the bbox's pixel centre (bboxCx) plus half a pixel.\n const dx = a.elbow.x - b.pivot.x;\n const dy = a.elbow.y - b.pivot.y;\n const off = Math.hypot(dx, dy);\n if (off > POSE_PIVOT_TOLERANCE) {\n warnings.push(\n `${pose}: its elbow end is ${px(off)} px off ${arm}'s elbow — the raised forearm detaches ` +\n `from the arm at the joint once it swaps in. Remove ${key}.cx/cy from the layout so it stays ` +\n `pinned on the elbow through later arm retunes (free), or set ${key}.cx to ` +\n `${Math.round(stats.bboxCx + 0.5 + dx)} and ${key}.cy to ${Math.round(stats.bboxCy + 0.5 - dy)} (free).`,\n );\n }\n\n // Width: B's elbow end against A's elbow run, by the w to set.\n const armRun = a.seamRun[1] - a.seamRun[0];\n const poseRun = 2 * b.radius;\n const widthRatio = poseRun / armRun;\n const widthBad = Math.abs(widthRatio - 1) > POSE_WIDTH_TOLERANCE;\n if (widthBad) {\n warnings.push(\n `${pose}: its elbow end is ${px(poseRun)} px wide, ${Math.round(Math.abs(widthRatio - 1) * 100)}% off ` +\n `${arm}'s elbow run (${px(armRun)} px) — the sleeve steps at the joint once it swaps in. ` +\n `Set ${key}.w to ${Math.round(stats.w / widthRatio)} (free).`,\n );\n }\n\n // Length: B from its pivot up to its hand, A from its elbow down to its\n // hand. A new w scales the width with it, so it only mends the length when\n // the width fits after.\n const armLen = a.elbow.y - bottomRowY(armLayer);\n const poseLen = b.top - b.pivot.y;\n const lengthRatio = poseLen / armLen;\n if (Math.abs(lengthRatio - 1) > POSE_LENGTH_TOLERANCE) {\n const fix = 1 / lengthRatio;\n const freeFix = Math.abs(widthRatio * fix - 1) <= POSE_WIDTH_TOLERANCE;\n warnings.push(\n `${pose}: its length from the elbow end to the hand is ${px(poseLen)} px against ${arm}'s ` +\n `${px(armLen)} px from its elbow to its hand — ` +\n (freeFix\n ? `the raised hand reaches the wrong height. Set ${key}.w to ${Math.round(stats.w * fix)} (free)` +\n (widthBad ? `, which fixes the width too.` : `.`)\n : `the raised hand reaches the wrong height, and no single w fits both its length and its width. ` +\n `Regenerate forearm_pose.png with the forearm and hand as long as the hanging arm's below its elbow. Billed.`),\n );\n }\n return warnings;\n}\n","/**\n * The measure's lip set checks. The rig folds the mouth open off the layers'\n * own alpha edges, per canvas column inside the opening (where `mouth_inner`\n * has a run): the interior's top must reach the line above it and the skin must\n * reach the interior, or a gap shows the face between them at rest. The\n * geometry is the rig's own: `mouthOpening`, run on the three layers as\n * `auto_rig_from_layers` runs it. The composer meets that contract by\n * construction; these checks are for a set it did not cut (hand-prepared\n * layers, a re-cut) and for the drawings the contract cannot save: a mouth too\n * small to fold, a line too thin to close on, green the key left, an interior\n * with holes. The lip layers' straight edges are the split's cuts, and so are\n * the inside layers' (`mouth_tongue`, `mouth_teeth`), so the generic edge and\n * flat-cut checks skip them all (`isLipLayerRole`). Of an inside layer the rig reads\n * only its box, so it is checked for the set it needs, its canvas and its box.\n */\n\nimport path from \"node:path\";\nimport {\n ALPHA_OPAQUE,\n LIP_INSIDE_ROLES,\n LIP_ROLES,\n LayerGeometryError,\n columnRuns,\n createLayerSetMeasurer,\n isLipInsideRole,\n mouthOpening,\n type LayerInput,\n type LipInsideRole,\n type LipRole,\n type Opening,\n} from \"@ikijs/editor\";\nimport type { LayerStats } from \"./measure\";\nimport { MIN_OPENING_WIDTH } from \"./compose-lips\";\nimport { decodePng } from \"./node-images\";\n\n/** A lip set's layer: one of its three, or an inside layer. */\nexport const isLipLayerRole = (role: string): role is LipRole | LipInsideRole =>\n (LIP_ROLES as readonly string[]).includes(role) || isLipInsideRole(role);\n\n/** The opening's height at its centre, rows, under which it is too small to\n * fold. Our own value, provisional. */\nconst MIN_OPENING_ROWS = 8;\n/** The line's height at the centre, rows, under which a closed mouth has no\n * line to close on (a hairline folds to nothing). Our own value, provisional. */\nconst MIN_LINE_ROWS = 2;\n/** Green excess `g - max(r, b)` above which an opaque lip pixel is key green\n * left over rather than art. Our own value, provisional. */\nconst GREEN_EXCESS = 40;\n/** The share of the opening's area that may be transparent inside\n * `mouth_inner`'s own span before the face shows through it. Our own value,\n * provisional. */\nconst INTERIOR_GAP_FRACTION = 0.05;\n\n/** What the report says of the opening, for judging a half-open mouth. */\nexport interface LipFacts {\n opening: { width: number; height: number; line: number };\n /** `MouthOpen` below which the slit has not opened: `v* = w' / (H + w')`. */\n deadZone: number;\n}\n\n/** A list of columns as the warning names it: the count and the first. */\nconst columns = (cols: number[]) =>\n `${cols.length} column${cols.length === 1 ? \"\" : \"s\"} (first at x=${cols[0]})`;\n\n/**\n * Warn of a lip set the rig refuses or would fold badly, and report the\n * opening it reads. `layers` holds the measured, non-empty layers of `absDir`\n * by role; a set with no lip layer is a legacy mouth and says nothing.\n * `inPlace` (a set a cut placed on a drawn mouth) keeps only what the rig\n * refuses and the opening's facts: every other check's remedy is recomposing\n * or regenerating the set's sources, which the cut's own checks do not reach.\n */\nexport async function lipWarnings(\n absDir: string,\n layers: Record<string, LayerStats>,\n inPlace = false,\n): Promise<{ warnings: string[]; lips?: LipFacts }> {\n const warnings: string[] = [];\n const present = LIP_ROLES.filter((role) => layers[role] !== undefined);\n const inside = LIP_INSIDE_ROLES.filter((role) => layers[role] !== undefined);\n if (present.length === 0) {\n if (inside.length > 0) {\n warnings.push(\n `${inside.join(\"/\")}: a lip set's inside layer with no lip set — auto_rig_from_layers refuses ` +\n `it (it is cut from the interior and clipped to it). Recompose from mouth_keyed.png + ` +\n `mouth_interior.png, or remove it.`,\n );\n }\n return { warnings };\n }\n\n const legacy = [\"mouth\", \"mouth_open\"].filter(\n (role) => layers[role] !== undefined,\n );\n if (legacy.length > 0) {\n warnings.push(\n `${present.join(\"/\")}: the lip set cannot be mixed with ${legacy.join(\"/\")} — auto_rig_from_layers ` +\n `refuses it. Remove one route: compose again with only mouth_keyed.png + mouth_interior.png, ` +\n `or without them.`,\n );\n }\n if (present.length < LIP_ROLES.length) {\n const missing = LIP_ROLES.filter((role) => layers[role] === undefined);\n warnings.push(\n `${present.join(\"/\")}: partial lip set, missing ${missing.join(\"/\")} — auto_rig_from_layers ` +\n `refuses it. Compose mouth_keyed.png + mouth_interior.png together, which cuts all three.`,\n );\n return { warnings };\n }\n\n const { mouth_inner: inner, lip_upper: upper } = layers;\n for (const role of [\"lip_lower\", \"lip_upper\", ...inside]) {\n const stats = layers[role];\n if (stats.canvasW !== inner.canvasW || stats.canvasH !== inner.canvasH) {\n warnings.push(\n `${role}: its canvas ${stats.canvasW}x${stats.canvasH} differs from mouth_inner's ` +\n `${inner.canvasW}x${inner.canvasH} — auto_rig_from_layers refuses layers of different ` +\n `sizes; recompose them together.`,\n );\n return { warnings };\n }\n }\n // Of an inside layer the rig reads only its box, and the cavity clips\n // whatever leaves its own: the measured alpha > 8 box (`bboxCx ± w/2`), in\n // pixel edges.\n const box = (m: LayerStats) => ({\n x0: m.bboxCx - m.w / 2,\n x1: m.bboxCx + m.w / 2,\n y0: m.bboxCy - m.h / 2,\n y1: m.bboxCy + m.h / 2,\n });\n const cavity = box(inner);\n for (const role of inside) {\n const b = box(layers[role]);\n if (\n !inPlace &&\n (b.x0 < cavity.x0 ||\n b.x1 > cavity.x1 ||\n b.y0 < cavity.y0 ||\n b.y1 > cavity.y1)\n ) {\n warnings.push(\n `${role}: its box leaves mouth_inner's — the cavity clips it away there. Recompose from ` +\n `mouth_keyed.png + mouth_interior.png (free).`,\n );\n }\n }\n\n const measurer = createLayerSetMeasurer({\n width: inner.canvasW,\n height: inner.canvasH,\n });\n const set = new Map<string, LayerInput>();\n const green: string[] = [];\n for (const role of LIP_ROLES) {\n const fileName = `${role}.png`;\n const { rgba } = await decodePng(path.join(absDir, fileName));\n // Decoded here rather than through `measured`: the green scan below needs\n // the pixels. layerStats counts alpha > 8 and the measurer alpha >= 8, so\n // a layer measured non-empty is never empty here.\n set.set(role, measurer.add({ role, fileName, rgba })!);\n for (let i = 0; i < rgba.length; i += 4) {\n if (\n rgba[i + 3] >= ALPHA_OPAQUE &&\n rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS\n ) {\n green.push(role);\n break;\n }\n }\n }\n let opening: Opening;\n try {\n opening = mouthOpening(set);\n } catch (err) {\n if (err instanceof LayerGeometryError) {\n warnings.push(err.message);\n return { warnings };\n }\n throw err;\n }\n\n const innerRuns = columnRuns(set.get(\"mouth_inner\")!);\n const noInterior: number[] = [];\n const gap: number[] = [];\n const noLine: number[] = [];\n const skinGap: number[] = [];\n let area = 0;\n let hollow = 0;\n for (let x = opening.x0; x <= opening.x1; x++) {\n const runs = innerRuns.get(x);\n if (runs === undefined) {\n noInterior.push(x);\n continue;\n }\n const span = runs[runs.length - 1][1] - runs[0][0];\n area += span;\n hollow += span - runs.reduce((n, r) => n + r[1] - r[0], 0);\n const c = opening.at(x);\n if (c.lineH <= 0) noLine.push(x);\n else if (c.Tu > c.T) gap.push(x);\n if (c.Bl < c.Bb) skinGap.push(x);\n }\n // The composer always cuts to the contract, so these come from a set it did\n // not cut: recomposing from the two sources is the free fix.\n const recompose = (file: string, ask: string) =>\n `Recompose from mouth_keyed.png + mouth_interior.png (free); if it persists, regenerate ${file} ${ask}. Billed.`;\n const regenKeyed = recompose(\n \"mouth_keyed.png\",\n \"with a closed outline and solid lips under it\",\n );\n if (!inPlace && noInterior.length > 0) {\n warnings.push(\n `mouth_inner: no interior in ${columns(noInterior)} of the opening — the fold has nothing to scale there. ${recompose(\"mouth_interior.png\", \"as one solid cavity\")}`,\n );\n }\n if (!inPlace && gap.length > 0) {\n warnings.push(\n `lip_upper: a gap between the line and the interior in ${columns(gap)} — the face shows through it ` +\n `at rest (the interior's top must reach the line's ink). ${regenKeyed}`,\n );\n }\n if (!inPlace && noLine.length > 0) {\n warnings.push(\n `lip_upper: no line above the interior in ${columns(noLine)} — nothing closes the mouth there. ${regenKeyed}`,\n );\n }\n if (!inPlace && skinGap.length > 0) {\n warnings.push(\n `lip_lower: a gap between the interior and the skin in ${columns(skinGap)} — the face shows through ` +\n `it once the mouth opens (the skin must reach the interior's bottom). ${regenKeyed}`,\n );\n }\n\n const width = opening.x1 - opening.x0 + 1;\n const centre = opening.at(opening.centre);\n if (!inPlace && width < MIN_OPENING_WIDTH * upper.w) {\n warnings.push(\n `mouth_inner: the opening is ${width} px wide, ${Math.round((100 * width) / upper.w)}% of lip_upper's ${upper.w} px ` +\n `(under ${Math.round(100 * MIN_OPENING_WIDTH)}%) — too narrow to fold; the slit stays a hairline. ` +\n `Regenerate mouth_keyed.png with the mouth open wider. Billed.`,\n );\n }\n if (!inPlace && centre.H < MIN_OPENING_ROWS) {\n // measure_layers sees only the layers, so a set layout.mouth_inner.h is\n // named in the message; a w past the canvas is not suggested at all.\n const w = Math.ceil((upper.w * MIN_OPENING_ROWS) / centre.H);\n const retune = w <= inner.canvasW ? w : null;\n warnings.push(\n `mouth_inner: the opening is ${centre.H} px tall at its centre (under ${MIN_OPENING_ROWS}) — too small to fold; ` +\n `the slit stays shut until MouthOpen is nearly 1. ` +\n (retune === null\n ? \"\"\n : `If the mouth is smaller than the reference's, set layout.mouth_inner.w to ${retune} ` +\n `(free; the whole set scales with it, so scale layout.mouth_inner.h too if it is set). Otherwise `) +\n `${retune === null ? \"R\" : \"r\"}egenerate mouth_keyed.png with the mouth open taller. Billed.`,\n );\n }\n if (!inPlace && opening.w < MIN_LINE_ROWS) {\n warnings.push(\n `lip_upper: the upper line is ${opening.w} px at the opening's centre (under ${MIN_LINE_ROWS}) — a hairline ` +\n `closes to nothing. Regenerate mouth_keyed.png ` +\n `with a bolder upper line, never thinner than the reference's mouth line. Billed.`,\n );\n }\n if (!inPlace && green.length > 0) {\n warnings.push(\n `${green.join(\"/\")}: opaque green left (key green, g exceeds r and b by over ${GREEN_EXCESS}) — it shows as a ` +\n `green fringe on the lips. Regenerate mouth_keyed.png with the green only inside the opening, or ` +\n `mouth_interior.png without green in it. Billed.`,\n );\n }\n if (!inPlace && area > 0 && hollow > INTERIOR_GAP_FRACTION * area) {\n warnings.push(\n `mouth_inner: ${Math.round((100 * hollow) / area)}% of the opening is transparent inside the interior's ` +\n `own span (over ${Math.round(100 * INTERIOR_GAP_FRACTION)}%) — the face shows through it. ` +\n `Regenerate mouth_interior.png as one solid cavity. Billed.`,\n );\n }\n\n return {\n warnings,\n lips: {\n opening: { width, height: centre.H, line: opening.w },\n deadZone: centre.overlap / (centre.H + centre.overlap),\n },\n };\n}\n","/**\n * The pixel work that turns a green-keyed open mouth plus a drawn interior\n * into the lip set the rig folds (`mouth_inner`, `lip_lower`, `lip_upper`),\n * with the interior's light paint as `mouth_tongue` and `mouth_teeth`.\n * Buffers in, buffers out: no file is read here, the composer hands over what\n * it decoded and gets PNGs back.\n *\n * The key (`keyGreen`) runs at SOURCE resolution. A model's \"flat #00FF00\" is\n * never that (bob's came back as (9, 245, 3)) and its line has less green than\n * red, so no formula of a pixel's own colour gives a half-mixed pixel half its\n * alpha. The fill's colour is therefore read off the art (the median of the\n * clearly green pixels), and each pixel near the fill is read against the far\n * end of ITS OWN ramp: the farthest pixel in reach that lies on the line from\n * the fill's colour through the pixel. The antialiasing becomes alpha, which\n * the premultiplied resize that follows carries cleanly.\n *\n * The split (`splitLipSet`) runs at the COMPOSED size. Every boundary it cuts\n * on is then an integer row of the pixels the rig reads, and its assertion\n * reads them through the rig's own `mouthOpening`, so what the composer checks\n * is what the rig will see. The interior is grown sideways only under ink and\n * never above its own column's hole top, which is what keeps the rig's\n * per-column contract (`Tu <= T <= lineTop`, `Bl >= Bb`) true by construction\n * rather than by luck of the art.\n *\n * The interior is split by lightness on the hole: a pixel at or over\n * CAVITY_LUMA (a tooth, the tongue) goes to `mouth_teeth` above its column's\n * hole middle and to `mouth_tongue` below it, and `mouth_inner` takes the\n * cavity's fill there, so the cavity is a dark fill with its own shading that\n * the rig clips the two to, the teeth riding the line and the tongue the\n * opening's bottom. Its edge is soft: a frame pixel beside the hole whose ink\n * is partial (alpha 128..254) was ink mixed with green, and the cavity takes\n * its share of it, `255 - alpha`, under ALPHA_OPAQUE, so no read of the\n * contract changes.\n *\n * The two columns beside the hole are grown into under the outline's side\n * wall. When the frame has ink above the first grown row the wall is the\n * line's own end, and it folds with the interior (its grown rows join\n * `mouth_inner`, not `lip_upper`), so the rig reads the line's bottom at the\n * interior's top there too and the closed line's ends are the drawn ends,\n * tapered. A column with no ink above its first grown row (an under-the-line\n * end) keeps every pixel in `lip_upper`; the rig still accepts it, its wall\n * past the opening thinned and, shut, shaped like a drawn flick.\n *\n * The preview (`closedLips`) shows the set as the rig draws it at rest: the\n * lips resampled through the lip meshes' own landed rows (`mouthRestShift`,\n * measured as the rig measures the final canvas layers), so the thinned line\n * and its tapered ends are in it, the interior left out (shut, it has zero\n * height).\n */\n\nimport sharp from \"sharp\";\nimport {\n ALPHA_OPAQUE,\n columnRuns,\n createLayerSetMeasurer,\n mouthOpening,\n mouthRestShift,\n type LayerInput,\n type Opening,\n} from \"@ikijs/editor\";\nimport { AutoRigInputError } from \"./limits\";\nimport { cropToBuffer } from \"./node-images\";\nimport { TRIM_THRESHOLD, boxWithoutStraySpecks, luma } from \"./trim\";\n\nexport const KEYED_SRC = \"mouth_keyed.png\";\nexport const INTERIOR_SRC = \"mouth_interior.png\";\n\n/** Green excess `(g - max(r, b)) / 255` at which a visible pixel is a fill\n * candidate; the fill is never full excess (bob's is 0.925). */\nconst KEY_CANDIDATE = 0.5;\n/** Levels (Euclidean) from the fill's median colour within which a pixel is\n * the fill. A ramp's last pixels past it are cut with the fill. */\nconst KEY_FILL_DIST = 20;\n/** Px (Chebyshev) from the fill within which a pixel may be a mix with it, and\n * within which the plateau of its ramp is sought. */\nconst KEY_REACH = 8;\n/** Levels a reference may sit off the segment from its colour to the fill's. */\nconst KEY_COLLINEAR = 12;\n/** A share of green under this is a stroke's own shading, not a mix: read as\n * zero, a true mix this small left opaque is 13 levels off at most. */\nconst KEY_MIN_SHARE = 0.05;\n/** Green outside the opening's region, as a share of the opening's, over\n * which the key is refused. */\nconst STRAY_KEY_FRACTION = 0.02;\n/** The opening's width, as a share of the frame's, under which it is too\n * small to fold. */\nexport const MIN_OPENING_WIDTH = 0.3;\n/** A second hole as a share of the largest, from which the opening is not\n * one region. */\nconst SECOND_HOLE_FRACTION = 0.05;\n/** A dark pixel (luma under this) under the opening belongs to its lower\n * outline band; skin is lighter. */\nconst BAND_LUMA = 150;\n/** The band's cap, in strokes: more is not an outline. */\nconst BAND_CAP = 3;\n/** Luma under which an interior's pixel is cavity rather than tooth or tongue:\n * the cavity's fill is read under it, and the hole's pixels at or over it are\n * cut into `mouth_teeth` / `mouth_tongue`. */\nexport const CAVITY_LUMA = 100;\n/** The lip rim's skin rule, the spike's: a pixel is skin at red, green and\n * blue over these floors, which a peach lip clears and a cavity's dark red or\n * a tongue's pink does not; but not a tooth, whose green and blue are over\n * these ceilings (near-white). */\nconst SKIN_MIN_R = 225;\nconst SKIN_MIN_G = 160;\nconst SKIN_MIN_B = 135;\nconst TEETH_MIN_G = 215;\nconst TEETH_MIN_B = 205;\nconst isSkin = (r: number, g: number, b: number): boolean =>\n r > SKIN_MIN_R &&\n g > SKIN_MIN_G &&\n b > SKIN_MIN_B &&\n !(g > TEETH_MIN_G && b > TEETH_MIN_B);\n\ninterface Components {\n /** Per pixel: its set's index, or -1 off the mask. */\n label: Int32Array;\n sizes: number[];\n /** Inclusive pixel boxes. */\n boxes: { x0: number; y0: number; x1: number; y1: number }[];\n}\n\n/** The sets of a mask, 4-connected, flood-filled on a stack that never\n * outgrows the image: a pixel is marked as it is pushed. */\nfunction components(mask: Uint8Array, W: number, H: number): Components {\n const n = W * H;\n const label = new Int32Array(n).fill(-1);\n const stack = new Int32Array(n);\n const sizes: number[] = [];\n const boxes: Components[\"boxes\"] = [];\n for (let start = 0; start < n; start++) {\n if (!mask[start] || label[start] >= 0) continue;\n const id = sizes.length;\n const box = { x0: W, y0: H, x1: -1, y1: -1 };\n let size = 0;\n let depth = 0;\n label[start] = id;\n stack[depth++] = start;\n while (depth > 0) {\n const p = stack[--depth];\n size++;\n const px = p % W;\n const py = (p - px) / W;\n box.x0 = Math.min(box.x0, px);\n box.x1 = Math.max(box.x1, px);\n box.y0 = Math.min(box.y0, py);\n box.y1 = Math.max(box.y1, py);\n for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {\n for (let x = Math.max(0, px - 1); x <= Math.min(W - 1, px + 1); x++) {\n if (x !== px && y !== py) continue;\n const q = y * W + x;\n if (mask[q] && label[q] < 0) {\n label[q] = id;\n stack[depth++] = q;\n }\n }\n }\n }\n sizes.push(size);\n boxes.push(box);\n }\n return { label, sizes, boxes };\n}\n\n/** The largest set's index, or -1 for none. */\nconst largest = (sizes: number[]): number =>\n sizes.reduce((best, s, i) => (best < 0 || s > sizes[best] ? i : best), -1);\n\n/**\n * Chebyshev dilation of `mask` by `reach`: done along the rows and then down\n * the columns, which is the same box as one pass over the square.\n */\nfunction dilate(mask: Uint8Array, W: number, H: number, reach: number) {\n const rows = new Uint8Array(W * H);\n const prefix = new Int32Array(Math.max(W, H) + 1);\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) prefix[x + 1] = prefix[x] + mask[y * W + x];\n for (let x = 0; x < W; x++) {\n rows[y * W + x] =\n prefix[Math.min(W, x + reach + 1)] - prefix[Math.max(0, x - reach)] > 0\n ? 1\n : 0;\n }\n }\n const out = new Uint8Array(W * H);\n for (let x = 0; x < W; x++) {\n for (let y = 0; y < H; y++) prefix[y + 1] = prefix[y] + rows[y * W + x];\n for (let y = 0; y < H; y++) {\n out[y * W + x] =\n prefix[Math.min(H, y + reach + 1)] - prefix[Math.max(0, y - reach)] > 0\n ? 1\n : 0;\n }\n }\n return out;\n}\n\n/**\n * The share of green in the pixel at byte offset `i`, read against the\n * foreground at `j`: where it lies on the segment from `j`'s colour to `g`,\n * clamped to 0..1. `j`'s colour must not be `g`'s.\n */\nfunction shareOf(rgba: Buffer, i: number, j: number, g: number[]): number {\n const dr = g[0] - rgba[j];\n const dg = g[1] - rgba[j + 1];\n const db = g[2] - rgba[j + 2];\n const t =\n ((rgba[i] - rgba[j]) * dr +\n (rgba[i + 1] - rgba[j + 1]) * dg +\n (rgba[i + 2] - rgba[j + 2]) * db) /\n (dr * dr + dg * dg + db * db);\n return Math.min(1, Math.max(0, t));\n}\n\n/**\n * Key the green out of a straight-alpha RGBA mouth, estimating each mixed\n * pixel's real alpha. See the header: the fill is the art's own green, a pixel\n * near it is read against the farthest pixel in reach on its own colour ramp,\n * and a share under KEY_MIN_SHARE is shading, not green. A pixel under alpha\n * 128 is a candidate for nothing and a reference for nobody (a PNG keeps RGB\n * under zero alpha, so invisible green must neither open a hole nor spoil the\n * region check), but green left faintly visible is cleared with the fill: it\n * would come out of the resize as a green fringe on the lip.\n */\nexport function keyGreen(rgba: Buffer, W: number, H: number): Buffer {\n const n = W * H;\n const noGreen = new AutoRigInputError(\n `${KEYED_SRC}: no green opening (#00FF00) to key — regenerate it with the inside of the open mouth painted ONE flat pure green`,\n );\n\n const hist = [\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n ];\n let candidates = 0;\n for (let p = 0; p < n; p++) {\n const i = p * 4;\n if (rgba[i + 3] < ALPHA_OPAQUE) continue;\n const excess = (rgba[i + 1] - Math.max(rgba[i], rgba[i + 2])) / 255;\n if (excess < KEY_CANDIDATE) continue;\n candidates++;\n for (let c = 0; c < 3; c++) hist[c][rgba[i + c]]++;\n }\n if (candidates === 0) throw noGreen;\n const median = (h: Uint32Array): number => {\n let seen = 0;\n for (let v = 0; v < 256; v++) {\n seen += h[v];\n if (seen * 2 >= candidates) return v;\n }\n return 255;\n };\n const G = [median(hist[0]), median(hist[1]), median(hist[2])];\n\n // The fill: visible pixels the art's key colour owns. `ref` is every visible\n // pixel that is not (the only ones a mixed pixel may read itself against).\n const out = Buffer.from(rgba);\n const fill = new Uint8Array(n);\n const ref = new Uint8Array(n);\n let fillCount = 0;\n for (let p = 0; p < n; p++) {\n const i = p * 4;\n if (rgba[i + 3] === 0) continue;\n const dr = rgba[i] - G[0];\n const dg = rgba[i + 1] - G[1];\n const db = rgba[i + 2] - G[2];\n const green = dr * dr + dg * dg + db * db <= KEY_FILL_DIST * KEY_FILL_DIST;\n if (rgba[i + 3] < ALPHA_OPAQUE) {\n if (green) out[i + 3] = 0;\n } else if (green) {\n fill[p] = 1;\n fillCount++;\n } else {\n ref[p] = 1;\n }\n }\n if (fillCount === 0) throw noGreen;\n\n const reach = dilate(fill, W, H, KEY_REACH);\n const collinear = KEY_COLLINEAR * KEY_COLLINEAR;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n const p = y * W + x;\n if (!reach[p] || fill[p] || out[p * 4 + 3] === 0) continue;\n const i = p * 4;\n // The pixel itself always qualifies, so there is no fallback.\n let best = i;\n let bestD2 =\n (rgba[i] - G[0]) ** 2 +\n (rgba[i + 1] - G[1]) ** 2 +\n (rgba[i + 2] - G[2]) ** 2;\n const y1 = Math.min(H - 1, y + KEY_REACH);\n const x1 = Math.min(W - 1, x + KEY_REACH);\n for (let qy = Math.max(0, y - KEY_REACH); qy <= y1; qy++) {\n for (let qx = Math.max(0, x - KEY_REACH); qx <= x1; qx++) {\n const q = qy * W + qx;\n if (q === p || !ref[q]) continue;\n const j = q * 4;\n const d2 =\n (rgba[j] - G[0]) ** 2 +\n (rgba[j + 1] - G[1]) ** 2 +\n (rgba[j + 2] - G[2]) ** 2;\n if (d2 <= bestD2) continue;\n const t = shareOf(rgba, i, j, G);\n const er = rgba[i] - rgba[j] - t * (G[0] - rgba[j]);\n const eg = rgba[i + 1] - rgba[j + 1] - t * (G[1] - rgba[j + 1]);\n const eb = rgba[i + 2] - rgba[j + 2] - t * (G[2] - rgba[j + 2]);\n if (er * er + eg * eg + eb * eb > collinear) continue;\n bestD2 = d2;\n best = j;\n }\n }\n const k = shareOf(rgba, i, best, G);\n if (k < KEY_MIN_SHARE) continue;\n rgba.copy(out, i, best, best + 3);\n out[i + 3] = Math.round(rgba[i + 3] * (1 - k));\n }\n }\n for (let p = 0; p < n; p++) if (fill[p]) out[p * 4 + 3] = 0;\n\n const { sizes } = components(fill, W, H);\n const main = largest(sizes);\n const strays = sizes.filter((_, i) => i !== main);\n const strayPx = strays.reduce((a, b) => a + b, 0);\n if (strayPx > STRAY_KEY_FRACTION * sizes[main]) {\n throw new AutoRigInputError(\n `${KEYED_SRC}: green outside the opening (${strayPx} px in ${strays.length} regions beside the opening's) — the key must be one flat region inside the outline; regenerate with no green elsewhere`,\n );\n }\n return out;\n}\n\n/** Levels (per channel) from the ground's median colour within which a pixel\n * is the ground. Near-white teeth (250, 248, 245) sit 5..10 off a pure white\n * ground, so a floor like the legacy parts' 238 would key them out. */\nconst GROUND_TOLERANCE = 4;\n/** A border whose median is light in every channel (over this) is a ground,\n * not the drawing: a darker or more saturated one means the drawing itself\n * reaches the edges. A mid-grey ground under it therefore passes through, read\n * as the drawing reaching the edges. */\nconst GROUND_LIGHT = 200;\n/** The floor of a light ground the interior is keyed against: a light ground\n * under it in some channel (cream, grey) is not white. */\nconst GROUND_MIN = 238;\n/** The share of the border a white ground must own: under it the ground has\n * heavy noise, a gradient or a checkerboard \"fake transparency\" along the\n * border itself (a checkerboard owns about half), and the key would leave a\n * rind of it round the drawing. A drawing may touch about a third of the\n * border and still pass. */\nconst GROUND_BORDER_SHARE = 0.65;\n\n/**\n * Key the white ground out of an interior that came without alpha: the pixels\n * 4-connected to the border within GROUND_TOLERANCE of the border's median\n * colour. The legacy parts' rule (every near-white pixel) would take the teeth\n * with it, and the teeth are what this part is for. A light ground that is\n * not white (cream, grey), or a white one with heavy noise or a gradient along\n * the border that leaves it owning under half of it, cannot be keyed cleanly\n * and is refused: stretched into the opening it would show as a box. A border\n * that is not light is the drawing itself reaching the edges (\"filling the\n * image\"): only the white connected to the border is keyed, the corners an oval\n * leaves.\n */\nexport function keyBorderWhite(rgba: Buffer, W: number, H: number): Buffer {\n const border: number[][] = [[], [], []];\n const edge = (p: number) => {\n for (let c = 0; c < 3; c++) border[c].push(rgba[p * 4 + c]);\n };\n for (let x = 0; x < W; x++) {\n edge(x);\n edge((H - 1) * W + x);\n }\n for (let y = 1; y < H - 1; y++) {\n edge(y * W);\n edge(y * W + W - 1);\n }\n const ground = border.map((v) => v.sort((a, b) => a - b)[v.length >> 1]);\n const light = ground.every((v) => v >= GROUND_LIGHT);\n if (light && ground.some((v) => v < GROUND_MIN)) {\n throw new AutoRigInputError(\n `${INTERIOR_SRC} came back opaque on a non-white ground — regenerate it with a transparent background. Billed.`,\n );\n }\n if (!light) ground.fill(255);\n\n const out = Buffer.from(rgba);\n const seen = new Uint8Array(W * H);\n const stack = new Int32Array(W * H);\n let depth = 0;\n const seed = (p: number) => {\n if (seen[p]) return;\n for (let c = 0; c < 3; c++) {\n if (Math.abs(rgba[p * 4 + c] - ground[c]) > GROUND_TOLERANCE) return;\n }\n seen[p] = 1;\n stack[depth++] = p;\n };\n for (let x = 0; x < W; x++) {\n seed(x);\n seed((H - 1) * W + x);\n }\n for (let y = 0; y < H; y++) {\n seed(y * W);\n seed(y * W + W - 1);\n }\n if (light && depth < GROUND_BORDER_SHARE * border[0].length) {\n throw new AutoRigInputError(\n `${INTERIOR_SRC} came back opaque on a white ground too noisy or shaded to key cleanly — regenerate it with a transparent background. Billed.`,\n );\n }\n while (depth > 0) {\n const p = stack[--depth];\n out[p * 4 + 3] = 0;\n const x = p % W;\n if (x > 0) seed(p - 1);\n if (x < W - 1) seed(p + 1);\n if (p >= W) seed(p - W);\n if (p < W * H - W) seed(p + W);\n }\n return out;\n}\n\n/** The box of the part's drawing: the composer's trim (stray specks aside),\n * or every pixel the trim keeps when no speck lies outside the drawing.\n * null when nothing is kept. */\nfunction drawingBox(rgba: Buffer, W: number, H: number) {\n const speckless = boxWithoutStraySpecks(rgba, W, H);\n if (speckless !== null) {\n return {\n x: speckless.left,\n y: speckless.top,\n w: speckless.width,\n h: speckless.height,\n };\n }\n let x0 = W;\n let y0 = H;\n let x1 = -1;\n let y1 = -1;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n if (rgba[(y * W + x) * 4 + 3] <= TRIM_THRESHOLD) continue;\n x0 = Math.min(x0, x);\n x1 = Math.max(x1, x);\n y0 = Math.min(y0, y);\n y1 = Math.max(y1, y);\n }\n }\n return x1 < 0 ? null : { x: x0, y: y0, w: x1 - x0 + 1, h: y1 - y0 + 1 };\n}\n\n/**\n * The drawn interior, ready to fit into the opening: trimmed, with the lip rim\n * a generator draws round the cavity removed (the skin-coloured sets touching\n * the trimmed border: the spike's interior prompt drew a peach lower lip\n * twice), and the cavity's colour read off what is left, for the flat fill the\n * split lays under it. The caller has keyed a white ground out of an interior\n * that came without alpha.\n */\nexport async function prepInterior(\n rgba: Buffer,\n W: number,\n H: number,\n): Promise<{ png: Buffer; cavity: [number, number, number] }> {\n const empty = new AutoRigInputError(\n `${INTERIOR_SRC}: nothing but lips/skin after trimming — regenerate it with the cavity, the teeth and the tongue only, NO lips`,\n );\n const first = drawingBox(rgba, W, H);\n if (first === null) throw empty;\n const cw = first.w;\n const ch = first.h;\n const crop = Buffer.alloc(cw * ch * 4);\n for (let y = 0; y < ch; y++) {\n const from = ((first.y + y) * W + first.x) * 4;\n rgba.copy(crop, y * cw * 4, from, from + cw * 4);\n }\n\n const skin = new Uint8Array(cw * ch);\n for (let p = 0; p < cw * ch; p++) {\n const i = p * 4;\n if (\n crop[i + 3] > TRIM_THRESHOLD &&\n isSkin(crop[i], crop[i + 1], crop[i + 2])\n )\n skin[p] = 1;\n }\n const { label, boxes } = components(skin, cw, ch);\n const rim = boxes.map(\n (b) => b.x0 === 0 || b.y0 === 0 || b.x1 === cw - 1 || b.y1 === ch - 1,\n );\n for (let p = 0; p < cw * ch; p++) {\n if (label[p] >= 0 && rim[label[p]]) crop[p * 4 + 3] = 0;\n }\n\n const box = drawingBox(crop, cw, ch);\n if (box === null) throw empty;\n\n // The cavity: the dark pixels' mean, or everything's when none is dark.\n const sum = [0, 0, 0];\n const all = [0, 0, 0];\n let dark = 0;\n let count = 0;\n for (let y = box.y; y < box.y + box.h; y++) {\n for (let x = box.x; x < box.x + box.w; x++) {\n const i = (y * cw + x) * 4;\n if (crop[i + 3] < ALPHA_OPAQUE) continue;\n count++;\n for (let c = 0; c < 3; c++) all[c] += crop[i + c];\n if (luma(crop, i) < CAVITY_LUMA) {\n dark++;\n for (let c = 0; c < 3; c++) sum[c] += crop[i + c];\n }\n }\n }\n if (count === 0) throw empty;\n const [from, over] = dark > 0 ? [sum, dark] : [all, count];\n const cavity = from.map((v) => Math.round(v / over)) as [\n number,\n number,\n number,\n ];\n return { png: await cropToBuffer(crop, cw, ch, box), cavity };\n}\n\nconst rawOf = async (png: Buffer) =>\n sharp(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });\n\nconst encode = (rgba: Buffer, w: number, h: number) =>\n sharp(rgba, { raw: { width: w, height: h, channels: 4 } })\n .png()\n .toBuffer();\n\n/**\n * The opening of a keyed frame: its transparent pixels the outside cannot\n * reach through transparent pixels (so its boundary is at or above\n * ALPHA_OPAQUE), as the largest set of them. Refuses a frame with no such hole,\n * one too narrow to fold, and one with a second hole of\n * SECOND_HOLE_FRACTION of the largest or more.\n */\nfunction enclosedHole(frame: Buffer, w: number, h: number) {\n const n = w * h;\n const alpha = (p: number) => frame[p * 4 + 3];\n const outside = new Uint8Array(n);\n const stack = new Int32Array(n);\n let depth = 0;\n const seed = (p: number) => {\n if (!outside[p] && alpha(p) < ALPHA_OPAQUE) {\n outside[p] = 1;\n stack[depth++] = p;\n }\n };\n for (let x = 0; x < w; x++) {\n seed(x);\n seed((h - 1) * w + x);\n }\n for (let y = 0; y < h; y++) {\n seed(y * w);\n seed(y * w + w - 1);\n }\n while (depth > 0) {\n const p = stack[--depth];\n const x = p % w;\n if (x > 0) seed(p - 1);\n if (x < w - 1) seed(p + 1);\n if (p >= w) seed(p - w);\n if (p < n - w) seed(p + w);\n }\n const mask = new Uint8Array(n);\n for (let p = 0; p < n; p++) {\n if (alpha(p) < ALPHA_OPAQUE && !outside[p]) mask[p] = 1;\n }\n const { label, sizes, boxes } = components(mask, w, h);\n const main = largest(sizes);\n if (main < 0) {\n throw new AutoRigInputError(\n `${KEYED_SRC}: the outline is not closed round the opening (the key reached the outside, or the line is broken or too thin at this size) — regenerate with ONE closed, bolder outline`,\n );\n }\n const box = boxes[main];\n const holeW = box.x1 - box.x0 + 1;\n if (holeW < MIN_OPENING_WIDTH * w) {\n throw new AutoRigInputError(\n `${KEYED_SRC}: the opening is only ${holeW} px wide of the mouth's ${w} — too small to fold; regenerate with the mouth open wider, or, if its outline is broken (only a small pocket of the opening was enclosed), with ONE closed, bolder outline`,\n );\n }\n const others = sizes.filter(\n (s, i) => i !== main && s >= SECOND_HOLE_FRACTION * sizes[main],\n );\n if (others.length > 0) {\n throw new AutoRigInputError(\n `${KEYED_SRC}: the opening is not one connected region (${others.length + 1} holes: teeth or tongue drawn into the green?) — regenerate with nothing drawn inside the green`,\n );\n }\n return { label, main, box };\n}\n\ntype LipRgba = { mouth_inner: Buffer; lip_lower: Buffer; lip_upper: Buffer };\n\n/** The three layers, raw RGBA on a `w` x `h` canvas, as the rig measures\n * them; null for a layer with no opaque pixel. */\nfunction measureLips(\n layers: LipRgba,\n w: number,\n h: number,\n): Map<string, LayerInput | null> {\n const measurer = createLayerSetMeasurer({ width: w, height: h });\n return new Map(\n Object.entries(layers).map(([role, rgba]) => [\n role,\n measurer.add({ role, fileName: `${role}.png`, rgba }),\n ]),\n );\n}\n\n/**\n * Read the three layers back through the rig's own `mouthOpening` and assert\n * the fold's contract on every column of the opening it reads. A violation is\n * an invariant of the split, not input, so it throws a plain Error naming the\n * column.\n */\nfunction assertFoldContract(layers: LipRgba, w: number, h: number): Opening {\n const byRole = new Map<string, LayerInput>();\n for (const [role, layer] of measureLips(layers, w, h)) {\n // The outline above the opening and the interior in it always exist; the\n // skin under it is the art's.\n if (layer === null && role === \"lip_lower\") {\n throw new AutoRigInputError(\n `${KEYED_SRC}: no lip_lower after the split — there is no skin under the opening; draw the lower lip under the outline`,\n );\n }\n byRole.set(role, layer!);\n }\n const opening = mouthOpening(byRole);\n const runs = columnRuns(byRole.get(\"mouth_inner\")!);\n for (let col = opening.x0; col <= opening.x1; col++) {\n const c = opening.at(col);\n const why = !runs.has(col)\n ? \"has no interior run\"\n : c.Tu > c.T\n ? `has a gap between the line and the interior (Tu ${c.Tu} > T ${c.T})`\n : c.T > c.lineTop || c.lineH <= 0\n ? `has no line above the interior (T ${c.T}, line top ${c.lineTop})`\n : c.Bl < c.Bb\n ? `has a gap between the interior and the skin (Bl ${c.Bl} < Bb ${c.Bb})`\n : null;\n if (why !== null) throw new Error(`splitLipSet: column ${col} ${why}`);\n }\n return opening;\n}\n\n/**\n * Split a keyed, trimmed and composed-size mouth frame into the lip set. Per\n * opening column (a column of the enclosed hole) `top` / `bot` are the hole's\n * first row and last row + 1:\n * lip_upper every pixel above `top`, every pixel of a column outside the\n * opening (the corner hooks) except a side wall's grown rows, the\n * hole's faint upper half;\n * mouth_inner the band (the ink from `bot` down while dark, at most\n * BAND_CAP strokes) over the interior over a flat cavity fill, on\n * the hole, the band and the first skin row `R`, grown once\n * sideways under ink and never above its own column's `top`\n * (the grown rows of a side column with ink above them are\n * `lip_upper`'s no longer: the wall folds with the interior);\n * lip_lower every row from `R` down (row `R` is in both: a one-row overlap,\n * not a gap);\n * mouth_teeth / mouth_tongue the hole's pixels whose colour in `mouth_inner`\n * is at or over CAVITY_LUMA, above / below the column's hole\n * middle, opaque; `mouth_inner` takes the cavity's fill there;\n * the rim a frame pixel outside `mouth_inner` beside the hole with alpha\n * 128..254: the cavity's fill at `255 - alpha` in `mouth_inner`.\n * A side column (beside the hole) whose frame has no ink above its first grown\n * row keeps those rows in `lip_upper` and out of `mouth_inner`'s fold.\n * The result is read back through the rig's own `mouthOpening` and the\n * contract asserted (`assertFoldContract`).\n */\nexport async function splitLipSet(\n keyedPng: Buffer,\n w: number,\n h: number,\n interior: { png: Buffer; cavity: [number, number, number] },\n): Promise<{\n inner: Buffer;\n lower: Buffer;\n upper: Buffer;\n tongue: Buffer;\n teeth: Buffer;\n opening: Opening;\n}> {\n const { data: frame, info } = await rawOf(keyedPng);\n if (info.width !== w || info.height !== h) {\n throw new Error(\n `splitLipSet: the frame is ${info.width}x${info.height}, not ${w}x${h}`,\n );\n }\n const n = w * h;\n const alpha = (p: number) => frame[p * 4 + 3];\n const { label, main, box: hb } = enclosedHole(frame, w, h);\n const holeW = hb.x1 - hb.x0 + 1;\n\n const top = new Int32Array(w).fill(-1);\n const bot = new Int32Array(w).fill(-1);\n for (let y = 0; y < h; y++) {\n for (let x = hb.x0; x <= hb.x1; x++) {\n if (label[y * w + x] !== main) continue;\n if (top[x] < 0) top[x] = y;\n bot[x] = y + 1;\n }\n }\n // The stroke: the opaque rows directly above the hole at its centre column.\n const centre = Math.round((hb.x0 + hb.x1) / 2);\n let stroke = 0;\n while (\n top[centre] - 1 - stroke >= 0 &&\n alpha((top[centre] - 1 - stroke) * w + centre) >= ALPHA_OPAQUE\n )\n stroke++;\n const bandCap = BAND_CAP * Math.max(1, stroke);\n\n // Per opening column: the band's end and the first skin row R (-1: none).\n const skinRow = new Int32Array(w).fill(-1);\n const inM = new Uint8Array(n);\n for (let x = hb.x0; x <= hb.x1; x++) {\n let y = bot[x];\n while (\n y < h &&\n y - bot[x] < bandCap &&\n alpha(y * w + x) >= ALPHA_OPAQUE &&\n luma(frame, (y * w + x) * 4) < BAND_LUMA\n )\n y++;\n for (let k = top[x]; k < y; k++) inM[k * w + x] = 1;\n let r = y;\n while (r < h && alpha(r * w + x) < ALPHA_OPAQUE) r++;\n if (r < h) {\n skinRow[x] = r;\n inM[r * w + x] = 1;\n }\n }\n\n // Grown once, from M as it was: sideways, under ink only, and in an opening\n // column never above its own hole top.\n const grown = Uint8Array.from(inM);\n for (let y = 0; y < h; y++) {\n for (let x = 0; x < w; x++) {\n const p = y * w + x;\n if (inM[p] || alpha(p) < ALPHA_OPAQUE) continue;\n if (top[x] >= 0 && y < top[x]) continue;\n if ((x > 0 && inM[p - 1]) || (x < w - 1 && inM[p + 1])) grown[p] = 1;\n }\n }\n\n // The columns beside the hole whose grown rows are the outline's side wall:\n // the frame is opaque on the row above the first one. Those rows fold with\n // the interior; a column with no ink above them keeps its pixels in the\n // line (an under-the-line end the rig still accepts, its wall thinned and,\n // shut, shaped like a drawn flick).\n const wall = new Uint8Array(w);\n for (const x of [hb.x0 - 1, hb.x1 + 1]) {\n if (x < 0 || x >= w) continue;\n let first = 0;\n while (first < h && !(grown[first * w + x] && !inM[first * w + x])) first++;\n if (first > 0 && first < h && alpha((first - 1) * w + x) >= ALPHA_OPAQUE)\n wall[x] = 1;\n }\n\n // The interior fitted to the hole's box grown one pixel each side.\n const gx = hb.x0 - 1;\n const gy = hb.y0 - 1;\n const gw = holeW + 2;\n const gh = hb.y1 - hb.y0 + 3;\n const { data: fitted } = await sharp(interior.png)\n .resize(gw, gh, { fit: \"fill\" })\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n\n const hole = (q: number) => label[q] === main;\n // Above its column's hole middle: the line's half of the opening, for the\n // faint pixels and for the light paint alike.\n const upperHalf = (x: number, y: number) => 2 * y < top[x] + bot[x];\n // The hole's faint pixels in its upper half are the line's antialiasing, the\n // lower half's the band's.\n const faintUpper = (p: number, x: number, y: number) =>\n y < bot[x] && hole(p) && upperHalf(x, y);\n const besideHole = (p: number, x: number, y: number) =>\n (x > 0 && hole(p - 1)) ||\n (x < w - 1 && hole(p + 1)) ||\n (y > 0 && hole(p - w)) ||\n (y < h - 1 && hole(p + w));\n\n const upper = Buffer.alloc(n * 4);\n const lower = Buffer.alloc(n * 4);\n const inner = Buffer.alloc(n * 4);\n const tongue = Buffer.alloc(n * 4);\n const teeth = Buffer.alloc(n * 4);\n const copy = (to: Buffer, p: number) =>\n frame.copy(to, p * 4, p * 4, p * 4 + 4);\n for (let y = 0; y < h; y++) {\n for (let x = 0; x < w; x++) {\n const p = y * w + x;\n const inOpening = top[x] >= 0;\n if (\n (!inOpening || y < top[x] || faintUpper(p, x, y)) &&\n !(wall[x] && grown[p])\n )\n copy(upper, p);\n if (inOpening && skinRow[x] >= 0 && y >= skinRow[x]) copy(lower, p);\n\n if (!grown[p]) {\n // The rim: the ink's partial alpha is its coverage, the rest the\n // opening's, which the cavity fills.\n const a = alpha(p);\n if (a >= ALPHA_OPAQUE && a < 255 && besideHole(p, x, y)) {\n inner.set(interior.cavity, p * 4);\n inner[p * 4 + 3] = 255 - a;\n }\n continue;\n }\n const out = [...interior.cavity];\n const ix = x - gx;\n const iy = y - gy;\n if (ix >= 0 && ix < gw && iy >= 0 && iy < gh) {\n const i = (iy * gw + ix) * 4;\n const a = fitted[i + 3] / 255;\n for (let c = 0; c < 3; c++) out[c] += (fitted[i + c] - out[c]) * a;\n }\n // The frame's own ink goes over it on the hole's rows (but not the faint\n // upper half, which is the line's), on the band and the skin row, and on\n // a side wall's rows.\n if ((inM[p] || wall[x]) && !faintUpper(p, x, y)) {\n const a = alpha(p) / 255;\n for (let c = 0; c < 3; c++) out[c] += (frame[p * 4 + c] - out[c]) * a;\n }\n inner[p * 4] = Math.round(out[0]);\n inner[p * 4 + 1] = Math.round(out[1]);\n inner[p * 4 + 2] = Math.round(out[2]);\n inner[p * 4 + 3] = 255;\n // The hole's light paint is a layer of its own, and the cavity is\n // repainted its fill under it.\n if (hole(p) && luma(inner, p * 4) >= CAVITY_LUMA) {\n const to = upperHalf(x, y) ? teeth : tongue;\n inner.copy(to, p * 4, p * 4, p * 4 + 4);\n inner.set(interior.cavity, p * 4);\n }\n }\n }\n\n const opening = assertFoldContract(\n { mouth_inner: inner, lip_lower: lower, lip_upper: upper },\n w,\n h,\n );\n const [innerPng, lowerPng, upperPng, tonguePng, teethPng] = await Promise.all(\n [inner, lower, upper, tongue, teeth].map((b) => encode(b, w, h)),\n );\n return {\n inner: innerPng,\n lower: lowerPng,\n upper: upperPng,\n tongue: tonguePng,\n teeth: teethPng,\n opening,\n };\n}\n\n/**\n * The rig's rest shift of the lips for the three canvas-sized layers: the\n * lip meshes' own field at MouthOpen 0 (`mouthRestShift`). Measured on the\n * canvas, not on the mouth-sized frame: `detectAlphaBbox` grows a box a pixel\n * each side and clamps it to the image, so a frame clamps where the canvas\n * does not, and the knot grid, which starts at the union's edge, lands\n * elsewhere. The measurement is the rig's own, of the same bytes.\n */\nexport async function restShiftOf(\n layers: { mouth_inner: Buffer; lip_lower: Buffer; lip_upper: Buffer },\n width: number,\n height: number,\n): Promise<ReturnType<typeof mouthRestShift>> {\n const [mouth_inner, lip_lower, lip_upper] = await Promise.all(\n [layers.mouth_inner, layers.lip_lower, layers.lip_upper].map(\n async (png) => (await rawOf(png)).data,\n ),\n );\n const byRole = new Map<string, LayerInput>();\n for (const [role, layer] of measureLips(\n { mouth_inner, lip_lower, lip_upper },\n width,\n height,\n )) {\n if (layer === null) {\n throw new AutoRigInputError(\n `layout.mouth_inner places the lip set so that ${role} falls off the canvas (nothing of it is left) — move it back on the canvas`,\n );\n }\n byRole.set(role, layer);\n }\n return mouthRestShift(byRole);\n}\n\n/**\n * The lips as the rig draws them at rest (MouthOpen 0), each column resampled\n * through the lip mesh's own landed rows: a source row lands at its centre\n * moved by the field there (`mouthRestShift`, the same knots, triangles and\n * stored offsets the rig has, so the preview is what the mesh draws; a\n * per-column fold is a pixel or more off on the lower lip, whose fold carries\n * integer-row reads). Only the rows whose centres the field answers land:\n * those inside the part's box, the layer's alpha box, so every row outside it\n * is transparent and contributes nothing, but for the one beyond each end,\n * landed a step past the edge row for the edge to blend into. The thin and\n * the squashes are positive scales, so the landed rows keep their order; each\n * destination row is blended linearly from the two consecutive landed rows\n * bracketing its centre, the way the GPU samples the mesh (rounding per row\n * would turn the smooth arc into a staircase the rig never draws),\n * premultiplied so an edge neither darkens nor lightens, and is transparent\n * when no pair brackets it. A constant field is a plain sub-pixel shift. The\n * flick's sideways pull is not previewed: the field is a column's dy alone.\n * `left` and `top` are the\n * frame's column and row on the canvas; +y is up and rows go down the image,\n * so a row lands at -dy. The interior is left out: shut, it has no height.\n */\nexport async function closedLips(\n upper: Buffer,\n lower: Buffer,\n shift: ReturnType<typeof mouthRestShift>,\n left: number,\n top: number,\n): Promise<{ upper: Buffer; lower: Buffer }> {\n const shut = async (png: Buffer, role: \"lip_upper\" | \"lip_lower\") => {\n const { data, info } = await rawOf(png);\n const { width: w, height: h } = info;\n const out = Buffer.alloc(w * h * 4);\n for (let x = 0; x < w; x++) {\n const px = (row: number, c: number) =>\n row < 0 || row >= h ? 0 : data[(row * w + x) * 4 + c];\n // [source row, its landed centre], in row order.\n const landed: [number, number][] = [];\n for (let row = 0; row < h; row++) {\n const dy = shift(role, left + x, top + row);\n if (dy !== undefined) landed.push([row, row + 0.5 - dy]);\n }\n // The rows just past the box (transparent), a landed step beyond its\n // edge rows: the edge rows blend into nothing over their outer half,\n // as a drawn edge does, rather than ending at their centres.\n if (landed.length > 1) {\n const [a, b] = landed;\n const [y, z] = landed.slice(-2);\n landed.unshift([a[0] - 1, 2 * a[1] - b[1]]);\n landed.push([z[0] + 1, 2 * z[1] - y[1]]);\n }\n let i = 0;\n for (let to = 0; to < h; to++) {\n const centre = to + 0.5;\n while (i + 1 < landed.length && landed[i + 1][1] < centre) i++;\n if (i + 1 >= landed.length || landed[i][1] > centre) continue;\n const [r0, y0] = landed[i];\n const [r1, y1] = landed[i + 1];\n const t = (centre - y0) / (y1 - y0);\n const a0 = px(r0, 3);\n const a1 = px(r1, 3);\n const a = (1 - t) * a0 + t * a1;\n if (a === 0) continue;\n const o = (to * w + x) * 4;\n for (let c = 0; c < 3; c++)\n out[o + c] = Math.round(\n ((1 - t) * a0 * px(r0, c) + t * a1 * px(r1, c)) / a,\n );\n out[o + 3] = Math.round(a);\n }\n }\n return encode(out, w, h);\n };\n const [u, l] = await Promise.all([\n shut(upper, \"lip_upper\"),\n shut(lower, \"lip_lower\"),\n ]);\n return { upper: u, lower: l };\n}\n","/**\n * The trim the composer cuts every part by, shared with the lip set's interior:\n * the alpha a trim keeps, and the stray specks a background removal leaves\n * beside a drawing.\n */\n\nimport { ALPHA_OPAQUE } from \"@ikijs/editor\";\n\n/** The alpha a part's trim cuts at: what it keeps is over this. */\nexport const TRIM_THRESHOLD = 12;\n/** Of a part's kept pixels, the share under which a faint detached set is a stray speck. */\nexport const STRAY_SPECK_FRACTION = 0.01;\n\n/** Luma (0..255) of the RGBA pixel at byte offset `i`. */\nexport function luma(rgba: Buffer, i: number): number {\n return 0.299 * rgba[i] + 0.587 * rgba[i + 1] + 0.114 * rgba[i + 2];\n}\n\n/**\n * The box of a trimmed part without its stray specks, or null when no stray\n * speck lies outside its drawing. The part's kept pixels (alpha over\n * TRIM_THRESHOLD, the trim's own cut) form 8-connected sets; a stray speck is\n * a set that never reaches ALPHA_OPAQUE and holds under STRAY_SPECK_FRACTION of\n * them, the residue a background removal leaves beside a drawing. Kept, one\n * such speck widened a generated body's box by 70 px on one side and placed\n * the body 32 px off its centre. A drawn stroke reaches ALPHA_OPAQUE, so a\n * detached wisp or strand is never dropped, and a part painted wholly under\n * it (a soft blush) drops nothing.\n */\nexport function boxWithoutStraySpecks(\n rgba: Buffer,\n W: number,\n H: number,\n): { left: number; top: number; width: number; height: number } | null {\n const n = W * H;\n // The share is of the whole part, so count it before any set is judged.\n let kept = 0;\n for (let p = 0; p < n; p++) if (rgba[p * 4 + 3] > TRIM_THRESHOLD) kept++;\n // Each set is judged as its fill ends and only its box is kept, so memory\n // is a byte per pixel plus a stack grown to the deepest fill, not a label\n // per pixel and a record per set. A pixel is marked as it is pushed, so the\n // stack never outgrows the image.\n const visited = new Uint8Array(n);\n let stack = new Int32Array(1024);\n // [left, top, right, bottom] of the drawing's sets and of the stray ones.\n const drawing = [W, H, -1, -1];\n const strays = [W, H, -1, -1];\n let anyOpaque = false;\n for (let start = 0; start < n; start++) {\n if (visited[start] || rgba[start * 4 + 3] <= TRIM_THRESHOLD) continue;\n let setLeft = W;\n let setTop = H;\n let setRight = -1;\n let setBottom = -1;\n let size = 0;\n let opaque = false;\n let depth = 0;\n visited[start] = 1;\n stack[depth++] = start;\n while (depth > 0) {\n const p = stack[--depth];\n size++;\n if (rgba[p * 4 + 3] >= ALPHA_OPAQUE) opaque = true;\n const px = p % W;\n const py = (p - px) / W;\n setLeft = Math.min(setLeft, px);\n setTop = Math.min(setTop, py);\n setRight = Math.max(setRight, px);\n setBottom = Math.max(setBottom, py);\n for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {\n for (let x = Math.max(0, px - 1); x <= Math.min(W - 1, px + 1); x++) {\n const q = y * W + x;\n if (!visited[q] && rgba[q * 4 + 3] > TRIM_THRESHOLD) {\n visited[q] = 1;\n if (depth === stack.length) {\n const grown = new Int32Array(Math.min(n, stack.length * 2));\n grown.set(stack);\n stack = grown;\n }\n stack[depth++] = q;\n }\n }\n }\n }\n anyOpaque ||= opaque;\n const into =\n !opaque && size < kept * STRAY_SPECK_FRACTION ? strays : drawing;\n into[0] = Math.min(into[0], setLeft);\n into[1] = Math.min(into[1], setTop);\n into[2] = Math.max(into[2], setRight);\n into[3] = Math.max(into[3], setBottom);\n }\n if (!anyOpaque || strays[2] < 0) return null;\n const [left, top, right, bottom] = drawing;\n // A set's box reaches past the drawing's only where one of its pixels does,\n // and a speck inside the drawing's box moves nothing, so it is left be.\n if (\n strays[0] >= left &&\n strays[1] >= top &&\n strays[2] <= right &&\n strays[3] <= bottom\n )\n return null;\n return { left, top, width: right - left + 1, height: bottom - top + 1 };\n}\n","/**\n * Compose AI-generated part PNGs into canvas-aligned, role-named layers for the\n * Iki auto-rig (`auto_rig_from_layers` / `@ikijs/editor` generateIkiFromLayerSet).\n * Each part is alpha-trimmed, resized to a target width, optionally mirrored,\n * and pasted at a chosen center on a shared transparent canvas, CANVAS wide and\n * `canvasHeight` tall (CANVAS unless a full body sets it) — the nose by its\n * dense core, the drawing inside a soft nose's feather.\n *\n * Ports the composer that shipped as a script in the Claude Code plugin, so a\n * plugin user gets it from the MCP server instead of an ad-hoc `sharp` install.\n * Composing is deterministic: same parts -> same layers, so re-run freely after\n * tuning `layout` (no image re-generation needed).\n *\n * The mouth has two routes. `mouth.png` (+ optional `mouth_open.png`) is a\n * closed drawing and an open one that cross-fade. `mouth_keyed.png` (the open\n * mouth, its inside flat #00FF00) + `mouth_interior.png` is the lip set: the\n * composer keys and splits it into `mouth_inner` / `lip_lower` / `lip_upper` on\n * one frame (./compose-lips), which the rig folds open like an eyelid, and the\n * interior's light paint into `mouth_tongue` / `mouth_teeth` clipped to it.\n *\n * `sharp` must stay confined to @ikijs/mcp; part decoding goes through\n * ./node-images, this package's single image-decode boundary.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport sharp from \"sharp\";\nimport {\n ALPHA_OPAQUE,\n isLipInsideRole,\n detectAlphaBbox as scanAlphaBbox,\n} from \"@ikijs/editor\";\nimport { cropToBuffer, decodePng } from \"./node-images\";\nimport { TRIM_THRESHOLD, boxWithoutStraySpecks, luma } from \"./trim\";\nimport { measureDir, type MeasureReport, type NoseSpeck } from \"./measure\";\nimport { denseCoreOf, isSpeckCore } from \"./measure-turn\";\nimport {\n ARM_WIDTH,\n armPlacement,\n forearmPosePlacement,\n forearmPoseWidth,\n} from \"./compose-arms\";\nimport {\n INTERIOR_SRC,\n KEYED_SRC,\n closedLips,\n keyBorderWhite,\n keyGreen,\n prepInterior,\n restShiftOf,\n splitLipSet,\n} from \"./compose-lips\";\nimport {\n AutoRigInputError,\n MAX_CANVAS_DIM,\n resolveInputDir,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\n\n/**\n * The layer canvas's width, and its default height, in px. The width is NOT an\n * input: the layout defaults below place parts against it (hair_front alone is\n * 660px wide, and sharp rejects a composite input larger than its\n * destination), so a different width would need its own layout. The height is\n * `canvasHeight`: the canvas grows downward from this square, so every default\n * keeps its place. The tuning surface is `layout` overrides.\n */\nexport const CANVAS = 1100;\n\n/** The layer canvas, in px: CANVAS wide and `canvasHeight` tall. */\ninterface Canvas {\n width: number;\n height: number;\n}\n\n/**\n * The canvas as error messages name it: \"1100\" when square, as every message\n * did before the height could grow, and \"1100x3650\" when tall.\n */\nfunction canvasName(canvas: Canvas): string {\n return canvas.width === canvas.height\n ? `${canvas.width}`\n : `${canvas.width}x${canvas.height}`;\n}\n\n// Iris width as a fraction of the sclera width. Anime irises fill most of the\n// eye opening and are clipped by the lids — the auto-rig clips iris->sclera at\n// runtime, so a large iris cannot spill. The first sample's 32% iris read as a\n// bead floating in white; the defaults below are bob's, 50px in a\n// 98px opening (0.51). A caller retunes eye size through\n// `layout.eye_L/eye_R.w` and MUST move `layout.iris_L/iris_R.w` with it to keep\n// that ratio.\nconst EYE_W = 98;\nconst IRIS_W = 50;\n\n/** The eyewhite source that prepEyeSplit() splits into sclera + lash. */\nconst EYEWHITE_SRC = \"eyewhite.png\";\n/** Luminance below this (0..255) = a dark lash/outline pixel in the eyewhite. */\nconst EYE_LASH_LUMA = 120;\n// Of the eye's dark pixels, those in the TOP this-fraction are the upper lash,\n// an arc that folds DOWN over the eye on blink instead of a full ring that\n// shrinks in place; those below it are the lower lid's line and lashes.\nexport const LASH_KEEP_FRACTION = 0.5;\n// A light pixel whose red exceeds its blue by this much is the lid's skin, not\n// the white. Measured on five drawn eyewhites: each sclera's median r - b sits\n// between -11 (mint's blue-white) and 0, and each lid band's 5th percentile\n// between 37 and 55 (silver-hood's band 242,208,191, mint's 231,196,184). A\n// cool shade painted on the white (the test fixture's 200,205,225) runs blue\n// over red, so it can never match.\nconst EYE_LID_WARMTH = 30;\n\ninterface RoleLayout {\n /** Part file name in the parts dir (the eye pair's two are split in memory). */\n src: string;\n /** Center in canvas px, origin top-left, y down. */\n cx: number;\n cy: number;\n /** Target width in px. */\n w: number;\n /**\n * Target height in px. Omitted, the height follows the part's own aspect\n * ratio — which is the right default for every role whose drawing already has\n * the proportions it should. It exists for the one that does not: an eyewhite\n * comes back flatter than the reference often enough that three generations\n * asking for \"taller\" landed at 0.47, while stretching a flat white lens ~15%\n * is invisible and free. Set it on the sclera and its lash together or the\n * fold tears — they share one frame.\n */\n h?: number;\n optional?: boolean;\n mirror?: boolean;\n noTrim?: boolean;\n}\n\n/**\n * The nose's layout. Its `w`, `h` and `cx` size and place its dense core\n * (`denseCoreOf`), not its whole trimmed part: a soft nose is mostly feather,\n * and sized by its extent it renders as a dot. A part with no core, or whose\n * core is a speck of it (`isSpeckCore`: a lone nostril mark or highlight,\n * which sized to `w` would blow the whole nose up), is sized and placed whole\n * instead, and the speck is warned about. Unlike every other role's, its `cy`\n * is optional. Set, it is the core's centre row; absent, the core's bottom row\n * — the tip — lands NOSE_TIP_AT of the way from the eye row down to the\n * mouth's.\n */\ninterface NoseLayout extends Omit<RoleLayout, \"cy\"> {\n cy?: number;\n}\n\n/**\n * An arm's layout. Its `cx`, `cy` and `w` are optional, each derived from the\n * placed body when unset (compose-arms.ts): `w` is ARM_WIDTH of the body's\n * width, and an unset `cx` or `cy` hangs the arm's shoulder pivot, the one\n * the rig turns it about, on the body box's shoulder corner on that axis. A\n * set one keeps every other role's meaning. The pose forearms share its shape\n * with their own derivation (compose-arms.ts): an unset `w` scales the\n * forearm's elbow end to the placed arm's elbow run, and an unset `cx` or\n * `cy` pins its elbow-end pivot on the arm's elbow.\n */\nexport interface ArmLayout extends Omit<RoleLayout, \"cx\" | \"cy\" | \"w\"> {\n cx?: number;\n cy?: number;\n w?: number;\n}\n\n/** A box in a part's own px, origin top-left. */\ninterface Box {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/**\n * Where a nose with no `cy` puts its tip, as a fraction of the way from the\n * eye row down to the mouth's. Bob's: tip row 554 between eye row 475 and\n * mouth row 594 (79/119 ≈ 0.66), so the default rows land bob's nose where his\n * own layout placed it.\n */\nconst NOSE_TIP_AT = 0.66;\n\n// ── DEFAULT LAYOUT (tune per character through `layout`) ──────────────────────\n// These defaults assume the standard framing the character skill prompts for\n// (a front-facing face centred across the canvas, in its top CANVAS rows).\n// They are canvas px from the top-left, so a taller canvas only adds room\n// below them. The face, eyes, irises,\n// lashes, brows, nose and mouth are bob's own tuning; bob wears his\n// blush at its default placement, picked on his face (below). The features'\n// defaults are proportions of the face: resolveLayout carries them with the\n// face's cx, cy and w; the front side locks, tuned on the first character\n// to wear them, are carried with the face the same way. The hair and\n// the torso depend on the hairstyle and on how the torso is framed, so they are\n// older defaults every character retunes from the report. If the rendered model is misaligned, tune cx/cy/w through the\n// `layout` override and re-run — composing is cheap and the parts do not need\n// regenerating.\n//\n// eyeSide reminder: eye_L = character's LEFT eye = screen RIGHT (larger cx).\n// Which way a source faces is fixed by the mirror flags below, and \"left eye\"\n// cannot say it — it reads as the viewer's left or the character's. So in\n// image terms: eyewhite.png is the eye on the SCREEN LEFT, its lash wing (outer\n// corner) at the image's left end and its lash-free tear duct at the right;\n// brow.png is the brow on the SCREEN RIGHT, its thick head at the image's left\n// end and its tail at the right; blush.png is the blush on the SCREEN LEFT,\n// its outer end (toward the face's edge) at the image's left end and its\n// inner end (toward the nose) at the right; hair_side.png is the front side\n// lock on the SCREEN LEFT, hanging, its root at the image's top; arm.png is\n// the arm on the SCREEN LEFT (the character's right), hanging, its shoulder at the image's top and\n// its hand at the bottom; forearm_pose.png is that arm's forearm raised, on\n// the SCREEN LEFT too: standing up from its elbow, the open hand at the\n// image's top with the thumb at its right (toward the body), a rounded\n// closed elbow end at the bottom. A part drawn the other way round is\n// flipped for free with `mirrorParts`.\n// eye_* = the WHITE sclera (upper lashes recolored white) = the blink clip mask + fold.\n// iris_* = colored disc on top, clipped to the sclera, drives gaze.\n// lash_lower_* = the lower lid's dark line and lashes, ABOVE the iris (it\n// covers the iris's bottom edge, as the drawing does) and folding\n// with the white. Placed on the eye's frame, so it has no layout key.\n// lash_* = the dark upper lashes, a separate layer ABOVE the iris that folds\n// down to cover the closed-eye seam. eye_*, lash_lower_* and lash_* are\n// split from a single `eyewhite.png` (white almond + dark lashes) by\n// prepEyeSplit().\nconst DEFAULT_LAYOUT = {\n // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir\n // without them still composes (head-only character).\n hair_back: { src: \"hair_back.png\", cx: 550, cy: 523, w: 800, optional: true },\n // The bust's torso, cut off by a square canvas's bottom, so the character is\n // not a floating head; a full body on a tall canvas sets `layout.body`\n // itself. It rides the rig's `bodyWarp`, which the head hangs from.\n body: { src: \"body.png\", cx: 550, cy: 1017, w: 840, optional: true },\n // The arms, one part for both: arm_R (screen left) takes arm.png as drawn\n // and arm_L mirrors it, like the blush. They draw over the body and under\n // the face. They have no cx/cy/w defaults: each is derived from the placed\n // body (ArmLayout). OPTIONAL and opt-in: a parts dir without arm.png\n // composes as a bust does, and `skipped` never lists them.\n arm_L: { src: \"arm.png\", optional: true, mirror: true },\n arm_R: { src: \"arm.png\", optional: true, mirror: false },\n // The face is drawn without a neck, so its box is the skull and centres\n // above the eye row (bob's skull at 437 against his eyes' 475).\n face: { src: \"face.png\", cx: 550, cy: 437, w: 400 },\n // The cheek blush, one part for both cheeks: blush_R (screen left) takes it\n // as drawn and blush_L mirrors it, like the eyewhite. It draws over the face\n // and under the nose. Its box sits below each eye, centred 5 px outside the\n // eye's centre and 55 px under its row, above the nose tip: on bob's face,\n // which narrows fast below the eye row, a 2:1 blush there stays on the\n // cheek through the turn, where one 26 px further out reached the ears.\n // OPTIONAL: a parts dir without it composes, and nothing reports it missing.\n blush_L: { src: \"blush.png\", cx: 641, cy: 530, w: 56, optional: true, mirror: true }, // prettier-ignore\n blush_R: { src: \"blush.png\", cx: 459, cy: 530, w: 56, optional: true, mirror: false }, // prettier-ignore\n // The nose, drawn on its own (the face is drawn without one): the auto-rig\n // leads the head turn with it and keys the other features' slide on its\n // presence, so without it the features stay on the face plate. `w` is the\n // width of its dense core, and it has no `cy`: its row comes from the tip\n // rule (NOSE_TIP_AT), between the eyes and the mouth, so it follows them\n // when they are retuned. OPTIONAL: a parts dir without it composes.\n nose: { src: \"nose.png\", cx: 550, w: 20, optional: true },\n mouth: { src: \"mouth.png\", cx: 550, cy: 594, w: 76 },\n // Cross-fades with `mouth` on ParamMouthOpenY (opacity, not scaleY) once the\n // auto-rig sees both roles. Same cx/w as `mouth` so the lip width matches;\n // its top edge (not center) lines up with the closed mouth's top edge since\n // the mouth opens downward from a fixed upper lip — hence the +2 cy nudge\n // rather than sharing cy outright. Optional: composes fine without it.\n mouth_open: {\n src: \"mouth_open.png\",\n cx: 550,\n cy: 596,\n w: 76,\n optional: true,\n },\n // The lip set's ONE frame, mouth_open's place: the keyed mouth is split into\n // mouth_inner / lip_lower / lip_upper, the interior's light paint into\n // mouth_tongue / mouth_teeth, and all of them land here, so a retune moves\n // them together. The other four have no key of their own (LIP_FRAME).\n // OPTIONAL and opt-in: with mouth_keyed.png + mouth_interior.png it stands\n // in for mouth and mouth_open.\n mouth_inner: {\n src: KEYED_SRC,\n cx: 550,\n cy: 596,\n w: 76,\n optional: true,\n },\n // eye_* (sclera) and lash_* share the eyewhite's cropped frame via noTrim (so\n // they are NOT re-bboxed independently): the upper lash stays anchored ABOVE\n // the sclera center, so on blink it folds DOWN over the eye like the sample\n // model instead of the whole eye shrinking in place. Same cx/cy/w.\n eye_L: { src: \"eyewhite_sclera.png\", cx: 636, cy: 475, w: EYE_W, mirror: true, noTrim: true }, // prettier-ignore\n eye_R: { src: \"eyewhite_sclera.png\", cx: 464, cy: 475, w: EYE_W, mirror: false, noTrim: true }, // prettier-ignore\n // A little under the white's centre and toward the nose, as bob's sits.\n iris_L: { src: \"iris.png\", cx: 631, cy: 480, w: IRIS_W, mirror: false },\n iris_R: { src: \"iris.png\", cx: 469, cy: 480, w: IRIS_W, mirror: false },\n lash_L: {\n src: \"eyewhite_lash.png\",\n cx: 636,\n cy: 475,\n w: EYE_W,\n mirror: true,\n noTrim: true,\n },\n lash_R: { src: \"eyewhite_lash.png\", cx: 464, cy: 475, w: EYE_W, mirror: false, noTrim: true }, // prettier-ignore\n brow_L: { src: \"brow.png\", cx: 645, cy: 405, w: 105, mirror: false },\n brow_R: { src: \"brow.png\", cx: 455, cy: 405, w: 105, mirror: true },\n // The front side locks, one part for both: hair_side_R (screen left) takes\n // hair_side.png as drawn and hair_side_L mirrors it, like the blush. They\n // draw over the face, brows and lashes and under the bangs. Mint's tuned\n // placement (cy 545 at mint's face cy 431, carried to the default face:\n // 437 + 114 = 551), tuned per character through `layout.hair_side_*`: the\n // lock's root top lies above the brow row (405) so the bangs' temple hides it\n // (for a 1:5 lock, whose height follows the image's aspect: w 90 is 450 tall,\n // so cy 551 puts the top at 326), and the lock runs from the temple over the\n // front of the ear and down along the cheek's edge, the ear's rim and lobe\n // showing beside it. Its box overlaps the eye's by about 15 px at the\n // default face, fine only because a drawn lock's root tapers (the measure's \"covers\n // the eye's outer corner\" check catches a lock that does not).\n // OPTIONAL: a parts dir without it composes.\n hair_side_L: { src: \"hair_side.png\", cx: 715, cy: 551, w: 90, optional: true, mirror: true }, // prettier-ignore\n hair_side_R: { src: \"hair_side.png\", cx: 385, cy: 551, w: 90, optional: true, mirror: false }, // prettier-ignore\n hair_front: { src: \"hair_front.png\", cx: 550, cy: 425, w: 660 },\n // The pose forearms, one drawing for both: forearm_pose_R (screen left)\n // takes forearm_pose.png as drawn and forearm_pose_L mirrors it, like the\n // arms. The rig draws them above the face and the hair, so they come last.\n // No cx/cy/w defaults: an unset `w` scales the forearm's elbow end to the\n // placed arm's elbow run, an unset `cx` or `cy` pins its elbow-end pivot\n // on the arm's elbow (ArmLayout). OPTIONAL and opt-in, like the arms.\n forearm_pose_L: { src: \"forearm_pose.png\", optional: true, mirror: true },\n forearm_pose_R: { src: \"forearm_pose.png\", optional: true, mirror: false },\n} satisfies Record<string, RoleLayout | NoseLayout | ArmLayout>;\n\nexport type Role = keyof typeof DEFAULT_LAYOUT;\n\n/** The lower lash of each eye, and the eye whose placement it takes. */\nconst LOWER_LASH = { lash_lower_L: \"eye_L\", lash_lower_R: \"eye_R\" } as const;\n/** The eyewhite's lower lid, split in memory like the sclera and lash. */\nconst LOWER_LASH_SRC = \"eyewhite_lash_lower.png\";\n\n/** The lip set's other layers, and the role whose frame they are cut on. */\nconst LIP_FRAME = {\n mouth_tongue: \"mouth_inner\",\n mouth_teeth: \"mouth_inner\",\n lip_lower: \"mouth_inner\",\n lip_upper: \"mouth_inner\",\n} as const;\n\n/** A role the composer writes a layer for. */\nexport type LayerRole = Role | keyof typeof LOWER_LASH | keyof typeof LIP_FRAME;\n\n/** The arm roles, placed off the body (ArmLayout). */\ntype ArmRole = \"arm_L\" | \"arm_R\";\n/** The pose forearm roles, placed off their arm's elbow (ArmLayout). */\ntype PoseRole = \"forearm_pose_L\" | \"forearm_pose_R\";\n\n/**\n * The merged layout, typed so a default other than the nose's, the arms' and\n * the pose forearms' that drops its `cy` fails to compile: `resolveLayout` builds it from\n * DEFAULT_LAYOUT.\n */\ntype ResolvedLayout = Record<\n Exclude<Role, \"nose\" | ArmRole | PoseRole>,\n RoleLayout\n> & {\n nose: NoseLayout;\n} & Record<ArmRole | PoseRole, ArmLayout>;\n\n/**\n * Draw order (back -> front): the roles of @ikijs/editor ROLE_TABLE the\n * composer writes, in its order — a test holds it to that subsequence.\n */\nexport const ORDER: LayerRole[] = [\n \"hair_back\",\n \"body\",\n \"arm_L\",\n \"arm_R\",\n \"face\",\n \"blush_L\",\n \"blush_R\",\n \"nose\",\n \"mouth\",\n \"mouth_open\",\n \"mouth_inner\",\n \"mouth_tongue\",\n \"mouth_teeth\",\n \"lip_lower\",\n \"lip_upper\",\n \"eye_L\",\n \"eye_R\",\n \"iris_L\",\n \"iris_R\",\n \"lash_lower_L\",\n \"lash_lower_R\",\n \"lash_L\",\n \"lash_R\",\n \"brow_L\",\n \"brow_R\",\n \"hair_side_L\",\n \"hair_side_R\",\n \"hair_front\",\n \"forearm_pose_L\",\n \"forearm_pose_R\",\n];\n\n/**\n * The part files a parts dir holds: every source the layout reads from disk,\n * and the eyewhite the eye pair is split from in memory.\n */\nconst PART_FILES = [\n ...new Set(\n Object.values(DEFAULT_LAYOUT)\n .map((cfg) => cfg.src)\n .filter((src) => !src.startsWith(\"eyewhite_\")),\n ),\n EYEWHITE_SRC,\n INTERIOR_SRC,\n];\n\n/** Per-role placement overrides; anything omitted keeps the default above. */\nexport type LayoutOverride = Partial<\n Record<Role, { cx?: number; cy?: number; w?: number; h?: number }>\n>;\n\nexport interface ComposeInput {\n /** Directory of the generated part PNGs (relative paths resolve against cwd). */\n partsDir: string;\n /**\n * Existing directory under cwd to write the role layers into. Callers reuse\n * one across runs (it must pre-exist), so the compose leaves it holding\n * exactly the roles it reports: the layer an earlier run wrote for any role\n * this run does not write — a skipped role, or an arm once arm.png is gone\n * — is removed rather than left for the next tool to pick up.\n */\n outDir: string;\n layout?: LayoutOverride;\n /**\n * Part files to flip left-right as they are read, e.g. `[\"eyewhite.png\"]`\n * for an eye drawn facing the other way. It flips the SOURCE, so every role\n * cut from it flips together — the eye pair's sclera and lash stay in one\n * frame, which a per-role flag would leave to the caller to keep in sync.\n */\n mirrorParts?: string[];\n /**\n * The canvas's height in px: an even integer in CANVAS..MAX_CANVAS_DIM,\n * CANVAS (a square bust canvas) when omitted, and every output at CANVAS is\n * byte-identical to an omitted one. The width stays CANVAS. The canvas grows\n * downward: every default and every override keeps its canvas px from the\n * top-left, so the head lands where it does on a bust and a full body gets\n * room below. Model space is centred on the canvas, so an odd height, which\n * would put the head on a half pixel, is refused.\n */\n canvasHeight?: number;\n}\n\nexport interface ComposedLayer {\n role: LayerRole;\n path: string;\n /** Size of the placed part itself (the file is always CANVAS x the canvas\n * height). */\n width: number;\n height: number;\n left: number;\n top: number;\n}\n\nexport type ComposeResult =\n | {\n ok: true;\n outDir: string;\n layers: ComposedLayer[];\n /**\n * Roles whose optional part was absent from the parts dir, and the lower\n * lashes when the eyewhite draws no dark lower lid. The arms and the\n * pose forearms are opt-in and never listed: a parts dir without\n * arm.png composes as a bust does, though an earlier compose's arm\n * layers are still removed. The lip roles are never listed either, and\n * with the lip set neither are `mouth` and `mouth_open`, which the set\n * stands in for.\n */\n skipped: LayerRole[];\n /** The rest pose, flattened: a pose forearm is invisible there, so it\n * never shows in this one, and the lip set shows closed, as the rig\n * draws the rest pose. */\n preview: string;\n /** Written only with a pose forearm: the switch at 1 as the rig draws\n * it — each arm with a pose forearm cropped to the rows above its\n * elbow (the hanging forearm hidden), the pose forearms over\n * everything. */\n previewPose?: string;\n measure: MeasureReport;\n }\n | { ok: false; error: string };\n\n/**\n * The roles drawn on the face, but the nose (resolveLayout places it on its\n * own). Their defaults are placed relative to the face's: a layout that moves\n * or scales the face carries them with it.\n */\nconst FACE_FEATURES = [\n \"blush_L\",\n \"blush_R\",\n \"mouth\",\n \"mouth_open\",\n \"mouth_inner\",\n \"eye_L\",\n \"eye_R\",\n \"iris_L\",\n \"iris_R\",\n \"lash_L\",\n \"lash_R\",\n \"brow_L\",\n \"brow_R\",\n \"hair_side_L\",\n \"hair_side_R\",\n] as const satisfies readonly Exclude<Role, \"nose\">[];\n\n/**\n * Merge caller overrides onto the defaults. Input boundary: an unknown role, a\n * non-finite centre or an out-of-range width or height fails fast,\n * path-qualified, before any decode. `w` is capped at the canvas's width and\n * `h` at its height, so a part sized whole can never exceed the canvas width\n * (a nose, sized by its core, is checked in partBuffer); `cx`/`cy` are\n * unbounded here because a part may legitimately hang off an edge —\n * assertOnCanvas() rejects the one that lands nowhere on it.\n *\n * The face's override applies first. Each feature's default is then moved\n * with the face's centre and scaled by its width against the default face's,\n * so the defaults are proportions of the face; a feature's own override still\n * names canvas px.\n */\nfunction resolveLayout(\n overrides: LayoutOverride | undefined,\n canvas: Canvas,\n): ResolvedLayout {\n const resolved: ResolvedLayout = { ...DEFAULT_LAYOUT };\n if (overrides === undefined) return resolved;\n const sets = new Map<\n Role,\n { cx?: number; cy?: number; w?: number; h?: number }\n >();\n for (const [role, override] of Object.entries(overrides)) {\n if (!Object.prototype.hasOwnProperty.call(DEFAULT_LAYOUT, role)) {\n throw new AutoRigInputError(\n `layout.${role}: unknown role — expected one of ${Object.keys(DEFAULT_LAYOUT).join(\", \")}`,\n );\n }\n if (override === undefined) continue;\n // Only the fields the override sets: spread over the entry, an explicit\n // undefined would erase the default it leaves alone.\n const set: { cx?: number; cy?: number; w?: number; h?: number } = {};\n for (const field of [\"cx\", \"cy\"] as const) {\n const value = override[field];\n if (value === undefined) continue;\n if (!Number.isFinite(value)) {\n throw new AutoRigInputError(\n `layout.${role}.${field} must be a finite number, got ${String(value)}`,\n );\n }\n set[field] = value;\n }\n for (const field of [\"w\", \"h\"] as const) {\n const value = override[field];\n if (value === undefined) continue;\n const max = field === \"w\" ? canvas.width : canvas.height;\n if (!Number.isInteger(value) || value < 1 || value > max) {\n throw new AutoRigInputError(\n `layout.${role}.${field} must be an integer in 1..${max}, got ${String(value)}`,\n );\n }\n set[field] = value;\n }\n sets.set(role as Role, set);\n }\n const face = { ...resolved.face, ...sets.get(\"face\") };\n resolved.face = face;\n const base = DEFAULT_LAYOUT.face;\n const scale = face.w / base.w;\n const x = (cx: number) => face.cx + (cx - base.cx) * scale;\n const w = (width: number) => Math.max(1, Math.round(width * scale));\n for (const role of FACE_FEATURES) {\n const d = DEFAULT_LAYOUT[role];\n const cy = face.cy + (d.cy - base.cy) * scale;\n resolved[role] = { ...d, cx: x(d.cx), cy, w: w(d.w), ...sets.get(role) };\n }\n // The nose has no default cy (the tip rule places it, off the eye and\n // mouth rows above), so it merges on its own.\n const nose = DEFAULT_LAYOUT.nose;\n resolved.nose = {\n ...nose,\n cx: x(nose.cx),\n w: w(nose.w),\n ...sets.get(\"nose\"),\n };\n for (const [role, set] of sets) {\n if (role === \"face\" || role === \"nose\") continue;\n if ((FACE_FEATURES as readonly Role[]).includes(role)) continue;\n mergeRole(resolved, role, set);\n }\n return resolved;\n}\n\n/**\n * Merge an override's set fields onto a role's resolved entry. Generic over\n * the role so one statement types for every kind of entry, the arms' among\n * them, whose cx/cy/w may stay unset.\n */\nfunction mergeRole<R extends Role>(\n resolved: ResolvedLayout,\n role: R,\n set: { cx?: number; cy?: number; w?: number; h?: number },\n): void {\n resolved[role] = { ...resolved[role], ...set };\n}\n\n/**\n * Input boundary for `canvasHeight`: an even integer in CANVAS..MAX_CANVAS_DIM,\n * CANVAS when omitted. Model space is centred on the canvas, so an odd height\n * would put the head on a half pixel.\n */\nfunction resolveCanvasHeight(value: number | undefined): number {\n if (value === undefined) return CANVAS;\n if (\n !Number.isInteger(value) ||\n value % 2 !== 0 ||\n value < CANVAS ||\n value > MAX_CANVAS_DIM\n ) {\n throw new AutoRigInputError(\n `canvasHeight must be an even integer in ${CANVAS}..${MAX_CANVAS_DIM}, got ${String(value)}`,\n );\n }\n return value;\n}\n\n/**\n * Input boundary for `mirrorParts`: a name that is not a part file (a typo, or\n * a role such as `eye_L`) would otherwise flip nothing and read as success.\n */\nfunction resolveMirrorParts(names: string[] | undefined): Set<string> {\n const mirrored = new Set<string>();\n for (const [i, name] of (names ?? []).entries()) {\n if (!PART_FILES.includes(name)) {\n throw new AutoRigInputError(\n `mirrorParts[${i}]: unknown part ${JSON.stringify(name)} — expected one of ${PART_FILES.join(\", \")}`,\n );\n }\n mirrored.add(name);\n }\n return mirrored;\n}\n\n/**\n * Some generated parts come back opaque on a white background (no alpha).\n * Key near-white pixels to transparent so they can layer cleanly.\n */\nfunction keyWhiteToAlpha(rgba: Buffer): Buffer {\n const keyed = Buffer.from(rgba);\n for (let i = 0; i < keyed.length; i += 4) {\n if (keyed[i] > 238 && keyed[i + 1] > 238 && keyed[i + 2] > 238) {\n keyed[i + 3] = 0;\n }\n }\n return keyed;\n}\n\n/** A PNG part's dense core (`null` when no pixel reaches the core's alpha)\n * and its own bounds, both in its own px. */\nasync function coreAndBoundsOf(\n png: Buffer,\n): Promise<{ core: Box | null; bounds: Box }> {\n const { data, info } = await sharp(png)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return {\n core: denseCoreOf(data, info.width, info.height),\n bounds: { x: 0, y: 0, w: info.width, h: info.height },\n };\n}\n\n/** Whether a part keeps a pixel the auto-rig counts as coverage. */\nexport async function hasCoverage(png: Buffer): Promise<boolean> {\n const { data, info } = await sharp(png)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n return scanAlphaBbox(data, info.width, info.height) !== null;\n}\n\n/** What a nose part's layout sizes, decided on the trimmed source part. */\ninterface NoseSizing {\n /** The box layout `w`/`h` size, in the trimmed source part's px (not the\n * resized part's). */\n box: Box;\n /** The whole part stood in for the core: it has none, or it is a speck. */\n whole: boolean;\n /** The core's and the part's sizes when a speck was the reason. */\n speck?: NoseSpeck;\n}\n\n/**\n * What a nose part's layout sizes: its dense core, in its own px — or its own\n * bounds, so it is sized and placed whole, when no pixel reaches the core's\n * alpha (a nose painted wholly translucent) or the core is a speck of those\n * bounds (`isSpeckCore`).\n */\nasync function noseSizingOf(png: Buffer): Promise<NoseSizing> {\n const { core, bounds } = await coreAndBoundsOf(png);\n if (core === null) return { box: bounds, whole: true };\n if (isSpeckCore(core, bounds)) {\n return {\n box: bounds,\n whole: true,\n speck: {\n core: { w: core.w, h: core.h },\n part: { w: bounds.w, h: bounds.h },\n },\n };\n }\n return { box: core, whole: false };\n}\n\n/** A part trimmed and flipped, not yet resized: a PNG and its size. */\ninterface Trimmed {\n data: Buffer;\n w: number;\n h: number;\n}\n\n/**\n * Trim/mirror a part, ready to be resized (`sizedPart`). `inMemory` carries\n * the eye pair's two split buffers and the lip set's keyed mouth; every other\n * role is read from the parts dir. `flipSource` is a `mirrorParts` entry for\n * the file the role is cut from. A pose forearm is measured between this and\n * the resize, to learn the width that fits it to its arm.\n * Missing optional part -> null; missing required part -> AutoRigInputError.\n */\nexport async function trimmedPart(\n role: LayerRole,\n cfg: Omit<RoleLayout, \"cx\" | \"cy\" | \"w\">,\n partsDir: string,\n inMemory: Buffer | undefined,\n flipSource: boolean,\n): Promise<Trimmed | null> {\n let img: sharp.Sharp;\n if (inMemory !== undefined) {\n img = sharp(inMemory);\n } else {\n const srcPath = path.join(partsDir, cfg.src);\n if (!fs.existsSync(srcPath)) {\n // An optional role's part may be absent from the parts dir; the\n // auto-rig only requires face/eye_L/eye_R/mouth.\n if (cfg.optional) return null;\n // Name the role, not just the file: one source feeds two roles\n // (brow.png -> brow_L/brow_R), so the path alone does not say what broke.\n throw new AutoRigInputError(\n `missing part source for role \"${role}\": ${srcPath}` +\n (role === \"mouth\"\n ? \" — draw mouth.png (with mouth_open.png), or the lip set's mouth_keyed.png + mouth_interior.png\"\n : \"\"),\n );\n }\n const png = await decodePng(srcPath);\n // decodePng is the package's decode boundary: it caps the source at\n // MAX_INPUT_PIXELS and reports a bad/corrupt file as a path-qualified\n // AutoRigInputError, so the raw re-wrap below is already bounded.\n img = sharp(png.hasAlpha ? png.rgba : keyWhiteToAlpha(png.rgba), {\n raw: { width: png.width, height: png.height, channels: 4 },\n });\n }\n // noTrim parts (the eye and lash pairs) keep their shared pre-cropped frame so\n // sclera and lash stay aligned; everything else is alpha-trimmed to its own\n // bbox, less any stray speck beside the drawing.\n if (!cfg.noTrim) {\n // The rest of the pipeline reads this trimmed raw, so the source is\n // decoded and trimmed once. Only file sources and the keyed mouth are\n // trimmed (the eye pair's halves are noTrim), and the file sources are\n // raw already, so a part with no stray speck composes byte-identically.\n const kept = await img\n .trim({ threshold: TRIM_THRESHOLD })\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n const { width: keptW, height: keptH } = kept.info;\n img = sharp(kept.data, {\n raw: { width: keptW, height: keptH, channels: 4 },\n });\n const box = boxWithoutStraySpecks(kept.data, keptW, keptH);\n if (box !== null) img = img.extract(box);\n }\n // A flipped source under a mirrored role cancels out. sharp's flop() sets a\n // flag rather than toggling it, so the two cannot simply be applied in turn.\n if ((cfg.mirror ?? false) !== flipSource) img = img.flop();\n // Materialise the trimmed part BEFORE resizing: its size is bounded by the\n // source decode limit, so the size the resize WOULD produce can be checked\n // against the canvas while only the bounded buffer is allocated.\n const trimmed = await img.png().toBuffer({ resolveWithObject: true });\n return {\n data: trimmed.data,\n w: trimmed.info.width,\n h: trimmed.info.height,\n };\n}\n\n/**\n * Resize a trimmed part to its layout width. The nose is resized so its dense\n * core, not its whole part, comes out `w` wide (and `h` tall when set),\n * unless its whole part stood in for the core. Either way the nose's sizing\n * decision (`noseSizingOf`) always comes back as `nose`, and no other role\n * has one.\n */\nexport async function sizedPart(\n role: LayerRole,\n cfg: Omit<RoleLayout, \"cx\" | \"cy\">,\n trimmed: Trimmed,\n canvas: Canvas,\n): Promise<{ buf: Buffer; w: number; h: number; nose?: NoseSizing }> {\n const { w: trimmedW, h: trimmedH } = trimmed;\n // What `w`/`h` size: the nose's dense core, measured on the trimmed, flipped\n // part — the whole part scales with it, feather and all — or that whole\n // part when it has no core or the core is a speck, and every other role's\n // whole part.\n const nose = role === \"nose\" ? await noseSizingOf(trimmed.data) : undefined;\n const sized = nose?.box ?? { x: 0, y: 0, w: trimmedW, h: trimmedH };\n const width = Math.round((trimmedW * cfg.w) / sized.w);\n const height =\n cfg.h === undefined\n ? Math.round((trimmedH * width) / trimmedW)\n : Math.round((trimmedH * cfg.h) / sized.h);\n // resolveLayout bounds w and an explicit h, so for a part sized whole only\n // the aspect-derived height can run past the canvas; a nose sized by its\n // core can overrun either dimension.\n if (width > canvas.width || height > canvas.height) {\n const field = width > canvas.width || cfg.h === undefined ? \"w\" : \"h\";\n throw new AutoRigInputError(\n `layout.${role}.${field}: resized part ${width}x${height} exceeds the ${canvasName(canvas)} canvas`,\n );\n }\n const resized = await sharp(trimmed.data)\n // Width alone keeps the source aspect. With h, fit:\"fill\" is the point —\n // stretch to the given box instead. Both options stay off the width-only\n // path: passing height:undefined alongside fit:\"fill\" makes sharp drop the\n // aspect it would otherwise preserve.\n .resize(cfg.h === undefined ? { width } : { width, height, fit: \"fill\" })\n .png()\n .toBuffer({ resolveWithObject: true });\n return {\n buf: resized.data,\n w: resized.info.width,\n h: resized.info.height,\n nose,\n };\n}\n\n/**\n * Trim/mirror a part and resize it to its layout width: `trimmedPart` then\n * `sizedPart`. Missing optional part -> null; missing required part ->\n * AutoRigInputError.\n */\nasync function partBuffer(\n role: LayerRole,\n cfg: Omit<RoleLayout, \"cx\" | \"cy\">,\n partsDir: string,\n inMemory: Buffer | undefined,\n flipSource: boolean,\n canvas: Canvas,\n): Promise<{ buf: Buffer; w: number; h: number; nose?: NoseSizing } | null> {\n const trimmed = await trimmedPart(role, cfg, partsDir, inMemory, flipSource);\n return trimmed === null ? null : sizedPart(role, cfg, trimmed, canvas);\n}\n\n/**\n * Refuse a placed part that lands nowhere on the canvas. Running off an edge is\n * legitimate — a bust's `body` is meant to be cut off by the canvas bottom — so\n * the test is INTERSECTION, not containment. A part that misses the canvas\n * entirely composes to a fully transparent layer that nothing downstream flags\n * (measureDir warns per measured layer, and an empty one has no geometry), so a\n * sign-flipped centre would otherwise read as success.\n */\nfunction assertOnCanvas(\n source: string,\n w: number,\n h: number,\n left: number,\n top: number,\n canvas: Canvas,\n): void {\n if (\n left + w <= 0 ||\n top + h <= 0 ||\n left >= canvas.width ||\n top >= canvas.height\n ) {\n throw new AutoRigInputError(\n `${source}: the placed part (${w}x${h} at ${left},${top}) falls entirely outside the ${canvasName(canvas)} canvas`,\n );\n }\n}\n\n/** Where a part lands, centred on its layout cx/cy. The nose has its own. */\nfunction placement(\n role: Exclude<Role, \"nose\" | ArmRole | PoseRole>,\n cfg: RoleLayout,\n w: number,\n h: number,\n canvas: Canvas,\n) {\n const left = Math.round(cfg.cx - w / 2);\n const top = Math.round(cfg.cy - h / 2);\n assertOnCanvas(`layout.${role}.cx/cy`, w, h, left, top, canvas);\n return { left, top };\n}\n\n/**\n * Where the nose lands: by the box it was sized by (`noseSizingOf`), in the\n * resized part's px — its dense core, or its whole bounds when those stood in.\n * `cx` centres the box's columns. A set `cy` centres its rows; absent, its\n * bottom row — the tip, the last row index at alpha ≥ 128 — lands on\n * round(E + NOSE_TIP_AT·(M − E)), E the eyes' mean row and M the mouth's. A\n * box's centre is `x + w/2`, as placement() takes it: pixel x covers\n * [x, x + 1).\n */\nfunction nosePlacement(\n layout: ResolvedLayout,\n mouthKey: \"mouth\" | \"mouth_inner\",\n box: Box,\n w: number,\n h: number,\n canvas: Canvas,\n) {\n const { cx, cy } = layout.nose;\n const left = Math.round(cx - (box.x + box.w / 2));\n let top: number;\n if (cy !== undefined) {\n top = Math.round(cy - (box.y + box.h / 2));\n } else {\n const eyeRow = (layout.eye_L.cy + layout.eye_R.cy) / 2;\n const tipRow = Math.round(\n eyeRow + NOSE_TIP_AT * (layout[mouthKey].cy - eyeRow),\n );\n top = tipRow - (box.y + box.h - 1);\n }\n assertOnCanvas(\n cy !== undefined\n ? \"layout.nose.cx/cy\"\n : `layout.nose.cx/cy (cy unset: its tip row comes from layout.eye_L/eye_R/${mouthKey}.cy)`,\n w,\n h,\n left,\n top,\n canvas,\n );\n return { left, top };\n}\n\nfunction blankCanvas(canvas: Canvas) {\n return sharp({\n create: {\n width: canvas.width,\n height: canvas.height,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n });\n}\n\n/**\n * The eyewhite's light ink drawn detached above its white, as a row-major\n * mask (1 = detached). Light ink is non-transparent at luma EYE_LASH_LUMA or\n * over. Its sets are 8-connected through visibly painted pixels only (alpha\n * ALPHA_OPAQUE or over), so a faint antialiased pixel between a crease and\n * the white does not join them. Each fainter pixel is fringe of the nearest\n * painted set it reaches through faint pixels whose alpha never rises on the\n * way (ties go to the set met first in row-major order, the higher one).\n * Antialiasing fades away from what it edges, so a translucent stroke past a\n * fainter halo does not become the fringe of the set the halo edges. Faint\n * ink that no painted set reaches this way forms sets of its own. So does a\n * noisy faint pixel brighter than every claimed neighbour and touching no\n * painted pixel: above the white's top, it is dropped. The white is the\n * largest painted set. Another set is detached above it when each of its own\n * pixels, fringe aside, lies above the white's topmost painted pixel in its\n * column, or, past either end of the white, above the top of that end's\n * column; it goes with its fringe. A crease often runs on past the eye's\n * corners, and judged only over the white, one pixel out there would keep\n * the whole crease. A shade painted on the white touches it, so it is part\n * of the white; a mark below the white, or beside an end and level with it,\n * is left.\n */\nfunction detachedAboveWhite(rgba: Buffer, W: number, H: number): Uint8Array {\n const n = W * H;\n // 2 = painted light ink, 1 = fainter light ink, 0 = neither.\n const ink = new Uint8Array(n);\n for (let p = 0; p < n; p++) {\n const alpha = rgba[p * 4 + 3];\n if (alpha > 0 && luma(rgba, p * 4) >= EYE_LASH_LUMA)\n ink[p] = alpha >= ALPHA_OPAQUE ? 2 : 1;\n }\n const label = new Int32Array(n).fill(-1);\n // A pixel is labelled as it is pushed, so it is pushed once and neither the\n // flood fill's stack nor the fringe's queue outgrows the image.\n const stack = new Int32Array(n);\n const near = (p: number, visit: (q: number) => void) => {\n const px = p % W;\n const py = (p - px) / W;\n for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {\n for (let x = Math.max(0, px - 1); x <= Math.min(W - 1, px + 1); x++) {\n visit(y * W + x);\n }\n }\n };\n const sizes: number[] = [];\n const fill = (start: number) => {\n const id = sizes.length;\n let size = 0;\n let depth = 0;\n label[start] = id;\n stack[depth++] = start;\n while (depth > 0) {\n const p = stack[--depth];\n size++;\n near(p, (q) => {\n if (ink[q] === ink[start] && label[q] === -1) {\n label[q] = id;\n stack[depth++] = q;\n }\n });\n }\n sizes.push(size);\n };\n for (let p = 0; p < n; p++) if (ink[p] === 2 && label[p] === -1) fill(p);\n const paintedSets = sizes.length;\n // The fringe: breadth-first from every painted pixel at once, each faint\n // pixel no more opaque than the one before taking the set that reaches it\n // first.\n let head = 0;\n let tail = 0;\n for (let p = 0; p < n; p++) if (ink[p] === 2) stack[tail++] = p;\n while (head < tail) {\n const p = stack[head++];\n near(p, (q) => {\n if (\n ink[q] === 1 &&\n label[q] === -1 &&\n rgba[q * 4 + 3] <= rgba[p * 4 + 3]\n ) {\n label[q] = label[p];\n stack[tail++] = q;\n }\n });\n }\n for (let p = 0; p < n; p++) if (ink[p] === 1 && label[p] === -1) fill(p);\n\n const detached = new Uint8Array(n);\n if (paintedSets === 0 || sizes.length < 2) return detached;\n let white = 0;\n for (let id = 1; id < paintedSets; id++) {\n if (sizes[id] > sizes[white]) white = id;\n }\n // A set's own pixels: a painted set's painted ones, a faint set's all.\n const own = (p: number) => ink[p] === 2 || label[p] >= paintedSets;\n // The white's topmost painted row per column (the scan is row-major, so\n // the first pixel met is the top).\n const whiteTop = new Int32Array(W).fill(-1);\n for (let p = 0; p < n; p++) {\n const x = p % W;\n if (label[p] === white && own(p) && whiteTop[x] === -1)\n whiteTop[x] = (p - x) / W;\n }\n // An 8-connected set covers one unbroken run of columns, so every column\n // the white misses lies past one of its ends and takes that end's top.\n let first = 0;\n while (whiteTop[first] === -1) first++;\n let last = W - 1;\n while (whiteTop[last] === -1) last--;\n whiteTop.fill(whiteTop[first], 0, first);\n whiteTop.fill(whiteTop[last], last + 1);\n const above = new Uint8Array(sizes.length).fill(1);\n for (let p = 0; p < n; p++) {\n const id = label[p];\n if (id === -1 || id === white || !own(p)) continue;\n const x = p % W;\n if ((p - x) / W >= whiteTop[x]) above[id] = 0;\n }\n for (let p = 0; p < n; p++) {\n const id = label[p];\n if (id !== -1 && id !== white && above[id]) detached[p] = 1;\n }\n return detached;\n}\n\n/**\n * Split eyewhite.png (white almond + dark lashes) into a sclera (the upper\n * lash recolored to white; the whole drawing's alpha = the blink clip-mask\n * shape), a dark UPPER-lash layer and a dark LOWER-lid layer. All are cropped\n * to the SAME eye bbox so they stay aligned (consumed with noTrim): the lash\n * arc keeps its position at the top of the sclera, so on blink it folds DOWN\n * over the eye rather than the eye shrinking in place.\n *\n * The lower lid's dark line and lashes stay in the sclera as drawn and are\n * copied into their own layer, which draws over the iris. Recolored white they\n * would show as white flicks wherever a lash hangs below the white, and left\n * in the sclera alone the iris would paint over the line. The sclera keeps\n * them so its alpha, which the rig measures the eye by, is the drawing's.\n * `lashLower` is null when the eyewhite draws no dark pixel below the upper\n * lash's fraction.\n *\n * A light mark drawn detached above the white, such as a double-eyelid crease,\n * is dropped from the sclera (`detachedAboveWhite`). The sclera is the iris's\n * clip, and at half blink the fold carries such a mark down into the iris's\n * path. The frame is still the source's alpha bbox, crease and all, so the\n * layout places the pair where it did before.\n *\n * The lid's skin drawn as a band over the lash is dropped from the sclera too.\n * It meets the white at the corners, so the detached rule keeps it as the\n * white's; left in the clip, the rig's `blinkFold` carries it over the iris's\n * rows at half blink, where the lash its `lashFold` folds does not cover it,\n * and a taller iris shows through it above the lash at rest. The cut takes\n * only warm skin (painted, light, red over blue by EYE_LID_WARMTH) above the\n * lowest dark row over the white, in the columns that have a lash there.\n * Its limits: a band drawn over a lash-free column (the tear duct, the\n * corners) stays, since there colour alone cannot tell it from the white's\n * own warm shading or caruncle; a lid as cool as the white is not told apart\n * from it; the band's antialiased edge\n * under alpha ALPHA_OPAQUE is not cut, so it stays in the clip as the white's\n * fringe, a faint outline of the band; and a sclera tinted warmer than the\n * rule everywhere has no white top, so it is left whole. The frame is\n * unchanged.\n *\n * Both come back as PNG buffers. The script this ports wrote them back into the\n * parts dir, but that dir is an INPUT here (reads are deliberately unconfined),\n * so the tool never writes there — only under the confined outDir.\n */\nasync function prepEyeSplit(\n partsDir: string,\n): Promise<{ sclera: Buffer; lash: Buffer; lashLower: Buffer | null }> {\n const srcPath = path.join(partsDir, EYEWHITE_SRC);\n if (!fs.existsSync(srcPath)) {\n throw new AutoRigInputError(`missing eyewhite source: ${srcPath}`);\n }\n const { width: W, height: H, rgba: data } = await decodePng(srcPath);\n\n // Eye content bbox (alpha) → the shared cropped frame for both outputs.\n let minX = W;\n let minY = H;\n let maxX = -1;\n let maxY = -1;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n if (data[(y * W + x) * 4 + 3] > 8) {\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n }\n }\n if (maxX < 0) {\n throw new AutoRigInputError(`eyewhite is fully transparent: ${srcPath}`);\n }\n // Dark pixels above this row are the upper lash; below it, the lower lid.\n const lashCutoffY = minY + LASH_KEEP_FRACTION * (maxY - minY + 1);\n const detached = detachedAboveWhite(data, W, H);\n const isDark = (i: number) =>\n data[i + 3] > 0 && luma(data, i) < EYE_LASH_LUMA;\n const isLight = (i: number) =>\n data[i + 3] >= ALPHA_OPAQUE && luma(data, i) >= EYE_LASH_LUMA;\n const isWarm = (i: number) => data[i] - data[i + 2] >= EYE_LID_WARMTH;\n // Each column's white top: its first painted, light, cool pixel that is not\n // a mark detached above the white (a cool crease would stop the cut).\n const whiteTop = new Int32Array(W).fill(-1);\n for (let x = 0; x < W; x++) {\n for (let y = 0; y < H; y++) {\n const i = (y * W + x) * 4;\n if (!detached[y * W + x] && isLight(i) && !isWarm(i)) {\n whiteTop[x] = y;\n break;\n }\n }\n }\n // The columns outside the outermost two with a white top take the nearer\n // one's. A column between them with no cool pixel stays -1 and is left\n // uncut, and with no white top anywhere nothing is cut.\n let first = 0;\n while (first < W && whiteTop[first] === -1) first++;\n if (first < W) {\n let last = W - 1;\n while (whiteTop[last] === -1) last--;\n whiteTop.fill(whiteTop[first], 0, first);\n whiteTop.fill(whiteTop[last], last + 1);\n }\n // The row the lid's skin is cut above: the lowest dark row over the white,\n // in a column with one only (-1: no cut). Any dark pixel counts, a lash\n // tail hanging past lashCutoffY too, so a misread keeps skin rather than\n // cutting under the lash. A lash-free column is never cut: there a lid band\n // and the white's own warm shading or caruncle sit on the white alike.\n const lidStop = new Int32Array(W).fill(-1);\n for (let x = 0; x < W; x++) {\n for (let y = whiteTop[x] - 1; y >= 0; y--) {\n if (isDark((y * W + x) * 4)) {\n lidStop[x] = y;\n break;\n }\n }\n }\n\n const sclera = Buffer.from(data);\n const lash = Buffer.from(data);\n const lashLower = Buffer.from(data);\n let lowerInk = false;\n for (let y = 0; y < H; y++) {\n for (let x = 0; x < W; x++) {\n const i = (y * W + x) * 4;\n const dark = isDark(i);\n const upper = y <= lashCutoffY;\n if (dark && upper) sclera[i] = sclera[i + 1] = sclera[i + 2] = 255; // dark -> white\n if (detached[y * W + x]) sclera[i + 3] = 0;\n if (y < lidStop[x] && isLight(i) && isWarm(i)) sclera[i + 3] = 0;\n if (!(dark && upper)) lash[i + 3] = 0;\n if (dark && !upper) lowerInk = true;\n else lashLower[i + 3] = 0;\n }\n }\n const region = {\n x: minX,\n y: minY,\n w: maxX - minX + 1,\n h: maxY - minY + 1,\n };\n return {\n sclera: await cropToBuffer(sclera, W, H, region),\n lash: await cropToBuffer(lash, W, H, region),\n lashLower: lowerInk ? await cropToBuffer(lashLower, W, H, region) : null,\n };\n}\n\n/** Whether any pixel is not fully opaque. An alpha channel alone proves\n * nothing: an image saved as RGBA can still be opaque on its white ground. */\nfunction hasTransparency(rgba: Buffer): boolean {\n for (let p = 3; p < rgba.length; p += 4) if (rgba[p] < 255) return true;\n return false;\n}\n\n/** The lip set's two sources, keyed and prepared: the keyed open mouth as a\n * PNG at source resolution, and the interior trimmed with its cavity's\n * colour. */\nexport interface LipSources {\n keyedPng: Buffer;\n interior: { png: Buffer; cavity: [number, number, number] };\n}\n\n/**\n * Decode, key and prepare the lip set's two files. Both are decoded at source\n * resolution, because the key reads the antialiasing of the source's own\n * pixels (./compose-lips); a part with no alpha has its white ground keyed\n * first.\n */\nexport async function readLipSources(\n keyedPath: string,\n interiorPath: string,\n): Promise<LipSources> {\n const k = await decodePng(keyedPath);\n const keyedRgba = keyGreen(\n hasTransparency(k.rgba) ? k.rgba : keyWhiteToAlpha(k.rgba),\n k.width,\n k.height,\n );\n const i = await decodePng(interiorPath);\n const interior = await prepInterior(\n hasTransparency(i.rgba)\n ? i.rgba\n : keyBorderWhite(i.rgba, i.width, i.height),\n i.width,\n i.height,\n );\n return {\n keyedPng: await sharp(keyedRgba, {\n raw: { width: k.width, height: k.height, channels: 4 },\n })\n .png()\n .toBuffer(),\n interior,\n };\n}\n\n/**\n * The lip set's two sources, keyed and prepared, or `undefined` for the legacy\n * mouth. Opt-in like the arms: both files present is the set, neither is the\n * legacy route, and one without the other, or either beside the legacy\n * drawings, is refused (auto_rig_from_layers refuses the mix; the composer\n * refuses it first, naming what to remove).\n */\nasync function prepLipSources(\n partsDir: string,\n mirrored: Set<string>,\n): Promise<LipSources | undefined> {\n const has = (name: string) => fs.existsSync(path.join(partsDir, name));\n const keyed = has(KEYED_SRC);\n const interior = has(INTERIOR_SRC);\n if (keyed && !interior) {\n throw new AutoRigInputError(\n `${KEYED_SRC} needs ${INTERIOR_SRC}: the composer fits the drawn interior into the keyed opening — draw it (billed)`,\n );\n }\n if (interior && !keyed) {\n throw new AutoRigInputError(\n `${INTERIOR_SRC} needs ${KEYED_SRC}: the composer cuts the lip set from the keyed open mouth and fits the interior into its opening — draw it (billed)`,\n );\n }\n if (!keyed) return undefined;\n const legacy = [\"mouth.png\", \"mouth_open.png\"].filter(has);\n if (legacy.length > 0) {\n throw new AutoRigInputError(\n `${KEYED_SRC}/${INTERIOR_SRC} cannot be composed beside mouth.png/mouth_open.png (the lip set replaces the mouth drawings, and auto_rig_from_layers refuses the mix) — remove ${legacy.join(\" and \")}`,\n );\n }\n\n const lips = await readLipSources(\n path.join(partsDir, KEYED_SRC),\n path.join(partsDir, INTERIOR_SRC),\n );\n const prepared = lips.interior;\n return {\n keyedPng: lips.keyedPng,\n interior: mirrored.has(INTERIOR_SRC)\n ? { ...prepared, png: await sharp(prepared.png).flop().png().toBuffer() }\n : prepared,\n };\n}\n\n/**\n * Compose a parts directory into role-named layers plus a flattened preview,\n * then measure the result so the caller sees the geometry checks inline.\n *\n * Error boundary: ONLY AutoRigInputError (caller input / filesystem) →\n * `{ ok:false }`, matching autoRigFromLayers; any other throw propagates.\n */\nexport async function composeLayersFromParts(\n input: ComposeInput,\n): Promise<ComposeResult> {\n try {\n // Resolve the output dir FIRST (fail-fast): reject a missing or escaping\n // target before spending the decode budget on a run that cannot be written.\n const outDir = resolveOutputDir(input.outDir);\n const partsDir = resolveInputDir(input.partsDir);\n // resolveOutputDir already realpath's outDir; resolveInputDir does not (its\n // reads are deliberately unconfined), so realpath partsDir here too before\n // comparing — otherwise a symlink alias of the same directory would slip\n // past a lexical check. Composing a parts dir into itself would overwrite\n // originals like face.png/hair_front.png with resized, cropped layers, and\n // skipped-role cleanup would delete sources with no surviving part.\n if (fs.realpathSync(partsDir) === outDir) {\n throw new AutoRigInputError(\n `partsDir and outDir resolve to the same directory (${outDir}): composing would overwrite the source parts`,\n );\n }\n // Before anything decodes, like every other input check.\n const canvas: Canvas = {\n width: CANVAS,\n height: resolveCanvasHeight(input.canvasHeight),\n };\n const layout = resolveLayout(input.layout, canvas);\n const mirrored = resolveMirrorParts(input.mirrorParts);\n\n const split = await prepEyeSplit(partsDir);\n const splitSources = new Map<string, Buffer>([\n [\"eyewhite_sclera.png\", split.sclera],\n [\"eyewhite_lash.png\", split.lash],\n ]);\n if (split.lashLower !== null) {\n splitSources.set(LOWER_LASH_SRC, split.lashLower);\n }\n\n const lips = await prepLipSources(partsDir, mirrored);\n // The set's split, stashed where mouth_inner is placed for the two lip\n // layers cut on the same frame.\n let lipSplit:\n | {\n split: Awaited<ReturnType<typeof splitLipSet>>;\n w: number;\n h: number;\n left: number;\n top: number;\n }\n | undefined;\n\n // Place every role before writing any: a rejected placement must leave\n // outDir as the last compose left it, not half overwritten.\n const placed: {\n role: LayerRole;\n part: { buf: Buffer; w: number; h: number };\n left: number;\n top: number;\n /** An arm's, for a pose forearm to hang from: the rig's elbow pivot on\n * the canvas and the elbow seam's run, px. */\n elbow?: { x: number; y: number };\n elbowRun?: number;\n }[] = [];\n const skipped: LayerRole[] = [];\n // Compose's verdict on the nose's source part when its core was a speck,\n // for the report; otherwise the report judges the composed nose layer.\n let noseSpeck: NoseSpeck | undefined;\n for (const role of ORDER) {\n // With the lip set, mouth and mouth_open are neither placed nor listed in\n // `skipped`: the set stands in for them.\n if (lips !== undefined && (role === \"mouth\" || role === \"mouth_open\")) {\n continue;\n }\n if (role === \"mouth_inner\") {\n // Opt-in like the arms: without the lip set, nothing to place.\n if (lips === undefined) continue;\n const cfg = layout.mouth_inner;\n // Never null: the keyed part is in memory.\n const part = (await partBuffer(\n role,\n cfg,\n partsDir,\n lips.keyedPng,\n mirrored.has(KEYED_SRC),\n canvas,\n ))!;\n const split = await splitLipSet(\n part.buf,\n part.w,\n part.h,\n lips.interior,\n );\n const { left, top } = placement(role, cfg, part.w, part.h, canvas);\n lipSplit = { split, w: part.w, h: part.h, left, top };\n placed.push({\n role,\n part: { buf: split.inner, w: part.w, h: part.h },\n left,\n top,\n });\n continue;\n }\n if (\n role === \"mouth_tongue\" ||\n role === \"mouth_teeth\" ||\n role === \"lip_lower\" ||\n role === \"lip_upper\"\n ) {\n if (lipSplit === undefined) continue;\n const { split, w, h, left, top } = lipSplit;\n const buf = {\n mouth_tongue: split.tongue,\n mouth_teeth: split.teeth,\n lip_lower: split.lower,\n lip_upper: split.upper,\n }[role];\n // An interior with no light paint has no tongue or teeth to cut.\n if (isLipInsideRole(role) && !(await hasCoverage(buf))) {\n skipped.push(role);\n continue;\n }\n placed.push({ role, part: { buf, w, h }, left, top });\n continue;\n }\n // A lower lash is placed by its eye's layout, on the sclera's frame.\n const lower = role === \"lash_lower_L\" || role === \"lash_lower_R\";\n const key: Role = lower ? LOWER_LASH[role] : role;\n if (lower && split.lashLower === null) {\n skipped.push(role);\n continue;\n }\n if (key === \"arm_L\" || key === \"arm_R\") {\n const arm = layout[key];\n // Arms are opt-in: a parts dir without arm.png composes as a bust\n // does, the arms neither placed nor listed in `skipped`.\n if (!fs.existsSync(path.join(partsDir, arm.src))) continue;\n const body = placed.find((p) => p.role === \"body\");\n if (body === undefined) {\n throw new AutoRigInputError(\n \"arm.png: an arm needs body.png — the composer hangs each arm on the body's shoulder, and auto_rig_from_layers hangs it from the body\",\n );\n }\n const w = arm.w ?? Math.max(1, Math.round(ARM_WIDTH * body.part.w));\n // Never null: the part is there, checked above.\n const part = (await partBuffer(\n role,\n { ...arm, w },\n partsDir,\n undefined,\n mirrored.has(arm.src),\n canvas,\n ))!;\n const { left, top, elbow, elbowRun } = await armPlacement(\n key,\n arm,\n part,\n {\n left: body.left,\n top: body.top,\n w: body.part.w,\n h: body.part.h,\n },\n );\n const unset = ([\"cx\", \"cy\"] as const).filter(\n (field) => arm[field] === undefined,\n );\n assertOnCanvas(\n unset.length === 0\n ? `layout.${key}.cx/cy`\n : `layout.${key}.cx/cy (${unset.join(\"/\")} unset: its shoulder pivot hangs on the shoulder corner of layout.body's box)`,\n part.w,\n part.h,\n left,\n top,\n canvas,\n );\n placed.push({ role, part, left, top, elbow, elbowRun });\n continue;\n }\n if (key === \"forearm_pose_L\" || key === \"forearm_pose_R\") {\n const pose = layout[key];\n // Opt-in like the arms: neither placed nor listed in `skipped`.\n if (!fs.existsSync(path.join(partsDir, pose.src))) continue;\n const armRole = key === \"forearm_pose_L\" ? \"arm_L\" : \"arm_R\";\n const arm = placed.find((p) => p.role === armRole);\n if (arm?.elbow === undefined || arm.elbowRun === undefined) {\n throw new AutoRigInputError(\n \"forearm_pose.png: a pose forearm needs arm.png — the composer pins it on the arm's elbow, and auto_rig_from_layers hangs it from the arm\",\n );\n }\n // Never null: the part is there, checked above.\n const trimmed = (await trimmedPart(\n role,\n pose,\n partsDir,\n undefined,\n mirrored.has(pose.src),\n ))!;\n const w =\n pose.w ?? (await forearmPoseWidth(key, trimmed, arm.elbowRun));\n let part;\n try {\n part = await sizedPart(role, { ...pose, w }, trimmed, canvas);\n } catch (err) {\n // A derived w the user never set is not blamed on the layout key.\n if (pose.w === undefined && err instanceof AutoRigInputError) {\n throw new AutoRigInputError(\n err.message.replace(\n `layout.${role}.w:`,\n `layout.${role}.w (unset: scaled to ${armRole}'s elbow run):`,\n ),\n );\n }\n throw err;\n }\n const { left, top } = await forearmPosePlacement(\n key,\n pose,\n part,\n arm.elbow,\n );\n const unset = ([\"cx\", \"cy\"] as const).filter(\n (field) => pose[field] === undefined,\n );\n assertOnCanvas(\n unset.length === 0\n ? `layout.${key}.cx/cy`\n : `layout.${key}.cx/cy (${unset.join(\"/\")} unset: its elbow-end pivot hangs on the elbow of layout.${armRole}'s placed arm)`,\n part.w,\n part.h,\n left,\n top,\n canvas,\n );\n placed.push({ role, part, left, top });\n continue;\n }\n const cfg = lower ? { ...layout[key], src: LOWER_LASH_SRC } : layout[key];\n const inMemory = splitSources.get(cfg.src);\n const part = await partBuffer(\n role,\n cfg,\n partsDir,\n inMemory,\n // The split halves are cut from eyewhite.png, the file a caller names.\n mirrored.has(inMemory === undefined ? cfg.src : EYEWHITE_SRC),\n canvas,\n );\n // A lower lid too faint for the alpha the rig reads coverage at, or\n // that the resize erased, would be a layer it refuses as empty.\n if (part === null || (lower && !(await hasCoverage(part.buf)))) {\n skipped.push(role);\n continue;\n }\n // The nose is placed by the box it was sized by. A whole part that stood\n // in is placed by the resized part's own bounds. A core is measured\n // again on the resized part rather than scaled, since resampling moves\n // its edges and the tip rule lands its exact bottom row — and is not\n // judged again here: the source part's verdict decided how it was sized.\n let left: number;\n let top: number;\n if (key === \"nose\") {\n noseSpeck = part.nose?.speck;\n const { core, bounds } = await coreAndBoundsOf(part.buf);\n const box = part.nose?.whole ? bounds : (core ?? bounds);\n ({ left, top } = nosePlacement(\n layout,\n lips === undefined ? \"mouth\" : \"mouth_inner\",\n box,\n part.w,\n part.h,\n canvas,\n ));\n } else {\n ({ left, top } = placement(key, layout[key], part.w, part.h, canvas));\n }\n // The eye pair's halves are cut from one eyewhite into one frame. Set\n // apart, the blink fold tears — and a lash narrowed inside its sclera\n // still lies on it and inks its top row, so nothing in the composed\n // layers would show it. Compared as placed, not as set: an h equal to\n // the one the aspect gives lands on the same frame as leaving it unset.\n if (role === \"lash_L\" || role === \"lash_R\") {\n const eyeRole = role === \"lash_L\" ? \"eye_L\" : \"eye_R\";\n const eye = placed.find((p) => p.role === eyeRole);\n if (\n eye !== undefined &&\n (eye.left !== left ||\n eye.top !== top ||\n eye.part.w !== part.w ||\n eye.part.h !== part.h)\n ) {\n throw new AutoRigInputError(\n `layout.${role} places the lash at ${part.w}x${part.h} (${left},${top}), but layout.${eyeRole} ` +\n `places its sclera at ${eye.part.w}x${eye.part.h} (${eye.left},${eye.top}) — they are cut from one ` +\n `eyewhite into one frame, and the blink fold tears where they part. Set cx/cy/w/h the same on both.`,\n );\n }\n }\n placed.push({ role, part, left, top });\n }\n\n // Every layer is built, and the closed lip preview measured from them,\n // before the first sweep or write: a lip layer the canvas clips away is\n // refused with outDir as the last compose left it.\n const built = new Map<LayerRole, Buffer>();\n for (const { role, part, left, top } of placed) {\n // role layer: this part alone on a full canvas at its position.\n built.set(\n role,\n await blankCanvas(canvas)\n .composite([{ input: part.buf, left, top }])\n .png()\n .toBuffer(),\n );\n }\n // The preview shows the lip set shut by the field the rig's own\n // measurement of the written layers gives, as it draws the rest pose.\n const closed =\n lipSplit === undefined\n ? undefined\n : await closedLips(\n lipSplit.split.upper,\n lipSplit.split.lower,\n await restShiftOf(\n {\n mouth_inner: built.get(\"mouth_inner\")!,\n lip_lower: built.get(\"lip_lower\")!,\n lip_upper: built.get(\"lip_upper\")!,\n },\n canvas.width,\n canvas.height,\n ),\n lipSplit.left,\n lipSplit.top,\n );\n\n // Drop the layer an earlier compose into the same dir wrote for each role\n // this run does not write — a skipped one, or an arm once arm.png is\n // gone: left behind it would contradict the result, since measureDir\n // globs the directory (the report would still show a body) and the next\n // auto_rig_from_layers would rig the stale file into the model. Only the\n // fixed ORDER role names, under the confined outDir, are ever removed.\n for (const role of ORDER) {\n if (placed.some((p) => p.role === role)) continue;\n fs.rmSync(path.join(outDir, `${role}.png`), { force: true });\n }\n // The pose preview exists only with a pose forearm, so it is swept with\n // the layers: left behind it would show a forearm the layers no longer\n // hold.\n const posed = (role: LayerRole) =>\n role === \"forearm_pose_L\" || role === \"forearm_pose_R\";\n if (!placed.some((p) => posed(p.role))) {\n fs.rmSync(path.join(outDir, \"preview-pose.png\"), { force: true });\n }\n const layers: ComposedLayer[] = [];\n for (const { role, part, left, top } of placed) {\n const outPath = path.join(outDir, `${role}.png`);\n writeFileAtomic(outPath, built.get(role)!);\n layers.push({\n role,\n path: outPath,\n width: part.w,\n height: part.h,\n left,\n top,\n });\n }\n // What a role contributes to a rest-pose preview: the lips shut, the\n // interior and what it clips left out (shut, it has no height); null for\n // nothing.\n const restInput = (role: LayerRole, buf: Buffer): Buffer | null => {\n if (role === \"mouth_inner\" || isLipInsideRole(role)) return null;\n if (closed === undefined) return buf;\n if (role === \"lip_upper\") return closed.upper;\n if (role === \"lip_lower\") return closed.lower;\n return buf;\n };\n const preview: { input: Buffer; left: number; top: number }[] = [];\n for (const { role, part, left, top } of placed) {\n const input = restInput(role, part.buf);\n if (!posed(role) && input !== null) preview.push({ input, left, top });\n }\n\n // Flattened preview over a light bg so transparency reads clearly.\n const previewPng = await sharp({\n create: {\n width: canvas.width,\n height: canvas.height,\n channels: 4,\n background: { r: 245, g: 245, b: 248, alpha: 1 },\n },\n })\n .composite(preview)\n .png()\n .toBuffer();\n const previewPath = path.join(outDir, \"preview.png\");\n writeFileAtomic(previewPath, previewPng);\n\n // The switch at 1, as the rig draws it: an arm whose side has a pose\n // forearm keeps the rows above its elbow (the upper arm and the sleeve;\n // the hanging forearm hides), and the pose forearms, last in `placed`,\n // draw over everything.\n let previewPosePath: string | undefined;\n if (placed.some((p) => posed(p.role))) {\n const pose: { input: Buffer; left: number; top: number }[] = [];\n for (const { role, part, left, top, elbow } of placed) {\n const armPosed =\n elbow !== undefined &&\n placed.some(\n (p) =>\n p.role ===\n (role === \"arm_L\" ? \"forearm_pose_L\" : \"forearm_pose_R\"),\n );\n if (!armPosed) {\n const input = restInput(role, part.buf);\n if (input !== null) pose.push({ input, left, top });\n continue;\n }\n const rows = Math.min(part.h, Math.max(1, Math.round(elbow.y - top)));\n pose.push({\n input: await sharp(part.buf)\n .extract({ left: 0, top: 0, width: part.w, height: rows })\n .png()\n .toBuffer(),\n left,\n top,\n });\n }\n const posePng = await sharp({\n create: {\n width: canvas.width,\n height: canvas.height,\n channels: 4,\n background: { r: 245, g: 245, b: 248, alpha: 1 },\n },\n })\n .composite(pose)\n .png()\n .toBuffer();\n previewPosePath = path.join(outDir, \"preview-pose.png\");\n writeFileAtomic(previewPosePath, posePng);\n }\n\n return {\n ok: true,\n outDir,\n layers,\n skipped,\n preview: previewPath,\n ...(previewPosePath === undefined\n ? {}\n : { previewPose: previewPosePath }),\n measure: await measureDir(outDir, noseSpeck),\n };\n } catch (err) {\n if (err instanceof AutoRigInputError)\n return { ok: false, error: err.message };\n throw err;\n }\n}\n","/**\n * Where the composer hangs an arm. One arm.png is the arm on the screen LEFT:\n * `arm_R` takes it as drawn and `arm_L` mirrored. Each of an arm's `cx` / `cy`\n * that the layout leaves unset is derived from the placed body's box: the\n * arm's shoulder pivot lands on the box's shoulder corner on that axis — the\n * box's left edge for `arm_R`, its right edge for `arm_L`, SHOULDER_DROP of\n * its height under its top. On a torso widest at its shoulders, the cap's\n * centre then sits on the torso's edge, overlapping it by the cap's radius.\n * An unset `w` is ARM_WIDTH of the body's width.\n *\n * The pivot is the rig's own: `armGeometry`, run on the resized part as\n * `auto_rig_from_layers` runs it on the composed layer, so the rig turns the\n * composed arm about the target to the pixel, with no second copy of its\n * shoulder rule here to keep in step.\n *\n * A pose forearm (`forearm_pose.png`: the screen-left forearm raised,\n * `forearm_pose_R` as drawn and `forearm_pose_L` mirrored) hangs from its\n * arm's elbow, so the composer puts its elbow end where the rig turns it. An\n * unset `w` scales it so its elbow-end width (2 r_e, measured on the trimmed\n * source) equals the placed arm's seam run, and an unset `cx` or `cy` pins\n * its elbow-end pivot (`forearmPoseGeometry`, measured on the resized part as\n * the shoulder is) on the arm's placed elbow. Both read the rig's geometry,\n * none of it copied here.\n */\n\nimport sharp from \"sharp\";\nimport {\n LayerGeometryError,\n armGeometry,\n createLayerSetMeasurer,\n forearmPoseGeometry,\n type ArmGeometry,\n type ForearmPoseGeometry,\n} from \"@ikijs/editor\";\nimport type { ArmLayout } from \"./compose\";\nimport { AutoRigInputError } from \"./limits\";\n\n/** An arm's default width, as a share of the placed body's width. Our own\n * value, provisional: to be picked by eye on the first full-body character. */\nexport const ARM_WIDTH = 0.4;\n/** How far under the body box's top its shoulder corners lie, as a share of\n * its height. Our own value, provisional: to be picked by eye on the first\n * full-body character. */\nexport const SHOULDER_DROP = 0.12;\n\n/** A placed part's box on the canvas, px. */\ninterface PlacedBox {\n left: number;\n top: number;\n w: number;\n h: number;\n}\n\n/**\n * Where an arm's resized part lands: by its rig shoulder pivot on the body\n * box's shoulder corner for each of `cx` / `cy` left unset, centred on a set\n * one as every other role's part is. An arm the rig would refuse as too short\n * is refused here, path-qualified.\n */\nexport async function armPlacement(\n role: \"arm_L\" | \"arm_R\",\n cfg: Pick<ArmLayout, \"cx\" | \"cy\">,\n part: { buf: Buffer; w: number; h: number },\n body: PlacedBox,\n): Promise<{\n left: number;\n top: number;\n /** The rig's elbow pivot on the canvas, px. */\n elbow: { x: number; y: number };\n /** The elbow seam's widest run, px: what a pose forearm's elbow end fits. */\n elbowRun: number;\n}> {\n const { data } = await sharp(part.buf)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n const layer = createLayerSetMeasurer({ width: part.w, height: part.h }).add({\n role,\n fileName: \"arm.png\",\n rgba: data,\n });\n if (layer === null) {\n throw new AutoRigInputError(\n `layout.${role}: arm.png is empty after alpha threshold once resized`,\n );\n }\n let g: ArmGeometry;\n try {\n // The axis keeps `side` the role's own all the same: arm_R on the screen\n // left, arm_L on the right.\n g = armGeometry(layer, role === \"arm_R\" ? Infinity : -Infinity);\n } catch (err) {\n if (err instanceof LayerGeometryError) {\n throw new AutoRigInputError(`layout.${role}: ${err.message}`);\n }\n throw err;\n }\n // Model space is centred on the measured canvas, here the part itself.\n const pivotX = g.shoulder.x + part.w / 2;\n const pivotY = part.h / 2 - g.shoulder.y;\n const cornerX = role === \"arm_R\" ? body.left : body.left + body.w;\n const cornerY = body.top + SHOULDER_DROP * body.h;\n const left = Math.round(\n cfg.cx === undefined ? cornerX - pivotX : cfg.cx - part.w / 2,\n );\n const top = Math.round(\n cfg.cy === undefined ? cornerY - pivotY : cfg.cy - part.h / 2,\n );\n return {\n left,\n top,\n elbow: {\n x: left + g.elbow.x + part.w / 2,\n y: top + part.h / 2 - g.elbow.y,\n },\n elbowRun: g.seamRun[1] - g.seamRun[0],\n };\n}\n\ntype PoseRole = \"forearm_pose_L\" | \"forearm_pose_R\";\n\n/** A pose forearm's geometry on a PNG of the given size, read as the rig\n * reads a layer; an empty one is refused path-qualified. */\nasync function poseGeometryOf(\n role: PoseRole,\n png: Buffer,\n size: { w: number; h: number },\n when: string,\n): Promise<ForearmPoseGeometry> {\n const { data } = await sharp(png)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n const layer = createLayerSetMeasurer({\n width: size.w,\n height: size.h,\n }).add({ role, fileName: \"forearm_pose.png\", rgba: data });\n if (layer === null) {\n throw new AutoRigInputError(\n `layout.${role}: forearm_pose.png is empty after alpha threshold${when}`,\n );\n }\n return forearmPoseGeometry(layer);\n}\n\n/**\n * The width that fits a pose forearm to its arm: the trimmed source scaled\n * so its elbow end's width (2 r_e) equals the arm's elbow run, at least 1.\n */\nexport async function forearmPoseWidth(\n role: PoseRole,\n trimmed: { data: Buffer; w: number; h: number },\n elbowRun: number,\n): Promise<number> {\n const g = await poseGeometryOf(role, trimmed.data, trimmed, \"\");\n return Math.max(1, Math.round((trimmed.w * elbowRun) / (2 * g.radius)));\n}\n\n/**\n * Where a pose forearm's resized part lands: its elbow-end pivot on the\n * arm's placed elbow for each of `cx` / `cy` left unset, centred on a set one\n * as every other role's part is.\n */\nexport async function forearmPosePlacement(\n role: PoseRole,\n cfg: Pick<ArmLayout, \"cx\" | \"cy\">,\n part: { buf: Buffer; w: number; h: number },\n elbow: { x: number; y: number },\n): Promise<{ left: number; top: number }> {\n const { pivot } = await poseGeometryOf(role, part.buf, part, \" once resized\");\n // Model space is centred on the canvas, here the part itself.\n const pivotX = pivot.x + part.w / 2;\n const pivotY = part.h / 2 - pivot.y;\n return {\n left: Math.round(\n cfg.cx === undefined ? elbow.x - pivotX : cfg.cx - part.w / 2,\n ),\n top: Math.round(\n cfg.cy === undefined ? elbow.y - pivotY : cfg.cy - part.h / 2,\n ),\n };\n}\n","/**\n * The text lines `auto_rig_from_layers` prints the turn solve's report-only\n * `hairSide` numbers as, after the `PHYSICS` lines. An agent reads them; none\n * refuses the rig.\n */\n\nimport type { HairSideRoom, TurnSolveReport } from \"@ikijs/editor\";\n\n/** A px figure to one decimal with its sign always shown, `+0.0` included, as\n * the `SWEEP` lines' `signed` does; a negative that rounds to zero is `+0.0`\n * too, never `-0.0`. */\nfunction signedPx(px: number): string {\n const s = px.toFixed(1);\n if (s === \"-0.0\") return \"+0.0\";\n return s.startsWith(\"-\") ? s : `+${s}`;\n}\n\n/**\n * `hairSide` as text lines, none when it is absent (a set with no side lock,\n * whose result text stays as it was). Per side lock, the screen-left one\n * first and labelled by its ROLE — `hair_side_R` hangs on the screen left —\n * one line per metric the report holds: `HAIRSIDE cover <role>`, `HAIRSIDE\n * tail <role>`; for a lock with neither, `HAIRSIDE <role>: no cover or tail\n * row`; for a lock with no `rowRuns`, `HAIRSIDE <role>: unavailable — <why>`.\n * Poses read as the parameter setting that reproduces them; px are model px,\n * and the cover's row is given in model space and as model px from the\n * top of the model's `canvas`, as a `FOLD` line gives its rest point.\n */\nexport function formatHairSideReport(\n hairSide: TurnSolveReport[\"hairSide\"],\n canvas: { width: number; height: number },\n): string[] {\n if (hairSide === undefined) return [];\n return [hairSide.left, hairSide.right].flatMap((room) =>\n room === undefined ? [] : roomLines(room, canvas),\n );\n}\n\nfunction roomLines(\n room: HairSideRoom,\n canvas: { width: number; height: number },\n): string[] {\n const { role, cover, tail, unavailable } = room;\n if (unavailable !== undefined) {\n return [`HAIRSIDE ${role}: unavailable — ${unavailable}`];\n }\n const lines: string[] = [];\n if (cover !== undefined) {\n // A model row's centre is half a px off the integer row it lies on.\n const row = Math.floor(canvas.height / 2 - cover.y);\n lines.push(\n `HAIRSIDE cover ${role}: the lock's outer edge ${signedPx(cover.px)} model px outside the head's edge ` +\n `at ParamAngleX=${cover.deg}, ${signedPx(cover.rest)} at rest (least over the rows it covers at rest, at model y ${cover.y.toFixed(1)}, row ${row} model px from the top; ` +\n `negative: the turn bares cheek the lock hides at rest)`,\n );\n }\n if (tail !== undefined) {\n const lash =\n tail.lashToLock === undefined\n ? \"\"\n : ` / lash ${signedPx(tail.lashToLock)} model px`;\n lines.push(\n `HAIRSIDE tail ${role}: eye ${signedPx(tail.eyeToLock)} model px${lash} from the lock's face-side edge ` +\n `at ParamAngleX=${tail.deg} (negative: under the lock, intended), ` +\n `corner ${signedPx(tail.eyeToPlate)} model px from the head's edge (positive: inside it; negative: past it)`,\n );\n }\n if (lines.length === 0) lines.push(`HAIRSIDE ${role}: no cover or tail row`);\n return lines;\n}\n","/**\n * The text lines `auto_rig_from_layers` and `render_poses` print the engine's\n * `checkPhysics` report as, after the fold report.\n */\n\nimport type { PhysicsReport, PhysicsTarget } from \"@ikijs/engine\";\nimport { foldPose } from \"./fold-report\";\n\n/**\n * `report` as text lines: one `PHYSICS` line per target in the report's\n * order, or `PHYSICS: no rigs`. A line gives the target's kind, its rig (`id`,\n * or `id/segment [inputs]` for a chain segment), `input -> output`, the step's\n * setting with the output's peak, when, its final value and the largest part\n * move with what the output drives, then the idle's peak, when and move, and\n * ` — <why>` when the target is not `ok`.\n */\nexport function formatPhysicsReport(report: PhysicsReport): string[] {\n if (report.targets.length === 0) return [\"PHYSICS: no rigs\"];\n return report.targets.map(targetLine);\n}\n\nfunction targetLine(t: PhysicsTarget): string {\n const inputs = t.input.join(\", \");\n const rig =\n t.rig.kind === \"chain\"\n ? `${t.rig.id}/${t.rig.segment} [${inputs}]`\n : `${t.rig.id} ${inputs}`;\n const drives =\n t.drives.length === 0 ? \"\" : ` (${t.drives.map((d) => d.id).join(\", \")})`;\n const { step, idle } = t;\n return (\n `PHYSICS ${t.kind} ${rig} -> ${t.output}: ` +\n `step ${foldPose(step.values).name} peak ${step.peak.toFixed(2)} at ${step.at.toFixed(2)} s, ` +\n `final ${step.final.toFixed(2)}, moves ${pxText(step.displacementPx)} model px${drives}; ` +\n `idle peak ${idle.peak.toFixed(2)} at ${idle.at.toFixed(2)} s, ${pxText(idle.displacementPx)} model px` +\n (t.why === undefined ? \"\" : ` — ${t.why}`)\n );\n}\n\n/** One decimal, floored as the engine's frozen `why` is, so a frozen 0.96 px\n * never reads `1.0` on its own line. */\nfunction pxText(px: number): string {\n return (Math.floor(px * 10) / 10).toFixed(1);\n}\n","/**\n * `view_illustration_grid`: a picture on the layer canvas as an agent reads\n * coordinates off it — a crop at an integer zoom, nearest-neighbour so the\n * pixels stay readable, with a grid every `step` canvas px labelled along the\n * top and left edges, and optionally landmarks drawn over it.\n *\n * Frame: canvas px of the CANVAS-wide canvas `loadIllustration` produces,\n * origin top-left, x right, y down. A grid line labelled `v` sits on the left\n * (top) edge of canvas pixel `v`; a landmark coordinate `v` names that pixel,\n * so landmarks are drawn through pixel centres, half a pixel past the line.\n * The picture is shown as given, its opaque backdrop included; only real\n * transparency shows the view's own backdrop.\n *\n * Labels are drawn from a small built-in bitmap font rather than SVG text,\n * whose glyphs come from whatever fonts the host has installed: a server in\n * a container without fonts would draw a grid with no numbers on it.\n */\n\nimport sharp from \"sharp\";\nimport { readPictureOnCanvas, type CanvasPicture } from \"./illustration\";\nimport {\n AutoRigInputError,\n resolveOutputPath,\n writeFileAtomic,\n} from \"./limits\";\n\nexport interface GridCrop {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\nexport interface ViewIllustrationGridInput {\n /** The picture (PNG, JPEG or WebP), resolved against cwd. */\n imagePath: string;\n /** A `.png` under the working directory, its folder existing. */\n outputPath: string;\n /** Canvas px; the whole canvas when omitted, clamped to it otherwise. */\n crop?: GridCrop;\n /** Integer 1..8; 1 when omitted. */\n zoom?: number;\n /** Grid spacing in canvas px, an integer of at least 5; 50 when omitted. */\n step?: number;\n /** Drawn generically by shape, each labelled with its key path. */\n landmarks?: Record<string, unknown>;\n}\n\nexport type ViewIllustrationGridResult =\n | {\n ok: true;\n path: string;\n crop: GridCrop;\n zoom: number;\n step: number;\n canvas: { width: number; height: number };\n }\n | { ok: false; error: string };\n\nconst DEFAULT_ZOOM = 1;\nconst MAX_ZOOM = 8;\nconst DEFAULT_STEP = 50;\n/** Under this, labels every step would overrun each other at zoom 1. */\nconst MIN_STEP = 5;\n/** An agent reads the view back as an image; a bigger one is downscaled on\n * the way and its grid stops being legible, long before this. */\nconst MAX_OUTPUT_PIXELS = 4096 * 4096;\n\ntype RGB = [number, number, number];\n/** What a transparent part of the picture shows. A mid green, rare in skin\n * and hair, so the figure's edge reads against it. */\nconst VIEW_BACKDROP: RGB = [64, 160, 96];\nconst GRID_COLOR: RGB = [0, 255, 255];\nconst GRID_OPACITY = 0.45;\nconst LABEL_COLOR: RGB = [255, 255, 0];\n/** Dark enough under a label that its colour reads over light paint. */\nconst LABEL_BOX_OPACITY = 0.8;\n/** The strokes flanking every landmark's line, one either side: whatever\n * the paint under it, one of them stands out, and the line between them\n * keeps its key's colour. */\nconst STROKE_DARK: RGB = [0, 0, 0];\nconst STROKE_LIGHT: RGB = [255, 255, 255];\n/** One colour per top-level landmark key, in order, cycling. */\nconst LANDMARK_COLORS: RGB[] = [\n [255, 64, 64],\n [64, 255, 64],\n [255, 64, 255],\n [255, 160, 0],\n [80, 160, 255],\n [255, 255, 255],\n [160, 96, 255],\n];\n/** Polylines under these keys close back to their first point. */\nconst CLOSED_KEYS = new Set([\"frontHair\", \"skull\", \"polygon\", \"bodyOnly\"]);\n/** So do those at these paths: the side locks' polygons, under `L` and `R`\n * as an eye's or a brow's parts are. */\nconst CLOSED_PATHS = new Set([\"sideHair.L\", \"sideHair.R\"]);\n/** Deeper than any landmark set nests; a cyclic object stops here. */\nconst MAX_DEPTH = 16;\n\n// ---- bitmap font ----\n\n/** Glyphs 5 px wide and 8 tall (row 6 the baseline, row 7 descenders). Each\n * glyph is 8 base-32 digits, one per row, the row's 5 bits leftmost-high. */\nconst FONT_CHARS =\n \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz._[]-?\";\nconst FONT_ROWS =\n \"ehjlphe0 4c4444e0 eh1248v0 v2421he0 26aiv220 vgu11he0 68guhhe0 v1248880 \" +\n \"ehhehhe0 ehhf12c0 ehhvhhh0 uhhuhhu0 ehggghe0 sihhhis0 vgguggv0 vgguggg0 \" +\n \"ehgnhhf0 hhhvhhh0 e44444e0 72222ic0 hikokih0 ggggggv0 hrllhhh0 hhpljhh0 \" +\n \"ehhhhhe0 uhhuggg0 ehhhlid0 uhhukih0 fgge11u0 v4444440 hhhhhhe0 hhhhha40 \" +\n \"hhhllla0 hha4ahh0 hha44440 v1248gv0 00e1fhf0 ggmphhu0 00egghe0 11djhhf0 \" +\n \"00ehvge0 698s8880 00fhhf1e ggmphhh0 40c444e0 206222ic ggikoki0 c44444e0 \" +\n \"00qllhh0 00mphhh0 00ehhhe0 00uhhugg 00fhhf11 00mpggg0 00fge1u0 88s88960 \" +\n \"00hhhjd0 00hhha40 00hhlla0 00ha4ah0 00hhhf1e 00v248v0 00000cc0 0000000v \" +\n \"e88888e0 e22222e0 000v0000 eh124040\";\nconst GLYPH_W = 5;\nconst GLYPH_H = 8;\n/** Each font pixel drawn as a TEXT_SCALE square, so labels survive the\n * downscale an image takes on its way to an agent. */\nconst TEXT_SCALE = 2;\nconst TEXT_PAD = 2;\n\nconst GLYPHS = (() => {\n const rows = FONT_ROWS.split(\" \");\n const map = new Map<string, number[]>();\n [...FONT_CHARS].forEach((ch, i) =>\n map.set(\n ch,\n [...rows[i]].map((d) => parseInt(d, 32)),\n ),\n );\n return map;\n})();\n\n/** A label's size in output px, its padded box included. */\nfunction textSize(text: string): { w: number; h: number } {\n return {\n w: text.length * (GLYPH_W + 1) * TEXT_SCALE - TEXT_SCALE + 2 * TEXT_PAD,\n h: GLYPH_H * TEXT_SCALE + 2 * TEXT_PAD,\n };\n}\n\n// ---- drawing on an RGB buffer ----\n\n/** An RGB view, 3 bytes per pixel. */\nexport interface Image {\n width: number;\n height: number;\n rgb: Buffer;\n}\n\nfunction blend(img: Image, x: number, y: number, c: RGB, a: number): void {\n if (x < 0 || y < 0 || x >= img.width || y >= img.height) return;\n const i = (y * img.width + x) * 3;\n for (let k = 0; k < 3; k++) {\n img.rgb[i + k] = Math.round(img.rgb[i + k] * (1 - a) + c[k] * a);\n }\n}\n\n/** (x, y) in continuous output px: the pixel holding it. */\nfunction plot(img: Image, x: number, y: number, c: RGB): void {\n blend(img, Math.floor(x), Math.floor(y), c, 1);\n}\n\n/** A segment in output px, clipped to the image first (Liang-Barsky), so a\n * landmark far off the crop costs nothing. */\nfunction drawSegment(\n img: Image,\n ax: number,\n ay: number,\n bx: number,\n by: number,\n c: RGB,\n): void {\n const dx = bx - ax;\n const dy = by - ay;\n let t0 = 0;\n let t1 = 1;\n const edges: [number, number][] = [\n [-dx, ax + 1],\n [dx, img.width - ax],\n [-dy, ay + 1],\n [dy, img.height - ay],\n ];\n for (const [p, q] of edges) {\n if (p === 0) {\n if (q < 0) return;\n continue;\n }\n const r = q / p;\n if (p < 0) t0 = Math.max(t0, r);\n else t1 = Math.min(t1, r);\n if (t0 > t1) return;\n }\n const x0 = ax + t0 * dx;\n const y0 = ay + t0 * dy;\n const x1 = ax + t1 * dx;\n const y1 = ay + t1 * dy;\n const n = Math.max(\n 1,\n Math.ceil(Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0))),\n );\n for (let k = 0; k <= n; k++) {\n plot(img, x0 + ((x1 - x0) * k) / n, y0 + ((y1 - y0) * k) / n, c);\n }\n}\n\n/** A landmark's line: its colour between a dark stroke on one side (on\n * the right going from a to b, inside a box drawn clockwise) and a light\n * one on the other, each a px wide. */\nfunction drawStroke(\n img: Image,\n ax: number,\n ay: number,\n bx: number,\n by: number,\n c: RGB,\n): void {\n const len = Math.hypot(bx - ax, by - ay);\n const nx = len > 0 ? Math.round(-(by - ay) / len) : 0;\n const ny = len > 0 ? Math.round((bx - ax) / len) : 1;\n drawSegment(img, ax + nx, ay + ny, bx + nx, by + ny, STROKE_DARK);\n drawSegment(img, ax - nx, ay - ny, bx - nx, by - ny, STROKE_LIGHT);\n drawSegment(img, ax, ay, bx, by, c);\n}\n\nfunction drawText(\n img: Image,\n left: number,\n top: number,\n text: string,\n c: RGB,\n): void {\n const { w, h } = textSize(text);\n for (let y = top; y < top + h; y++) {\n for (let x = left; x < left + w; x++) {\n blend(img, x, y, [0, 0, 0], LABEL_BOX_OPACITY);\n }\n }\n [...text].forEach((ch, k) => {\n const rows = GLYPHS.get(ch) ?? GLYPHS.get(\"?\")!;\n const gx = left + TEXT_PAD + k * (GLYPH_W + 1) * TEXT_SCALE;\n rows.forEach((bits, row) => {\n for (let col = 0; col < GLYPH_W; col++) {\n if (!(bits & (1 << (GLYPH_W - 1 - col)))) continue;\n for (let sy = 0; sy < TEXT_SCALE; sy++) {\n for (let sx = 0; sx < TEXT_SCALE; sx++) {\n blend(\n img,\n gx + col * TEXT_SCALE + sx,\n top + TEXT_PAD + row * TEXT_SCALE + sy,\n c,\n 1,\n );\n }\n }\n }\n });\n });\n}\n\n/** Output-px bounds `[x0, y0, x1, y1]` of a drawn shape. */\ntype Bounds = [number, number, number, number];\n\nfunction boundsOf(xs: number[], ys: number[]): Bounds {\n return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)];\n}\n\n/** A label near (x, y), moved inside the image, for a shape any of which is\n * in view; none for a shape wholly off it. */\nfunction drawLabel(\n img: Image,\n shape: Bounds,\n x: number,\n y: number,\n text: string,\n c: RGB,\n) {\n const [x0, y0, x1, y1] = shape;\n if (x1 < 0 || y1 < 0 || x0 >= img.width || y0 >= img.height) return;\n const { w, h } = textSize(text);\n const left = Math.max(0, Math.min(img.width - w, Math.round(x)));\n const top = Math.max(0, Math.min(img.height - h, Math.round(y)));\n drawText(img, left, top, text, c);\n}\n\n// ---- landmarks ----\n\ntype Shape =\n | { kind: \"box\"; box: number[] }\n | { kind: \"ellipse\"; cx: number; cy: number; rx: number; ry: number }\n | { kind: \"line\"; points: number[][]; closed: boolean }\n | { kind: \"points\"; points: number[][] };\n\ninterface LabelledShape {\n label: string;\n color: RGB;\n shape: Shape;\n}\n\nconst isNum = (v: unknown): v is number =>\n typeof v === \"number\" && Number.isFinite(v);\nconst isPair = (v: unknown): v is [number, number] =>\n Array.isArray(v) && v.length === 2 && v.every(isNum);\n\n/**\n * Every shape the landmarks hold, by shape alone: a 4-number array is a box,\n * `{ cx, cy, rx, ry }` an ellipse, a list of `[x, y]` a polyline (closed\n * under CLOSED_KEYS and at CLOSED_PATHS), points under a key ending in `Seeds` or anywhere under\n * `samples` markers, a lone `[x, y]` a marker. Anything else is walked into,\n * or skipped.\n */\nfunction collectShapes(landmarks: Record<string, unknown>): LabelledShape[] {\n const out: LabelledShape[] = [];\n const walk = (\n v: unknown,\n path: string,\n key: string,\n inSamples: boolean,\n color: RGB,\n depth: number,\n ): void => {\n if (depth > MAX_DEPTH) return;\n const add = (shape: Shape): void => {\n out.push({ label: path, color, shape });\n };\n if (isPair(v)) return add({ kind: \"points\", points: [v] });\n if (Array.isArray(v) && v.length === 4 && v.every(isNum)) {\n return add({ kind: \"box\", box: v });\n }\n if (Array.isArray(v) && v.length > 0 && v.every(isPair)) {\n if (inSamples || key.endsWith(\"Seeds\")) {\n return add({ kind: \"points\", points: v });\n }\n if (v.length < 2) return;\n return add({\n kind: \"line\",\n points: v,\n closed: CLOSED_KEYS.has(key) || CLOSED_PATHS.has(path),\n });\n }\n if (Array.isArray(v)) {\n v.forEach((item, i) =>\n walk(item, `${path}[${i}]`, key, inSamples, color, depth + 1),\n );\n return;\n }\n if (typeof v !== \"object\" || v === null) return;\n const o = v as Record<string, unknown>;\n if (isNum(o.cx) && isNum(o.cy) && isNum(o.rx) && isNum(o.ry)) {\n return add({ kind: \"ellipse\", cx: o.cx, cy: o.cy, rx: o.rx, ry: o.ry });\n }\n for (const [k, child] of Object.entries(o)) {\n walk(\n child,\n `${path}.${k}`,\n k,\n inSamples || k === \"samples\",\n color,\n depth + 1,\n );\n }\n };\n Object.entries(landmarks).forEach(([k, v], i) =>\n walk(\n v,\n k,\n k,\n k === \"samples\",\n LANDMARK_COLORS[i % LANDMARK_COLORS.length],\n 0,\n ),\n );\n return out;\n}\n\n/** Marker half-size in output px. */\nconst MARKER = 3;\n\nfunction drawShapes(\n img: Image,\n shapes: LabelledShape[],\n toX: (x: number) => number,\n toY: (y: number) => number,\n zoom: number,\n): void {\n const labels: [Bounds, number, number, string, RGB][] = [];\n for (const { label, color, shape } of shapes) {\n if (shape.kind === \"box\") {\n const [x0, y0, x1, y1] = shape.box.map((v, k) =>\n k % 2 === 0 ? toX(v) : toY(v),\n );\n drawStroke(img, x0, y0, x1, y0, color);\n drawStroke(img, x1, y0, x1, y1, color);\n drawStroke(img, x1, y1, x0, y1, color);\n drawStroke(img, x0, y1, x0, y0, color);\n const at = boundsOf([x0, x1], [y0, y1]);\n labels.push([at, at[0], at[1] - textSize(label).h, label, color]);\n } else if (shape.kind === \"ellipse\") {\n const { cx, cy, rx, ry } = shape;\n // Enough sides that each is a few output px, bounded either way.\n const n = Math.min(\n 1024,\n Math.max(16, Math.ceil((Math.PI * 2 * Math.max(rx, ry) * zoom) / 4)),\n );\n for (let k = 0; k < n; k++) {\n const a = (Math.PI * 2 * k) / n;\n const b = (Math.PI * 2 * (k + 1)) / n;\n drawStroke(\n img,\n toX(cx + rx * Math.cos(a)),\n toY(cy + ry * Math.sin(a)),\n toX(cx + rx * Math.cos(b)),\n toY(cy + ry * Math.sin(b)),\n color,\n );\n }\n const at = boundsOf(\n [toX(cx - rx), toX(cx + rx)],\n [toY(cy - ry), toY(cy + ry)],\n );\n labels.push([at, at[2] + 2, at[1], label, color]);\n } else if (shape.kind === \"line\") {\n const pts = shape.points;\n const last = shape.closed ? pts.length : pts.length - 1;\n for (let k = 0; k < last; k++) {\n const [ax, ay] = pts[k];\n const [bx, by] = pts[(k + 1) % pts.length];\n drawStroke(img, toX(ax), toY(ay), toX(bx), toY(by), color);\n }\n const at = boundsOf(\n pts.map((p) => toX(p[0])),\n pts.map((p) => toY(p[1])),\n );\n labels.push([at, toX(pts[0][0]) + 2, toY(pts[0][1]) + 2, label, color]);\n } else {\n shape.points.forEach(([px, py], k) => {\n const x = Math.floor(toX(px));\n const y = Math.floor(toY(py));\n drawStroke(img, x - MARKER, y, x + MARKER, y, color);\n drawStroke(img, x, y - MARKER, x, y + MARKER, color);\n const text = shape.points.length > 1 ? `${label}[${k}]` : label;\n const at: Bounds = [x - MARKER, y - MARKER, x + MARKER, y + MARKER];\n labels.push([at, x + MARKER + 2, y + MARKER + 2, text, color]);\n });\n }\n }\n // After every shape, so no outline is drawn over a label.\n for (const [at, x, y, text, color] of labels) {\n drawLabel(img, at, x, y, text, color);\n }\n}\n\n// ---- the tool ----\n\n/** The crop of the picture at an integer zoom, nearest-neighbour, its real\n * transparency shown over VIEW_BACKDROP. */\nexport function pictureView(\n pic: CanvasPicture,\n crop: GridCrop,\n zoom: number,\n): Image {\n const ow = crop.w * zoom;\n const oh = crop.h * zoom;\n const img: Image = { width: ow, height: oh, rgb: Buffer.alloc(ow * oh * 3) };\n for (let oy = 0; oy < oh; oy++) {\n const sy = crop.y + Math.floor(oy / zoom);\n for (let ox = 0; ox < ow; ox++) {\n const s = (sy * pic.width + crop.x + Math.floor(ox / zoom)) * 4;\n const a = pic.rgba[s + 3] / 255;\n const o = (oy * ow + ox) * 3;\n for (let c = 0; c < 3; c++) {\n img.rgb[o + c] = Math.round(\n pic.rgba[s + c] * a + VIEW_BACKDROP[c] * (1 - a),\n );\n }\n }\n }\n return img;\n}\n\n/** Draw `landmarks` over a view of `crop` at `zoom`, each shape labelled\n * with its key path. A landmark names a pixel: drawn through its centre. */\nexport function drawLandmarks(\n img: Image,\n landmarks: Record<string, unknown>,\n crop: GridCrop,\n zoom: number,\n): void {\n const centreX = (x: number) => (x + 0.5 - crop.x) * zoom;\n const centreY = (y: number) => (y + 0.5 - crop.y) * zoom;\n drawShapes(img, collectShapes(landmarks), centreX, centreY, zoom);\n}\n\nfunction checkInt(\n value: number,\n name: string,\n min: number,\n max: number,\n): number {\n if (!Number.isInteger(value) || value < min || value > max) {\n throw new AutoRigInputError(\n `${name} must be an integer ${max === Infinity ? `of at least ${min}` : `in ${min}..${max}`}, not ${value}`,\n );\n }\n return value;\n}\n\n/** The crop's pixel rectangle on the canvas: grown out to whole pixels and\n * clamped to the canvas. */\nfunction clampCrop(\n crop: GridCrop | undefined,\n width: number,\n height: number,\n): GridCrop {\n if (crop === undefined) return { x: 0, y: 0, w: width, h: height };\n for (const k of [\"x\", \"y\", \"w\", \"h\"] as const) {\n if (!isNum(crop[k])) {\n throw new AutoRigInputError(`crop.${k} must be a finite number`);\n }\n }\n if (crop.w <= 0 || crop.h <= 0) {\n throw new AutoRigInputError(\n `crop must have a positive size, not ${crop.w}x${crop.h}`,\n );\n }\n const x0 = Math.max(0, Math.floor(crop.x));\n const y0 = Math.max(0, Math.floor(crop.y));\n const x1 = Math.min(width, Math.ceil(crop.x + crop.w));\n const y1 = Math.min(height, Math.ceil(crop.y + crop.h));\n if (x1 <= x0 || y1 <= y0) {\n throw new AutoRigInputError(\n `crop { x: ${crop.x}, y: ${crop.y}, w: ${crop.w}, h: ${crop.h} } misses the ${width}x${height} canvas`,\n );\n }\n return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };\n}\n\n/**\n * Write the gridded view. Only caller-input failures (`AutoRigInputError`)\n * come back as `{ ok: false, error }`; any refusal writes nothing.\n */\nexport async function viewIllustrationGrid(\n input: ViewIllustrationGridInput,\n): Promise<ViewIllustrationGridResult> {\n try {\n // First, so a refused path costs no decode.\n const outFile = resolveOutputPath(input.outputPath, \".png\");\n const zoom = checkInt(input.zoom ?? DEFAULT_ZOOM, \"zoom\", 1, MAX_ZOOM);\n const step = checkInt(\n input.step ?? DEFAULT_STEP,\n \"step\",\n MIN_STEP,\n Infinity,\n );\n const landmarks = input.landmarks;\n if (\n landmarks !== undefined &&\n (typeof landmarks !== \"object\" ||\n landmarks === null ||\n Array.isArray(landmarks))\n ) {\n throw new AutoRigInputError(\"landmarks must be an object\");\n }\n\n const pic = await readPictureOnCanvas(input.imagePath);\n const crop = clampCrop(input.crop, pic.width, pic.height);\n const ow = crop.w * zoom;\n const oh = crop.h * zoom;\n if (ow * oh > MAX_OUTPUT_PIXELS) {\n throw new AutoRigInputError(\n `the view would be ${ow}x${oh} = ${ow * oh} px, over ${MAX_OUTPUT_PIXELS}; take a smaller crop or zoom`,\n );\n }\n\n const img = pictureView(pic, crop, zoom);\n\n const toX = (x: number) => (x - crop.x) * zoom;\n const toY = (y: number) => (y - crop.y) * zoom;\n const first = (from: number) => Math.ceil(from / step) * step;\n const columns: number[] = [];\n const rows: number[] = [];\n for (let gx = first(crop.x); gx < crop.x + crop.w; gx += step)\n columns.push(gx);\n for (let gy = first(crop.y); gy < crop.y + crop.h; gy += step)\n rows.push(gy);\n for (const gx of columns) {\n for (let y = 0; y < oh; y++)\n blend(img, toX(gx), y, GRID_COLOR, GRID_OPACITY);\n }\n for (const gy of rows) {\n for (let x = 0; x < ow; x++)\n blend(img, x, toY(gy), GRID_COLOR, GRID_OPACITY);\n }\n\n if (landmarks !== undefined) drawLandmarks(img, landmarks, crop, zoom);\n\n // Last, so the coordinates stay readable over everything. A label that\n // would overrun the one before it is left out (their boxes may touch: the\n // padding keeps them apart); the left column starts under the top row's.\n const band = textSize(\"0\").h;\n let nextFree = 0;\n for (const gx of columns) {\n const x = toX(gx) + 2;\n if (x < nextFree) continue;\n drawText(img, x, 0, String(gx), LABEL_COLOR);\n nextFree = x + textSize(String(gx)).w;\n }\n nextFree = band + 2;\n for (const gy of rows) {\n const y = toY(gy) + 2;\n if (y < nextFree) continue;\n drawText(img, 0, y, String(gy), LABEL_COLOR);\n nextFree = y + band;\n }\n\n const png = await sharp(img.rgb, {\n raw: { width: ow, height: oh, channels: 3 },\n })\n .png()\n .toBuffer();\n writeFileAtomic(outFile, png);\n return {\n ok: true,\n path: outFile,\n crop,\n zoom,\n step,\n canvas: { width: pic.width, height: pic.height },\n };\n } catch (e) {\n if (e instanceof AutoRigInputError) return { ok: false, error: e.message };\n throw e;\n }\n}\n","/**\n * One finished character picture on the layer canvas, and the raster helpers\n * an in-place cut of it is built from.\n *\n * Frame: canvas px, origin top-left, x right, y down, CANVAS wide and as tall\n * as the picture's aspect gives — the frame of the layer PNGs the cut writes,\n * so a landmark read off `view_illustration_grid` lands on the same pixel here.\n *\n * Masks are one byte per canvas pixel, row-major, 1 on and 0 off. A point\n * `[x, y]` names the pixel at column x, row y.\n */\n\nimport sharp from \"sharp\";\nimport { CANVAS } from \"./compose\";\nimport {\n AutoRigInputError,\n MAX_CANVAS_DIM,\n MAX_INPUT_PIXELS,\n resolveInputPath,\n} from \"./limits\";\n\nexport type Point = [number, number];\n/** `[x0, y0, x1, y1]`, both corners inside: columns x0..x1, rows y0..y1. */\nexport type Box = [number, number, number, number];\nexport type Mask = Uint8Array;\n\n/** What every helper needs to index a canvas-sized buffer. */\nexport interface CanvasSize {\n width: number;\n height: number;\n}\n\nexport interface Illustration extends CanvasSize {\n /** The paint's own colour, 3 floats per pixel in 0..255: a soft edge's\n * colour with the backdrop taken back out of it. */\n rgb: Float32Array;\n /** Coverage, 0..1 per pixel. */\n alpha: Float32Array;\n /** `transparent`: the file's own alpha. `flat`: an opaque picture whose\n * backdrop colour was keyed out. */\n background: \"transparent\" | \"flat\";\n /** The keyed backdrop colour, on a `flat` picture. */\n backdrop?: [number, number, number];\n}\n\n/** The picture scaled onto the canvas, straight-alpha RGBA bytes. */\nexport interface CanvasPicture extends CanvasSize {\n rgba: Buffer;\n /** The same picture upright at its own size, straight-alpha RGBA bytes:\n * what a flat backdrop is keyed on, before the resize spreads its edges. */\n source: CanvasSize & { rgba: Buffer };\n}\n\nexport interface LoadIllustrationOptions {\n /** Points on backdrop the figure encloses (a gap between an arm and the\n * body), each keyed like the backdrop around the figure. Used on a picture\n * with a flat backdrop only. */\n backgroundSeeds?: Point[];\n}\n\n/** Formats a finished picture comes in; anything else sharp could open\n * (an SVG that might pull in other files, a PDF) is refused. */\nconst PICTURE_FORMATS = new Set([\"png\", \"jpeg\", \"webp\"]);\n\n/**\n * Decode `imagePath`, turn it upright by its EXIF orientation and scale it to\n * CANVAS wide (Lanczos), its height by the picture's aspect, keeping the\n * upright picture at its own size beside it. Refuses a missing file, another\n * format, a picture over MAX_INPUT_PIXELS and one whose canvas would be over\n * MAX_CANVAS_DIM tall.\n */\nexport async function readPictureOnCanvas(\n imagePath: string,\n): Promise<CanvasPicture> {\n const file = resolveInputPath(imagePath, \"picture\");\n let meta: sharp.Metadata;\n try {\n meta = await sharp(file).metadata();\n } catch (e) {\n throw new AutoRigInputError(\n `failed to read picture ${file}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n if (!PICTURE_FORMATS.has(meta.format ?? \"\")) {\n throw new AutoRigInputError(\n `picture must be a PNG, JPEG or WebP, not ${meta.format ?? \"unknown\"}: ${file}`,\n );\n }\n // EXIF orientations 5 to 8 turn the picture a quarter: its upright width is\n // the stored height.\n const quarter = (meta.orientation ?? 1) >= 5;\n const w = (quarter ? meta.height : meta.width) ?? 0;\n const h = (quarter ? meta.width : meta.height) ?? 0;\n if (w * h > MAX_INPUT_PIXELS) {\n throw new AutoRigInputError(\n `picture is ${w}x${h} = ${w * h} px, over the ${MAX_INPUT_PIXELS} px limit: ${file}`,\n );\n }\n const height = Math.max(1, Math.round((h * CANVAS) / w));\n if (height > MAX_CANVAS_DIM) {\n throw new AutoRigInputError(\n `picture is ${w}x${h}; at ${CANVAS} px wide its canvas would be ${height} px tall, over ${MAX_CANVAS_DIM}: ${file}`,\n );\n }\n let source: CanvasPicture[\"source\"];\n try {\n const { data, info } = await sharp(file, {\n limitInputPixels: MAX_INPUT_PIXELS,\n })\n .rotate()\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n source = { width: info.width, height: info.height, rgba: data };\n } catch (e) {\n throw new AutoRigInputError(\n `failed to decode picture ${file}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n const rgba = await toCanvas(source, height);\n return { width: CANVAS, height, rgba, source };\n}\n\n/** Straight-alpha RGBA bytes scaled to CANVAS x `height` (Lanczos3, which\n * sharp runs on premultiplied colour, so clear pixels lend none). */\nasync function toCanvas(\n { width, height: h, rgba }: CanvasPicture[\"source\"],\n height: number,\n): Promise<Buffer> {\n return sharp(rgba, { raw: { width, height: h, channels: 4 } })\n .resize(CANVAS, height, { fit: \"fill\", kernel: \"lanczos3\" })\n .raw()\n .toBuffer();\n}\n\n/** A picture with at least this share of its pixels under half alpha has\n * real transparency and keeps it; below it (a stray clear speck on an opaque\n * picture) the backdrop is keyed. */\nconst TRANSPARENT_SHARE = 0.005;\n/** How deep into the picture the border ring reaches, px. */\nconst RING = 4;\n/** Euclidean RGB distance a ring pixel may sit from the backdrop's colour and\n * still be the backdrop: a JPEG's noise of a few levels per channel. */\nconst FLAT_TOLERANCE = 12;\n/** Share of the border ring that must be the backdrop. The figure may cross\n * the frame (a bust's chest, long hair), but a two-colour or gradient\n * background leaves no one colour on most of the ring. */\nconst MIN_BACKDROP_SHARE = 0.6;\n/** Euclidean RGB distance from the backdrop under which backdrop beside\n * paint that mixes with no one paint is no paint at all: the noise floor,\n * keyed to alpha 0. Without it a JPEG's noise beside the figure would key\n * as faint specks of paint. */\nconst KEY_T0 = 14;\n/** Euclidean RGB distance a pixel may sit off the line from the backdrop to\n * a paint beside it and still be a mix of the two, at its share `t` of that\n * paint: ROUNDING + MIX_TOLERANCE * t. Over the pixel's own rounding and a\n * flat paint's grain at its share; under what a sliver of a second paint\n * moves it: looser, an outline's inner px (a tenth pale beside the ink)\n * reads as ink with the backdrop showing through, and a thin line on a\n * mid-tone ground comes out partly clear. */\nconst MIX_TOLERANCE = 4;\n/** A PNG's rounding of a pixel, under one level per channel: tighter, the\n * faint outer px of an antialiased edge (whose share is too small for\n * MIX_TOLERANCE to cover it) mixes with nothing. */\nconst ROUNDING = 1;\n/** The key floods the backdrop only through pixels under this distance, and\n * paint at or past it is what a soft edge is measured against. Worked on\n * the picture the in-place cut was first tried on; flooding further runs\n * into pale paint with no outline (a peach disc on white) and keys all of\n * it partly clear. */\nconst KEY_FLOOD = 32;\n/** Picture px a soft edge may take to climb from the backdrop to its paint:\n * an antialiased edge takes one, a soft-shaded lineless edge about six. A\n * wider ramp keys partly as paint (its outer px measured against its\n * middle), and backdrop further than this from paint is clear however far\n * its colour drifts (a gradient, a soft shadow). */\nconst RAMP = 6;\n/** How much further toward its paint (Euclidean RGB, along the line from\n * the backdrop) a pixel beside a step of a ramp, and no nearer the\n * backdrop, must lie for the ramp to go on climbing: over a PNG's\n * rounding, under one step of a soft edge. A pixel with no such neighbour\n * is the paint the ramp ends on, opaque. Without it the rim of a flat\n * region beside a darker paint of its own hue (black hair beside its\n * shadow) reads as a step toward that paint and comes out partly clear. */\nconst CLIMB = 3;\n/** Below this alpha a pixel takes the colour the resize carried from the\n * keyed picture rather than its own with the backdrop taken out: dividing\n * by a near zero alpha amplifies noise into colours the paint never had. */\nconst DECONTAM_MIN_ALPHA = 0.05;\n\n/** The pixel indices of the ring RING px in from every edge. */\nfunction borderRing({ width, height }: CanvasSize): number[] {\n const out: number[] = [];\n for (let y = 0; y < height; y++) {\n const edgeRow = y < RING || y >= height - RING;\n for (let x = 0; x < width; x++) {\n if (edgeRow || x < RING || x >= width - RING) out.push(y * width + x);\n }\n }\n return out;\n}\n\n/** The median of `values` (the upper one of an even count). */\nexport function median(values: number[]): number {\n const s = [...values].sort((a, b) => a - b);\n return s[s.length >> 1];\n}\n\n/**\n * Load a picture onto the canvas with its background matted out. A picture\n * with real transparency keeps its own alpha. An opaque one must stand on one\n * flat colour, measured on the canvas's border ring (a ring that is not is\n * refused, naming what it measured), and is keyed at its own size, before\n * the resize: there an edge is at most a few px of mix between the backdrop\n * and one paint, and the resize then spreads the keyed alpha exactly as it\n * spread the drawn edge, its overshoot past the edge clipped to clear (see\n * {@link keySource}). The backdrop is what a flood from the border (and from\n * each of `backgroundSeeds`) reaches through pixels near its colour, so paint\n * of the backdrop's colour inside the figure (white eyes on a white ground)\n * stays. The backdrop is taken back out of each soft pixel's colour\n * (`F = (C - (1 - a) B) / a`), so the keyed picture over its backdrop gives\n * the picture back.\n */\nexport async function loadIllustration(\n imagePath: string,\n options: LoadIllustrationOptions = {},\n): Promise<Illustration> {\n return matteIllustration(await readPictureOnCanvas(imagePath), options);\n}\n\n/** {@link loadIllustration} on a picture already on the canvas. */\nexport async function matteIllustration(\n pic: CanvasPicture,\n options: LoadIllustrationOptions = {},\n): Promise<Illustration> {\n const { width, height, rgba, source } = pic;\n const n = width * height;\n const rgb = new Float32Array(n * 3);\n const srcAlpha = new Float32Array(n);\n let clear = 0;\n for (let i = 0; i < n; i++) {\n for (let c = 0; c < 3; c++) rgb[i * 3 + c] = rgba[i * 4 + c];\n srcAlpha[i] = rgba[i * 4 + 3] / 255;\n if (srcAlpha[i] < 0.5) clear++;\n }\n if (clear / n >= TRANSPARENT_SHARE) {\n return { width, height, rgb, alpha: srcAlpha, background: \"transparent\" };\n }\n\n const ring = borderRing(pic);\n const opaqueRing = ring.filter((i) => srcAlpha[i] >= 0.5);\n const backdrop = [0, 1, 2].map((c) =>\n median(opaqueRing.map((i) => rgb[i * 3 + c])),\n ) as [number, number, number];\n const flatShare =\n opaqueRing.filter((i) => offBackdrop(rgba, i, backdrop) <= FLAT_TOLERANCE)\n .length / ring.length;\n if (flatShare < MIN_BACKDROP_SHARE) {\n throw new AutoRigInputError(\n `picture's backdrop is not one flat colour: ${Math.round(flatShare * 100)}% of its ${RING} px border ring is within ${FLAT_TOLERANCE} of its median colour rgb(${backdrop.map(Math.round).join(\", \")}), and at least ${MIN_BACKDROP_SHARE * 100}% must be; give the picture on one flat colour or with a transparent background`,\n );\n }\n\n // Each seed starts the flood at the picture pixel under its canvas pixel.\n const seeds = (options.backgroundSeeds ?? []).map(([sx, sy], k) => {\n const x = Math.round(sx);\n const y = Math.round(sy);\n if (!(x >= 0 && y >= 0 && x < width && y < height)) {\n throw new AutoRigInputError(\n `backgroundSeeds[${k}] (${sx}, ${sy}) is off the ${width}x${height} canvas`,\n );\n }\n const { i, dist, ok } = backdropSeed(pic, backdrop, x, y);\n if (!ok) {\n throw new AutoRigInputError(\n `backgroundSeeds[${k}] (${sx}, ${sy}) is on paint, not backdrop: its colour is ${Math.round(dist)} from the backdrop rgb(${backdrop.map(Math.round).join(\", \")}), and a seed must be under ${KEY_FLOOD}`,\n );\n }\n return i;\n });\n\n const keyed = await toCanvas(\n { ...source, rgba: keySource(source, backdrop, seeds) },\n height,\n );\n const alpha = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const a = keyed[i * 4 + 3] / 255;\n alpha[i] = a;\n // Clear (the backdrop) keeps its own colour; opaque is the picture's.\n if (a === 0 || a === 1) continue;\n for (let c = 0; c < 3; c++) {\n rgb[i * 3 + c] =\n a > DECONTAM_MIN_ALPHA\n ? Math.max(\n 0,\n Math.min(255, (rgb[i * 3 + c] - (1 - a) * backdrop[c]) / a),\n )\n : keyed[i * 4 + c];\n }\n }\n return { width, height, rgb, alpha, background: \"flat\", backdrop };\n}\n\n/**\n * The rule a `backgroundSeeds` point is held to, at canvas pixel (x, y),\n * integers on the canvas: the picture pixel under it at the picture's own\n * size (`i`, where it starts the key's flood) must be under KEY_FLOOD from\n * the backdrop (`dist`), or under half alpha.\n */\nexport function backdropSeed(\n { width, height, source }: CanvasPicture,\n backdrop: readonly number[],\n x: number,\n y: number,\n): { i: number; dist: number; ok: boolean } {\n const px = Math.min(\n source.width - 1,\n Math.floor(((x + 0.5) * source.width) / width),\n );\n const py = Math.min(\n source.height - 1,\n Math.floor(((y + 0.5) * source.height) / height),\n );\n const i = py * source.width + px;\n const dist = offBackdrop(source.rgba, i, backdrop);\n return { i, dist, ok: dist < KEY_FLOOD || source.rgba[i * 4 + 3] < 128 };\n}\n\n/** Fill `out` with the in-picture 8-neighbours of pixel `i`; how many. */\nfunction neighbours8(\n { width, height }: CanvasSize,\n i: number,\n out: Int32Array,\n): number {\n const x = i % width;\n const y = (i - x) / width;\n let k = 0;\n for (let dy = -1; dy <= 1; dy++) {\n if (y + dy < 0 || y + dy >= height) continue;\n for (let dx = -1; dx <= 1; dx++) {\n if ((dx || dy) && x + dx >= 0 && x + dx < width) {\n out[k++] = i + dy * width + dx;\n }\n }\n }\n return k;\n}\n\n/** Euclidean RGB distance of RGBA pixel `i` from `backdrop`. */\nfunction offBackdrop(\n rgba: Uint8Array,\n i: number,\n backdrop: readonly number[],\n): number {\n return Math.hypot(\n rgba[i * 4] - backdrop[0],\n rgba[i * 4 + 1] - backdrop[1],\n rgba[i * 4 + 2] - backdrop[2],\n );\n}\n\n/**\n * Key `backdrop` out of the picture at its own size: straight-alpha RGBA\n * bytes, the paint's colour with the backdrop taken out.\n *\n * Keyed here, before the resize, an edge is a step from the backdrop to one\n * paint over at most a few px, and nothing rings past it; the resize then\n * spreads the keyed alpha as it spread the edge, and clips its overshoot\n * past the edge to clear. (Keyed after the resize, that overshoot lies on\n * the far side of the backdrop from the paint, and a rule that keeps a dark\n * line beside pale paint on a mid-tone ground opaque cannot also key it\n * clear: the line lies on that far side too.)\n *\n * The rule: the flood's backdrop is clear and the rest is opaque paint,\n * except a pixel that is a step of a ramp from the backdrop to a paint\n * further in, which takes its share of the way. A pixel is a mix with the\n * share `t` of paint Q (a pixel within RAMP px) when it lies on the line from\n * the backdrop to Q, at `t` along it (see MIX_TOLERANCE); of the paints it\n * mixes with, the one furthest out gives its share (on a soft-shaded edge\n * that is the flat paint the ramp ends on, not the next step of the ramp).\n * On the paint side it must also be a step: a neighbour nearer the backdrop\n * is backdrop or a lesser step toward the same paint (so paint behind an\n * opaque line, or across the inner edge of a thin one, is not measured\n * against it), and one no nearer climbs on toward that paint (so the rim of\n * a flat region is not, see CLIMB). Backdrop off its colour beside paint\n * that mixes with no one paint (two paints and the backdrop in one px) takes\n * the least alpha that keeps its paint inside 0..255, so it still stacks\n * back.\n */\nfunction keySource(\n src: CanvasPicture[\"source\"],\n backdrop: readonly number[],\n seeds: number[],\n): Buffer {\n const { width: w, height: h, rgba } = src;\n const n = w * h;\n const d = new Float32Array(n * 3);\n const dist = new Float32Array(n);\n const soft = new Uint8Array(n);\n for (let i = 0; i < n; i++) {\n for (let c = 0; c < 3; c++) d[i * 3 + c] = rgba[i * 4 + c] - backdrop[c];\n dist[i] = offBackdrop(rgba, i, backdrop);\n soft[i] = dist[i] < KEY_FLOOD || rgba[i * 4 + 3] < 128 ? 1 : 0;\n }\n const reached = floodFromIndices(src, soft, [...borderRing(src), ...seeds]);\n\n // Steps from the backdrop into the paint, 8-connected (a diagonal edge's\n // ramp is as many steps deep as a straight one's), out to RAMP + 1; the\n // queue holds every pixel it numbered, nearest the backdrop first.\n const FAR = 255;\n const nb = new Int32Array(8);\n const depth = new Uint8Array(n).fill(FAR);\n const queue = new Int32Array(n);\n let tail = 0;\n for (let i = 0; i < n; i++) {\n if (reached[i]) {\n depth[i] = 0;\n queue[tail++] = i;\n }\n }\n for (let head = 0; head < tail; head++) {\n const i = queue[head];\n if (depth[i] > RAMP) continue;\n for (let k = neighbours8(src, i, nb) - 1; k >= 0; k--) {\n const j = nb[k];\n if (depth[j] === FAR) {\n depth[j] = depth[i] + 1;\n queue[tail++] = j;\n }\n }\n }\n\n /** Pixel `i`'s share of the way from the backdrop to the colour of\n * pixel `p`, when it is a mix of the two: taking the backdrop back out\n * at that share leaves it within ROUNDING + MIX_TOLERANCE * share of the\n * line to `p`. NaN when it is not, or the share is not above 0. */\n const shareOf = (i: number, p: number): number => {\n const d0 = d[i * 3];\n const d1 = d[i * 3 + 1];\n const d2 = d[i * 3 + 2];\n const q0 = d[p * 3];\n const q1 = d[p * 3 + 1];\n const q2 = d[p * 3 + 2];\n const t = (d0 * q0 + d1 * q1 + d2 * q2) / (dist[p] * dist[p]);\n if (!(t > 0)) return NaN;\n const r = (d0 - t * q0) ** 2 + (d1 - t * q1) ** 2 + (d2 - t * q2) ** 2;\n return r <= (ROUNDING + MIX_TOLERANCE * t) ** 2 ? t : NaN;\n };\n /** The paint pixel the last `mixShare` found. */\n let mixPaint = -1;\n /** The least share pixel `i` is a mix at with paint within RAMP px (the\n * paint furthest out it mixes with), under `upTo`; `upTo` if none. */\n const mixShare = (i: number, upTo: number): number => {\n const x = i % w;\n const y = (i - x) / w;\n let best = upTo;\n for (\n let yy = Math.max(0, y - RAMP);\n yy <= Math.min(h - 1, y + RAMP);\n yy++\n ) {\n for (\n let xx = Math.max(0, x - RAMP);\n xx <= Math.min(w - 1, x + RAMP);\n xx++\n ) {\n const p = yy * w + xx;\n if (reached[p] || dist[p] < KEY_FLOOD) continue;\n const t = shareOf(i, p);\n if (t < best) {\n best = t;\n mixPaint = p;\n }\n }\n }\n return best;\n };\n\n const alpha = new Float32Array(n);\n const paintNear = dilate(src, invert(reached), RAMP);\n for (let i = 0; i < n; i++) {\n if (!reached[i]) {\n alpha[i] = 1;\n } else if (paintNear[i]) {\n // Backdrop beside paint: the paint's soft edge where it mixes with it,\n // however faint (the outer step of a pale ramp is under the noise\n // floor); past the noise floor and mixing with no one paint, the\n // least alpha that holds it.\n let a = mixShare(i, Infinity);\n if (a === Infinity) {\n a = 0;\n if (dist[i] < KEY_T0) continue;\n for (let c = 0; c < 3; c++) {\n const dc = d[i * 3 + c];\n const room = dc > 0 ? 255 - backdrop[c] : backdrop[c];\n a = Math.max(a, Math.abs(dc) / Math.max(room, 1));\n }\n }\n alpha[i] = a;\n }\n }\n for (let k = 0; k < tail; k++) {\n const i = queue[k];\n const step = depth[i];\n if (step === 0 || step > RAMP) continue;\n const around = neighbours8(src, i, nb);\n // Only beside backdrop or a step of a ramp: cheap, before the search.\n let nearer = false;\n for (let m = 0; m < around; m++) {\n if (depth[nb[m]] < step && alpha[nb[m]] < 1) nearer = true;\n }\n if (!nearer) continue;\n const a = mixShare(i, 1);\n if (!(a < 1)) continue;\n const p = mixPaint;\n // The pixel nearer the backdrop is backdrop, or a lesser step toward\n // the same paint; one further in climbs further toward it.\n let chained = false;\n let climbs = false;\n for (let m = 0; m < around; m++) {\n const j = nb[m];\n if (depth[j] < step) {\n chained ||= depth[j] === 0 || (alpha[j] < 1 && shareOf(j, p) < a);\n } else {\n const climb =\n ((d[j * 3] - d[i * 3]) * d[p * 3] +\n (d[j * 3 + 1] - d[i * 3 + 1]) * d[p * 3 + 1] +\n (d[j * 3 + 2] - d[i * 3 + 2]) * d[p * 3 + 2]) /\n dist[p];\n climbs ||= climb > CLIMB;\n }\n }\n if (chained && climbs) alpha[i] = a;\n }\n\n const out = Buffer.alloc(n * 4);\n for (let i = 0; i < n; i++) {\n const a = alpha[i];\n for (let c = 0; c < 3; c++) {\n out[i * 4 + c] =\n a > 0 && a < 1\n ? Math.max(\n 0,\n Math.min(255, Math.round(backdrop[c] + d[i * 3 + c] / a)),\n )\n : rgba[i * 4 + c];\n }\n out[i * 4 + 3] = Math.round(a * rgba[i * 4 + 3]);\n }\n return out;\n}\n\n/**\n * Opaque paint a flood from the border would have keyed had it reached it:\n * within KEY_FLOOD of a `flat` picture's backdrop colour. Backdrop the\n * figure encloses (a gap between strands closed by a collar) reads so, and\n * so does paint of the backdrop's colour inside a line (white eyes on a\n * white ground); empty on a `transparent` picture.\n */\nexport function backdropColoured(pic: Illustration): Mask {\n const m = new Uint8Array(pic.width * pic.height);\n const b = pic.backdrop;\n if (!b) return m;\n for (let i = 0; i < m.length; i++) {\n if (pic.alpha[i] < 1) continue;\n const d = Math.hypot(\n pic.rgb[i * 3] - b[0],\n pic.rgb[i * 3 + 1] - b[1],\n pic.rgb[i * 3 + 2] - b[2],\n );\n if (d < KEY_FLOOD) m[i] = 1;\n }\n return m;\n}\n\n// ---- raster helpers ----\n\n/** Slack for a crossing that lands on a pixel's centre but comes out a hair\n * off it in floating point. */\nconst ON_CENTRE = 1e-9;\n\n/**\n * The pixels inside a polygon whose vertices name pixels, like every other\n * landmark: the outline runs through pixel centres, as the grid viewer draws\n * it, and a pixel is in when its centre is inside (even-odd rule) or on the\n * outline. The square from `[0, 0]` to `[4, 4]` covers columns 0..4 and rows\n * 0..4.\n */\nexport function polygonMask(size: CanvasSize, points: readonly Point[]): Mask {\n const { width, height } = size;\n const m = new Uint8Array(width * height);\n const set = (x: number, y: number) => {\n if (x >= 0 && y >= 0 && x < width && y < height) m[y * width + x] = 1;\n };\n let y0 = Infinity;\n let y1 = -Infinity;\n for (const [, y] of points) {\n y0 = Math.min(y0, y);\n y1 = Math.max(y1, y);\n }\n const top = Math.max(0, Math.floor(y0));\n const bottom = Math.min(height - 1, Math.ceil(y1));\n for (let y = top; y <= bottom; y++) {\n const xs: number[] = [];\n for (let i = 0; i < points.length; i++) {\n const [ax, ay] = points[i];\n const [bx, by] = points[(i + 1) % points.length];\n if ((ay <= y && by > y) || (by <= y && ay > y)) {\n xs.push(ax + ((y - ay) / (by - ay)) * (bx - ax));\n }\n }\n xs.sort((a, b) => a - b);\n for (let k = 0; k + 1 < xs.length; k += 2) {\n const from = Math.max(0, Math.ceil(xs[k] - ON_CENTRE));\n const to = Math.min(width - 1, Math.floor(xs[k + 1] + ON_CENTRE));\n for (let x = from; x <= to; x++) m[y * width + x] = 1;\n }\n }\n // The crossing rule above is half-open in y, so the outline's own pixels\n // are drawn too: a bottom edge, a lower vertex, a sliver thinner than a row.\n for (let i = 0; i < points.length; i++) {\n const [ax, ay] = points[i];\n const [bx, by] = points[(i + 1) % points.length];\n const n = Math.max(\n 1,\n Math.ceil(Math.max(Math.abs(bx - ax), Math.abs(by - ay))),\n );\n for (let k = 0; k <= n; k++) {\n set(\n Math.round(ax + ((bx - ax) * k) / n),\n Math.round(ay + ((by - ay) * k) / n),\n );\n }\n }\n return m;\n}\n\n/** The pixels of a box, both corners included, clipped to the canvas. */\nexport function boxMask(size: CanvasSize, [x0, y0, x1, y1]: Box): Mask {\n const { width, height } = size;\n const m = new Uint8Array(width * height);\n const left = Math.max(0, Math.ceil(x0));\n const right = Math.min(width - 1, Math.floor(x1));\n const bottom = Math.min(height - 1, Math.floor(y1));\n for (let y = Math.max(0, Math.ceil(y0)); y <= bottom; y++) {\n for (let x = left; x <= right; x++) m[y * width + x] = 1;\n }\n return m;\n}\n\n/** Grow a mask by a Chebyshev radius `r` (a square), in two separable passes. */\nexport function dilate(size: CanvasSize, m: Mask, r: number): Mask {\n const { width, height } = size;\n const t = new Uint8Array(width * height);\n const o = new Uint8Array(width * height);\n for (let y = 0; y < height; y++) {\n const row = y * width;\n let run = -Infinity;\n for (let x = 0; x < width; x++) {\n if (m[row + x]) run = x;\n if (x - run <= r) t[row + x] = 1;\n }\n run = Infinity;\n for (let x = width - 1; x >= 0; x--) {\n if (m[row + x]) run = x;\n if (run - x <= r) t[row + x] = 1;\n }\n }\n for (let x = 0; x < width; x++) {\n let run = -Infinity;\n for (let y = 0; y < height; y++) {\n if (t[y * width + x]) run = y;\n if (y - run <= r) o[y * width + x] = 1;\n }\n run = Infinity;\n for (let y = height - 1; y >= 0; y--) {\n if (t[y * width + x]) run = y;\n if (run - y <= r) o[y * width + x] = 1;\n }\n }\n return o;\n}\n\nfunction invert(m: Mask): Mask {\n return m.map((v) => (v ? 0 : 1));\n}\n\nexport const and = (a: Mask, b: Mask): Mask =>\n a.map((v, i) => (v && b[i] ? 1 : 0));\nexport const or = (a: Mask, b: Mask): Mask =>\n a.map((v, i) => (v || b[i] ? 1 : 0));\nexport const andNot = (a: Mask, b: Mask): Mask =>\n a.map((v, i) => (v && !b[i] ? 1 : 0));\n\n/** The number of on pixels. */\nexport function count(m: ArrayLike<number>): number {\n let n = 0;\n for (let i = 0; i < m.length; i++) if (m[i]) n++;\n return n;\n}\n\n/** Shrink a mask by a Chebyshev radius `r`; off-canvas counts as on, so a\n * mask touching the edge does not shrink away from it. */\nexport function erode(size: CanvasSize, m: Mask, r: number): Mask {\n return invert(dilate(size, invert(m), r));\n}\n\n/** 4-connected flood over `pass` from pixel indices. */\nfunction floodFromIndices(\n { width, height }: CanvasSize,\n pass: Mask,\n seeds: Iterable<number>,\n): Mask {\n const out = new Uint8Array(width * height);\n const queue = new Int32Array(width * height);\n let head = 0;\n let tail = 0;\n for (const i of seeds) {\n if (pass[i] && !out[i]) {\n out[i] = 1;\n queue[tail++] = i;\n }\n }\n const visit = (j: number) => {\n if (pass[j] && !out[j]) {\n out[j] = 1;\n queue[tail++] = j;\n }\n };\n while (head < tail) {\n const i = queue[head++];\n const x = i % width;\n if (x > 0) visit(i - 1);\n if (x < width - 1) visit(i + 1);\n if (i >= width) visit(i - width);\n if (i < (height - 1) * width) visit(i + width);\n }\n return out;\n}\n\n/** The index of the pixel a point names: rounded, then held on the canvas\n * (a coordinate just under the width rounds to it). */\nexport function pixelIndex(\n { width, height }: CanvasSize,\n [x, y]: Point,\n): number {\n const px = Math.max(0, Math.min(width - 1, Math.round(x)));\n const py = Math.max(0, Math.min(height - 1, Math.round(y)));\n return py * width + px;\n}\n\n/** 4-connected flood over `pass` from seed points, each at the pixel it\n * names; a seed off `pass` starts nothing. */\nexport function flood(\n size: CanvasSize,\n pass: Mask,\n seeds: readonly Point[],\n): Mask {\n return floodFromIndices(\n size,\n pass,\n seeds.map((p) => pixelIndex(size, p)),\n );\n}\n\n/** The mask with every hole closed: off pixels no 4-connected path of off\n * pixels joins to the canvas's edge. */\nexport function fillHoles(size: CanvasSize, m: Mask): Mask {\n const { width, height } = size;\n const edge: number[] = [];\n for (let x = 0; x < width; x++) edge.push(x, (height - 1) * width + x);\n for (let y = 0; y < height; y++) edge.push(y * width, y * width + width - 1);\n return invert(floodFromIndices(size, invert(m), edge));\n}\n\n/**\n * Each pixel takes the value most of its (2r+1)² window has, the window cut\n * at the canvas's edge (a tie is off). Removes speckle between two labels.\n */\nexport function majority(size: CanvasSize, m: Mask, r: number): Mask {\n const { width, height } = size;\n const w1 = width + 1;\n // Summed-area table: any window's count in four reads, whatever r is.\n const sum = new Int32Array(w1 * (height + 1));\n for (let y = 0; y < height; y++) {\n let row = 0;\n for (let x = 0; x < width; x++) {\n row += m[y * width + x];\n sum[(y + 1) * w1 + x + 1] = sum[y * w1 + x + 1] + row;\n }\n }\n const out = new Uint8Array(width * height);\n for (let y = 0; y < height; y++) {\n const ya = Math.max(0, y - r);\n const yb = Math.min(height, y + r + 1);\n for (let x = 0; x < width; x++) {\n const xa = Math.max(0, x - r);\n const xb = Math.min(width, x + r + 1);\n const on =\n sum[yb * w1 + xb] -\n sum[ya * w1 + xb] -\n sum[yb * w1 + xa] +\n sum[ya * w1 + xa];\n out[y * width + x] = on * 2 > (yb - ya) * (xb - xa) ? 1 : 0;\n }\n }\n return out;\n}\n\n/**\n * Push-pull fill. Where `known` is above 0 a colour stays as it is (`known`\n * weighs it into the coarser levels); the rest is read, bilinearly, off a\n * half-size level made of the known colours, recursively, so a hole takes\n * the colours around it, smoothly, however wide it is. With no known pixel\n * at all there is nothing to fill from, and `rgb` comes back unchanged.\n */\nexport function pushPull(\n size: CanvasSize,\n rgb: Float32Array,\n known: ArrayLike<number>,\n): Float32Array {\n const { width: w, height: h } = size;\n let any = false;\n for (let i = 0; i < w * h && !any; i++) any = known[i] > 0;\n if (!any) return new Float32Array(rgb);\n if (w <= 2 || h <= 2) return fillFromMean(rgb, known, w * h);\n const w2 = (w + 1) >> 1;\n const h2 = (h + 1) >> 1;\n const c2 = new Float32Array(w2 * h2 * 3);\n const k2 = new Float32Array(w2 * h2);\n for (let y = 0; y < h; y++) {\n for (let x = 0; x < w; x++) {\n const k = known[y * w + x];\n if (!(k > 0)) continue;\n const j = (y >> 1) * w2 + (x >> 1);\n k2[j] += k;\n for (let c = 0; c < 3; c++) c2[j * 3 + c] += rgb[(y * w + x) * 3 + c] * k;\n }\n }\n for (let j = 0; j < w2 * h2; j++) {\n if (k2[j] > 0) {\n for (let c = 0; c < 3; c++) c2[j * 3 + c] /= k2[j];\n k2[j] = 1;\n }\n }\n const f2 = pushPull({ width: w2, height: h2 }, c2, k2);\n const out = new Float32Array(rgb);\n for (let y = 0; y < h; y++) {\n for (let x = 0; x < w; x++) {\n if (known[y * w + x] > 0) continue;\n const fx = Math.min(w2 - 1, Math.max(0, (x - 0.5) / 2));\n const fy = Math.min(h2 - 1, Math.max(0, (y - 0.5) / 2));\n const x0 = Math.floor(fx);\n const y0 = Math.floor(fy);\n const x1 = Math.min(w2 - 1, x0 + 1);\n const y1 = Math.min(h2 - 1, y0 + 1);\n const tx = fx - x0;\n const ty = fy - y0;\n for (let c = 0; c < 3; c++) {\n const top =\n f2[(y0 * w2 + x0) * 3 + c] * (1 - tx) +\n f2[(y0 * w2 + x1) * 3 + c] * tx;\n const bottom =\n f2[(y1 * w2 + x0) * 3 + c] * (1 - tx) +\n f2[(y1 * w2 + x1) * 3 + c] * tx;\n out[(y * w + x) * 3 + c] = top * (1 - ty) + bottom * ty;\n }\n }\n }\n return out;\n}\n\n/** The coarsest level: an unknown pixel takes the known pixels' mean (there\n * is one), so a level with no source nearby still reads a picture colour. */\nfunction fillFromMean(\n rgb: Float32Array,\n known: ArrayLike<number>,\n n: number,\n): Float32Array {\n const mean = [0, 0, 0];\n let total = 0;\n for (let i = 0; i < n; i++) {\n const k = known[i];\n if (!(k > 0)) continue;\n total += k;\n for (let c = 0; c < 3; c++) mean[c] += rgb[i * 3 + c] * k;\n }\n const out = new Float32Array(rgb);\n for (let i = 0; i < n; i++) {\n if (known[i] > 0) continue;\n for (let c = 0; c < 3; c++) out[i * 3 + c] = mean[c] / total;\n }\n return out;\n}\n","/**\n * `cutLayersFromIllustration`: one finished character picture cut, in\n * place, into role layers on the canvas: the face, the front and back hair,\n * a side lock on each side given, the body and each custom part (a tail, a\n * ponytail) as its own file. Every\n * visible pixel is copied from the picture; what a layer hides when the rig\n * moves it (the forehead under the bangs, the hair behind the face, the\n * neck behind the chin, the cheek under a side lock) is filled in from the\n * paint around it.\n *\n * Driven by landmarks an agent reads off `view_illustration_grid`\n * (`illustration-landmarks.ts`), and checked: the report says, in numbers,\n * whether the layers stack back into the picture, whether each seed and\n * sample sits on the paint it should, how much of each fill was made up far\n * from any paint, and whether the front hair is wider than the face; and\n * `measure_layers`' own checks on the written directory follow.\n *\n * The drawn mouth is a closed line. Given a generated lip set (the\n * composer's keyed open mouth and interior), the composer cuts it and it is\n * placed on the drawn mouth's corners in place of that line.\n *\n * Frame: canvas px, origin top-left, x right, y down, CANVAS wide; every\n * layer is a canvas-sized PNG with the paint where the picture has it.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport sharp from \"sharp\";\nimport {\n hasCoverage,\n ORDER,\n readLipSources,\n sizedPart,\n trimmedPart,\n type LipSources,\n} from \"./compose\";\nimport { KEYED_SRC, splitLipSet } from \"./compose-lips\";\nimport {\n and,\n andNot,\n backdropColoured,\n backdropSeed,\n boxMask,\n count,\n dilate,\n erode,\n matteIllustration,\n or,\n pixelIndex,\n polygonMask,\n readPictureOnCanvas,\n type Box,\n type CanvasPicture,\n type CanvasSize,\n type Illustration,\n type Mask,\n type Point,\n} from \"./illustration\";\nimport {\n buildClassifier,\n classifyPicture,\n HAIR,\n NEITHER,\n readSamples,\n SKIN,\n withoutSample,\n type ColourClassifier,\n type SampleReads,\n} from \"./illustration-colour\";\nimport {\n fillFrom,\n hairSources,\n paintOf,\n SOURCE_INSET,\n type CutCheck,\n type CutContext,\n type LayerPaint,\n} from \"./illustration-context\";\nimport { cutFeatures, type FeatureCut } from \"./illustration-features\";\nimport { drawLandmarks, pictureView } from \"./illustration-grid\";\nimport {\n bridges,\n labelIllustration,\n LABEL_BODY,\n LABEL_FACE,\n LABEL_HAIR,\n maskBox,\n PAINT_ALPHA,\n type IllustrationLabels,\n} from \"./illustration-labels\";\nimport {\n validateLandmarks,\n type IllustrationLandmarks,\n} from \"./illustration-landmarks\";\nimport {\n AutoRigInputError,\n confineToWorkingDirectory,\n resolveInputPath,\n resolveOutputDir,\n writeFileAtomic,\n} from \"./limits\";\nimport { formatLipFacts, measureDir } from \"./measure\";\nimport { VISIBLE_MIN_PX } from \"./measure-hair-side\";\nimport type { LipFacts } from \"./measure-lips\";\n\nexport interface CutLayersFromIllustrationInput {\n /** The finished picture (PNG, JPEG or WebP), resolved against cwd. */\n imagePath: string;\n /** Checked by `validateLandmarks` against the picture's canvas. */\n landmarks: unknown;\n /** An existing directory under the working directory. */\n outputDir: string;\n /** The lip set's open mouth, its inside painted flat #00FF00 (what the\n * composer reads as `mouth_keyed.png`). With `mouthInterior` the lip set\n * is written in place of the drawn mouth, its corners on\n * `landmarks.mouth`'s; one without the other is refused. */\n mouthKeyed?: string;\n /** The lip set's cavity, teeth and tongue (the composer's\n * `mouth_interior.png`); see `mouthKeyed`. */\n mouthInterior?: string;\n}\n\nexport interface CutLayer {\n role: string;\n path: string;\n /** `[x0, y0, x1, y1]` of the painted pixels, both corners inside; null\n * for a layer with none. */\n box: Box | null;\n pixels: number;\n}\n\n/** `measureLayers`' report on the written directory, less the checks whose\n * only remedy is re-laying-out or regenerating a generated part (see\n * `measureDir`'s `inPlace`). */\nexport interface CutMeasure {\n warnings: string[];\n /** The lip set's opening as the rig reads it, with a lip set. */\n lips?: LipFacts;\n}\n\nexport interface CutCustomPart {\n id: string;\n path: string;\n box: Box | null;\n pixels: number;\n /** The landmark's tie, for the custom part's rig. */\n tie: Point;\n}\n\nexport type CutLayersFromIllustrationResult =\n | {\n ok: true;\n outputDir: string;\n canvas: CanvasSize;\n layers: CutLayer[];\n customParts: CutCustomPart[];\n previews: { labels: string; landmarks: string };\n checks: CutCheck[];\n measure: CutMeasure;\n /** No fail-level check failed. */\n passed: boolean;\n }\n | { ok: false; error: string };\n\n/** Skin carried under strands that cross the face's edge, px past it: what\n * shows when the strand swings off the face. Too little shows a gap. */\nconst FACE_MARGIN = 10;\n/** A drawn line's width at the canvas size, px: the strand's outline\n * beside a side lock, kept out of what the skin under it is coloured\n * from. */\nconst LOCK_LINE = 4;\n/** How far a side lock is carried up under the bangs from its top edge, px:\n * its hidden root. The rig moves a lock as the front hair down to the first\n * row on which it shows under the bangs and eases it to the face's motion\n * over 0.2 hh below; the measure (`measure-hair-side.ts`) reads the root as\n * hidden when the lock's top row lies under `hair_front`. Where the bangs'\n * hem dips below that first row, the lock under the dip already eases\n * toward the face while the hem moves as the bangs: on the nod the two\n * part by up to about 0.02 hh (the bangs' 0.18 against the face's 0.16),\n * about 5 px on a head at this canvas size, plus the measure's 3 px of\n * antialiasing. 12 px keeps the root under the hem past both with a\n * margin; the carry runs only where `hair_front` is opaque above, so more\n * would only lengthen the lock's box, whose top the rig pins its sway to. */\nconst SIDE_ROOT_REACH = 12;\n/** Hair and custom parts run on under the body's edge this far, px: what\n * shows when the body breathes or the head turns. Too little shows a gap\n * at the shoulder. */\nconst UNDER_BODY = 16;\n/** The head's hair runs on under each custom part's root this far, px: what\n * shows when the part swings. Too little shows a hole at the root. */\nconst UNDER_PART = 14;\n/** How far under the jaw's lowest face row the neck's own skin is looked\n * for, px: past the jaw's line, the shadow the chin casts on the neck and\n * a strand's tip hanging over it. Farther reaches down through a collar to\n * the chest. */\nconst NECK_REACH = 40;\n/** Columns of the neck's own side line carried up past its skin: a drawn\n * line's width at the canvas size. More reaches the strands and the\n * backdrop's fringe beside the neck. */\nconst NECK_LINE = 3;\n/** Alpha at which the picture's paint hides whatever a fill puts under it:\n * full, at 8 bits. Under a soft edge the picture shows its backdrop, and a\n * fill there would show through. */\nconst OPAQUE_ALPHA = 1 - 0.5 / 255;\n/** A fill pixel farther than this from any source pixel (a square of this\n * half-size) was made up rather than carried on: it shows a flat average\n * colour where the picture would have shading. */\nconst FILL_REACH = 40;\n/** Share of a fill that may be made up before the check warns: past it,\n * what shows when the layer above moves is mostly one flat colour. */\nconst FILL_LIMIT = 0.25;\n/** A channel off by more than this many levels counts as off: past the\n * rounding of a soft edge, short of a visible change. */\nconst STACK_LEVELS = 24;\n/** Share of the canvas the stacked layers may get wrong, about a short\n * stroke's worth at the canvas size. */\nconst STACK_LIMIT = 0.003;\n\n/** A backdrop-coloured region smaller than this, px, is a highlight or a\n * gap in a line, not a pocket of backdrop worth a seed. */\nconst POCKET_PX = 200;\n/** Pockets the check names at most, largest first. */\nconst POCKETS_NAMED = 5;\n/** A pocket's ring is the paint this many px out from it, through\n * POCKET_RING_OUT: past its soft edge and the line round it (whose pixels\n * are a mix the floods may give to anything), into the paint that closes\n * it in. Sized for a line about 4 canvas px wide (2 picture px on a\n * picture about half the canvas); a much heavier line puts its own ink in\n * the ring, which reads as neither hair nor body and lowers the hair's\n * share. */\nconst POCKET_RING_IN = 4;\nconst POCKET_RING_OUT = 8;\n/** The largest pocket keyed on its own, as a share of the canvas: a gap\n * between strands is small and thin (twin's largest is about 0.5 %), a\n * pale panel edged with hair is not, and over this it is only named. */\nconst POCKET_KEY_SHARE = 0.01;\n/** A pocket whose ring is at least this share hair is a gap in the hair and\n * keyed as backdrop on its own; a gap closed at one end by the clothes\n * stays over it, a hole in a shirt is far under it. */\nconst POCKET_HAIR_SHARE = 0.8;\n/** The share of a pocket's pixels a `backgroundSeeds` point must be accepted\n * at for the pocket to be named for one: under it, a seed keys too little\n * of it to clear it, and the next cut names it again. */\nconst POCKET_SEED_SHARE = 0.5;\n\nconst fmt = (v: number, digits = 3) => Number(v.toFixed(digits));\nconst pct = (v: number) => `${(v * 100).toFixed(2)}%`;\n\nexport type { CutCheck } from \"./illustration-context\";\n\n// ---- fills and layers ----\n\n/** Lay `filled` colours, opaque, over `region` where the layer has no paint\n * of its own; `region` must lie under opaque paint of a layer drawn above.\n * Returns the pixels filled. */\nfunction fillUnder(\n pic: Illustration,\n layer: LayerPaint,\n region: Mask,\n filled: Float32Array | ((i: number) => ArrayLike<number>),\n): Mask {\n const done = new Uint8Array(region.length);\n for (let i = 0; i < region.length; i++) {\n if (!region[i] || layer.alpha[i] > 0) continue;\n if (layer.rgb === pic.rgb) layer.rgb = new Float32Array(pic.rgb);\n const rgb =\n typeof filled === \"function\"\n ? filled(i)\n : filled.subarray(i * 3, i * 3 + 3);\n for (let c = 0; c < 3; c++) layer.rgb[i * 3 + c] = rgb[c];\n layer.alpha[i] = 1;\n done[i] = 1;\n }\n return done;\n}\n\n/** Straight-alpha RGBA bytes; colour zeroed where nothing is painted. */\nexport function encodeLayer(layer: LayerPaint): Buffer {\n const n = layer.alpha.length;\n const buf = Buffer.alloc(n * 4);\n const byte = (v: number) => Math.max(0, Math.min(255, Math.round(v)));\n for (let i = 0; i < n; i++) {\n const a = byte(layer.alpha[i] * 255);\n if (a === 0) continue;\n for (let c = 0; c < 3; c++) buf[i * 4 + c] = byte(layer.rgb[i * 3 + c]);\n buf[i * 4 + 3] = a;\n }\n return buf;\n}\n\ninterface FillRegion {\n id: string;\n /** The pixels filled. */\n region: Mask;\n sources: Mask;\n /** Null for a fill made up by construction, reported without a limit. */\n limit: number | null;\n hint: string;\n}\n\ninterface BuiltLayers {\n roles: Map<string, LayerPaint>;\n parts: { id: string; tie: Point; paint: LayerPaint }[];\n fills: FillRegion[];\n features: FeatureCut;\n /** Where the picture's paint is opaque: what a fill may lie under. */\n opaque: Mask;\n}\n\n/** The face: its skin as drawn, the features lifted off it; under them,\n * under the bangs inside the skull, and a margin under strands that cross\n * its edge, skin filled from the skin around. */\nfunction faceLayer(\n ctx: CutContext,\n opaque: Mask,\n fills: FillRegion[],\n features: FeatureCut,\n) {\n const { pic, labels } = ctx;\n const { skin, skinSources: sources, holes } = features;\n const face = paintOf(pic, labels.face);\n for (let i = 0; i < holes.length; i++) if (holes[i]) face.alpha[i] = 0;\n fills.push({\n id: \"face.features\",\n region: fillUnder(pic, face, and(and(holes, labels.face), opaque), skin),\n sources,\n limit: null,\n hint: \"the skin under the eyes, the brows, the nose and the mouth, filled from the skin around by construction (it shows when a feature moves or an eye shuts)\",\n });\n const head = or(labels.skullArea, dilate(pic, labels.face, FACE_MARGIN));\n fills.push({\n id: \"face.forehead\",\n region: fillUnder(\n pic,\n face,\n and(head, and(labels.hairFront, opaque)),\n skin,\n ),\n sources,\n limit: FILL_LIMIT,\n hint: \"the skin under the bangs is made up far from any skin: pull landmarks.skull in to the head's outline, and put a landmarks.skinSeeds point on any forehead skin between strands the face's flood missed\",\n });\n const locks = sideLocks(labels);\n if (locks) {\n // No margin here: grown outward from the face, it lays skin beside the\n // ear's outer edge and under the lobe, where the hair is behind the\n // lock, and the lock leaning away shows it as a patch.\n const bridge = bridges(pic, locks, labels.face);\n // Coloured smoothly from the face's own paint round the gap, the ear's\n // shading with it (it reads neither skin nor hair, so the skin fill\n // would lay it flat and pale), less a line's width beside the lock (the\n // strand's soft edge and any of its outline the face kept) and less the\n // features lifted off the face, whose ink would bleed into the cheek.\n const across = fillFrom(\n pic,\n andNot(\n andNot(and(labels.face, labels.solid), holes),\n dilate(pic, locks, LOCK_LINE),\n ),\n );\n const hidden = or(labels.skullArea, bridge);\n fills.push({\n id: \"face.sideHair\",\n region: fillUnder(pic, face, and(hidden, and(locks, opaque)), (i) =>\n (bridge[i] ? across : skin).subarray(i * 3, i * 3 + 3),\n ),\n sources,\n limit: FILL_LIMIT,\n hint: \"the skin under the side locks is made up far from any skin: put a landmarks.skinSeeds point on the cheek and the ear beside each lock\",\n });\n }\n return face;\n}\n\n/** The front hair, a strand running through a brow's band refilled across\n * it, column by column, from the strand right above and right below: the\n * brow passes under it, and moving the brow leaves no trace in the hair. */\nfunction frontHairLayer(ctx: CutContext, fills: FillRegion[]): LayerPaint {\n const { pic, labels } = ctx;\n const { width, height } = pic;\n const layer = paintOf(pic, labels.hairFront);\n const strand = and(labels.strandThrough, labels.hairFront);\n const region = new Uint8Array(width * height);\n for (let x = 0; x < width; x++) {\n for (let y = 1; y < height; y++) {\n if (!strand[y * width + x] || strand[(y - 1) * width + x]) continue;\n let end = y;\n while (end < height && strand[end * width + x]) end++;\n const a = (y - 1) * width + x;\n const b = end * width + x;\n if (end < height && layer.alpha[a] > 0 && layer.alpha[b] > 0) {\n if (layer.rgb === pic.rgb) layer.rgb = new Float32Array(pic.rgb);\n for (let k = y; k < end; k++) {\n const i = k * width + x;\n const t = (k - y + 1) / (end - y + 1);\n for (let c = 0; c < 3; c++) {\n layer.rgb[i * 3 + c] =\n pic.rgb[a * 3 + c] * (1 - t) + pic.rgb[b * 3 + c] * t;\n }\n layer.alpha[i] = 1;\n region[i] = 1;\n }\n }\n y = end;\n }\n }\n fills.push({\n id: \"hair_front.strands\",\n region,\n sources: andNot(labels.hairFront, strand),\n limit: FILL_LIMIT,\n hint: \"a strand through a brow's band is refilled far from its own hair: check landmarks.brows' bands are no wider than the brow\",\n });\n return layer;\n}\n\n/** The back hair, with the head's shell behind the face and the bangs down\n * to shellLower, the hair under each custom part's root and under the\n * body's edge; and each custom part with its own margin under the body. */\nfunction hairLayers(ctx: CutContext, opaque: Mask, fills: FillRegion[]) {\n const { pic, lm, labels } = ctx;\n const { width } = pic;\n const sources = hairSources(ctx, labels.hairBack);\n const filled = fillFrom(pic, sources);\n const hairBack = paintOf(pic, labels.hairBack);\n\n const first = lm.shellLower[0];\n const last = lm.shellLower.at(-1)!;\n const shellArea = polygonMask(pic, [\n [0, 0],\n [width - 1, 0],\n [width - 1, last[1]],\n ...[...lm.shellLower].reverse(),\n [0, first[1]],\n ]);\n const cover = or(or(labels.face, labels.hairFront), labels.skullArea);\n fills.push({\n id: \"hair_back.shell\",\n region: fillUnder(\n pic,\n hairBack,\n and(and(cover, shellArea), opaque),\n filled,\n ),\n sources,\n limit: null,\n hint: \"the hair behind the face and the bangs, made up by construction (it shows only at the head's edge on a turn)\",\n });\n const locks = sideLocks(labels);\n if (locks) {\n fills.push({\n id: \"hair_back.sideHair\",\n region: fillUnder(\n pic,\n hairBack,\n and(and(locks, shellArea), opaque),\n filled,\n ),\n sources,\n limit: null,\n hint: \"the hair behind the side locks down to landmarks.shellLower, made up by construction (it shows beside a lock when the lock swings or the head turns)\",\n });\n }\n const near = dilate(pic, labels.hairBack, UNDER_PART);\n labels.parts.forEach(({ cut, mask }, k) => {\n fills.push({\n id: `custom.${cut.id}.root`,\n region: fillUnder(pic, hairBack, and(and(near, mask), opaque), filled),\n sources,\n limit: FILL_LIMIT,\n hint: `the head's hair under ${cut.id}'s root is made up far from any back hair: move landmarks.customParts[${k}]'s ${\"polygon\" in cut ? \"polygon\" : \"line\"} to where the part leaves the head's hair`,\n });\n });\n // Carried from hair that can colour it: a thin strand touching the body\n // has no source of its own and is not carried.\n const underBody = (from: Mask) =>\n and(\n dilate(pic, and(from, labels.bigHair), UNDER_BODY + SOURCE_INSET),\n and(labels.body, opaque),\n );\n fills.push({\n id: \"hair_back.underBody\",\n region: fillUnder(pic, hairBack, underBody(sources), filled),\n sources,\n limit: FILL_LIMIT,\n hint: \"the back hair under the body's edge is made up far from any back hair: check on preview-labels.png that the hair above the shoulders is labelled hair, adding landmarks.samples.hair points on its tones\",\n });\n\n const parts = labels.parts.map(({ cut, mask }, k) => {\n const paint = paintOf(pic, mask);\n const own = hairSources(ctx, mask);\n fills.push({\n id: `custom.${cut.id}.underBody`,\n region: fillUnder(pic, paint, underBody(own), fillFrom(pic, own)),\n sources: own,\n limit: FILL_LIMIT,\n hint: `${cut.id} under the body's edge is made up far from its own hair: check landmarks.customParts[${k}] takes the part's hair down to the shoulder`,\n });\n return { id: cut.id, tie: cut.tie, paint };\n });\n return { hairBack, parts };\n}\n\n/**\n * The body: as drawn, and the neck carried up behind the chin to neckTopY,\n * under the face and the front hair only (the back hair and the custom\n * parts are drawn under the body). Each column under the jaw's lowest face\n * row carries up the neck's own skin nearest under the jaw: skin-class\n * body paint clear of lines (`neckSkin`), found down through the body's\n * paint within NECK_REACH rows, past the jaw's line and the shadow it casts.\n * A column with none (a strand's tip, a line, the backdrop's fringe under\n * the jaw) between two that have it takes their colours, blended by\n * distance. Past the outermost ones, on the row their skin was found on,\n * the neck runs on over its skin-class paint near the line (which the\n * inset leaves out) and then its own side line, at most NECK_LINE columns\n * of it; anything else there is no neck and carries nothing. The hidden\n * neck is skin all over, its sides drawn as they are below the jaw.\n */\nfunction bodyLayer(ctx: CutContext, opaque: Mask, fills: FillRegion[]) {\n const { pic, lm, labels } = ctx;\n const { width, height } = pic;\n const body = paintOf(pic, labels.body);\n const sources = neckSkin(ctx);\n const jaws = new Int32Array(width).fill(-1);\n const from = new Int32Array(width).fill(-1);\n for (let x = 0; x < width; x++) {\n let jaw = -1;\n for (let y = height - 1; y >= 0 && jaw < 0; y--) {\n if (labels.label[y * width + x] === LABEL_FACE) jaw = y;\n }\n if (jaw < 0) continue;\n jaws[x] = jaw;\n for (let y = jaw + 1; y < height && y <= jaw + NECK_REACH; y++) {\n const i = y * width + x;\n if (labels.label[i] !== LABEL_BODY || !labels.solid[i]) break;\n if (sources[i]) {\n from[x] = i;\n break;\n }\n }\n }\n const colour = new Float32Array(width * 3);\n const carried = new Uint8Array(width);\n let left = -1;\n for (let x = 0; x < width; x++) {\n if (from[x] < 0) continue;\n for (let c = 0; c < 3; c++) colour[x * 3 + c] = pic.rgb[from[x] * 3 + c];\n carried[x] = 1;\n // The columns since the last with skin: blended across from both.\n for (let g = left + 1; left >= 0 && g < x; g++) {\n const t = (g - left) / (x - left);\n for (let c = 0; c < 3; c++) {\n colour[g * 3 + c] =\n colour[left * 3 + c] * (1 - t) + colour[x * 3 + c] * t;\n }\n carried[g] = 1;\n }\n left = x;\n }\n const first = from.findIndex((v) => v >= 0);\n let last = width - 1;\n while (last >= 0 && from[last] < 0) last--;\n // Out from each side of the neck on the row its skin was found on.\n for (const [end, step] of [\n [first, -1],\n [last, 1],\n ]) {\n if (end < 0) break;\n const row = Math.floor(from[end] / width);\n let line = 0;\n for (let x = end + step; x >= 0 && x < width && jaws[x] >= 0; x += step) {\n const i = row * width + x;\n if (labels.label[i] !== LABEL_BODY || !labels.solid[i]) break;\n // Skin up to the line, then the line itself.\n if (labels.classes[i] !== SKIN || line > 0) {\n if (labels.classes[i] !== NEITHER || line === NECK_LINE) break;\n line++;\n }\n for (let c = 0; c < 3; c++) colour[x * 3 + c] = pic.rgb[i * 3 + c];\n carried[x] = 1;\n }\n }\n const neck = new Uint8Array(width * height);\n for (let x = 0; x < width; x++) {\n if (!carried[x] || jaws[x] < 0) continue;\n for (let y = Math.round(lm.neckTopY); y <= jaws[x]; y++) {\n const i = y * width + x;\n if (opaque[i] && (labels.face[i] || labels.hairFront[i])) neck[i] = 1;\n }\n }\n fills.push({\n id: \"body.neck\",\n region: fillUnder(pic, body, neck, (i) => {\n const x = i % width;\n return colour.subarray(x * 3, x * 3 + 3);\n }),\n sources,\n limit: null,\n hint: \"the neck behind the chin, carried up to landmarks.neckTopY from the neck's own skin by construction\",\n });\n return body;\n}\n\n/** Every side lock's hair, or null with no `sideHair` polygon. */\nfunction sideLocks(labels: IllustrationLabels): Mask | null {\n const { L, R } = labels.hairSide;\n return L && R ? or(L, R) : (L ?? R ?? null);\n}\n\n/** Each side lock with paint, its root carried up from its top edge under\n * the front hair by SIDE_ROOT_REACH, column by column, as far as the front\n * hair is opaque above it, filled from the lock's own hair. */\nfunction sideLockLayers(\n ctx: CutContext,\n opaque: Mask,\n fills: FillRegion[],\n): Map<string, LayerPaint> {\n const { pic, labels } = ctx;\n const { width } = pic;\n const out = new Map<string, LayerPaint>();\n for (const side of [\"L\", \"R\"] as const) {\n const mask = labels.hairSide[side];\n if (!mask || count(mask) === 0) continue;\n const layer = paintOf(pic, mask);\n const root = new Uint8Array(mask.length);\n for (let i = width; i < mask.length; i++) {\n if (!mask[i] || mask[i - width]) continue;\n for (let j = i - width, k = 0; j >= 0 && k < SIDE_ROOT_REACH; k++) {\n if (!labels.hairFront[j] || !opaque[j]) break;\n root[j] = 1;\n j -= width;\n }\n }\n const own = hairSources(ctx, mask);\n fills.push({\n id: `hair_side_${side}.root`,\n region: fillUnder(pic, layer, root, fillFrom(pic, own)),\n sources: own,\n limit: FILL_LIMIT,\n hint: `the lock's root under the bangs is filled far from the lock's own hair (strands thinner than about 5 px have none clear of their lines); it never shows at rest: check on preview-labels.png that landmarks.sideHair.${side} holds the lock`,\n });\n out.set(`hair_side_${side}`, layer);\n }\n return out;\n}\n\n/** The neck's own skin: skin-class body paint, solid, clear of lines. */\nfunction neckSkin(ctx: CutContext): Mask {\n const { labels } = ctx;\n return erode(\n ctx.pic,\n labels.body.map((v, i) =>\n v && labels.solid[i] && labels.classes[i] === SKIN ? 1 : 0,\n ),\n SOURCE_INSET,\n );\n}\n\n/** The face, the features, the hair (the side locks too), the body and the\n * custom parts, with their fills. With `lipSet` the drawn mouth leaves the\n * face as no layer. */\nfunction buildLayers(ctx: CutContext, lipSet: boolean): BuiltLayers {\n const { pic } = ctx;\n const fills: FillRegion[] = [];\n const opaque = Uint8Array.from(pic.alpha, (a) => (a >= OPAQUE_ALPHA ? 1 : 0));\n const features = cutFeatures(ctx, lipSet);\n const face = faceLayer(ctx, opaque, fills, features);\n const { hairBack, parts } = hairLayers(ctx, opaque, fills);\n const body = bodyLayer(ctx, opaque, fills);\n return {\n roles: new Map([\n [\"hair_back\", hairBack],\n [\"body\", body],\n [\"face\", face],\n ...features.roles,\n ...sideLockLayers(ctx, opaque, fills),\n [\"hair_front\", frontHairLayer(ctx, fills)],\n ]),\n parts,\n fills,\n features,\n opaque,\n };\n}\n\n// ---- the lip set ----\n\n/** The layer each of the composer's lip-set buffers is written as. */\nconst LIP_LAYERS = {\n mouth_inner: \"inner\",\n mouth_tongue: \"tongue\",\n mouth_teeth: \"teeth\",\n lip_lower: \"lower\",\n lip_upper: \"upper\",\n} as const;\n\n/** The rows of a frame's first and last columns, each its paint's\n * alpha-weighted mean, as edge coordinates (a pixel's centre at +0.5): the\n * ends of a trimmed mouth's line, where its corners are. */\nasync function endRows(png: Buffer): Promise<[number, number]> {\n const { data, info } = await sharp(png)\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true });\n const row = (x: number) => {\n let sum = 0;\n let weight = 0;\n for (let y = 0; y < info.height; y++) {\n const a = data[(y * info.width + x) * 4 + 3];\n sum += a * (y + 0.5);\n weight += a;\n }\n return sum / weight;\n };\n return [row(0), row(info.width - 1)];\n}\n\n/**\n * The lip set, cut by the composer from the keyed mouth and the interior,\n * placed so its own corners (the trimmed frame's end columns, which are the\n * line's ends and go to `lip_upper`) land on landmarks.mouth's: scaled\n * uniformly by the two corners' distance, their midpoint on the drawn\n * corners'. Not turned: on a tilted drawn mouth the set lies level, centred\n * on the tilt. `mouth_tongue` / `mouth_teeth` only when the interior has\n * light paint for them, as the composer writes them.\n */\nasync function lipSetLayers(\n ctx: CutContext,\n lips: LipSources,\n): Promise<Map<string, LayerPaint>> {\n const { pic, lm } = ctx;\n const canvas = { width: pic.width, height: pic.height };\n const cfg = { src: KEYED_SRC };\n // Never null: the keyed part is in memory.\n const trimmed = (await trimmedPart(\n \"mouth_inner\",\n cfg,\n \"\",\n lips.keyedPng,\n false,\n ))!;\n const [rowA, rowB] = await endRows(trimmed.data);\n const { cornerL, cornerR } = lm.mouth;\n const drawn = Math.hypot(cornerR[0] - cornerL[0], cornerR[1] - cornerL[1]);\n const own = Math.hypot(trimmed.w - 1, rowB - rowA);\n const corners = \"landmarks.mouth.cornerL/cornerR\";\n /** The set sized `w` px wide and split by the composer. */\n const cutAt = async (w: number) => {\n let part;\n try {\n part = await sizedPart(\"mouth_inner\", { ...cfg, w }, trimmed, canvas);\n } catch (e) {\n // The composer names its layout key; here the size comes from the\n // corners.\n if (e instanceof AutoRigInputError) {\n throw new AutoRigInputError(\n e.message.replace(\n \"layout.mouth_inner.w:\",\n `${corners}: the lip set scaled to the corners,`,\n ),\n );\n }\n throw e;\n }\n return {\n part,\n split: await splitLipSet(part.buf, part.w, part.h, lips.interior),\n };\n };\n /** Whether the set cuts at `w` px wide. */\n const cutsAt = async (w: number) => {\n try {\n await cutAt(w);\n return true;\n } catch (e) {\n if (e instanceof AutoRigInputError) return false;\n throw e;\n }\n };\n const w = Math.max(1, Math.round((trimmed.w * drawn) / own));\n let cut;\n try {\n cut = await cutAt(w);\n } catch (e) {\n // Scaled down, the key's outline can thin past closing, which its own\n // message blames on the drawing. If it cuts at its drawn size, the\n // corners are what is too close: name the least distance that cuts.\n if (!(e instanceof AutoRigInputError) || w >= trimmed.w) throw e;\n if (!(await cutsAt(trimmed.w))) throw e;\n let lo = w;\n let hi = trimmed.w;\n while (hi - lo > 1) {\n const mid = (lo + hi) >> 1;\n if (await cutsAt(mid)) hi = mid;\n else lo = mid;\n }\n // The least distance whose width rounds to `hi`.\n const least = Math.ceil(((hi - 0.5) * own) / trimmed.w);\n throw new AutoRigInputError(\n `${corners} are ${Number(drawn.toFixed(1))} px apart, too close for the lip set: scaled that small, its outline thins past closing round the opening (the drawing itself cuts at its own size, so it needs no regenerating). It cuts from ${least} px apart: check the corners sit on the drawn mouth line's two ends; on a mouth drawn smaller than that, leave mouthKeyed and mouthInterior out to keep the drawn mouth`,\n );\n }\n const { part, split } = cut;\n // Read off the resized frame, not scaled from the trimmed one: the\n // resampler moves a row by a fraction of a pixel, which rounds to a row.\n const [landedA, landedB] = await endRows(part.buf);\n const left = Math.round((cornerL[0] + cornerR[0]) / 2 + 0.5 - part.w / 2);\n const top = Math.round(\n (cornerL[1] + cornerR[1]) / 2 + 0.5 - (landedA + landedB) / 2,\n );\n // Clipped by the canvas, a lip layer loses rows the fold reads, or is\n // lost whole and the set is partial, which the rig refuses.\n if (\n left < 0 ||\n top < 0 ||\n left + part.w > pic.width ||\n top + part.h > pic.height\n ) {\n throw new AutoRigInputError(\n `${corners} place the lip set, ${part.w}x${part.h} px, at (${left}, ${top}), past the ${pic.width}x${pic.height} canvas: the set reaches ${Math.round((landedA + landedB) / 2)} px above its corners and ${part.h - Math.round((landedA + landedB) / 2)} px below them. Check the corners sit on the drawn mouth line's two ends (corners too far apart make the set too big); with no room on the canvas round the mouth, leave mouthKeyed and mouthInterior out to keep the drawn mouth`,\n );\n }\n\n const out = new Map<string, LayerPaint>();\n for (const [role, key] of Object.entries(LIP_LAYERS)) {\n const buf = split[key];\n if ((key === \"tongue\" || key === \"teeth\") && !(await hasCoverage(buf))) {\n continue;\n }\n const rgba = await sharp({\n create: {\n width: pic.width,\n height: pic.height,\n channels: 4,\n background: { r: 0, g: 0, b: 0, alpha: 0 },\n },\n })\n .composite([{ input: buf, left, top }])\n .raw()\n .toBuffer();\n const n = pic.width * pic.height;\n const layer: LayerPaint = {\n rgb: new Float32Array(n * 3),\n alpha: new Float32Array(n),\n };\n for (let i = 0; i < n; i++) {\n for (let c = 0; c < 3; c++) layer.rgb[i * 3 + c] = rgba[i * 4 + c];\n layer.alpha[i] = rgba[i * 4 + 3] / 255;\n }\n out.set(role, layer);\n }\n return out;\n}\n\n// ---- checks ----\n\n/** Each written layer in draw order: the roles by ORDER, the custom parts\n * right after the back hair. */\nfunction stackOrder(built: BuiltLayers): Buffer[] {\n const out: Buffer[] = [];\n for (const role of ORDER) {\n const layer = built.roles.get(role);\n if (layer) out.push(encodeLayer(layer));\n if (role === \"hair_back\") {\n for (const p of built.parts) out.push(encodeLayer(p.paint));\n }\n }\n return out;\n}\n\nfunction stackCheck(ctx: CutContext, stacked: Buffer[]): CutCheck {\n const { pic, source, lm } = ctx;\n const n = pic.width * pic.height;\n const mouth = boxMask(pic, lm.mouth.box);\n const flat = pic.backdrop;\n let off = 0;\n let mouthOff = 0;\n const mouthPixels = count(mouth);\n const acc = new Float32Array(4);\n for (let i = 0; i < n; i++) {\n // Over the backdrop when it was keyed, so a soft edge compares as the\n // picture shows it; premultiplied over transparency otherwise.\n acc[0] = flat ? flat[0] : 0;\n acc[1] = flat ? flat[1] : 0;\n acc[2] = flat ? flat[2] : 0;\n acc[3] = flat ? 255 : 0;\n for (const layer of stacked) {\n const a = layer[i * 4 + 3] / 255;\n if (a === 0) continue;\n for (let c = 0; c < 3; c++) {\n acc[c] = layer[i * 4 + c] * a + acc[c] * (1 - a);\n }\n acc[3] = 255 * a + acc[3] * (1 - a);\n }\n // `acc` is premultiplied, which over the opaque backdrop is the colour\n // itself.\n const sa = source.rgba[i * 4 + 3] / 255;\n let worst = Math.abs(acc[3] - source.rgba[i * 4 + 3]);\n for (let c = 0; c < 3; c++) {\n worst = Math.max(worst, Math.abs(acc[c] - source.rgba[i * 4 + c] * sa));\n }\n if (worst <= STACK_LEVELS) continue;\n if (mouth[i]) mouthOff++;\n else off++;\n }\n const value = off / n;\n return {\n id: \"stack\",\n level: \"fail\",\n pass: value <= STACK_LIMIT,\n value: fmt(value, 5),\n limit: STACK_LIMIT,\n hint:\n value <= STACK_LIMIT\n ? \"the layers stack back into the picture\"\n : `the layers stacked differ from the picture on ${off} px (${pct(value)}) outside the mouth's box: paint no layer took, or a fill drawn over paint; find it on preview-labels.png and move the seed or outline that left it out`,\n apart: { mouthBox: fmt(mouthPixels ? mouthOff / mouthPixels : 0, 5) },\n };\n}\n\nconst className = (c: number) =>\n c === HAIR ? \"hair\" : c === SKIN ? \"skin\" : \"neither\";\n\nfunction seedsCheck(ctx: CutContext): CutCheck {\n const { pic, lm, labels, reads } = ctx;\n const problems: string[] = [];\n const unchecked: string[] = [];\n const show = (p: Point) => `[${p[0]}, ${p[1]}]`;\n lm.skinSeeds.forEach((p, k) => {\n const i = pixelIndex(pic, p);\n const where = `landmarks.skinSeeds[${k}] ${show(p)}`;\n if (!labels.solid[i]) {\n problems.push(\n `${where} is on the backdrop: move it onto the face's skin`,\n );\n } else if (labels.classes[i] !== SKIN) {\n problems.push(\n `${where} reads as ${labels.classes[i] === HAIR ? \"hair\" : \"neither hair nor skin (a line, a feature)\"}: move it onto plain skin, or add a landmarks.samples.skin.shadow point on that tone`,\n );\n }\n });\n lm.bodySeeds.forEach((p, k) => {\n const i = pixelIndex(pic, p);\n const where = `landmarks.bodySeeds[${k}] ${show(p)}`;\n if (!labels.solid[i]) {\n problems.push(\n `${where} is on the backdrop: move it onto the neck or the clothes`,\n );\n } else if (labels.classes[i] === HAIR && !labels.bodyOnlyArea[i]) {\n problems.push(\n `${where} reads as hair: move it onto the neck or the clothes, or put a landmarks.bodyOnly polygon over that paint`,\n );\n }\n });\n // A sample is a member of its own set, so it is judged by the classifier\n // the other samples make: one on a line or the other class's paint then\n // reads as what it really is. Only where its tone has another point; a\n // lone point carries its tone, and leaving it out says nothing.\n const all = [...reads.hair, ...reads.skin];\n const tone = (path: string) => path.slice(0, path.lastIndexOf(\"[\"));\n for (const s of all) {\n const own = s.path.includes(\".hair.\") ? HAIR : SKIN;\n if (!s.onPaint) {\n problems.push(\n `${s.path} ${show(s.point)} is on the backdrop: move it onto the ${className(own)}'s paint`,\n );\n continue;\n }\n const others = all.filter(\n (r) => r !== s && r.lab !== null && tone(r.path) === tone(s.path),\n );\n if (others.length === 0) {\n unchecked.push(tone(s.path));\n continue;\n }\n const judge = buildClassifier(withoutSample(reads, s.path));\n const cls = judge && s.rgb ? judge.classify(...s.rgb) : NEITHER;\n if (cls !== own) {\n problems.push(\n `${s.path} ${show(s.point)} reads as ${className(cls)} to the other samples: it sits on a line or on the other class's paint (move it onto a flat patch of ${className(own)}), or on a tone no other point covers (add a second point on that tone)`,\n );\n }\n }\n const note =\n unchecked.length > 0\n ? `; not judged against the rest (one point each): ${unchecked.join(\", \")}`\n : \"\";\n return {\n id: \"seeds\",\n level: \"fail\",\n pass: problems.length === 0,\n value: problems.length,\n limit: 0,\n hint:\n (problems.length === 0\n ? \"every seed and sample sits on its paint\"\n : problems.join(\"; \")) + note,\n };\n}\n\nfunction fillCheck(size: CanvasSize, fill: FillRegion): CutCheck {\n const reach = dilate(size, fill.sources, FILL_REACH);\n let total = 0;\n let far = 0;\n for (let i = 0; i < fill.region.length; i++) {\n if (!fill.region[i]) continue;\n total++;\n if (!reach[i]) far++;\n }\n const value = total ? far / total : 0;\n const pass = fill.limit === null || value <= fill.limit;\n const share = `${pct(value)} of the ${total} px filled are over ${FILL_REACH} px from the paint they are filled from`;\n return {\n id: `fills.${fill.id}`,\n level: \"warn\",\n pass,\n value: fmt(value),\n limit: fill.limit,\n hint:\n fill.limit === null\n ? `${share}: ${fill.hint}`\n : pass\n ? share\n : `${share}: ${fill.hint}`,\n };\n}\n\n/** A region of opaque, backdrop-coloured paint outside the face. */\ninterface Pocket {\n size: number;\n /** A point well inside it (2 px or more from its edge when it has one),\n * one a `backgroundSeeds` point is accepted at when it is `seedable`. */\n at: Point;\n /** Whether `at` is 2 px or more inside. */\n deep: boolean;\n /** Whether POCKET_SEED_SHARE of it takes a `backgroundSeeds` point\n * (`backdropSeed`), `at` among them: one under it is pale paint, near the\n * backdrop's colour on the canvas but past it in the picture (a fine\n * texture the resize averages). */\n seedable: boolean;\n pixels: number[];\n /** Share of the painted pixels POCKET_RING_IN to POCKET_RING_OUT px\n * around it labelled hair: the ink between the pocket and the paint\n * closing it in is looked through. */\n hairShare: number;\n}\n\n/**\n * Backdrop the figure encloses, out of the border flood's reach, stays\n * paint: it reads `neither`, and a flood from the body or the hair runs into\n * it. These are the backdrop-coloured regions outside the face of at least\n * POCKET_PX, largest first.\n */\nexport function findPockets(\n pic: Illustration,\n labels: IllustrationLabels,\n source: CanvasPicture,\n): Pocket[] {\n const { width, height, backdrop } = pic;\n // A picture with no backdrop to key has no backdrop-coloured paint.\n if (!backdrop) return [];\n const n = width * height;\n const candidate = and(\n backdropColoured(pic),\n labels.label.map((l) => (l === LABEL_FACE ? 0 : 1)),\n );\n const owner = new Int32Array(n).fill(-1);\n const deep = erode(pic, candidate, 2);\n const seedable = (i: number) =>\n backdropSeed(source, backdrop, i % width, Math.floor(i / width)).ok;\n const found: Omit<Pocket, \"hairShare\">[] = [];\n for (let s = 0; s < n; s++) {\n if (!candidate[s] || owner[s] !== -1) continue;\n const queue = [s];\n owner[s] = -2;\n for (let q = 0; q < queue.length; q++) {\n const i = queue[q];\n const x = i % width;\n for (const j of [\n x > 0 ? i - 1 : -1,\n x < width - 1 ? i + 1 : -1,\n i - width,\n i + width < n ? i + width : -1,\n ]) {\n if (j >= 0 && candidate[j] && owner[j] === -1) {\n owner[j] = -2;\n queue.push(j);\n }\n }\n }\n if (queue.length < POCKET_PX) continue;\n // Named at the first pixel a seed is accepted at, deep inside if one\n // is; a pocket no seed clears, at its first deep one.\n let deepSeed = -1;\n let anySeed = -1;\n let firstDeep = -1;\n let accepted = 0;\n for (const i of queue) {\n if (deep[i] && firstDeep < 0) firstDeep = i;\n if (!seedable(i)) continue;\n accepted++;\n if (anySeed < 0) anySeed = i;\n if (deep[i] && deepSeed < 0) deepSeed = i;\n }\n const takesSeed = accepted >= POCKET_SEED_SHARE * queue.length;\n const at = takesSeed\n ? deepSeed >= 0\n ? deepSeed\n : anySeed\n : firstDeep >= 0\n ? firstDeep\n : s;\n for (const i of queue) owner[i] = found.length;\n found.push({\n size: queue.length,\n at: [at % width, Math.floor(at / width)],\n deep: deep[at] === 1,\n seedable: takesSeed,\n pixels: queue,\n });\n }\n\n // Every pocket's ring at once: one search out from all of them, a pixel\n // going to the pocket that reaches it first, POCKET_RING_OUT steps deep\n // (8-connected, so a step is a Chebyshev px).\n const ring = new Float64Array(found.length);\n const hair = new Float64Array(found.length);\n const depth = new Int16Array(n).fill(-1);\n let front: number[] = [];\n for (let i = 0; i < n; i++) {\n if (owner[i] >= 0) {\n depth[i] = 0;\n front.push(i);\n }\n }\n for (let d = 1; d <= POCKET_RING_OUT && front.length > 0; d++) {\n const next: number[] = [];\n for (const i of front) {\n const x = i % width;\n const y = (i - x) / width;\n for (let dy = -1; dy <= 1; dy++) {\n const yy = y + dy;\n if (yy < 0 || yy >= height) continue;\n for (let dx = -1; dx <= 1; dx++) {\n const xx = x + dx;\n if (xx < 0 || xx >= width) continue;\n const j = yy * width + xx;\n if (depth[j] !== -1) continue;\n depth[j] = d;\n owner[j] = owner[i];\n next.push(j);\n if (d >= POCKET_RING_IN && !candidate[j] && labels.fg[j]) {\n ring[owner[i]]++;\n if (labels.label[j] === LABEL_HAIR) hair[owner[i]]++;\n }\n }\n }\n }\n front = next;\n }\n return found\n .map((p, k) => ({ ...p, hairShare: ring[k] ? hair[k] / ring[k] : 0 }))\n .sort((a, b) => b.size - a.size);\n}\n\n/**\n * The pockets to key as backdrop on their own, a point inside each: those\n * the hair rings (a gap between strands, between a tail and the head's\n * hair), up to POCKET_KEY_SHARE of the canvas. A pocket rung by skin, cloth\n * or a mix (a white shirt on a white ground) may be paint, and is left to\n * the agent; so is one holding a `paintSeeds` point, and one over the cap.\n */\nexport function hairRungPockets(\n pic: Illustration,\n labels: IllustrationLabels,\n paintSeeds: Point[],\n source: CanvasPicture,\n): Point[] {\n const paint = new Set(paintSeeds.map((p) => pixelIndex(pic, p)));\n const cap = POCKET_KEY_SHARE * pic.width * pic.height;\n return findPockets(pic, labels, source)\n .filter(\n (p) =>\n p.seedable &&\n p.deep &&\n p.size <= cap &&\n p.hairShare >= POCKET_HAIR_SHARE &&\n !p.pixels.some((i) => paint.has(i)),\n )\n .map((p) => p.at);\n}\n\n/** The pockets keyed on their own and those named for `backgroundSeeds`:\n * its value is how many of both, each to be looked at. A pocket no seed is\n * accepted in is pale paint, said so and not counted. */\nfunction pocketsCheck(ctx: CutContext): CutCheck {\n const found = findPockets(ctx.pic, ctx.labels, ctx.source);\n const pockets = found.filter((p) => p.seedable);\n const pale = found.filter((p) => !p.seedable);\n const show = (p: Point) => `[${p[0]}, ${p[1]}]`;\n const list = (ps: Pocket[]) => {\n const named = ps\n .slice(0, POCKETS_NAMED)\n .map((p) => `${show(p.at)} (${p.size} px)`);\n return `${ps.length > named.length ? `the largest ${named.length} at` : \"at\"} ${named.join(\", \")}`;\n };\n const parts: string[] = [];\n const plural = (k: number, one: string, many: string) =>\n `${k} ${k === 1 ? one : many}`;\n // An automatic key may have taken paint: it always warns, first, so the\n // keyed points are looked at on preview-labels.png.\n if (ctx.keyed.length > 0) {\n parts.push(\n `keyed ${plural(ctx.keyed.length, \"gap\", \"gaps\")} the hair rings as backdrop on ${ctx.keyed.length === 1 ? \"its\" : \"their\"} own, at ${ctx.keyed.map(show).join(\", \")}; check each on preview-labels.png, and if one is paint (an ornament, a pale panel), add a point inside it to landmarks.paintSeeds`,\n );\n }\n if (pockets.length > 0) {\n const one = pockets.length === 1;\n parts.push(\n `${plural(pockets.length, \"region\", \"regions\")} of backdrop-coloured paint the border flood cannot reach, ${list(pockets)}, ${one ? \"is\" : \"are\"} cut into a layer: if ${one ? \"it is\" : \"one is\"} backdrop showing through (a gap between the neck and a tail, under an arm), add its point to landmarks.backgroundSeeds`,\n );\n }\n if (pale.length > 0) {\n const one = pale.length === 1;\n parts.push(\n `${plural(pale.length, \"region\", \"regions\")} near the backdrop's colour, ${list(pale)}, ${one ? \"is\" : \"are\"} pale paint, not backdrop (the picture there is too far from the backdrop's colour to key), and ${one ? \"stays\" : \"stay\"} in ${one ? \"its layer\" : \"their layers\"}: ${one ? \"it needs\" : \"they need\"} nothing`,\n );\n }\n const value = ctx.keyed.length + pockets.length;\n return {\n id: \"pockets\",\n level: \"warn\",\n pass: value === 0,\n value,\n limit: 0,\n keyed: ctx.keyed,\n hint:\n parts.length === 0\n ? \"no backdrop-coloured paint outside the face\"\n : parts.join(\"; \"),\n };\n}\n\nfunction frontHairWidthCheck(ctx: CutContext, built: BuiltLayers): CutCheck {\n const { pic, lm } = ctx;\n const row = Math.round((lm.eyes.L.iris.cy + lm.eyes.R.iris.cy) / 2);\n const face = built.roles.get(\"face\")!;\n let x0 = Infinity;\n let x1 = -Infinity;\n for (let x = 0; x < pic.width; x++) {\n if (face.alpha[row * pic.width + x] > 0.5) {\n x0 = Math.min(x0, x);\n x1 = x;\n }\n }\n const faceWidth = x1 >= x0 ? x1 - x0 + 1 : 0;\n const hairBox = maskBox(pic, built.roles.get(\"hair_front\")!.alpha);\n const hairWidth = hairBox ? hairBox[2] - hairBox[0] + 1 : 0;\n if (faceWidth === 0) {\n return {\n id: \"frontHairWidth\",\n level: \"warn\",\n pass: false,\n value: null,\n limit: 1,\n hint: `no face on the eye row ${row}: put landmarks.skinSeeds on the cheeks so the face's flood reaches it`,\n };\n }\n const value = hairWidth / faceWidth;\n return {\n id: \"frontHairWidth\",\n level: \"warn\",\n pass: value <= 1,\n value: fmt(value),\n limit: 1,\n hint:\n value <= 1\n ? `hair_front is ${hairWidth} px wide, the face ${faceWidth} px at the eye row ${row}`\n : `hair_front is ${hairWidth} px wide, wider than the face's ${faceWidth} px at the eye row ${row}: the head turn will be clamped; narrow landmarks.frontHair to the face, leaving the hair beyond it in the back hair`,\n };\n}\n\n/**\n * A side lock as the rig needs it: hair in its polygon; a top row whose\n * pixels each have the front hair's opaque paint right above, so its root is\n * carried under the bangs (a stretch of VISIBLE_MIN_PX or more past them\n * shows the root at rest, the measure's reading); and, at rest, clear of its\n * eye (`overEye`: the rig slides the eye's outer corner under the lock on\n * the turn). Each problem names which way to move the polygon.\n */\nfunction sideHairCheck(\n ctx: CutContext,\n built: BuiltLayers,\n side: \"L\" | \"R\",\n): CutCheck {\n const { pic, labels } = ctx;\n const { opaque } = built;\n const { width } = pic;\n const at = `landmarks.sideHair.${side}`;\n const role = `hair_side_${side}`;\n /** Outward, as the viewer sees it: L is on the viewer's right. */\n const outward = side === \"L\" ? \"right\" : \"left\";\n const mask = labels.hairSide[side]!;\n const problems: string[] = [];\n const box = maskBox(pic, mask);\n if (!box) {\n // Hair inside the polygon that another cut took: the front hair keeps\n // what both claim, and L what both sides' polygons claim.\n const inside = and(labels.hair, polygonMask(pic, ctx.lm.sideHair![side]!));\n const takers = [\n [\n labels.hairFront,\n \"landmarks.frontHair, which keeps the paint both claim\",\n ],\n [\n side === \"R\" ? labels.hairSide.L : undefined,\n \"landmarks.sideHair.L, which keeps the paint both sides' polygons claim\",\n ],\n ] as const;\n const took = takers.filter(([m]) => m && count(and(inside, m)) > 0);\n problems.push(\n count(inside) === 0\n ? `${at} holds no hair, so no ${role} is written: move it onto the lock hanging in front of the ear on the viewer's ${outward}, or check on preview-labels.png that the lock is labelled hair (add landmarks.samples.hair points on its tones)`\n : `all of the hair inside ${at} is taken by ${took.map(([, by]) => by).join(\", and by \")}, so no ${role} is written: ${took.some(([m]) => m !== labels.hairFront) ? \"pull the two polygons apart\" : \"start the polygon below the front hair's edge (or the hair is the bangs', not a side lock)\"}`,\n );\n } else {\n const top = box[1];\n const front = (j: number) => j >= 0 && labels.hairFront[j] && opaque[j];\n // The top row's pixels with no front hair right above, in stretches.\n let shown = 0;\n let x0 = Infinity;\n let x1 = -Infinity;\n let stretch = 0;\n for (let x = box[0]; x <= box[2] + 1; x++) {\n const i = top * width + x;\n if (x <= box[2] && mask[i] && !front(i - width)) {\n stretch++;\n continue;\n }\n if (stretch >= VISIBLE_MIN_PX) {\n shown += stretch;\n x0 = Math.min(x0, x - stretch);\n x1 = Math.max(x1, x - 1);\n }\n stretch = 0;\n }\n if (shown > 0) {\n // How far up the front hair is over those columns, if anywhere.\n let gap = Infinity;\n for (let x = x0; x <= x1; x++) {\n for (let y = top - 1; y >= 0 && top - 1 - y < gap; y--) {\n if (front(y * width + x)) {\n gap = top - 1 - y;\n break;\n }\n }\n }\n const above = Number.isFinite(gap)\n ? `hair_front ends ${gap} px above it there`\n : \"no hair_front lies above it there\";\n problems.push(\n `${role}'s top row (y ${top}) shows past hair_front on ${shown} px, x ${x0}-${x1}: ${above}, so its root shows at rest and is not carried under the bangs. Move ${at}'s top up${Number.isFinite(gap) ? ` ${gap} px or more` : \"\"} into landmarks.frontHair (the two may overlap; the front hair keeps the paint both take), or extend landmarks.frontHair down over the lock's top`,\n );\n }\n const over = overEye(ctx, built, side);\n if (over) {\n problems.push(\n `${role} reaches ${over.px} px over eye_${side} at rest (to x ${over.x} on y ${over.y}), past landmarks.eyes.${side}.box's ${EYE_BOX_SPARE} px of spare and the lock's ${LOCK_LINE} px outline: the rig slides the eye's outer corner under the lock on the turn, so it must lie clear of it at rest. Pull ${at}'s inner edge back ${over.px} px or more to the ${outward}, to x ${side === \"R\" ? \"<=\" : \">=\"} ${over.edge}, and widen landmarks.frontHair over the hair it leaves; if hair is really drawn over the eye there, the cut cannot split it from the eye: report it`,\n );\n }\n }\n return {\n id: `sideHair.${side}`,\n level: \"warn\",\n pass: problems.length === 0,\n value: problems.length,\n limit: 0,\n hint:\n problems.length > 0\n ? problems.join(\"; \")\n : `${role} is ${count(mask)} px, its root carried up to ${SIDE_ROOT_REACH} px under hair_front`,\n };\n}\n\n/** The spare a declared eye box keeps past the drawn eye, px: the opening\n * check asks for 2 to 4. */\nconst EYE_BOX_SPARE = 4;\n\n/**\n * Whether a side lock lies over its eye at rest (the rig slides the eye's\n * outer corner under the lock on the turn, so the corner must be clear of\n * it). A cut eye stops where a lock covers it, so the eye's own layer cannot\n * tell; this reads the box the agent declared round the whole drawn eye\n * instead. On the eye's rows (its layer's, or the box's without one) the\n * lock's paint may reach into the box from its outer edge by the box's spare\n * and the lock's own outline (EYE_BOX_SPARE + LOCK_LINE); `px` is how far\n * past that it reaches, reported from VISIBLE_MIN_PX, with the column it\n * reaches and its row.\n */\nfunction overEye(\n ctx: CutContext,\n built: BuiltLayers,\n side: \"L\" | \"R\",\n): { px: number; x: number; y: number; edge: number } | null {\n const { pic, lm } = ctx;\n const { width } = pic;\n const lock = built.roles.get(`hair_side_${side}`);\n if (!lock) return null;\n // The box's pixels, as the eye is cut from (`boxMask`'s convention).\n const [bx0, by0, bx1, by1] = lm.eyes[side].box;\n const x0 = Math.max(0, Math.ceil(bx0));\n const y0 = Math.max(0, Math.ceil(by0));\n const x1 = Math.min(width - 1, Math.floor(bx1));\n const y1 = Math.min(pic.height - 1, Math.floor(by1));\n const eye = built.roles.get(`eye_${side}`);\n const eyeBox =\n eye &&\n maskBox(\n pic,\n eye.alpha.map((a) => (a >= 0.5 ? 1 : 0)),\n );\n const top = eyeBox ? Math.max(y0, eyeBox[1]) : y0;\n const bottom = eyeBox ? Math.min(y1, eyeBox[3]) : y1;\n const allowed = EYE_BOX_SPARE + LOCK_LINE;\n let best: { px: number; x: number; y: number; edge: number } | null = null;\n for (let y = top; y <= bottom; y++) {\n for (let x = x0; x <= x1; x++) {\n if (lock.alpha[y * width + x] < 0.5) continue;\n const depth = side === \"R\" ? x - x0 + 1 : x1 - x + 1;\n const px = depth - allowed;\n if (px >= VISIBLE_MIN_PX && (!best || px > best.px)) {\n best = {\n px,\n x,\n y,\n edge: side === \"R\" ? x0 + allowed - 1 : x1 - allowed + 1,\n };\n }\n }\n }\n return best;\n}\n\n// ---- previews ----\n\ntype Image = ReturnType<typeof pictureView>;\ntype RGB = [number, number, number];\nconst LABEL_COLOURS: Record<string, RGB> = {\n features: [40, 200, 70],\n face: [255, 190, 140],\n hair_front: [235, 50, 60],\n hair_side: [250, 140, 30],\n hair_back: [150, 60, 220],\n body: [40, 100, 240],\n};\nconst PART_COLOURS: RGB[] = [\n [30, 200, 220],\n [60, 220, 90],\n [235, 205, 30],\n [235, 90, 200],\n];\n/** The label colour's share over the picture: enough to read the label,\n * little enough to see the paint under it. */\nconst LABEL_OPACITY = 0.6;\n\nfunction labelsPreview(ctx: CutContext, built: BuiltLayers): Image {\n const { pic, source, labels } = ctx;\n const img = pictureView(\n source,\n { x: 0, y: 0, w: pic.width, h: pic.height },\n 1,\n );\n const tint = (m: Mask, c: RGB) => {\n for (let i = 0; i < m.length; i++) {\n if (!m[i]) continue;\n for (let k = 0; k < 3; k++) {\n img.rgb[i * 3 + k] = Math.round(\n img.rgb[i * 3 + k] * (1 - LABEL_OPACITY) + c[k] * LABEL_OPACITY,\n );\n }\n }\n };\n tint(labels.face, LABEL_COLOURS.face);\n tint(labels.body, LABEL_COLOURS.body);\n tint(labels.hairFront, LABEL_COLOURS.hair_front);\n tint(labels.hairBack, LABEL_COLOURS.hair_back);\n for (const m of [labels.hairSide.L, labels.hairSide.R]) {\n if (m) tint(m, LABEL_COLOURS.hair_side);\n }\n labels.parts.forEach(({ mask }, k) =>\n tint(mask, PART_COLOURS[k % PART_COLOURS.length]),\n );\n tint(built.features.holes, LABEL_COLOURS.features);\n return img;\n}\n\nfunction landmarksPreview(ctx: CutContext): Image {\n const crop = { x: 0, y: 0, w: ctx.pic.width, h: ctx.pic.height };\n const img = pictureView(ctx.source, crop, 1);\n drawLandmarks(img, ctx.lm as unknown as Record<string, unknown>, crop, 1);\n return img;\n}\n\n// ---- the tool ----\n\n/** The colour classifier, or a refusal naming the set with no sample on\n * paint. */\nfunction classifierFor(\n pic: Illustration,\n lm: IllustrationLandmarks,\n): { classifier: ColourClassifier; reads: SampleReads } {\n const reads = readSamples(pic, lm.samples);\n const classifier = buildClassifier(reads);\n if (classifier === null) {\n const empty = reads.hair.every((r) => r.lab === null) ? \"hair\" : \"skin\";\n throw new AutoRigInputError(\n `landmarks.samples.${empty}: no sample is on paint, so there is nothing to tell hair from skin by; move them onto the ${empty}`,\n );\n }\n return { classifier, reads };\n}\n\n/**\n * Cut the picture into layers in `outputDir`. Only caller-input failures\n * (`AutoRigInputError`) come back as `{ ok: false, error }`; a refusal\n * writes nothing. A write that fails part-way says the dir is now a mix:\n * the files written before it replace an earlier cut's of the same name, and\n * the rest of that cut's files (a role this cut would have removed too) are\n * still there until the cut is run again.\n */\nexport async function cutLayersFromIllustration(\n input: CutLayersFromIllustrationInput,\n): Promise<CutLayersFromIllustrationResult> {\n try {\n // First, so a refused target costs no decode.\n const outDir = resolveOutputDir(input.outputDir);\n if (\n (input.mouthKeyed === undefined) !==\n (input.mouthInterior === undefined)\n ) {\n throw new AutoRigInputError(\n input.mouthKeyed === undefined\n ? \"mouthInterior needs mouthKeyed: the lip set is cut from the keyed open mouth, and the interior is fitted into its opening; give both, or neither to keep the drawn mouth\"\n : \"mouthKeyed needs mouthInterior: the drawn interior is fitted into the keyed opening; give both, or neither to keep the drawn mouth\",\n );\n }\n const source = await readPictureOnCanvas(input.imagePath);\n const lm = validateLandmarks(input.landmarks, source);\n // Keyed before the cut, so a key that fails costs no cut.\n const lips =\n input.mouthKeyed === undefined || input.mouthInterior === undefined\n ? undefined\n : await readLipSources(\n resolveInputPath(input.mouthKeyed, \"mouthKeyed\"),\n resolveInputPath(input.mouthInterior, \"mouthInterior\"),\n );\n const pass = async (backgroundSeeds: Point[]) => {\n const pic = await matteIllustration(source, { backgroundSeeds });\n const { classifier, reads } = classifierFor(pic, lm);\n const classes = classifyPicture(pic, classifier, PAINT_ALPHA);\n const labels = labelIllustration(pic, lm, classes);\n return { pic, classifier, reads, labels };\n };\n let first = await pass(lm.backgroundSeeds);\n // Gaps between strands are keyed without a seed: one more pass with a\n // point inside each, not a loop (a gap a key opens cannot ring another).\n const keyed =\n first.pic.background === \"flat\"\n ? hairRungPockets(first.pic, first.labels, lm.paintSeeds, source)\n : [];\n if (keyed.length > 0) first = await pass([...lm.backgroundSeeds, ...keyed]);\n const { pic, classifier, reads, labels } = first;\n const ctx: CutContext = {\n pic,\n source,\n lm,\n classifier,\n reads,\n labels,\n keyed,\n };\n\n const built = buildLayers(ctx, lips !== undefined);\n const lipLayers = lips\n ? await lipSetLayers(ctx, lips)\n : new Map<string, LayerPaint>();\n const checks: CutCheck[] = [\n stackCheck(ctx, stackOrder(built)),\n seedsCheck(ctx),\n ...built.features.checks,\n ...built.fills.map((f) => fillCheck(pic, f)),\n frontHairWidthCheck(ctx, built),\n ...([\"L\", \"R\"] as const)\n .filter((side) => lm.sideHair?.[side])\n .map((side) => sideHairCheck(ctx, built, side)),\n pocketsCheck(ctx),\n ];\n\n // Encode everything before writing anything.\n const png = (layer: LayerPaint) =>\n sharp(encodeLayer(layer), {\n raw: { width: pic.width, height: pic.height, channels: 4 },\n })\n .png()\n .toBuffer();\n const rgbPng = (img: Image) =>\n sharp(img.rgb, {\n raw: { width: img.width, height: img.height, channels: 3 },\n })\n .png()\n .toBuffer();\n const roleFiles: { role: string; layer: LayerPaint; data: Buffer }[] = [];\n for (const role of ORDER) {\n const layer = built.roles.get(role) ?? lipLayers.get(role);\n if (layer) roleFiles.push({ role, layer, data: await png(layer) });\n }\n const partFiles = await Promise.all(\n built.parts.map(async (p) => ({ ...p, data: await png(p.paint) })),\n );\n const previews = {\n labels: await rgbPng(labelsPreview(ctx, built)),\n landmarks: await rgbPng(landmarksPreview(ctx)),\n };\n\n let customDir = path.join(outDir, \"custom\");\n if (partFiles.length > 0) {\n try {\n fs.mkdirSync(customDir, { recursive: true });\n } catch (e) {\n throw new AutoRigInputError(\n `write: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n // Before any layer is written: a `custom` symlink out of the output\n // dir would carry the writes with it.\n customDir = confineToWorkingDirectory(\n outDir,\n customDir,\n \"custom parts dir\",\n customDir,\n );\n }\n const labelsPath = path.join(outDir, \"preview-labels.png\");\n const landmarksPath = path.join(outDir, \"preview-landmarks.png\");\n let layers: CutLayer[];\n let customParts: CutCustomPart[];\n try {\n layers = roleFiles.map(({ role, layer, data }) => {\n const file = path.join(outDir, `${role}.png`);\n writeFileAtomic(file, data);\n return { role, path: file, ...coverage(pic, layer) };\n });\n customParts = partFiles.map(({ id, tie, paint, data }) => {\n const file = path.join(customDir, `${id}.png`);\n writeFileAtomic(file, data);\n return { id, path: file, tie, ...coverage(pic, paint) };\n });\n writeFileAtomic(labelsPath, previews.labels);\n writeFileAtomic(landmarksPath, previews.landmarks);\n } catch (e) {\n // Past the inputs' checks, unlike a refusal: the dir is a mix of this\n // cut's files written so far and an earlier cut's other files.\n if (!(e instanceof AutoRigInputError)) throw e;\n throw new AutoRigInputError(\n `${e.message}; the cut stopped part-way: in ${outDir} the files it wrote before that one replace an earlier cut's of the same name, and the rest of the earlier cut's files (any role this cut would have removed too) are still there, so the dir is a mix of the two until the cut is run again`,\n );\n }\n // An earlier cut into the same dir may have written a role this one does\n // not (the drawn `mouth` before a lip set, or the set before the drawn\n // mouth): left behind it would be measured and rigged with these, and\n // the rig refuses the mouth beside the lip set. Removed only once every\n // file of this cut is written, so a failed write removes nothing (the\n // dir is then a mix, which the message says). Only the fixed role names,\n // under the confined outDir, are ever removed.\n for (const role of ORDER) {\n if (roleFiles.some((f) => f.role === role)) continue;\n fs.rmSync(path.join(outDir, `${role}.png`), { force: true });\n }\n\n let measure: CutMeasure;\n try {\n const report = await measureDir(outDir, undefined, { inPlace: true });\n measure = {\n warnings: report.warnings,\n ...(report.lips && { lips: report.lips }),\n };\n } catch (e) {\n // The layers are written: a dir the measure refuses (a stray PNG it\n // cannot decode, too many files) is reported, not a refusal.\n if (!(e instanceof AutoRigInputError)) throw e;\n measure = {\n warnings: [`the written layers could not be measured: ${e.message}`],\n };\n }\n\n return {\n ok: true,\n outputDir: outDir,\n canvas: { width: pic.width, height: pic.height },\n layers,\n customParts,\n previews: { labels: labelsPath, landmarks: landmarksPath },\n checks,\n measure,\n passed: checks.every((c) => c.pass || c.level === \"warn\"),\n };\n } catch (e) {\n if (e instanceof AutoRigInputError) return { ok: false, error: e.message };\n throw e;\n }\n}\n\n/** A layer's painted box and pixel count, as written (alpha over 0 at 8\n * bits). */\nfunction coverage(\n size: CanvasSize,\n layer: LayerPaint,\n): { box: Box | null; pixels: number } {\n const on = Uint8Array.from(layer.alpha, (a) =>\n Math.round(a * 255) > 0 ? 1 : 0,\n );\n return { box: maskBox(size, on), pixels: count(on) };\n}\n\n/**\n * A cut as the tool's text: the written files one per line, a `CHECK` line\n * per check (`WARN` a warn-level check that did not pass, `FAIL` a\n * fail-level one), the `MEASURE:` lines, and last `CUT pass` or `CUT FAIL:`\n * with the failed fail-level checks.\n */\nexport function formatCutReport(\n r: Extract<CutLayersFromIllustrationResult, { ok: true }>,\n): string {\n const show = (v: number | null) => (v === null ? \"none\" : `${v}`);\n const checks = r.checks.map((c) => {\n const verdict = c.pass ? \"pass\" : c.level === \"warn\" ? \"WARN\" : \"FAIL\";\n const apart = c.apart\n ? `; the mouth's box, counted apart: ${pct(c.apart.mouthBox)} of it off`\n : \"\";\n return `CHECK ${c.id}: ${verdict} ${show(c.value)} (limit ${show(c.limit)}) ${c.hint}${apart}`;\n });\n const measure = [\n ...(r.measure.lips ? [formatLipFacts(r.measure.lips)] : []),\n ...(r.measure.warnings.length > 0\n ? r.measure.warnings\n : [\"all geometry checks passed\"]),\n ].map((line) => `MEASURE: ${line}`);\n const failed = r.checks\n .filter((c) => !c.pass && c.level === \"fail\")\n .map((c) => c.id);\n return [\n ...r.layers.map((l) => l.path),\n ...r.customParts.map((p) => p.path),\n r.previews.labels,\n r.previews.landmarks,\n ...checks,\n ...measure,\n failed.length === 0 ? \"CUT pass\" : `CUT FAIL: ${failed.join(\", \")}`,\n ].join(\"\\n\");\n}\n","/**\n * Hair, skin or neither, by colour, from the samples an agent placed on the\n * picture rather than from a threshold chosen for one picture.\n *\n * Colours are compared in OKLab: distances there track how different two\n * colours look about evenly across hues and lightness, so \"nearer\" means the\n * same for orange hair on warm skin as for pink hair on peach. Each sample\n * reads the median of a small patch, so one stray pixel under it does not\n * move a whole class.\n *\n * A set is its samples joined to the median of its `base` samples: a pixel's\n * distance to the set is its distance to the nearest of those segments, so a\n * tone between the base and a sampled shadow or highlight is as near as the\n * samples themselves. A pixel takes the nearer set when it lies within that\n * set's reach, or is at most RATIO as far from it as from the other set; it\n * is `neither` otherwise: ink, ribbons, clothes, eye paint, which lie about\n * as far from either. The reach scales with how far apart the two sets are\n * and with the set's own spread and noise, never with an absolute colour\n * level, so two close sets get a tight reach and a painterly picture a wider\n * one; the ratio carries a set's unsampled shades on its far side from the\n * other set however close the two sets come.\n */\n\nimport {\n median,\n pixelIndex,\n type Illustration,\n type Point,\n} from \"./illustration\";\nimport type { IllustrationSamples } from \"./illustration-landmarks\";\n\nexport type Lab = [number, number, number];\n\n/** A pixel's colour class. */\nexport const NEITHER = 0;\nexport const HAIR = 1;\nexport const SKIN = 2;\nexport type ColourClass = typeof NEITHER | typeof HAIR | typeof SKIN;\n\nconst toLinear = (v: number): number => {\n const c = v / 255;\n return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;\n};\n\n/** sRGB, 0..255 per channel, to OKLab (L 0..1). */\nexport function srgbToOklab(r: number, g: number, b: number): Lab {\n const lr = toLinear(r);\n const lg = toLinear(g);\n const lb = toLinear(b);\n const l = Math.cbrt(\n 0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb,\n );\n const m = Math.cbrt(\n 0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb,\n );\n const s = Math.cbrt(\n 0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb,\n );\n return [\n 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,\n 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,\n 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,\n ];\n}\n\nexport const dist = (a: Lab, b: Lab): number =>\n Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);\n\n/** Distance from `p` to the segment `a`-`b`. */\nexport function segmentDistance(p: Lab, a: Lab, b: Lab): number {\n let len2 = 0;\n let along = 0;\n for (let c = 0; c < 3; c++) {\n const d = b[c] - a[c];\n len2 += d * d;\n along += (p[c] - a[c]) * d;\n }\n const t = len2 > 0 ? Math.max(0, Math.min(1, along / len2)) : 0;\n return Math.hypot(\n p[0] - a[0] - t * (b[0] - a[0]),\n p[1] - a[1] - t * (b[1] - a[1]),\n p[2] - a[2] - t * (b[2] - a[2]),\n );\n}\n\n/** Half-size of the square patch a sample reads: 5 x 5 px. */\nconst PATCH_RADIUS = 2;\n/** Alpha at which a pixel counts as paint for a sample's patch and for the\n * \"is this sample on paint\" test. */\nconst PAINT_ALPHA = 0.5;\n\n/** One sample point as read off the picture. */\nexport interface SampleRead {\n /** Its landmark path, for the report: `landmarks.samples.hair.base[0]`. */\n path: string;\n point: Point;\n /** The pixel under the point is paint, not backdrop. */\n onPaint: boolean;\n /** The patch's median colour; null when the patch holds no paint. */\n lab: Lab | null;\n /** The same median in sRGB, 0..255 per channel. */\n rgb: [number, number, number] | null;\n /** The patch's median distance from that colour: the paint's own\n * texture and noise there. */\n noise: number;\n}\n\n/** Read one sample: the median colour of the paint in its patch. */\nexport function readSample(\n pic: Illustration,\n point: Point,\n path: string,\n): SampleRead {\n const { width, height, rgb, alpha } = pic;\n const centre = pixelIndex(pic, point);\n const px = centre % width;\n const py = (centre - px) / width;\n const labs: Lab[] = [];\n const rgbs: number[][] = [];\n for (let y = py - PATCH_RADIUS; y <= py + PATCH_RADIUS; y++) {\n for (let x = px - PATCH_RADIUS; x <= px + PATCH_RADIUS; x++) {\n if (x < 0 || y < 0 || x >= width || y >= height) continue;\n const i = y * width + x;\n if (alpha[i] < PAINT_ALPHA) continue;\n rgbs.push([rgb[i * 3], rgb[i * 3 + 1], rgb[i * 3 + 2]]);\n }\n }\n const onPaint = alpha[centre] >= PAINT_ALPHA;\n if (rgbs.length === 0) {\n return { path, point, onPaint, lab: null, rgb: null, noise: 0 };\n }\n // The median per sRGB channel, one patch colour both spaces agree on.\n const mid = [0, 1, 2].map((c) => median(rgbs.map((v) => v[c]))) as [\n number,\n number,\n number,\n ];\n const lab = srgbToOklab(...mid);\n for (const v of rgbs) labs.push(srgbToOklab(v[0], v[1], v[2]));\n return {\n path,\n point,\n onPaint,\n lab,\n rgb: mid,\n noise: median(labs.map((v) => dist(v, lab))),\n };\n}\n\nexport interface SampleReads {\n hair: SampleRead[];\n skin: SampleRead[];\n /** How many of `hair`, from its start, are `base` samples. */\n hairBase: number;\n /** How many of `skin`, from its start, are `base` samples. */\n skinBase: number;\n}\n\n/** Every sample of the landmarks, read, each set's `base` first. */\nexport function readSamples(\n pic: Illustration,\n samples: IllustrationSamples,\n): SampleReads {\n const at = \"landmarks.samples\";\n const read = (set: string, tone: string, pts: Point[] | undefined) =>\n (pts ?? []).map((p, k) => readSample(pic, p, `${at}.${set}.${tone}[${k}]`));\n const hair = [\n ...read(\"hair\", \"base\", samples.hair.base),\n ...read(\"hair\", \"shadow\", samples.hair.shadow),\n ...read(\"hair\", \"highlight\", samples.hair.highlight),\n ];\n const skin = [\n ...read(\"skin\", \"base\", samples.skin.base),\n ...read(\"skin\", \"shadow\", samples.skin.shadow),\n ];\n return {\n hair,\n skin,\n hairBase: samples.hair.base.length,\n skinBase: samples.skin.base.length,\n };\n}\n\n/** A set's reach is at least this share of the gap between the two sets:\n * under half, so the bisector between them is never past either reach and\n * paint far off both (ink, cloth) stays `neither`. */\nconst SEP_SHARE = 0.35;\n/** ... and at least this many times its samples' patch noise (the lower\n * median over the set, so one sample on a busy patch does not widen it),\n * so a textured paint's own grain stays in its class. */\nconst NOISE_SCALE = 3;\n/** ... and at least this share of its own spread (its base to its farthest\n * sample): a set sampled over a wide range of tones has unsampled tones\n * beside them. */\nconst SPREAD_SHARE = 0.25;\n/** A colour at most this share as far from one set as from the other is\n * that set's, past its reach: clearly on its side. A set's own unsampled\n * shades measure about a quarter; ink, cloth, a ribbon or grey, about as\n * far from both sets, half or more. Without it, two close sets (pale hair\n * on pale skin) leave every unsampled shade `neither`, and a body flood\n * takes shaded locks. */\nconst RATIO = 1 / 3;\n/** Merge samples closer than this share of the gap between the sets: a long\n * sample list of one tone costs one segment, not hundreds. */\nconst MERGE_SHARE = 0.05;\n\n/** One colour set: segments from its base's median to each sample. */\ninterface ColourSet {\n anchor: Lab;\n members: Lab[];\n}\n\nfunction setDistance(p: Lab, set: ColourSet): number {\n let best = Infinity;\n for (const m of set.members) {\n best = Math.min(best, segmentDistance(p, set.anchor, m));\n }\n return best;\n}\n\nfunction buildSet(reads: SampleRead[], baseCount: number): ColourSet | null {\n const labs = reads.filter((r) => r.lab !== null).map((r) => r.lab!);\n const base = reads\n .slice(0, baseCount)\n .filter((r) => r.lab !== null)\n .map((r) => r.lab!);\n const from = base.length > 0 ? base : labs;\n if (from.length === 0) return null;\n const anchor = [0, 1, 2].map((c) => median(from.map((v) => v[c]))) as Lab;\n return { anchor, members: labs };\n}\n\nfunction merge(set: ColourSet, tolerance: number): ColourSet {\n const kept: Lab[] = [];\n for (const m of set.members) {\n if (!kept.some((k) => dist(k, m) <= tolerance)) kept.push(m);\n }\n return { anchor: set.anchor, members: kept };\n}\n\nexport interface ColourClassifier {\n /** The class of an sRGB colour, 0..255 per channel. */\n classify(r: number, g: number, b: number): ColourClass;\n /** How far an sRGB colour lies from each set (OKLab), unquantised: what\n * a mix is measured by, as a share of the way toward another paint. */\n distances(r: number, g: number, b: number): { hair: number; skin: number };\n /** How far apart the two sets are (OKLab). */\n separation: number;\n /** How far past each set a colour still belongs to it (OKLab). */\n reach: { hair: number; skin: number };\n}\n\n/** 6 bits per channel: a 4-level quantisation, far under any gap between\n * two classes, that lets a picture's few thousand distinct colours be\n * classified once each. */\nconst LUT_BITS = 6;\nconst LUT_SHIFT = 8 - LUT_BITS;\n\n/**\n * The classifier for one picture's samples; null when either set has no\n * sample on paint, so there is nothing to tell hair from skin by.\n */\nexport function buildClassifier(reads: SampleReads): ColourClassifier | null {\n const hair0 = buildSet(reads.hair, reads.hairBase);\n const skin0 = buildSet(reads.skin, reads.skinBase);\n if (hair0 === null || skin0 === null) return null;\n let separation = Infinity;\n for (const m of hair0.members) {\n separation = Math.min(separation, setDistance(m, skin0));\n }\n for (const m of skin0.members) {\n separation = Math.min(separation, setDistance(m, hair0));\n }\n const hair = merge(hair0, MERGE_SHARE * separation);\n const skin = merge(skin0, MERGE_SHARE * separation);\n\n const reachOf = (set: ColourSet, own: SampleRead[]): number => {\n // The lower median: of two samples, one straddling a line, the other.\n const noises = own\n .filter((r) => r.lab !== null)\n .map((r) => r.noise)\n .sort((x, y) => x - y);\n const noise = noises[(noises.length - 1) >> 1];\n const spread = Math.max(0, ...set.members.map((m) => dist(m, set.anchor)));\n return Math.max(\n SEP_SHARE * separation,\n NOISE_SCALE * noise,\n SPREAD_SHARE * spread,\n );\n };\n const reach = {\n hair: reachOf(hair, reads.hair),\n skin: reachOf(skin, reads.skin),\n };\n\n const lut = new Int8Array(1 << (3 * LUT_BITS)).fill(-1);\n const classify = (r: number, g: number, b: number): ColourClass => {\n const q = (v: number) =>\n Math.max(0, Math.min(255, Math.round(v))) >> LUT_SHIFT;\n const key = (q(r) << (2 * LUT_BITS)) | (q(g) << LUT_BITS) | q(b);\n const hit = lut[key];\n if (hit >= 0) return hit as ColourClass;\n // The quantisation cell's centre stands for the cell.\n const centre = (k: number) => (k << LUT_SHIFT) + (1 << LUT_SHIFT) / 2 - 0.5;\n const lab = srgbToOklab(\n centre(key >> (2 * LUT_BITS)),\n centre((key >> LUT_BITS) & ((1 << LUT_BITS) - 1)),\n centre(key & ((1 << LUT_BITS) - 1)),\n );\n const dh = setDistance(lab, hair);\n const ds = setDistance(lab, skin);\n // A colour as near both sets (two sets sampled on the same paint) goes\n // to hair: a tie has to fall somewhere, and the regions and the floods\n // then decide.\n const cls: ColourClass =\n dh <= ds\n ? dh <= reach.hair || dh <= RATIO * ds\n ? HAIR\n : NEITHER\n : ds <= reach.skin || ds <= RATIO * dh\n ? SKIN\n : NEITHER;\n lut[key] = cls;\n return cls;\n };\n const distances = (r: number, g: number, b: number) => {\n const lab = srgbToOklab(r, g, b);\n return { hair: setDistance(lab, hair), skin: setDistance(lab, skin) };\n };\n return { classify, distances, separation, reach };\n}\n\n/** Every pixel's class by its colour (the paint's own, the backdrop taken\n * out of a soft edge); 0 where alpha is under `minAlpha`, so a caller reads\n * NEITHER there only together with alpha. */\nexport function classifyPicture(\n pic: Illustration,\n classifier: ColourClassifier,\n minAlpha: number,\n): Uint8Array {\n const n = pic.width * pic.height;\n const out = new Uint8Array(n);\n for (let i = 0; i < n; i++) {\n if (pic.alpha[i] < minAlpha) continue;\n out[i] = classifier.classify(\n pic.rgb[i * 3],\n pic.rgb[i * 3 + 1],\n pic.rgb[i * 3 + 2],\n );\n }\n return out;\n}\n\n/** `reads` without the sample at `path`: the classifier a sample is judged\n * by, so a sample on the wrong paint cannot vouch for itself. */\nexport function withoutSample(reads: SampleReads, path: string): SampleReads {\n const drop = (list: SampleRead[], base: number) => {\n const k = list.findIndex((r) => r.path === path);\n return k < 0\n ? { list, base }\n : {\n list: list.filter((_, j) => j !== k),\n base: k < base ? base - 1 : base,\n };\n };\n const hair = drop(reads.hair, reads.hairBase);\n const skin = drop(reads.skin, reads.skinBase);\n return {\n hair: hair.list,\n skin: skin.list,\n hairBase: hair.base,\n skinBase: skin.base,\n };\n}\n","/**\n * What the stages of an in-place cut share: the context they cut from, a\n * layer in memory, a check, and the fills every stage builds layers with.\n */\n\nimport {\n erode,\n pushPull,\n type CanvasPicture,\n type Illustration,\n type Mask,\n type Point,\n} from \"./illustration\";\nimport {\n HAIR,\n SKIN,\n type ColourClassifier,\n type SampleReads,\n} from \"./illustration-colour\";\nimport type { IllustrationLabels } from \"./illustration-labels\";\nimport type { IllustrationLandmarks } from \"./illustration-landmarks\";\n\n/** One number an agent acts on. */\nexport interface CutCheck {\n id: string;\n /** `fail`: the cut is wrong and `passed` is false while it fails.\n * `warn`: worth a look; `passed` ignores it. */\n level: \"fail\" | \"warn\";\n pass: boolean;\n /** Null when there is nothing to measure (no face on the eye row). */\n value: number | null;\n /** Null for a number reported without a limit. */\n limit: number | null;\n /** Which landmark to move, and which way, when the check fails. */\n hint: string;\n /** Measured apart from `value`: on `stack`, the share of the mouth box's\n * own pixels off (the mouth is replaced later, so it does not count). */\n apart?: { mouthBox: number };\n /** On `pockets`: the hair-rung pockets keyed as backdrop on their own, a\n * point inside each. */\n keyed?: Point[];\n}\n\n/** A layer in memory: the paint's colour and its coverage per pixel. Its\n * `rgb` is the picture's own, shared, until a fill writes to it. */\nexport interface LayerPaint {\n rgb: Float32Array;\n alpha: Float32Array;\n}\n\n/** Everything the cut works from, for the stages that build layers. */\nexport interface CutContext {\n pic: Illustration;\n source: CanvasPicture;\n lm: IllustrationLandmarks;\n classifier: ColourClassifier;\n reads: SampleReads;\n labels: IllustrationLabels;\n /** Pockets keyed as backdrop on their own, a point inside each. */\n keyed: Point[];\n}\n\n/** A fill's sources stay this far inside their paint: a pixel beside a line\n * is half line, and its colour would streak the fill. */\nexport const SOURCE_INSET = 2;\n\n/** Skin a fill may read from: the face's flood, skin by colour, solid, off\n * `holes` (the features, once they leave the face) and inset from lines. */\nexport function skinSources(ctx: CutContext, holes: Mask | null): Mask {\n const { labels } = ctx;\n const k = labels.skin.map((v, i) =>\n v && labels.solid[i] && labels.classes[i] === SKIN && !holes?.[i] ? 1 : 0,\n );\n return erode(ctx.pic, k, SOURCE_INSET);\n}\n\n/** Hair a fill may read from inside `mask`: hair by colour (no ink), solid,\n * inset from lines. */\nexport function hairSources(ctx: CutContext, mask: Mask): Mask {\n const { labels } = ctx;\n const k = mask.map((v, i) =>\n v && labels.solid[i] && labels.classes[i] === HAIR ? 1 : 0,\n );\n return erode(ctx.pic, k, SOURCE_INSET);\n}\n\n/** The picture's colours with every pixel off `sources` filled from them. */\nexport function fillFrom(pic: Illustration, sources: Mask): Float32Array {\n return pushPull(pic, pic.rgb, sources);\n}\n\n/** A layer of the picture's own paint over `mask`. */\nexport function paintOf(pic: Illustration, mask: Mask): LayerPaint {\n const alpha = new Float32Array(mask.length);\n for (let i = 0; i < mask.length; i++) if (mask[i]) alpha[i] = pic.alpha[i];\n return { rgb: pic.rgb, alpha };\n}\n","/**\n * The label map of an in-place cut: every painted pixel of the picture to\n * one of face, hair or body, then the hair split into the front hair, each\n * side lock, the back hair and each custom part.\n *\n * Colour decides first (`illustration-colour.ts`); where colour cannot tell\n * (lash ink the colour of near-black hair, a dark jacket under it) the\n * landmark regions do: nothing inside an eye box, a brow band, the nose or\n * mouth box or a `bodyOnly` polygon is hair. Floods from the agent's seeds\n * then take the face and the body, and whatever paint is still unlabelled\n * takes its nearest label.\n */\n\nimport {\n and,\n andNot,\n boxMask,\n dilate,\n erode,\n fillHoles,\n flood,\n majority,\n or,\n polygonMask,\n type Box,\n type CanvasSize,\n type Illustration,\n type Mask,\n} from \"./illustration\";\nimport { HAIR, NEITHER, SKIN, srgbToOklab } from \"./illustration-colour\";\nimport type {\n IllustrationBrow,\n IllustrationCustomCut,\n IllustrationLandmarks,\n} from \"./illustration-landmarks\";\n\n/** A label-map value. Feature layers get codes of their own past these. */\nexport const LABEL_NONE = 0;\nexport const LABEL_FACE = 1;\nexport const LABEL_HAIR = 2;\nexport const LABEL_BODY = 3;\n\n/** Alpha past which paint is solid enough to flood through or to read as a\n * fill's source. */\nexport const SOLID_ALPHA = 0.5;\n/** Alpha past which paint counts as hair; under it a strand's soft edge,\n * whose decontaminated colour is unreliable, goes by its nearest label.\n * Too high drops thin strands from the hair; too low lets edge noise in. */\nconst HAIR_ALPHA = 0.3;\n/** Alpha past which a pixel is painted at all. */\nexport const PAINT_ALPHA = 0.02;\n/** Hair pieces under this many px are specks if paint rings them (a button,\n * a blush speck); too small keeps hair-coloured specks on the face and the\n * clothes, too big gives real locks to whatever surrounds them. */\nconst SPECK_PX = 400;\n/** A speck whose 2 px ring is more than this share paint that is not hair\n * belongs to that paint; lower takes strand tips over clothes away from\n * the hair. */\nconst SPECK_RING_SHARE = 0.6;\n/** Speckle between hair and skin is smoothed with a (2r+1)² majority. */\nconst SMOOTH_RADIUS = 2;\n/** The face's outline: paint up to this many px past its skin flood (a\n * drawn line's width at the canvas size). Narrower leaves the outer half\n * of the line to the hair or the body; wider takes paint beside it. */\nconst OUTLINE_PX = 3;\n/** Hair-coloured paint thinner than 2r+1 px is a line, not a lock, where it\n * runs along the face's or the neck's skin. */\nconst THIN_RADIUS = 2;\n/** How far through paint from that skin such a line may lie: its whole\n * width (under 2r+1 px) and the soft edge between it and the skin. A wisp\n * with backdrop between it and the skin is not reached. */\nconst THIN_BESIDE_SKIN = 2 * THIN_RADIUS + 2;\n/** Paint that is neither hair nor skin this close to hair is the hair's own\n * outline (on thick paint, a collar or a ribbon, a thin rim). Smaller lets\n * a body flood run along the hair's outline. */\nconst INK_REACH = 3;\n/** A hair piece as thin as a drawn line (less than half of it left by an\n * erosion of LINE_RADIUS: a line and its soft edge, not a lock) holding no\n * hair sample, with more than this share of its 2 px ring the body's paint, is\n * the body's outline inked in a colour near the hair's: an outline has the\n * body on one side of it, about half its ring; a loose wisp has backdrop\n * all round. */\nconst OUTLINE_RING_SHARE = 0.3;\n/** Neither-paint thinner than 2r+1 px is a drawn line rather than cloth. */\nconst LINE_RADIUS = 3;\n/** A line joined to the hair is the hair's along this many px of itself:\n * past a line's far edge, which the soft edge between hair and line can\n * push beyond INK_REACH, and no further along a line that leaves the\n * hair (a collar's outline). */\nconst LINE_REACH = 8;\n\n/** The smallest box holding every on pixel; null for an empty mask. */\nexport function maskBox(size: CanvasSize, m: ArrayLike<number>): Box | null {\n let x0 = Infinity;\n let y0 = Infinity;\n let x1 = -Infinity;\n let y1 = -Infinity;\n for (let y = 0; y < size.height; y++) {\n for (let x = 0; x < size.width; x++) {\n if (!m[y * size.width + x]) continue;\n if (x < x0) x0 = x;\n if (x > x1) x1 = x;\n if (y < y0) y0 = y;\n y1 = y;\n }\n }\n return x1 < 0 ? null : [x0, y0, x1, y1];\n}\n\n/**\n * Where a lock interrupts the face's own paint: the lock's pixels on a run\n * of it along a row or a column whose pixels just past both ends are the\n * face's (a strand crossing from the ear to the cheek, or over the cheek).\n * A run with the face on one side only (beside the ear's outer edge, under\n * the lobe, beside the jaw) has hair behind it, and is left out. Its edges\n * are the lock's own outline along the strand, and across it the row or\n * column where the face's paint on one side ends. With `must`, only runs\n * holding a pixel of it count.\n */\nexport function bridges(\n size: CanvasSize,\n lock: Mask,\n face: Mask,\n must?: Mask,\n): Mask {\n const { width, height } = size;\n const out = new Uint8Array(width * height);\n /** Runs of `lock` along `n` lines of `len` pixels, pixel k of line j at\n * `at(j, k)`. */\n const along = (\n n: number,\n len: number,\n at: (j: number, k: number) => number,\n ) => {\n for (let j = 0; j < n; j++) {\n for (let k = 0; k < len; ) {\n if (!lock[at(j, k)]) {\n k++;\n continue;\n }\n const start = k;\n let held = !must;\n while (k < len && lock[at(j, k)]) {\n if (must?.[at(j, k)]) held = true;\n k++;\n }\n if (!held) continue;\n if (start > 0 && k < len && face[at(j, start - 1)] && face[at(j, k)]) {\n for (let q = start; q < k; q++) out[at(j, q)] = 1;\n }\n }\n }\n };\n along(height, width, (y, x) => y * width + x);\n along(width, height, (x, y) => y * width + x);\n return out;\n}\n\n/** Where a pixel lies against a brow's line (`browGeometry`). */\nexport interface BrowPlace {\n /** Distance from the line, px. */\n d: number;\n /** The y part of the offset from the line's nearest point: over 0 below\n * it. */\n dy: number;\n /** The band's half-width at the nearest point. */\n half: number;\n /** Past the line's first point (its tail) or last point (its inner end)\n * rather than beside it; null beside it. */\n end: \"tail\" | \"end\" | null;\n /** The nearest point lies in the line's first third, where the band\n * narrows to tailHalfWidth. */\n third: boolean;\n /** The line's direction there, a unit vector. */\n tx: number;\n ty: number;\n}\n\n/**\n * A brow's line as a band: the half-width runs from `tailHalfWidth` at the\n * tail up to `halfWidth` a third of the way along, where the brow reaches\n * its full thickness. Returns where a pixel lies against it.\n */\nexport function browGeometry(\n brow: IllustrationBrow,\n): (x: number, y: number) => BrowPlace {\n const { line, halfWidth, tailHalfWidth } = brow;\n const lengths = [0];\n for (let k = 1; k < line.length; k++) {\n lengths.push(\n lengths[k - 1] +\n Math.hypot(line[k][0] - line[k - 1][0], line[k][1] - line[k - 1][1]),\n );\n }\n const total = lengths.at(-1)!;\n const halfAt = (s: number) =>\n total > 0\n ? tailHalfWidth +\n (halfWidth - tailHalfWidth) * Math.min(1, (3 * s) / total)\n : halfWidth;\n return (x, y) => {\n let best: BrowPlace | null = null;\n for (let k = 0; k + 1 < line.length; k++) {\n const [ax, ay] = line[k];\n const [bx, by] = line[k + 1];\n const len2 = (bx - ax) ** 2 + (by - ay) ** 2;\n const raw =\n len2 > 0 ? ((x - ax) * (bx - ax) + (y - ay) * (by - ay)) / len2 : 0;\n const t = Math.max(0, Math.min(1, raw));\n const ox = x - ax - t * (bx - ax);\n const oy = y - ay - t * (by - ay);\n const d = Math.hypot(ox, oy);\n if (best && d >= best.d) continue;\n const s = lengths[k] + t * (lengths[k + 1] - lengths[k]);\n best = {\n d,\n dy: oy,\n half: halfAt(s),\n end:\n k === 0 && raw < 0\n ? \"tail\"\n : k === line.length - 2 && raw > 1\n ? \"end\"\n : null,\n third: total > 0 && 3 * s < total,\n tx: len2 > 0 ? (bx - ax) / Math.sqrt(len2) : 1,\n ty: len2 > 0 ? (by - ay) / Math.sqrt(len2) : 0,\n };\n }\n return best!;\n };\n}\n\n/** A brow's band: the pixels within the half-width of its centreline\n * (`browGeometry`). */\nexport function browBand(size: CanvasSize, brow: IllustrationBrow): Mask {\n const { width, height } = size;\n const m = new Uint8Array(width * height);\n const where = browGeometry(brow);\n const reach = Math.max(brow.halfWidth, brow.tailHalfWidth);\n const xs = brow.line.map((p) => p[0]);\n const ys = brow.line.map((p) => p[1]);\n const x0 = Math.max(0, Math.floor(Math.min(...xs) - reach));\n const x1 = Math.min(width - 1, Math.ceil(Math.max(...xs) + reach));\n const y0 = Math.max(0, Math.floor(Math.min(...ys) - reach));\n const y1 = Math.min(height - 1, Math.ceil(Math.max(...ys) + reach));\n for (let y = y0; y <= y1; y++) {\n for (let x = x0; x <= x1; x++) {\n const w = where(x, y);\n if (w.d <= w.half) m[y * width + x] = 1;\n }\n }\n return m;\n}\n\n/** 4-connected pieces of a mask: each pixel's piece id (-1 off the mask)\n * and each piece's size. */\nexport function pieces(\n size: CanvasSize,\n m: Mask,\n): { id: Int32Array; sizes: number[] } {\n const { width, height } = size;\n const id = new Int32Array(width * height).fill(-1);\n const sizes: number[] = [];\n const queue = new Int32Array(width * height);\n for (let s = 0; s < m.length; s++) {\n if (!m[s] || id[s] >= 0) continue;\n const k = sizes.length;\n let head = 0;\n let tail = 0;\n id[s] = k;\n queue[tail++] = s;\n while (head < tail) {\n const i = queue[head++];\n const x = i % width;\n const visit = (j: number) => {\n if (m[j] && id[j] < 0) {\n id[j] = k;\n queue[tail++] = j;\n }\n };\n if (x > 0) visit(i - 1);\n if (x < width - 1) visit(i + 1);\n if (i >= width) visit(i - width);\n if (i < (height - 1) * width) visit(i + width);\n }\n sizes.push(tail);\n }\n return { id, sizes };\n}\n\n/** Hair pieces smaller than SPECK_PX ringed mostly by paint that is not hair\n * (a hair-coloured button, a blush speck) leave the hair; hair beside one\n * counts in its ring but not as that paint. */\nexport function dropSpecks(size: CanvasSize, hair: Mask, solid: Mask): Mask {\n const { id, sizes } = pieces(size, hair);\n const small = new Uint8Array(hair.length);\n for (let i = 0; i < hair.length; i++) {\n if (id[i] >= 0 && sizes[id[i]] < SPECK_PX) small[i] = 1;\n }\n const ringOf = andNot(dilate(size, small, 2), small);\n // Each ring pixel counts once toward every small piece within 2 px of it.\n const paint = new Float64Array(sizes.length);\n const total = new Float64Array(sizes.length);\n const { width, height } = size;\n const seen = new Int32Array(25);\n for (let i = 0; i < hair.length; i++) {\n if (!ringOf[i]) continue;\n const x = i % width;\n const y = (i / width) | 0;\n let nSeen = 0;\n for (let dy = -2; dy <= 2; dy++) {\n for (let dx = -2; dx <= 2; dx++) {\n const nx = x + dx;\n const ny = y + dy;\n if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;\n const j = ny * width + nx;\n const k = id[j];\n if (k < 0 || !small[j]) continue;\n let dup = false;\n for (let q = 0; q < nSeen && !dup; q++) dup = seen[q] === k;\n if (dup) continue;\n seen[nSeen++] = k;\n total[k]++;\n if (solid[i] && !hair[i]) paint[k]++;\n }\n }\n }\n const out = new Uint8Array(hair);\n for (let i = 0; i < hair.length; i++) {\n const k = id[i];\n if (k >= 0 && small[i] && paint[k] > SPECK_RING_SHARE * total[k]) {\n out[i] = 0;\n }\n }\n return out;\n}\n\n/** Hair pieces of at least SPECK_PX: the hair a fill may run on from. */\nfunction bigPieces(size: CanvasSize, hair: Mask): Mask {\n const { id, sizes } = pieces(size, hair);\n return hair.map((v, i) => (v && sizes[id[i]] >= SPECK_PX ? 1 : 0));\n}\n\n/**\n * Unlabelled painted pixels take the label of the nearest labelled one:\n * first along paint, so ink joined to the hair goes with the hair rather\n * than across the backdrop to the body; then across anything, for paint no\n * labelled paint touches. Hair never spreads into `noHair`. Ties go to the\n * label reached first in row-major order.\n */\nexport function spreadLabels(\n size: CanvasSize,\n label: Uint8Array,\n fg: Mask,\n noHair: Mask,\n): void {\n const { width, height } = size;\n const grow = (through: (j: number) => boolean, mark: Uint8Array) => {\n const queue = new Int32Array(width * height);\n let head = 0;\n let tail = 0;\n for (let i = 0; i < label.length; i++) if (mark[i]) queue[tail++] = i;\n while (head < tail) {\n const i = queue[head++];\n const x = i % width;\n const hair = mark[i] === LABEL_HAIR;\n const visit = (j: number) => {\n if (!mark[j] && through(j) && !(hair && noHair[j])) {\n mark[j] = mark[i];\n queue[tail++] = j;\n }\n };\n if (x > 0) visit(i - 1);\n if (x < width - 1) visit(i + 1);\n if (i >= width) visit(i - width);\n if (i < (height - 1) * width) visit(i + width);\n }\n };\n grow((j) => fg[j] === 1, label);\n let left = false;\n for (let i = 0; i < label.length && !left; i++) {\n left = fg[i] === 1 && label[i] === LABEL_NONE;\n }\n if (!left) return;\n const near = new Uint8Array(label);\n grow(() => true, near);\n for (let i = 0; i < label.length; i++) {\n if (fg[i] && !label[i]) label[i] = near[i];\n }\n}\n\n/** The pixels of `through` a 4-connected path inside `through` joins to\n * `from` within `steps` px. */\nexport function reachThrough(\n size: CanvasSize,\n from: Mask,\n through: Mask,\n steps: number,\n): Mask {\n const { width, height } = size;\n const out = new Uint8Array(width * height);\n let front: number[] = [];\n for (let i = 0; i < from.length; i++) if (from[i]) front.push(i);\n for (let s = 0; s < steps && front.length > 0; s++) {\n const next: number[] = [];\n const visit = (j: number) => {\n if (through[j] && !out[j] && !from[j]) {\n out[j] = 1;\n next.push(j);\n }\n };\n for (const i of front) {\n const x = i % width;\n if (x > 0) visit(i - 1);\n if (x < width - 1) visit(i + 1);\n if (i >= width) visit(i - width);\n if (i < (height - 1) * width) visit(i + width);\n }\n front = next;\n }\n return out;\n}\n\n/** Where a side cut's boundary lies on row y: along its line, straight up\n * from the first point above it, and at `below` under its last. */\nfunction sideLineX(\n cut: Extract<IllustrationCustomCut, { side: string }>,\n y: number,\n): number {\n const ln = cut.line;\n if (y <= ln[0][1]) return ln[0][0];\n for (let k = 0; k + 1 < ln.length; k++) {\n const [ax, ay] = ln[k];\n const [bx, by] = ln[k + 1];\n if (y <= by) return ax + ((y - ay) / (by - ay)) * (bx - ax);\n }\n return cut.below;\n}\n\n/** One custom part's pixels, taken from `hairBack`. */\nfunction cutPart(\n size: CanvasSize,\n cut: IllustrationCustomCut,\n hairBack: Mask,\n classes: Uint8Array,\n): Mask {\n if (\"polygon\" in cut) return and(polygonMask(size, cut.polygon), hairBack);\n const { width, height } = size;\n const m = new Uint8Array(width * height);\n const ribbon = cut.ribbonBox ? boxMask(size, cut.ribbonBox) : undefined;\n const left = cut.side === \"left\";\n for (let y = 0; y < height; y++) {\n const lx = sideLineX(cut, y);\n for (let x = 0; x < width; x++) {\n const i = y * width + x;\n if (!hairBack[i]) continue;\n if (left ? x < lx : x > lx) m[i] = 1;\n else if (ribbon?.[i] && classes[i] === NEITHER) m[i] = 1;\n }\n }\n return m;\n}\n\nexport interface CutPart {\n cut: IllustrationCustomCut;\n mask: Mask;\n}\n\nexport interface IllustrationLabels {\n /** Per pixel: LABEL_FACE, LABEL_HAIR, LABEL_BODY, LABEL_NONE off paint. */\n label: Uint8Array;\n /** The colour classes the labels started from. */\n classes: Uint8Array;\n fg: Mask;\n solid: Mask;\n /** The skin the face's flood reached from `skinSeeds`. */\n skin: Mask;\n face: Mask;\n body: Mask;\n /** All of the hair; the four below split it. */\n hair: Mask;\n hairFront: Mask;\n /** Each side lock's hair, for the `sideHair` polygons given: inside its\n * polygon and not the front hair's (nor `L`'s, for `R`). */\n hairSide: { L?: Mask; R?: Mask };\n /** The head's hair behind the face, the side locks and every custom part\n * taken out. */\n hairBack: Mask;\n parts: CutPart[];\n /** Hair in pieces big enough to run on under the body's edge. */\n bigHair: Mask;\n /** Where nothing is hair whatever its colour. */\n noHair: Mask;\n frontHairArea: Mask;\n skullArea: Mask;\n bodyOnlyArea: Mask;\n /** Each brow's band (`browBand`), for the brows given. */\n browBands: { L?: Mask; R?: Mask };\n /** Hair a strand carries through a brow band: hair right above and right\n * below the band in its column. Labelled hair; its colour is the brow's\n * where the brow crosses, which the front hair refills. */\n strandThrough: Mask;\n}\n\n/** The darkest this share of an eye box's (a brow band's) paint that is\n * not skin is its lash (brow) ink, whose colour class says whether colour\n * can tell a strand from the lash. Larger reaches into the iris and the\n * strand itself. */\nconst INK_SHARE = 0.1;\n\n/**\n * Hair crossing an eye box: hair-coloured paint in it joined, through\n * hair-coloured paint, to hair-coloured paint outside it. Empty when most\n * of the box's ink is hair-coloured itself (near-black hair): there colour\n * cannot tell a strand from the lash, and everything in the box that is not\n * skin is the eye's.\n */\nexport function hairThroughBox(\n pic: Illustration,\n box: Box,\n classes: Uint8Array,\n): Mask {\n return hairThrough(pic, boxMask(pic, box), classes);\n}\n\n/** `hairThroughBox` over any region: a brow's band as well as an eye's\n * box. */\nfunction hairThrough(\n pic: Illustration,\n region: Mask,\n classes: Uint8Array,\n): Mask {\n const notSkin: { i: number; l: number }[] = [];\n for (let i = 0; i < region.length; i++) {\n if (!region[i] || pic.alpha[i] <= SOLID_ALPHA || classes[i] === SKIN) {\n continue;\n }\n const r = pic.rgb[i * 3];\n const g = pic.rgb[i * 3 + 1];\n const b = pic.rgb[i * 3 + 2];\n notSkin.push({ i, l: srgbToOklab(r, g, b)[0] });\n }\n notSkin.sort((a, b) => a.l - b.l);\n const ink = notSkin.slice(0, Math.ceil(notSkin.length * INK_SHARE));\n const hairInk = ink.filter((p) => classes[p.i] === HAIR).length;\n if (ink.length === 0 || hairInk * 2 > ink.length) {\n return new Uint8Array(region.length);\n }\n const hairy = classes.map((c, i) =>\n c === HAIR && pic.alpha[i] > HAIR_ALPHA ? 1 : 0,\n );\n const outside = and(andNot(dilate(pic, region, 1), region), hairy);\n return reachThrough(pic, outside, and(hairy, region), Infinity);\n}\n\n/** Where nothing is hair whatever its colour: the eye boxes and the brow\n * bands but the hair crossing them (`hairThrough`: the side hair a brow's\n * tail runs into is the hair's, not the brow's), the nose and mouth boxes\n * and the `bodyOnly` polygons. */\nfunction noHairRegions(\n pic: Illustration,\n lm: IllustrationLandmarks,\n classes: Uint8Array,\n): { noHair: Mask; bodyOnlyArea: Mask; browBands: { L?: Mask; R?: Mask } } {\n const size: CanvasSize = pic;\n const bodyOnlyArea = new Uint8Array(size.width * size.height);\n for (const poly of lm.bodyOnly) {\n const m = polygonMask(size, poly);\n for (let i = 0; i < m.length; i++) if (m[i]) bodyOnlyArea[i] = 1;\n }\n const regions: Mask[] = [\n andNot(\n boxMask(size, lm.eyes.L.box),\n hairThroughBox(pic, lm.eyes.L.box, classes),\n ),\n andNot(\n boxMask(size, lm.eyes.R.box),\n hairThroughBox(pic, lm.eyes.R.box, classes),\n ),\n boxMask(size, lm.mouth.box),\n bodyOnlyArea,\n ];\n if (lm.nose) regions.push(boxMask(size, lm.nose.box));\n const browBands: { L?: Mask; R?: Mask } = {};\n for (const side of [\"L\", \"R\"] as const) {\n const brow = lm.brows?.[side];\n if (!brow) continue;\n browBands[side] = browBand(size, brow);\n regions.push(\n andNot(browBands[side], hairThrough(pic, browBands[side], classes)),\n );\n }\n return { noHair: regions.reduce(or), bodyOnlyArea, browBands };\n}\n\n/** Rows a strand's test reaches past a brow band: a strand's edge beside\n * the band is a blend of hair and brow, and the hair it is judged by lies\n * past it. */\nconst STRAND_MARGIN = 4;\n\n/** The slants a strand through a brow band is followed at, as px across\n * per px down: up to 45 degrees off the vertical either way, in eighths.\n * Bangs fan out from the parting; a strand flatter than that crosses the\n * band along it and is not told from the brow. */\nconst STRAND_SLANTS = Array.from({ length: 17 }, (_, k) => (k - 8) / 8);\n\n/**\n * The strands that run through brow bands: band pixels (the band grown by\n * STRAND_MARGIN) on a straight path, at one of STRAND_SLANTS, that runs\n * through `through` paint (hair, or the brow's ink over it; never skin)\n * from hair right above the band to hair right below it. Such a pixel is\n * hair, whatever the brow's ink made it look like. A brow lying along the\n * band is never one: a steep path through it leaves the band on skin.\n */\nexport function strandsThrough(\n size: CanvasSize,\n bands: Mask,\n hair: Mask,\n through: Mask,\n): Mask {\n const { width, height } = size;\n const zone = dilate(size, bands, STRAND_MARGIN);\n const out = new Uint8Array(width * height);\n /** Follow slant `t` from (x, y) by `dir` rows until the path leaves the\n * zone: whether it left on hair having crossed only `through` paint. */\n const reaches = (x: number, y: number, t: number, dir: 1 | -1) => {\n for (let k = 1; ; k++) {\n const px = Math.round(x + dir * t * k);\n const py = y + dir * k;\n if (px < 0 || py < 0 || px >= width || py >= height) return false;\n const j = py * width + px;\n if (!zone[j]) return hair[j] === 1;\n if (!through[j]) return false;\n }\n };\n for (let i = 0; i < zone.length; i++) {\n if (!zone[i] || !through[i]) continue;\n const x = i % width;\n const y = (i - x) / width;\n for (const t of STRAND_SLANTS) {\n if (reaches(x, y, t, -1) && reaches(x, y, t, 1)) {\n out[i] = 1;\n break;\n }\n }\n }\n return out;\n}\n\n/** Hair by colour, off the never-hair regions; speckle smoothed only where\n * hair lies over skin (a thin strand against the backdrop keeps its raw\n * mask), carried through the brow bands where a strand runs through them\n * (before the specks are dropped: a strand's short end under a band is a\n * speck on its own), then the specks other paint rings dropped. */\nfunction colourHair(\n pic: Illustration,\n lm: IllustrationLandmarks,\n classes: Uint8Array,\n noHair: Mask,\n solid: Mask,\n skullArea: Mask,\n bands: Mask | null,\n): { hair: Mask; strandThrough: Mask } {\n const size: CanvasSize = pic;\n const { alpha } = pic;\n const hair: Mask = classes.map((c, i) =>\n c === HAIR && alpha[i] > HAIR_ALPHA && !noHair[i] ? 1 : 0,\n );\n const head = boxMask(size, headBox(size, lm, skullArea));\n const sm = majority(size, hair, SMOOTH_RADIUS);\n for (let i = 0; i < hair.length; i++) {\n if (head[i]) hair[i] = sm[i] && !noHair[i] && alpha[i] > HAIR_ALPHA ? 1 : 0;\n }\n const through = classes.map((c, i) => (solid[i] && c !== SKIN ? 1 : 0));\n const strandThrough = bands\n ? strandsThrough(size, bands, hair, through)\n : new Uint8Array(hair.length);\n return {\n hair: dropSpecks(size, or(hair, strandThrough), solid),\n strandThrough,\n };\n}\n\n/**\n * Near-black hair takes the lines drawn in the same ink. Thin hair (under\n * 2 THIN_RADIUS + 1 px) that a path through paint joins to the face's or\n * the neck's skin within THIN_BESIDE_SKIN px, outside the front hair, is\n * such a line and leaves the hair; anywhere else thin hair stays hair.\n */\nexport function releaseLines(\n size: CanvasSize,\n hair: Mask,\n skin: Mask,\n solid: Mask,\n frontHairArea: Mask,\n): Mask {\n const core = dilate(size, erode(size, hair, THIN_RADIUS), THIN_RADIUS);\n const band = reachThrough(size, skin, solid, THIN_BESIDE_SKIN);\n return hair.map((v, i) =>\n v && !core[i] && band[i] && !frontHairArea[i] ? 0 : v,\n );\n}\n\n/** The face: its skin flood, its outline (OUTLINE_PX into paint that is not\n * hair) and everything they enclose. */\nfunction faceOf(size: CanvasSize, skin: Mask, hair: Mask, fg: Mask): Mask {\n const outline = and(dilate(size, skin, OUTLINE_PX), andNot(fg, hair));\n return and(fillHoles(size, or(skin, outline)), fg);\n}\n\n/**\n * With a `neither` class the hair's own outline is unlabelled, and a body\n * flood would run along it: ink within INK_REACH of the hair, and a drawn\n * line joined to it along LINE_REACH px of the line, is the hair's.\n */\nexport function joinInk(size: CanvasSize, hair: Mask, ink: Mask): Mask {\n const line = andNot(\n ink,\n dilate(size, erode(size, ink, LINE_RADIUS), LINE_RADIUS),\n );\n const nearHair = dilate(size, hair, INK_REACH);\n const alongLine = reachThrough(size, hair, line, LINE_REACH);\n return hair.map((v, i) =>\n v || (ink[i] && (nearHair[i] || alongLine[i])) ? 1 : 0,\n );\n}\n\n/**\n * Label every painted pixel of `pic`. `classes` comes from\n * `classifyPicture` over the same picture.\n */\nexport function labelIllustration(\n pic: Illustration,\n lm: IllustrationLandmarks,\n classes: Uint8Array,\n): IllustrationLabels {\n const size: CanvasSize = pic;\n const n = pic.width * pic.height;\n const fg = Uint8Array.from(pic.alpha, (a) => (a > PAINT_ALPHA ? 1 : 0));\n const solid = Uint8Array.from(pic.alpha, (a) => (a > SOLID_ALPHA ? 1 : 0));\n const { noHair, bodyOnlyArea, browBands } = noHairRegions(pic, lm, classes);\n const skullArea = polygonMask(size, lm.skull);\n const frontHairArea = polygonMask(size, lm.frontHair);\n const sideAreas = {\n L: lm.sideHair?.L && polygonMask(size, lm.sideHair.L),\n R: lm.sideHair?.R && polygonMask(size, lm.sideHair.R),\n };\n /** Where hair is the front hair's or a side lock's: drawn over the face. */\n const overFace = [sideAreas.L, sideAreas.R]\n .filter((m) => m !== undefined)\n .reduce(or, frontHairArea);\n\n const bandList = [browBands.L, browBands.R].filter((b) => b !== undefined);\n const bands = bandList.length > 0 ? bandList.reduce(or) : null;\n const coloured = colourHair(\n pic,\n lm,\n classes,\n noHair,\n solid,\n skullArea,\n bands,\n );\n let hair = coloured.hair;\n const skinPass = classes.map((c, i) =>\n solid[i] && c === SKIN && !hair[i] ? 1 : 0,\n );\n const skin = flood(size, skinPass, lm.skinSeeds);\n const neck = flood(size, skinPass, lm.bodySeeds);\n hair = releaseLines(size, hair, or(skin, neck), solid, frontHairArea);\n let face = faceOf(size, skin, hair, fg);\n hair = joinInk(\n size,\n hair,\n classes.map((c, i) =>\n solid[i] && c === NEITHER && !face[i] && !noHair[i] ? 1 : 0,\n ),\n );\n // Again after joinInk, so a strand's own outline counts as hair above and\n // below the band and is carried through it with the strand.\n const strandThrough = bands\n ? or(\n coloured.strandThrough,\n strandsThrough(\n size,\n bands,\n hair,\n classes.map((c, i) => (solid[i] && c !== SKIN ? 1 : 0)),\n ),\n )\n : coloured.strandThrough;\n hair = or(hair, strandThrough);\n face = andNot(face, strandThrough);\n const bodyPass = classes.map((c, i) =>\n solid[i] && !hair[i] && !face[i] && (c !== HAIR || bodyOnlyArea[i]) ? 1 : 0,\n );\n const body = flood(size, bodyPass, lm.bodySeeds);\n const outline = bodyOutlines(size, hair, body, hairSamplePoints(size, lm));\n for (let i = 0; i < n; i++) {\n if (outline[i]) {\n hair[i] = 0;\n body[i] = 1;\n }\n }\n\n const label = new Uint8Array(n);\n for (let i = 0; i < n; i++) {\n label[i] = face[i]\n ? LABEL_FACE\n : hair[i]\n ? LABEL_HAIR\n : body[i] || (bodyOnlyArea[i] && fg[i])\n ? LABEL_BODY\n : LABEL_NONE;\n }\n spreadLabels(size, label, fg, noHair);\n // Paint of a brow band the hair closes in (between two strands through\n // it) is reached by no label that may enter it: it is the face's, as the\n // rest of the band is.\n for (let i = 0; i < n; i++) {\n if (fg[i] && label[i] === LABEL_NONE && bands?.[i]) label[i] = LABEL_FACE;\n }\n // Hair the face and the front hair or a side lock close in (an ear's\n // inner shading between the ear's line and a strand) is the face's: it is\n // no part of the back hair's mass.\n const headCover = label.map((l, i) =>\n l === LABEL_FACE || (l === LABEL_HAIR && overFace[i]) ? 1 : 0,\n );\n const enclosed = fillHoles(size, headCover);\n for (let i = 0; i < n; i++) {\n if (enclosed[i] && !headCover[i] && label[i] === LABEL_HAIR) {\n label[i] = LABEL_FACE;\n }\n }\n\n const is = (v: number) => label.map((l) => (l === v ? 1 : 0));\n const hairL = is(LABEL_HAIR);\n const hairFront = and(hairL, frontHairArea);\n let hairBack = andNot(hairL, frontHairArea);\n const hairSide: IllustrationLabels[\"hairSide\"] = {};\n // Just under the front hair the lock still moves as the bangs, and its\n // outline there runs on up beside the root: left to the face, so the\n // lock's first row stays under the bangs.\n const underFront = dilate(size, frontHairArea, OUTLINE_PX);\n for (const side of [\"L\", \"R\"] as const) {\n const area = sideAreas[side];\n if (!area) continue;\n const lock = and(hairBack, area);\n hairBack = andNot(hairBack, area);\n // The lock's own outline where it crosses the face: ink the face's outline rule took beside it, on a run of the lock\n // the face's paint closes at both ends. Left on the face, it shows as a line where the lock was once\n // the lock moves; the face's outer edge beside a lock stays the face's.\n const face = label.map((l) => (l === LABEL_FACE ? 1 : 0));\n const ink = face.map((v, i) =>\n v && area[i] && solid[i] && classes[i] === NEITHER ? 1 : 0,\n );\n const near = andNot(and(ink, dilate(size, lock, OUTLINE_PX)), underFront);\n const own = and(\n near,\n bridges(size, or(lock, near), andNot(face, near), lock),\n );\n for (let i = 0; i < n; i++) {\n if (own[i]) {\n label[i] = LABEL_HAIR;\n hairL[i] = 1;\n }\n }\n hairSide[side] = or(lock, own);\n }\n const parts: CutPart[] = [];\n for (const cut of lm.customParts) {\n const mask = cutPart(size, cut, hairBack, classes);\n hairBack = andNot(hairBack, mask);\n parts.push({ cut, mask });\n }\n\n return {\n label,\n classes,\n fg,\n solid,\n skin,\n face: is(LABEL_FACE),\n body: is(LABEL_BODY),\n hair: hairL,\n hairFront,\n hairSide,\n hairBack,\n parts,\n bigHair: bigPieces(size, hairL),\n noHair,\n frontHairArea,\n skullArea,\n bodyOnlyArea,\n browBands,\n strandThrough,\n };\n}\n\n/** The hair samples' pixels. */\nfunction hairSamplePoints(\n size: CanvasSize,\n lm: IllustrationLandmarks,\n): number[] {\n const { base, shadow = [], highlight = [] } = lm.samples.hair;\n return [...base, ...shadow, ...highlight].map(\n ([x, y]) => Math.round(y) * size.width + Math.round(x),\n );\n}\n\n/**\n * Hair is where the hair samples are. A hair piece as thin as a drawn line\n * (`LINE_RADIUS`) that no sample sits on,\n * lying along the body's paint (over OUTLINE_RING_SHARE of its ring), is the\n * body's outline inked in a colour near the hair's: long, so the speck rule\n * misses it. A loose wisp, backdrop all round, stays hair.\n */\nexport function bodyOutlines(\n size: CanvasSize,\n hair: Mask,\n body: Mask,\n samples: number[],\n): Mask {\n const { id, sizes } = pieces(size, hair);\n const sampled = new Set(samples.map((i) => id[i]).filter((k) => k >= 0));\n const core = erode(size, hair, LINE_RADIUS);\n const inCore = new Float64Array(sizes.length);\n for (let i = 0; i < hair.length; i++) if (core[i]) inCore[id[i]]++;\n const candidate = hair.map((v, i) =>\n v && !sampled.has(id[i]) && 2 * inCore[id[i]] < sizes[id[i]] ? 1 : 0,\n );\n // Each ring pixel counts once toward each candidate piece within 2 px.\n const ring = new Float64Array(sizes.length);\n const onBody = new Float64Array(sizes.length);\n const near = andNot(dilate(size, candidate, 2), hair);\n const { width, height } = size;\n for (let i = 0; i < hair.length; i++) {\n if (!near[i]) continue;\n const x = i % width;\n const y = (i - x) / width;\n const seen = new Set<number>();\n for (let dy = -2; dy <= 2; dy++) {\n for (let dx = -2; dx <= 2; dx++) {\n const nx = x + dx;\n const ny = y + dy;\n if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;\n const j = ny * width + nx;\n if (!candidate[j] || seen.has(id[j])) continue;\n seen.add(id[j]);\n ring[id[j]]++;\n if (body[i]) onBody[id[j]]++;\n }\n }\n }\n return candidate.map((v, i) =>\n v && onBody[id[i]] > OUTLINE_RING_SHARE * ring[id[i]] ? 1 : 0,\n );\n}\n\n/** Where hair lies over skin: the skull's box, the eyes' and the mouth's,\n * down to the mouth. */\nfunction headBox(\n size: CanvasSize,\n lm: IllustrationLandmarks,\n skullArea: Mask,\n): Box {\n const boxes: Box[] = [lm.eyes.L.box, lm.eyes.R.box, lm.mouth.box];\n const skull = maskBox(size, skullArea);\n if (skull) boxes.push(skull);\n return [\n Math.min(...boxes.map((b) => b[0])),\n Math.min(...boxes.map((b) => b[1])),\n Math.max(...boxes.map((b) => b[2])),\n Math.max(...boxes.map((b) => b[3])),\n ];\n}\n","/**\n * The features of an in-place cut: each eye split into the layers the rig's\n * eye roles expect (the sclera, the iris, the upper lash and the lower lid,\n * as the composer splits one drawn eye), the brows, the nose and the drawn\n * closed mouth; and the checks on the landmarks they were cut by.\n *\n * Every colour judgement here is relative: to the hair and skin samples, to\n * the paint just around a feature, or to the eye's own paint (its ink\n * against its white). Two pixels count as one paint only within the skin's\n * own noise (`samePaint`).\n */\n\nimport { LASH_KEEP_FRACTION } from \"./compose\";\nimport {\n and,\n andNot,\n boxMask,\n count,\n dilate,\n erode,\n fillHoles,\n median,\n or,\n type Box,\n type Illustration,\n type Mask,\n} from \"./illustration\";\nimport {\n dist,\n HAIR,\n segmentDistance,\n SKIN,\n srgbToOklab,\n type Lab,\n} from \"./illustration-colour\";\nimport {\n fillFrom,\n paintOf,\n skinSources,\n SOURCE_INSET,\n type CutCheck,\n type CutContext,\n type LayerPaint,\n} from \"./illustration-context\";\nimport {\n browGeometry,\n LABEL_HAIR,\n maskBox,\n pieces,\n reachThrough,\n} from \"./illustration-labels\";\nimport type { IllustrationBrow } from \"./illustration-landmarks\";\n\n/** A skin sample's patch noise times this is still that skin: the\n * classifier counts a set's reach the same way. */\nconst NOISE_SCALE = 3;\n/** Levels per 8-bit channel under which two pixels are one paint on a flat\n * picture: the resize's ringing beside a line and a PNG's rounding. Lower\n * takes that ringing into a feature (a pixel-wide halo of skin round it);\n * higher leaves a faint stroke's edge on the face. */\nconst SAME_PAINT_LEVELS = 4;\n/** The darkest, and the lightest, this share of an eye's paint outside its\n * iris ellipse: its lash ink, and its white. Larger reaches the white's\n * shading and the lash's soft edge. */\nconst EYE_EXTREME_SHARE = 0.1;\n/** The iris's own colour is read on the ellipse's lower ring between these\n * shares of its radii: off the pupil in its middle, off the outline at its\n * rim, under the lid. */\nconst IRIS_RING_IN = 0.5;\nconst IRIS_RING_OUT = 0.9;\n/** A piece detached above the lash under this share of the eye's main\n * piece is the lid's crease, left on the face. Larger takes a detached\n * lash flick to the face; smaller keeps a long crease in the eye, where\n * the blink fold carries it into the iris. */\nconst CREASE_SHARE = 0.25;\n/** Radius of the closing that takes a highlight on the iris's edge back\n * into it, px. Under a highlight's half-width leaves a notch in the iris;\n * over it bridges into the white beside the disc. */\nconst IRIS_CLOSE = 3;\n/** The iris takes this many px of its soft edge against the white: the\n * resize's blend, about two px on a picture under the canvas's size. */\nconst IRIS_RIM = 2;\n/** An eye covering under this share of its box: the box is loose and takes\n * the lines and shading round the eye into it. */\nconst LOOSE_SHARE = 0.2;\n/** The ellipse overlapping the disc found by under this (intersection over\n * union) is off it: the iris layer then holds white or loses its edge.\n * Measured: a well-placed ellipse 0.84 on the test's 13 x 17 px disc and\n * 0.80 on a painted eye (the disc's soft edge is not counted in it); 3 px\n * off the test's disc 0.68, 10 px off 0.38. */\nconst IRIS_IOU = 0.7;\n/** Radius of the closing that joins the disc's colour over its pupil and\n * highlight for the iris check, px. */\nconst DISC_CLOSE = 2;\n/** Iris-coloured paint this far past the ellipse (a share of its radius\n * along each axis) and joined to the iris is the iris's: a disc drawn\n * squarer than an ellipse puts its corners there. Farther takes another\n * feature's colour; nearer leaves the corners on the lids. */\nconst IRIS_MARGIN = 0.25;\n/** Columns either side of the iris ellipse the lash's thickness is read on,\n * to carry the lid across an iris shaded as dark as the lash. */\nconst LID_SIDE = 4;\n/** The eye takes this many px of rim past its paint, where it differs from\n * the skin around: its soft edge. */\nconst EYE_EDGE = 2;\n/** Px the `opening` hint leaves between the eye's paint, rim included,\n * and the box it suggests: the least of the 2 to 4 px to spare the skill\n * asks for (the rim adds up to EYE_EDGE more). */\nconst OPENING_SPARE = 2;\n/** Paint outside an eye box that runs on past it farther than this share\n * of the box's smaller side is a strand or a line passing the eye, not\n * the eye: a lash wing a box clips runs on a few px. */\nconst STROKE_PAST_SHARE = 0.5;\n/** Pieces of an eye's paint this close to such a stroke, px, are the\n * stroke's: an antialiased thin stroke breaks into pieces this far apart. */\nconst STROKE_GAP = 2;\n/** Paint this close to hair crossing an eye box is the hair's soft edge, not\n * the eye's; the hair labels' own reach for ink beside hair. */\nconst HAIR_EDGE = 3;\n/** A band pixel at least this share of the way from the paint around it,\n * from the skin samples and (near hair) from the hair samples toward the\n * brow's ink is the brow's: a pale brow is a mix of brow and skin, a brow\n * drawn through the bangs a mix of brow and hair. Higher leaves the pale\n * part behind when the brow moves (the trace this rule exists for); lower\n * takes the skin's and the hair's own shading. */\nconst BROW_SHARE = 0.2;\n/** The brow's ink is the median colour of this share of its band's paint\n * farthest from the paint around it. */\nconst BROW_CORE_SHARE = 0.2;\n/** Ink this close to hair, px, is the hair's soft edge, not brow left\n * past the band. Wider also skips the hair's own outline where the face\n * takes it, but with it the brow's lower edge between close strands; an\n * outline lying along the brow past its band can then read as brow, which\n * is why `browBand` only warns. */\nconst HAIR_LINE = 1;\n/** The brow takes this many px past its judged pixels, paint that differs\n * from the paint around: a soft stroke's faint rim and the resize's\n * overshoot beside it, a light halo left on the face when the brow moves\n * at 1. */\nconst BROW_EDGE = 2;\n/** Hair within this many px of a band pixel is what a mix there may be\n * with; farther, the pixel is judged against skin and the paint around\n * only, so a pale brow on skin is not called hair. */\nconst HAIR_NEAR = 2;\n/** A nose or mouth mark grows this many px: its soft edge, which differs\n * from the skin too little to be told by colour. */\nconst MARK_EDGE = 2;\n\n/** Rows a lower lid followed across the iris may drift per column: a lid's\n * curve, under 45 degrees over the iris. */\nconst LID_DRIFT = 1;\n/** Paint more than this many times `samePaint` off the blends of an eye's\n * ink and the skin around it is a paint of its own, a white, however\n * shaded; a drawn closed eye's light paint (its line's soft edge, and the\n * resize's overshoot beside it) lies within it. */\nconst WHITE_SCALE = 3;\n/** An eye with under this share of its paint white has no white to speak\n * of and is drawn closed. Measured: open test eyes 0.19 to 0.26, a painted\n * eye with a pale, shaded white 0.135, a closed test eye 0.02 (its line's\n * overshoot); this sits between the last two by ratio. */\nconst WHITE_SHARE = 0.06;\n\nconst fmt = (v: number, digits = 3) => Number(v.toFixed(digits));\nconst pct = (v: number) => `${(v * 100).toFixed(1)}%`;\n\nconst labOf = (rgb: Float32Array, i: number): Lab =>\n srgbToOklab(rgb[i * 3], rgb[i * 3 + 1], rgb[i * 3 + 2]);\n\n/** The median colour, per sRGB channel, of pixels `idx` of `rgb`. */\nfunction medianColour(\n rgb: Float32Array,\n idx: number[],\n): { rgb: [number, number, number]; lab: Lab } {\n const c = [0, 1, 2].map((k) => median(idx.map((i) => rgb[i * 3 + k]))) as [\n number,\n number,\n number,\n ];\n return { rgb: c, lab: srgbToOklab(...c) };\n}\n\ninterface Bounds {\n x0: number;\n y0: number;\n x1: number;\n y1: number;\n}\n\n/** A box's pixel bounds on the canvas, as `boxMask` takes them. */\nfunction bounds(pic: Illustration, [x0, y0, x1, y1]: Box): Bounds {\n return {\n x0: Math.max(0, Math.ceil(x0)),\n y0: Math.max(0, Math.ceil(y0)),\n x1: Math.min(pic.width - 1, Math.floor(x1)),\n y1: Math.min(pic.height - 1, Math.floor(y1)),\n };\n}\n\n/**\n * The distance under which two colours are the same skin: the skin\n * samples' own noise, scaled as the classifier scales it, and at least\n * SAME_PAINT_LEVELS of rounding at the skin's base colour, which a flat\n * picture with no noise still has beside every line.\n */\nfunction samePaint(ctx: CutContext): number {\n const skin = ctx.reads.skin.filter((r) => r.lab !== null);\n const noises = skin.map((r) => r.noise).sort((a, b) => a - b);\n const noise = noises[(noises.length - 1) >> 1];\n const base = skin[0].rgb!;\n const rounded = base.map((v) => v - SAME_PAINT_LEVELS) as [\n number,\n number,\n number,\n ];\n return Math.max(\n NOISE_SCALE * noise,\n dist(srgbToOklab(...base), srgbToOklab(...rounded)),\n );\n}\n\n/**\n * Skin, round a feature: skin by colour, and either within `same` of the\n * skin filled over the feature from around it (`around`), or no farther\n * from the skin samples than that skin is, as shading the samples cover\n * is. An eye's white, often skin by colour, is neither.\n */\nfunction skinTest(\n ctx: CutContext,\n around: Float32Array,\n same: number,\n): (i: number) => boolean {\n const { pic, labels, classifier } = ctx;\n const rgb = pic.rgb;\n return (i) => {\n if (labels.classes[i] !== SKIN) return false;\n if (dist(labOf(rgb, i), labOf(around, i)) <= same) return true;\n const own = classifier.distances(\n rgb[i * 3],\n rgb[i * 3 + 1],\n rgb[i * 3 + 2],\n );\n const local = classifier.distances(\n around[i * 3],\n around[i * 3 + 1],\n around[i * 3 + 2],\n );\n return own.skin <= local.skin + same;\n };\n}\n\n// ---- eyes ----\n\ntype Side = \"L\" | \"R\";\n\n/** Where one eye is cut: its box and its iris ellipse. */\ninterface EyeFrame {\n side: Side;\n /** `landmarks.eyes.<side>`, for hints. */\n at: string;\n b: Bounds;\n inBox: Mask;\n /** The ellipse's pixels inside the box. */\n ellipse: Mask;\n cx: number;\n cy: number;\n rx: number;\n ry: number;\n}\n\nfunction eyeFrame(ctx: CutContext, side: Side): EyeFrame {\n const { pic, lm } = ctx;\n const { box, iris } = lm.eyes[side];\n const b = bounds(pic, box);\n const ellipse = new Uint8Array(pic.width * pic.height);\n for (let y = b.y0; y <= b.y1; y++) {\n for (let x = b.x0; x <= b.x1; x++) {\n const u = (x - iris.cx) / iris.rx;\n const v = (y - iris.cy) / iris.ry;\n if (u * u + v * v <= 1) ellipse[y * pic.width + x] = 1;\n }\n }\n return {\n side,\n at: `landmarks.eyes.${side}`,\n b,\n inBox: boxMask(pic, box),\n ellipse,\n ...iris,\n };\n}\n\n/** Pixels outside an eye's box, Chebyshev, of (x, y): 0 inside it. */\nfunction pastBox(b: Bounds, x: number, y: number): number {\n return Math.max(b.x0 - x, x - b.x1, b.y0 - y, y - b.y1, 0);\n}\n\n/**\n * Paint outside the box (any label, hair included; not skin) that runs on\n * past it farther than STROKE_PAST_SHARE of the box's smaller side, from\n * within STROKE_GAP + EYE_EDGE px of the box: a strand or a line passing\n * the eye. Followed across gaps of up to STROKE_GAP px, as a thin\n * antialiased stroke breaks.\n */\nfunction longStrokes(\n ctx: CutContext,\n f: EyeFrame,\n isSkin: (i: number) => boolean,\n): { long: Mask; past: number } {\n const { pic, labels } = ctx;\n const { width, height } = pic;\n const { b } = f;\n const past = Math.max(\n 1,\n Math.round(STROKE_PAST_SHARE * Math.min(b.x1 - b.x0 + 1, b.y1 - b.y0 + 1)),\n );\n const wx0 = Math.max(0, b.x0 - past);\n const wx1 = Math.min(width - 1, b.x1 + past);\n const wy0 = Math.max(0, b.y0 - past);\n const wy1 = Math.min(height - 1, b.y1 + past);\n const isPaint = (x: number, y: number) => {\n if (x < wx0 || x > wx1 || y < wy0 || y > wy1) return false;\n if (pastBox(b, x, y) === 0) return false;\n const i = y * width + x;\n return labels.solid[i] === 1 && !isSkin(i);\n };\n const long = new Uint8Array(width * height);\n const seen = new Uint8Array(width * height);\n const near = STROKE_GAP + EYE_EDGE;\n for (let y = wy0; y <= wy1; y++) {\n for (let x = wx0; x <= wx1; x++) {\n const d = pastBox(b, x, y);\n if (d === 0 || d > near || seen[y * width + x] || !isPaint(x, y)) {\n continue;\n }\n const queue = [y * width + x];\n seen[queue[0]] = 1;\n let far = 0;\n for (let q = 0; q < queue.length; q++) {\n const i = queue[q];\n const px = i % width;\n const py = (i - px) / width;\n far = Math.max(far, pastBox(b, px, py));\n for (let dy = -STROKE_GAP; dy <= STROKE_GAP; dy++) {\n for (let dx = -STROKE_GAP; dx <= STROKE_GAP; dx++) {\n const nx = px + dx;\n const ny = py + dy;\n if (!isPaint(nx, ny) || seen[ny * width + nx]) continue;\n seen[ny * width + nx] = 1;\n queue.push(ny * width + nx);\n }\n }\n }\n if (far >= past) for (const i of queue) long[i] = 1;\n }\n }\n return { long, past };\n}\n\n/** Where an eye was found in its box: its drawing, and the long strokes\n * outside the box (`longStrokes`) that the drawing was cut clear of. */\ninterface EyeDrawing {\n eye: Mask;\n long: Mask;\n /** STROKE_PAST_SHARE of the box's smaller side, px. */\n past: number;\n}\n\n/**\n * The eye's drawing, the sclera's shape: what in its box is not skin\n * (`skinTest`), hair crossing the box and its soft edge left out (the labels\n * give the hair to the hair). The main piece and every other piece clear of\n * the box's border by more than its rim (EYE_EDGE) are the eye, but a small\n * piece detached above the lash,\n * the lid's crease, and pieces joined (across STROKE_GAP px) to a long\n * stroke outside the box or to hair crossing it (`strokePieces`): a strand\n * or a line crossing into the box, which stays with whatever it belongs to. Its holes are closed, and its soft rim\n * taken.\n */\nfunction eyeDrawing(\n ctx: CutContext,\n f: EyeFrame,\n around: Float32Array,\n same: number,\n): EyeDrawing {\n const { pic, labels } = ctx;\n const { width } = pic;\n const n = width * pic.height;\n const { b } = f;\n const isSkin = skinTest(ctx, around, same);\n // Hair crossing the box, and its soft edge: a blend of hair and skin that\n // is neither, and would join the eye to the strand.\n const hairEdge = dilate(\n pic,\n labels.label.map((l, i) => (l === LABEL_HAIR && f.inBox[i] ? 1 : 0)),\n HAIR_EDGE,\n );\n const paint = new Uint8Array(n);\n for (let y = b.y0; y <= b.y1; y++) {\n for (let x = b.x0; x <= b.x1; x++) {\n const i = y * width + x;\n if (labels.solid[i] && !hairEdge[i] && !isSkin(i)) paint[i] = 1;\n }\n }\n\n const { id, sizes } = pieces(pic, paint);\n let main = -1;\n const onBorder = new Set<number>();\n for (let y = b.y0; y <= b.y1; y++) {\n for (let x = b.x0; x <= b.x1; x++) {\n const k = id[y * width + x];\n if (k < 0) continue;\n if (main < 0 || sizes[k] > sizes[main]) main = k;\n // Within its rim of the border: the rim would reach it.\n if (\n x - b.x0 <= EYE_EDGE ||\n b.x1 - x <= EYE_EDGE ||\n y - b.y0 <= EYE_EDGE ||\n b.y1 - y <= EYE_EDGE\n ) {\n onBorder.add(k);\n }\n }\n }\n const { long, past } = longStrokes(ctx, f, isSkin);\n const strokes = strokePieces(pic, f, id, main, or(long, hairEdge));\n const eye0 = new Uint8Array(n);\n const creases = new Uint8Array(n);\n if (main >= 0) {\n // The main piece's top per column, and its rows.\n const mainTop = new Int32Array(width).fill(-1);\n let top = Infinity;\n let bottom = -Infinity;\n for (let y = b.y0; y <= b.y1; y++) {\n for (let x = b.x0; x <= b.x1; x++) {\n if (id[y * width + x] !== main) continue;\n if (mainTop[x] < 0) mainTop[x] = y;\n top = Math.min(top, y);\n bottom = y;\n }\n }\n const cut = top + LASH_KEEP_FRACTION * (bottom - top + 1);\n const above = new Map<number, boolean>();\n for (let y = b.y0; y <= b.y1; y++) {\n for (let x = b.x0; x <= b.x1; x++) {\n const k = id[y * width + x];\n if (k < 0 || k === main) continue;\n const ok =\n (mainTop[x] < 0 || y < mainTop[x]) &&\n y < cut &&\n (above.get(k) ?? true);\n above.set(k, ok);\n }\n }\n const crease = new Set<number>();\n for (const [k, ok] of above) {\n if (ok && sizes[k] < CREASE_SHARE * sizes[main]) crease.add(k);\n }\n for (let y = b.y0; y <= b.y1; y++) {\n for (let x = b.x0; x <= b.x1; x++) {\n const i = y * width + x;\n const k = id[i];\n if (k < 0 || strokes.has(k)) continue;\n if (crease.has(k)) creases[i] = 1;\n else if (k === main || !onBorder.has(k)) eye0[i] = 1;\n }\n }\n }\n // Its soft rim: the blends at its edge pass for shaded skin, and left on\n // the face they draw the eye's outline there once the eye shuts. Not\n // round a stroke it was cut clear of.\n const stroke = dilate(\n pic,\n Uint8Array.from(id, (k) => (k >= 0 && strokes.has(k) ? 1 : 0)),\n EYE_EDGE,\n );\n const eye = fillHoles(pic, eye0);\n const rim = dilate(pic, eye, EYE_EDGE);\n for (let y = b.y0; y <= b.y1; y++) {\n for (let x = b.x0; x <= b.x1; x++) {\n const i = y * width + x;\n if (\n rim[i] &&\n !eye[i] &&\n labels.solid[i] &&\n !hairEdge[i] &&\n !creases[i] &&\n !stroke[i] &&\n dist(labOf(pic.rgb, i), labOf(around, i)) > same\n ) {\n eye[i] = 1;\n }\n }\n }\n return { eye: and(eye, f.inBox), long, past };\n}\n\n/** The pieces of an eye's paint, but the main one, joined across\n * STROKE_GAP px, directly or through each other, to a long stroke outside\n * the box or to the soft edge of hair crossing it (`to`): a strand's own\n * line, leading into the strand. */\nfunction strokePieces(\n pic: Illustration,\n f: EyeFrame,\n id: Int32Array,\n main: number,\n to: Mask,\n): Set<number> {\n const { width, height } = pic;\n const { b } = f;\n const out = new Set<number>();\n const joined = (x: number, y: number) => {\n for (let dy = -STROKE_GAP; dy <= STROKE_GAP; dy++) {\n for (let dx = -STROKE_GAP; dx <= STROKE_GAP; dx++) {\n const nx = x + dx;\n const ny = y + dy;\n if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;\n const j = ny * width + nx;\n if (to[j] || (id[j] >= 0 && out.has(id[j]))) return true;\n }\n }\n return false;\n };\n for (let changed = true; changed; ) {\n changed = false;\n for (let y = b.y0; y <= b.y1; y++) {\n for (let x = b.x0; x <= b.x1; x++) {\n const k = id[y * width + x];\n if (k < 0 || k === main || out.has(k) || !joined(x, y)) continue;\n out.add(k);\n changed = true;\n }\n }\n }\n return out;\n}\n\n/** The eye's own colours, and how each of its pixels reads against them. */\ninterface EyeColours {\n ink: { rgb: [number, number, number]; lab: Lab };\n white: { rgb: [number, number, number]; lab: Lab };\n iris: { rgb: [number, number, number]; lab: Lab };\n /** Nearer the ink than the white. */\n dark(i: number): boolean;\n /** Nearer the white than the ink and the iris. */\n isWhite(i: number): boolean;\n /** Nearer the iris than the ink and the white. */\n nearIris(i: number): boolean;\n /** The iris's own colour, darker or lighter (`irisLike`). */\n irisLike(i: number): boolean;\n}\n\n/**\n * Its ink (the darkest EYE_EXTREME_SHARE of its paint outside the ellipse),\n * its white (the lightest) and its iris (the ellipse's lower ring), each a\n * median colour. A pixel is iris-like when it lies nearer the iris's own\n * shades (the line from black through the iris's colour on to full\n * lightness: its hue, darker or lighter) than the blends of the ink and the\n * skin around (`skin`), which the lid lines are, and than the white: a\n * squarish disc's dark rim is iris-like, a lid line beside it is not.\n */\nfunction eyeColours(\n pic: Illustration,\n f: EyeFrame,\n all: number[],\n skin: Lab,\n): EyeColours {\n const { width } = pic;\n const outside: number[] = [];\n const ring: number[] = [];\n for (const i of all) {\n const x = i % width;\n const y = (i - x) / width;\n if (!f.ellipse[i]) outside.push(i);\n const r = Math.hypot((x - f.cx) / f.rx, (y - f.cy) / f.ry);\n if (y > f.cy && r >= IRIS_RING_IN && r <= IRIS_RING_OUT) ring.push(i);\n }\n const byL = (outside.length > 0 ? outside : all)\n .map((i) => ({ i, l: labOf(pic.rgb, i)[0] }))\n .sort((p, q) => p.l - q.l);\n const share = Math.max(1, Math.ceil(byL.length * EYE_EXTREME_SHARE));\n const ink = medianColour(\n pic.rgb,\n byL.slice(0, share).map((p) => p.i),\n );\n const white = medianColour(\n pic.rgb,\n byL.slice(-share).map((p) => p.i),\n );\n const iris = medianColour(pic.rgb, ring.length > 0 ? ring : all);\n const dK = new Map<number, number>();\n const dW = new Map<number, number>();\n const dI = new Map<number, number>();\n for (const i of all) {\n const lab = labOf(pic.rgb, i);\n dK.set(i, dist(lab, ink.lab));\n dW.set(i, dist(lab, white.lab));\n dI.set(i, dist(lab, iris.lab));\n }\n const k = (i: number) => dK.get(i) ?? Infinity;\n const w = (i: number) => dW.get(i) ?? Infinity;\n const r = (i: number) => dI.get(i) ?? Infinity;\n const black: Lab = [0, 0, 0];\n const L = Math.max(iris.lab[0], 1e-6);\n const light: Lab = [1, iris.lab[1] / L, iris.lab[2] / L];\n return {\n ink,\n white,\n iris,\n dark: (i) => k(i) < w(i),\n isWhite: (i) => w(i) < k(i) && w(i) < r(i),\n nearIris: (i) => r(i) <= k(i) && r(i) < w(i),\n irisLike: (i) => {\n const lab = labOf(pic.rgb, i);\n const tone = segmentDistance(lab, black, light);\n return (\n tone < segmentDistance(lab, skin, ink.lab) &&\n tone < dist(lab, white.lab)\n );\n },\n };\n}\n\n/**\n * How far a colour lies off the blends of the eye's ink and the skin\n * around it (`skin`), in units of `same`: over WHITE_SCALE it is a paint of\n * its own. A drawn closed eye's light paint is the soft edge of its line,\n * such a blend.\n */\nfunction offBlend(lab: Lab, skin: Lab, c: EyeColours, same: number): number {\n return segmentDistance(lab, skin, c.ink.lab) / same;\n}\n\n/** The share of the eye's paint that is white: nearer its white than its\n * ink and iris, and a paint of its own (`offBlend`). */\nfunction whiteShare(\n pic: Illustration,\n c: EyeColours,\n all: number[],\n skin: Lab,\n same: number,\n): number {\n let white = 0;\n for (const i of all) {\n if (\n c.isWhite(i) &&\n offBlend(labOf(pic.rgb, i), skin, c, same) > WHITE_SCALE\n ) {\n white++;\n }\n }\n return white / all.length;\n}\n\n/** The rows the eye's drawing spans, and the row LASH_KEEP_FRACTION down\n * them that splits the upper lash from the lower lid, as the composer\n * splits a drawn eye. */\nfunction lashCutOf(pic: Illustration, all: number[]): number {\n let top = Infinity;\n let bottom = -Infinity;\n for (const i of all) {\n const y = Math.floor(i / pic.width);\n top = Math.min(top, y);\n bottom = Math.max(bottom, y);\n }\n return top + LASH_KEEP_FRACTION * (bottom - top + 1);\n}\n\n/**\n * The upper lid: per column, the bottom row of the lash's run of ink from\n * the eye's top (-1 with none), at most to the iris's centre row, so a\n * pupil touching the lash does not carry it down. Over the iris it is also\n * no deeper than the lash's top plus the lash's thickness beside the\n * ellipse (read on LID_SIDE columns either side and carried across in a\n * straight line): an iris shaded as dark as the lash at its top runs on\n * from the lash in colour.\n */\nfunction upperLid(\n pic: Illustration,\n f: EyeFrame,\n eye: Mask,\n c: EyeColours,\n): Int32Array {\n const { width } = pic;\n const { b, cx, cy, rx } = f;\n const lid = new Int32Array(width).fill(-1);\n const lashTop = new Int32Array(width).fill(-1);\n for (let x = b.x0; x <= b.x1; x++) {\n const at = (y: number) => y * width + x;\n const lashInk = (y: number) =>\n eye[at(y)] === 1 && c.dark(at(y)) && !c.nearIris(at(y));\n let y = b.y0;\n while (y <= b.y1 && !(eye[at(y)] && c.dark(at(y)))) y++;\n // The lash's soft top edge, a blend of its ink and the skin, may read\n // nearer the iris's colour: step past it before deciding.\n const first = y;\n while (y <= b.y1 && y - first < EYE_EDGE && !lashInk(y)) y++;\n if (y > b.y1 || y >= cy || !lashInk(y)) continue;\n lashTop[x] = first;\n while (y + 1 <= Math.min(b.y1, Math.floor(cy)) && lashInk(y + 1)) y++;\n lid[x] = y;\n }\n const thickness = (from: number, step: number): number | null => {\n const t: number[] = [];\n for (\n let x = from;\n t.length < LID_SIDE && x >= b.x0 && x <= b.x1;\n x += step\n ) {\n if (lashTop[x] >= 0) t.push(lid[x] - lashTop[x] + 1);\n }\n return t.length > 0 ? median(t) : null;\n };\n const left = thickness(Math.floor(cx - rx) - 1, -1);\n const right = thickness(Math.ceil(cx + rx) + 1, 1);\n if (left === null && right === null) return lid;\n for (let x = Math.ceil(cx - rx); x <= Math.floor(cx + rx); x++) {\n if (x < b.x0 || x > b.x1 || lashTop[x] < 0) continue;\n const u = (x - (cx - rx)) / (2 * rx);\n const t =\n left === null\n ? right!\n : right === null\n ? left\n : left + (right - left) * u;\n lid[x] = Math.min(lid[x], lashTop[x] + Math.round(t) - 1);\n }\n return lid;\n}\n\n/**\n * The lower lid's ink across the iris, inside the ellipse. The lower lid is\n * drawn over the iris and folds with the white, so where its line crosses\n * the disc it is the lid's, not the iris's. It is found where it shows on\n * its own, just outside the ellipse (its lowest run of ink below `lashCut`\n * and clear of the upper lid, on LID_SIDE columns either side), and\n * followed across the ellipse column\n * by column, drifting at most LID_DRIFT rows per column and never thicker\n * than beside it. Without a lid line outside the ellipse on both sides,\n * dark paint at the disc's bottom is the iris's own outline, and nothing is\n * carried.\n */\nfunction lowerLidAcross(\n pic: Illustration,\n f: EyeFrame,\n eye: Mask,\n c: EyeColours,\n lashCut: number,\n upper: Int32Array,\n): Mask {\n const { width } = pic;\n const { b, cx, rx } = f;\n const out = new Uint8Array(width * pic.height);\n const lashInk = (x: number, y: number) => {\n const i = y * width + x;\n return y > lashCut && eye[i] === 1 && c.dark(i) && !c.nearIris(i);\n };\n const runAt = (x: number): [number, number] | null => {\n let y = b.y1;\n while (y > lashCut && !lashInk(x, y)) y--;\n if (y <= lashCut) return null;\n const bottom = y;\n while (lashInk(x, y - 1)) y--;\n // The upper lash's own corner, hanging below the cut, is no lower lid.\n return y > upper[x] ? [y, bottom] : null;\n };\n const side = (from: number, step: number) => {\n const runs: [number, number][] = [];\n for (let k = 0; k < LID_SIDE; k++) {\n const x = from + k * step;\n if (x < b.x0 || x > b.x1) break;\n const run = runAt(x);\n if (run) runs.push(run);\n }\n return runs;\n };\n const left = side(Math.floor(cx - rx) - 1, -1);\n const right = side(Math.ceil(cx + rx) + 1, 1);\n if (left.length === 0 || right.length === 0) return out;\n const thickness = median([...left, ...right].map(([t, bt]) => bt - t + 1));\n const follow = (start: [number, number], x0: number, x1: number) => {\n const step = x1 >= x0 ? 1 : -1;\n let [top, bottom] = start;\n for (let x = x0; x !== x1 + step; x += step) {\n let lo = Infinity;\n let hi = -Infinity;\n for (let y = top - LID_DRIFT; y <= bottom + LID_DRIFT; y++) {\n if (y >= b.y0 && y <= b.y1 && lashInk(x, y)) {\n lo = Math.min(lo, y);\n hi = Math.max(hi, y);\n }\n }\n if (lo === Infinity) return; // the line ends\n if (hi - lo + 1 > thickness + 1) {\n lo = Math.max(lo, Math.round((top + bottom) / 2 - thickness / 2));\n hi = Math.min(hi, lo + thickness - 1);\n }\n for (let y = lo; y <= hi; y++) {\n if (lashInk(x, y)) out[y * width + x] = 1;\n }\n [top, bottom] = [lo, hi];\n }\n };\n follow(left[0], Math.floor(cx - rx), Math.ceil(cx + rx));\n follow(right[0], Math.ceil(cx + rx), Math.floor(cx - rx));\n return and(out, f.ellipse);\n}\n\n/**\n * The iris as it shows: the paint in the ellipse below the upper lid that\n * is not white, with the holes it closes (a highlight touching the lid\n * included: the part under the lash is counted in), the iris-like paint\n * joined to it within IRIS_MARGIN past the ellipse, and its soft rim\n * against the white; the lower lid's ink across it left out.\n */\nfunction irisShown(\n pic: Illustration,\n f: EyeFrame,\n eye: Mask,\n all: number[],\n c: EyeColours,\n lid: Int32Array,\n lowerAcross: Mask,\n same: number,\n): Mask {\n const { width } = pic;\n const n = width * pic.height;\n const coloured = new Uint8Array(n);\n const cap = new Uint8Array(n);\n for (let i = 0; i < n; i++) {\n if (!f.ellipse[i]) continue;\n const x = i % width;\n if ((i - x) / width <= lid[x]) cap[i] = 1;\n else if (eye[i] && !c.isWhite(i)) coloured[i] = 1;\n }\n const shape = fillHoles(\n pic,\n erode(pic, dilate(pic, or(coloured, cap), IRIS_CLOSE), IRIS_CLOSE),\n );\n const inEllipse = and(and(shape, andNot(f.ellipse, cap)), eye);\n // A disc squarer than the ellipse: its corners past the ellipse, joined\n // to it and iris-like, are the iris's, not the lids'.\n const margin = new Uint8Array(n);\n for (const i of all) {\n const x = i % width;\n const y = (i - x) / width;\n const r = Math.hypot((x - f.cx) / f.rx, (y - f.cy) / f.ry);\n if (\n !f.ellipse[i] &&\n r <= 1 + IRIS_MARGIN &&\n y > lid[x] &&\n !lowerAcross[i] &&\n c.irisLike(i)\n ) {\n margin[i] = 1;\n }\n }\n const disc = or(inEllipse, reachThrough(pic, inEllipse, margin, Infinity));\n // Left in the sclera, the soft rim shows as a ring where the iris was once\n // it moves.\n const near = dilate(pic, disc, IRIS_RIM);\n const shown = new Uint8Array(disc);\n for (const i of all) {\n if (!near[i] || shown[i] || c.dark(i)) continue;\n const x = i % width;\n if (\n (i - x) / width > lid[x] &&\n dist(labOf(pic.rgb, i), c.white.lab) > same\n ) {\n shown[i] = 1;\n }\n }\n return andNot(shown, lowerAcross);\n}\n\n/** The upper lash (the dark paint not iris above `lashCut`, and the eye's\n * rows above its first dark one, the lash's soft top edge, so the lash\n * shares the sclera's top row: the blink fold rides it) and the lower lid\n * (the dark paint not iris below it). */\nfunction lashesOf(\n pic: Illustration,\n all: number[],\n c: EyeColours,\n iris: Mask,\n lashCut: number,\n): { lash: Mask; lower: Mask } {\n const n = pic.width * pic.height;\n const lash = new Uint8Array(n);\n const lower = new Uint8Array(n);\n let lashTop = Infinity;\n for (const i of all) {\n if (iris[i] || !c.dark(i)) continue;\n const y = Math.floor(i / pic.width);\n if (y <= lashCut) {\n lash[i] = 1;\n lashTop = Math.min(lashTop, y);\n } else {\n lower[i] = 1;\n }\n }\n if (lashTop < Infinity) {\n for (const i of all) if (Math.floor(i / pic.width) < lashTop) lash[i] = 1;\n }\n return { lash, lower };\n}\n\n/** The iris layer: as it shows, and filled from the disc's own colours\n * (white highlights left out) where the lids cover it. */\nfunction irisLayer(\n pic: Illustration,\n shown: Mask,\n hidden: Mask,\n c: EyeColours,\n): LayerPaint {\n const layer = paintOf(pic, or(shown, hidden));\n let disc = erode(\n pic,\n shown.map((v, i) => (v && !c.isWhite(i) ? 1 : 0)),\n 1,\n );\n if (count(disc) === 0) disc = shown;\n if (count(hidden) === 0 || count(disc) === 0) return layer;\n const filled = fillFrom(pic, disc);\n layer.rgb = new Float32Array(pic.rgb);\n for (let i = 0; i < hidden.length; i++) {\n if (!hidden[i] || shown[i]) continue;\n for (let c3 = 0; c3 < 3; c3++) layer.rgb[i * 3 + c3] = filled[i * 3 + c3];\n layer.alpha[i] = 1;\n }\n return layer;\n}\n\n/** The sclera: the whole drawing's shape, filled wherever `covered` (the\n * upper lash, the iris) lies over it from the eye's white, its lightest\n * paint (that colour itself where none shows clear of the iris); the lower\n * lid and everything else as drawn. */\nfunction scleraLayer(\n pic: Illustration,\n eye: Mask,\n c: EyeColours,\n covered: Mask,\n iris: Mask,\n): LayerPaint {\n const n = pic.width * pic.height;\n const layer = paintOf(pic, eye);\n const whites = andNot(\n and(\n erode(\n pic,\n eye.map((v, i) => (v && c.isWhite(i) ? 1 : 0)),\n 1,\n ),\n eye,\n ),\n dilate(pic, iris, SOURCE_INSET),\n );\n const fill =\n count(whites) > 0\n ? fillFrom(pic, whites)\n : Float32Array.from({ length: n * 3 }, (_, k) => c.white.rgb[k % 3]);\n layer.rgb = new Float32Array(pic.rgb);\n for (let i = 0; i < n; i++) {\n if (!eye[i] || !covered[i]) continue;\n for (let k = 0; k < 3; k++) layer.rgb[i * 3 + k] = fill[i * 3 + k];\n }\n return layer;\n}\n\n/**\n * The disc the paint finds for the iris check: below the upper lid\n * (`below`) and off the lower lid, the iris-like paint grown from the\n * ellipse's inside, and the dark paint joined to it over the columns it\n * spans (a disc's top as dark as the lash), never the lash's or the lids'\n * ink beside it or the white's shading; closed over its pupil and\n * highlight (the lash above counted in, so a pupil touching it closes too),\n * its largest piece, within the columns and above the bottom row the\n * colour reaches. Grown by colour, its edges and its bottom row are the\n * disc's own wherever the ellipse lies on it.\n */\nfunction discFound(\n pic: Illustration,\n f: EyeFrame,\n eye: Mask,\n c: EyeColours,\n below: Mask,\n lower: Mask,\n): Mask {\n const { width } = pic;\n const tone = below.map((v, i) => (v && !lower[i] && c.irisLike(i) ? 1 : 0));\n const seeds = and(tone, f.ellipse);\n const coloured = or(seeds, reachThrough(pic, seeds, tone, Infinity));\n // Over the columns the colour spans, the dark paint joined to it: a\n // disc's top as dark as the lash.\n const span = maskBox(pic, coloured);\n const dark = below.map((v, i) => {\n const x = i % width;\n return v && !lower[i] && span && x >= span[0] && x <= span[2] && c.dark(i)\n ? 1\n : 0;\n });\n const grown = or(coloured, reachThrough(pic, coloured, dark, Infinity));\n const lash = andNot(eye, below);\n const disc = largestPiece(\n pic,\n and(\n fillHoles(\n pic,\n erode(pic, dilate(pic, or(grown, lash), DISC_CLOSE), DISC_CLOSE),\n ),\n below,\n ),\n );\n // No wider than its colour, and no lower: the closing may take a lid's\n // or a lash's ink beside it.\n return span\n ? disc.map((v, i) => {\n const x = i % width;\n const y = (i - x) / width;\n return v && x >= span[0] && x <= span[2] && y <= span[3] ? 1 : 0;\n })\n : disc;\n}\n\nfunction largestPiece(pic: Illustration, m: Mask): Mask {\n const { id, sizes } = pieces(pic, m);\n if (sizes.length === 0) return m;\n let best = 0;\n for (let k = 1; k < sizes.length; k++) if (sizes[k] > sizes[best]) best = k;\n return Uint8Array.from(id, (k) => (k === best ? 1 : 0));\n}\n\ninterface EyeCut {\n /** The whole drawing: the sclera's shape. */\n eye: Mask;\n sclera: LayerPaint;\n /** Null for an eye drawn closed. */\n iris: LayerPaint | null;\n lash: Mask;\n lower: Mask;\n checks: CutCheck[];\n}\n\n/**\n * One eye, split as the composer splits a drawn eye: the drawing\n * (`eyeDrawing`), read against its own ink, white and iris (`eyeColours`);\n * the lids (`upperLid`, `lowerLidAcross`); the iris as it shows\n * (`irisShown`); the lashes (`lashesOf`); then the iris and sclera layers.\n * An eye with no white (`whiteShare` under WHITE_SHARE) and no iris (the\n * ellipse's ring a blend of its ink and the skin, `offBlend`) is drawn\n * closed: it is all lash over the sclera's shape, with no iris.\n */\nfunction cutEye(\n ctx: CutContext,\n side: Side,\n around: Float32Array,\n same: number,\n): EyeCut {\n const { pic } = ctx;\n const n = pic.width * pic.height;\n const f = eyeFrame(ctx, side);\n const drawing = eyeDrawing(ctx, f, around, same);\n const { eye } = drawing;\n const all: number[] = [];\n for (let i = 0; i < n; i++) if (eye[i]) all.push(i);\n const none = new Uint8Array(n);\n if (all.length === 0) {\n return {\n eye,\n sclera: paintOf(pic, eye),\n iris: null,\n lash: none,\n lower: none,\n checks: [\n {\n id: `opening.${side}`,\n level: \"fail\",\n pass: false,\n value: null,\n limit: 1,\n hint: `nothing in ${f.at}.box differs from the skin around it: put the box round the drawn eye, lashes included`,\n },\n eyeCheck(side, null, false),\n irisSkipped(side, `no eye found in ${f.at}.box to find the iris in`),\n ],\n };\n }\n const skin = medianColour(around, all).lab;\n const c = eyeColours(pic, f, all, skin);\n const opening = openingCheck(ctx, side, drawing, around, same);\n const white = whiteShare(pic, c, all, skin, same);\n // An iris of its own colour on the ellipse's ring is an open eye whatever\n // its white: tinted, or mostly hidden behind a large iris.\n const irisOwn = offBlend(c.iris.lab, skin, c, same) > WHITE_SCALE;\n if (white < WHITE_SHARE && !irisOwn) {\n // Drawn closed: the line is the lash, folding over the sclera's shape,\n // which is the skin under it.\n const sclera = paintOf(pic, eye);\n sclera.rgb = around;\n return {\n eye,\n sclera,\n iris: null,\n lash: eye,\n lower: none,\n checks: [\n opening,\n eyeCheck(side, white, false),\n irisSkipped(side, \"no iris cut: the eye was read as drawn closed\"),\n ],\n };\n }\n\n const lid = upperLid(pic, f, eye, c);\n const lashCut = lashCutOf(pic, all);\n const lowerAcross = lowerLidAcross(pic, f, eye, c, lashCut, lid);\n const shown = irisShown(pic, f, eye, all, c, lid, lowerAcross, same);\n const { lash, lower } = lashesOf(pic, all, c, shown, lashCut);\n const cap = f.ellipse.map((v, i) =>\n v && Math.floor(i / pic.width) <= lid[i % pic.width] ? 1 : 0,\n );\n const hidden = or(and(cap, lash), lowerAcross);\n const iris = irisLayer(pic, shown, hidden, c);\n const irisMask = Uint8Array.from(iris.alpha, (a) => (a > 0 ? 1 : 0));\n const sclera = scleraLayer(\n pic,\n eye,\n c,\n or(lash, andNot(irisMask, lower)),\n irisMask,\n );\n const below = eye.map((v, i) =>\n v && Math.floor(i / pic.width) > lid[i % pic.width] && !lowerAcross[i]\n ? 1\n : 0,\n );\n return {\n eye,\n sclera,\n iris: count(irisMask) > 0 ? iris : null,\n lash,\n lower,\n checks: [\n opening,\n eyeCheck(side, white, true),\n irisCheck(\n pic,\n side,\n discFound(pic, f, eye, c, below, lower),\n and(f.ellipse, below),\n ),\n ],\n };\n}\n\n/** Whether the eye has a white (its `whiteShare` against WHITE_SHARE),\n * and, with too little, whether it was still cut open (`open`: its iris\n * ring is a paint of its own) or read as drawn closed. */\nfunction eyeCheck(side: Side, white: number | null, open: boolean): CutCheck {\n const id = `eye.${side}`;\n const at = `landmarks.eyes.${side}`;\n const base = { id, level: \"warn\" as const, limit: WHITE_SHARE };\n if (white === null) {\n return {\n ...base,\n pass: false,\n value: null,\n hint: \"no eye found to read a white in\",\n };\n }\n if (white >= WHITE_SHARE) {\n return {\n ...base,\n pass: true,\n value: fmt(white),\n hint: `${pct(white)} of the eye is white: cut open, its iris and lids apart`,\n };\n }\n if (open) {\n return {\n ...base,\n pass: false,\n value: fmt(white),\n hint: `only ${pct(white)} of the eye reads as white: the white is tinted or mostly hidden behind the iris. The eye was cut open, its iris apart, and the sclera under the iris and the lash was filled from the eye's lightest paint: look at eye_${side}.png to see that it reads as the white`,\n };\n }\n return {\n ...base,\n pass: false,\n value: fmt(white),\n hint: `the eye was read as drawn closed (${pct(white)} of it white, and the colour on ${at}.iris's ring a blend of its ink and the skin): its line is the lash over the sclera's shape, with no iris. That is right for a closed eye; for an open one it means ${at}.iris is off the iris: put the ellipse on the coloured disc`,\n };\n}\n\nfunction irisSkipped(side: Side, hint: string): CutCheck {\n return {\n id: `iris.${side}`,\n level: \"warn\",\n pass: false,\n value: null,\n limit: IRIS_IOU,\n hint,\n };\n}\n\n/** A side of an eye box. */\ntype BoxSide = \"top\" | \"bottom\" | \"left\" | \"right\";\n\n/**\n * Whether the box holds the whole eye: its paint touching the box's border\n * means the box clips it (how far the eye runs on past each side is read\n * by following its paint out of the box, and the box suggested leaves\n * OPENING_SPARE to OPENING_SPARE + EYE_EDGE px past it); an eye covering\n * under LOOSE_SHARE of its box warns. Where the paint the border cuts runs\n * on as a long stroke (`longStrokes`), the tool cannot tell a lash wing\n * from a strand or a line crossing the box: the hint says what it sees,\n * and a box clipping only such strokes warns rather than fails.\n */\nfunction openingCheck(\n ctx: CutContext,\n side: Side,\n drawing: EyeDrawing,\n around: Float32Array,\n same: number,\n): CutCheck {\n const { pic, labels, lm } = ctx;\n const { width, height } = pic;\n const { eye, long } = drawing;\n const at = `landmarks.eyes.${side}.box`;\n const box = lm.eyes[side].box;\n const b = bounds(pic, box);\n const id = `opening.${side}`;\n const eb = maskBox(pic, eye)!;\n const margins: Record<BoxSide, number> = {\n top: eb[1] - b.y0,\n bottom: b.y1 - eb[3],\n left: eb[0] - b.x0,\n right: b.x1 - eb[2],\n };\n const least = Math.min(...Object.values(margins));\n if (least === 0) {\n // Follow the eye's paint out of the box, as far again as the box.\n const reach = Math.max(b.x1 - b.x0, b.y1 - b.y0);\n const wx0 = Math.max(0, b.x0 - reach);\n const wx1 = Math.min(width - 1, b.x1 + reach);\n const wy0 = Math.max(0, b.y0 - reach);\n const wy1 = Math.min(height - 1, b.y1 + reach);\n const isSkin = skinTest(ctx, around, same);\n const isPaint = (x: number, y: number) => {\n const i = y * width + x;\n return labels.solid[i] && labels.label[i] !== LABEL_HAIR && !isSkin(i);\n };\n const seen = new Uint8Array(width * height);\n const queue: number[] = [];\n for (let y = b.y0; y <= b.y1; y++) {\n for (let x = b.x0; x <= b.x1; x++) {\n const i = y * width + x;\n if (eye[i]) {\n seen[i] = 1;\n queue.push(i);\n }\n }\n }\n const ext = { top: b.y0, bottom: b.y1, left: b.x0, right: b.x1 };\n for (let q = 0; q < queue.length; q++) {\n const i = queue[q];\n const x = i % width;\n const y = (i - x) / width;\n for (const [nx, ny] of [\n [x - 1, y],\n [x + 1, y],\n [x, y - 1],\n [x, y + 1],\n ]) {\n if (nx < wx0 || nx > wx1 || ny < wy0 || ny > wy1) continue;\n const j = ny * width + nx;\n if (seen[j]) continue;\n const inside = nx >= b.x0 && nx <= b.x1 && ny >= b.y0 && ny <= b.y1;\n if (inside || !isPaint(nx, ny)) continue;\n seen[j] = 1;\n queue.push(j);\n ext.top = Math.min(ext.top, ny);\n ext.bottom = Math.max(ext.bottom, ny);\n ext.left = Math.min(ext.left, nx);\n ext.right = Math.max(ext.right, nx);\n }\n }\n // Past where the paint was followed to: its rim, then the spare.\n const grow = (past: number) => past + EYE_EDGE + OPENING_SPARE;\n const sides: {\n side: BoxSide;\n move: string;\n stroke: string | null;\n }[] = [];\n const add = (s: BoxSide, move: string) => {\n const run = borderRun(pic, b, eye, s);\n sides.push({\n side: s,\n move,\n stroke:\n run && strokeAt(pic, b, long, s, run)\n ? `the paint its ${s} edge cuts, ${run[1] - run[0] + 1} px wide at ${s === \"top\" || s === \"bottom\" ? \"x\" : \"y\"} ${run[0]}..${run[1]}, runs on as a stroke more than ${drawing.past} px past the box: if it is hair or a line crossing the eye's box, leave that edge (the stroke is not the eye's, and the box would only follow it); if it is the eye's own (a lash wing), move ${move}`\n : null,\n });\n };\n if (margins.top === 0) {\n const g = grow(b.y0 - ext.top);\n add(\"top\", `y0 up by ${g} (to ${Math.max(0, box[1] - g)})`);\n }\n if (margins.bottom === 0) {\n const g = grow(ext.bottom - b.y1);\n add(\"bottom\", `y1 down by ${g} (to ${Math.min(height - 1, box[3] + g)})`);\n }\n if (margins.left === 0) {\n const g = grow(b.x0 - ext.left);\n add(\"left\", `x0 left by ${g} (to ${Math.max(0, box[0] - g)})`);\n }\n if (margins.right === 0) {\n const g = grow(ext.right - b.x1);\n add(\"right\", `x1 right by ${g} (to ${Math.min(width - 1, box[2] + g)})`);\n }\n const clipped = sides.filter((s) => s.stroke === null);\n const strokes = sides.filter((s) => s.stroke !== null);\n const parts: string[] = [];\n if (clipped.length > 0) {\n parts.push(\n `${at} clips the eye, whose paint touches its border; what it cuts off stays on the face and the lash tears on a blink. Grow it ${clipped.map((s) => `at its ${s.side}: move ${s.move}`).join(\"; \")}`,\n );\n }\n if (strokes.length > 0) {\n parts.push(\n `${at}'s border cuts paint it cannot tell from the eye: ${strokes.map((s) => s.stroke).join(\"; \")}`,\n );\n }\n return {\n id,\n level: clipped.length > 0 ? \"fail\" : \"warn\",\n pass: false,\n value: 0,\n limit: 1,\n hint: parts.join(\". \"),\n };\n }\n const area = (b.x1 - b.x0 + 1) * (b.y1 - b.y0 + 1);\n const covers = count(eye) / area;\n if (covers < LOOSE_SHARE) {\n return {\n id,\n level: \"warn\",\n pass: false,\n value: fmt(covers),\n limit: LOOSE_SHARE,\n hint: `the eye covers ${pct(covers)} of ${at}: a loose box takes the lines and shading round the eye into it; the eye's paint spans [${eb.join(\", \")}], so a box ${OPENING_SPARE} px round that is [${Math.max(0, eb[0] - OPENING_SPARE)}, ${Math.max(0, eb[1] - OPENING_SPARE)}, ${Math.min(width - 1, eb[2] + OPENING_SPARE)}, ${Math.min(height - 1, eb[3] + OPENING_SPARE)}]`,\n };\n }\n return {\n id,\n level: \"fail\",\n pass: true,\n value: least,\n limit: 1,\n hint: `the eye sits ${least} px or more inside ${at}`,\n };\n}\n\n/** The first and last of the eye's pixels on one border line of its box\n * (x along the top and bottom, y along the sides); null with none. */\nfunction borderRun(\n pic: Illustration,\n b: Bounds,\n eye: Mask,\n side: BoxSide,\n): [number, number] | null {\n const { width } = pic;\n const along = side === \"top\" || side === \"bottom\";\n const fixed = { top: b.y0, bottom: b.y1, left: b.x0, right: b.x1 }[side];\n const [from, to] = along ? [b.x0, b.x1] : [b.y0, b.y1];\n let first = -1;\n let last = -1;\n for (let v = from; v <= to; v++) {\n const i = along ? fixed * width + v : v * width + fixed;\n if (!eye[i]) continue;\n if (first < 0) first = v;\n last = v;\n }\n return first < 0 ? null : [first, last];\n}\n\n/** Whether a long stroke meets the eye's paint at `side` within `run`\n * (within STROKE_GAP + EYE_EDGE px outside the border). */\nfunction strokeAt(\n pic: Illustration,\n b: Bounds,\n long: Mask,\n side: BoxSide,\n run: [number, number],\n): boolean {\n const { width, height } = pic;\n const near = STROKE_GAP + EYE_EDGE;\n const along = side === \"top\" || side === \"bottom\";\n for (let v = run[0] - near; v <= run[1] + near; v++) {\n for (let d = 1; d <= near; d++) {\n const x = along ? v : side === \"left\" ? b.x0 - d : b.x1 + d;\n const y = along ? (side === \"top\" ? b.y0 - d : b.y1 + d) : v;\n if (x < 0 || y < 0 || x >= width || y >= height) continue;\n if (long[y * width + x]) return true;\n }\n }\n return false;\n}\n\n/**\n * The iris ellipse against the disc the colours find, both under the lash:\n * their overlap (intersection over union) and how far apart their centres\n * are, with which way to move the ellipse.\n */\nfunction irisCheck(\n pic: Illustration,\n side: Side,\n disc: Mask,\n ellipse: Mask,\n): CutCheck {\n const { width } = pic;\n const id = `iris.${side}`;\n const at = `landmarks.eyes.${side}.iris`;\n let inter = 0;\n let union = 0;\n const centre = (m: Mask) => {\n let sx = 0;\n let sy = 0;\n let k = 0;\n for (let i = 0; i < m.length; i++) {\n if (!m[i]) continue;\n sx += i % width;\n sy += Math.floor(i / width);\n k++;\n }\n return k > 0 ? [sx / k, sy / k] : null;\n };\n for (let i = 0; i < disc.length; i++) {\n if (disc[i] && ellipse[i]) inter++;\n if (disc[i] || ellipse[i]) union++;\n }\n const d = centre(disc);\n const e = centre(ellipse);\n const found = maskBox(pic, disc);\n if (!d || !e || !found) {\n return {\n id,\n level: \"warn\",\n pass: false,\n value: 0,\n limit: IRIS_IOU,\n hint: `no iris-coloured paint found under the lash inside the eye: check ${at} sits on the coloured disc`,\n };\n }\n const iou = union > 0 ? inter / union : 0;\n const dx = Math.round(d[0] - e[0]);\n const dy = Math.round(d[1] - e[1]);\n const said = `the ellipse overlaps the disc found by ${pct(iou)}, centres ${Math.hypot(dx, dy).toFixed(1)} px apart`;\n if (iou >= IRIS_IOU)\n return {\n id,\n level: \"warn\",\n pass: true,\n value: fmt(iou),\n limit: IRIS_IOU,\n hint: said,\n };\n const moves: string[] = [];\n if (dx !== 0)\n moves.push(`cx ${dx > 0 ? \"right\" : \"left\"} by ${Math.abs(dx)}`);\n if (dy !== 0) moves.push(`cy ${dy > 0 ? \"down\" : \"up\"} by ${Math.abs(dy)}`);\n return {\n id,\n level: \"warn\",\n pass: false,\n value: fmt(iou),\n limit: IRIS_IOU,\n hint: `${said}: ${moves.length > 0 ? `move ${at}.${moves.join(\" and \")}; ` : \"\"}the disc found spans x ${found[0]}..${found[2]} (rx about ${((found[2] - found[0] + 1) / 2).toFixed(1)}) and reaches down to y ${found[3]} (cy + ry)`,\n };\n}\n\n// ---- brows ----\n\n/** One brow as cut: its pixels, and whether its band held it whole (null\n * when the band holds no brow, which `browCheck` reports). */\ninterface BrowCut {\n brow: Mask;\n band: CutCheck | null;\n}\n\n/**\n * The brows. Brow ink is the paint in a band that is neither clean skin\n * nor clean hair: at least BROW_SHARE of the way toward the brow's ink from\n * the paint around the band, from the skin samples, and, where hair is near,\n * from the hair samples (a brow drawn through a strand is a mix of brow and\n * hair; a pale brow on skin, a mix of brow and skin). A brow takes no hair:\n * not the back hair's, which nothing refills, nor a front strand's own\n * paint; on a front strand running through the band (which the front hair\n * refills) only the brow's ink over it, and only where the samples call\n * the brow's ink and the strand apart (not near-black hair). A strand's\n * edge is not brow (`strandEdges`).\n */\nfunction cutBrows(\n ctx: CutContext,\n eyes: Mask,\n same: number,\n): { L?: BrowCut; R?: BrowCut } {\n const { pic, lm, labels, classifier } = ctx;\n const n = pic.width * pic.height;\n const bands = [labels.browBands.L, labels.browBands.R].filter(\n (m) => m !== undefined,\n );\n if (bands.length === 0) return {};\n const allBands = bands.reduce(or);\n // The paint around the band: hair and skin off lines, off the bands.\n const sources = erode(\n pic,\n labels.classes.map((c, i) =>\n labels.solid[i] && (c === HAIR || c === SKIN) && !allBands[i] && !eyes[i]\n ? 1\n : 0,\n ),\n SOURCE_INSET,\n );\n const around = fillFrom(pic, sources);\n const hairNear = or(\n labels.strandThrough,\n dilate(pic, andNot(labels.hair, allBands), HAIR_NEAR),\n );\n const isHair = (i: number) => labels.label[i] === LABEL_HAIR;\n\n const out: { L?: BrowCut; R?: BrowCut } = {};\n for (const side of [\"L\", \"R\"] as const) {\n const band = labels.browBands[side];\n if (!band) continue;\n const cand: number[] = [];\n const off = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n if (!band[i] || !labels.solid[i] || eyes[i]) continue;\n cand.push(i);\n off[i] = dist(labOf(pic.rgb, i), labOf(around, i));\n }\n const brow = new Uint8Array(n);\n if (cand.length === 0) {\n out[side] = { brow, band: null };\n continue;\n }\n const core = [...cand].sort((p, q) => off[q] - off[p]);\n const ink = medianColour(\n pic.rgb,\n core.slice(0, Math.max(1, Math.ceil(core.length * BROW_CORE_SHARE))),\n );\n const hairDistinct = classifier.classify(...ink.rgb) !== HAIR;\n const inkFrom = classifier.distances(...ink.rgb);\n const allowed = (i: number) =>\n labels.strandThrough[i]\n ? labels.hairFront[i] === 1 &&\n hairDistinct &&\n labels.classes[i] !== HAIR\n : !isHair(i);\n /** At least BROW_SHARE of the way to the brow's ink from every paint\n * it may be a mix with. */\n const isInk = (i: number) => {\n const toInk = dist(ink.lab, labOf(around, i));\n if (toInk <= same) return false;\n const d = classifier.distances(\n pic.rgb[i * 3],\n pic.rgb[i * 3 + 1],\n pic.rgb[i * 3 + 2],\n );\n const fromLocal = dist(labOf(pic.rgb, i), labOf(around, i)) / toInk;\n const fromSkin = inkFrom.skin > 0 ? d.skin / inkFrom.skin : 1;\n const fromHair =\n hairDistinct && hairNear[i] && inkFrom.hair > 0\n ? d.hair / inkFrom.hair\n : 1;\n return Math.min(fromLocal, fromSkin, fromHair) >= BROW_SHARE;\n };\n for (const i of cand) if (allowed(i) && isInk(i)) brow[i] = 1;\n // The rim may run past the band: a band a px or two off the stroke\n // would leave its soft edge behind. Clean paint there is a source of\n // `around` itself, so it never differs from it and stays.\n const rim = dilate(pic, brow, BROW_EDGE);\n for (let i = 0; i < n; i++) {\n if (!rim[i] || brow[i] || !labels.solid[i] || eyes[i] || !allowed(i)) {\n continue;\n }\n if (!band[i] && isHair(i)) continue;\n if (dist(labOf(pic.rgb, i), labOf(around, i)) > same) brow[i] = 1;\n }\n for (const i of strandEdges(pic, brow, lm.brows![side]!, isHair)) {\n brow[i] = 0;\n }\n const missed =\n count(brow) > 0\n ? browMissed(ctx, side, lm.brows![side]!, band, brow, eyes, isInk)\n : null;\n out[side] = { brow, band: missed };\n }\n return out;\n}\n\n/** The on pixels of a mask. */\nfunction maskIndices(m: Mask): number[] {\n const out: number[] = [];\n for (let i = 0; i < m.length; i++) if (m[i]) out.push(i);\n return out;\n}\n\n/**\n * The pieces of a brow cut that are a strand's edges, not brow: a piece\n * lying wholly on hair, or one running across the line farther than along\n * it (a brow runs along its line; a strand's edge crosses the band).\n */\nfunction strandEdges(\n pic: Illustration,\n brow: Mask,\n line: IllustrationBrow,\n isHair: (i: number) => boolean,\n): number[] {\n const { width } = pic;\n const where = browGeometry(line);\n const { id, sizes } = pieces(pic, brow);\n const k = sizes.length;\n const onFace = new Uint8Array(k);\n const span = Array.from({ length: k }, () => [\n Infinity,\n -Infinity,\n Infinity,\n -Infinity,\n ]);\n const dir = new Float64Array(k * 2).fill(NaN);\n for (let i = 0; i < brow.length; i++) {\n const p = id[i];\n if (p < 0) continue;\n if (!isHair(i)) onFace[p] = 1;\n const x = i % width;\n const y = (i - x) / width;\n if (Number.isNaN(dir[p * 2])) {\n const w = where(x, y);\n dir[p * 2] = w.tx;\n dir[p * 2 + 1] = w.ty;\n }\n const [tx, ty] = [dir[p * 2], dir[p * 2 + 1]];\n const along = x * tx + y * ty;\n const across = -x * ty + y * tx;\n const s = span[p];\n s[0] = Math.min(s[0], along);\n s[1] = Math.max(s[1], along);\n s[2] = Math.min(s[2], across);\n s[3] = Math.max(s[3], across);\n }\n const out: number[] = [];\n for (let i = 0; i < brow.length; i++) {\n const p = id[i];\n if (p < 0) continue;\n const s = span[p];\n if (!onFace[p] || s[3] - s[2] > s[1] - s[0]) out.push(i);\n }\n return out;\n}\n\n/** Brow ink found past its band, as a share of the brow, before the check\n * warns: past the band's soft rim, which the brow takes, a few px of a\n * stroke's blend is noise; a band off the brow leaves a strip. */\nconst BROW_MISS_SHARE = 0.05;\n\n/**\n * Whether the band holds the whole brow: brow ink (`ink`) clear of the\n * hair by HAIR_LINE px (its soft edge lies there), joined to the\n * brow's pixels (8-connected, through ink on the strands that cross it too), that runs on outside the band, up to `halfWidth` past its\n * edge, stays on the face when the brow moves. Said with which way the line is off and by how much: past the\n * band's lower or upper edge (move the line, or widen the band), or past\n * its tail or inner end (extend the line). A warning: other ink touching\n * the brow (the face's outline, a crease) can read as brow too.\n */\nfunction browMissed(\n ctx: CutContext,\n side: \"L\" | \"R\",\n brow: IllustrationBrow,\n band: Mask,\n cut: Mask,\n eyes: Mask,\n ink: (i: number) => boolean,\n): CutCheck {\n const { pic, labels } = ctx;\n const { width, height } = pic;\n const at = `landmarks.brows.${side}`;\n const where = browGeometry(brow);\n const hairLine = dilate(\n pic,\n labels.label.map((l) => (l === LABEL_HAIR ? 1 : 0)),\n HAIR_LINE,\n );\n const seen = new Uint8Array(cut);\n const queue: number[] = [];\n for (let i = 0; i < cut.length; i++) if (cut[i]) queue.push(i);\n const found: number[] = [];\n for (let q = 0; q < queue.length; q++) {\n const i = queue[q];\n const x = i % width;\n const y = (i - x) / width;\n for (let dy = -1; dy <= 1; dy++) {\n for (let dx = -1; dx <= 1; dx++) {\n const nx = x + dx;\n const ny = y + dy;\n if (nx < 0 || ny < 0 || nx >= width || ny >= height) continue;\n const j = ny * width + nx;\n if (seen[j]) continue;\n seen[j] = 1;\n if (band[j] || !labels.solid[j] || eyes[j] || !ink(j)) continue;\n const w = where(nx, ny);\n if (w.d > w.half + brow.halfWidth) continue;\n if (!hairLine[j]) found.push(j);\n queue.push(j);\n }\n }\n }\n const browPx = count(cut);\n const value = found.length / (browPx + found.length);\n const base = {\n id: `browBand.${side}`,\n level: \"warn\" as const,\n value: fmt(value),\n limit: BROW_MISS_SHARE,\n };\n if (value <= BROW_MISS_SHARE) {\n return {\n ...base,\n pass: true,\n hint: `the band holds the brow: ${found.length} px of brow ink past it`,\n };\n }\n // Which way most of it lies.\n const groups = new Map<string, { px: number[]; e: number; tail: number }>();\n for (const i of found) {\n const x = i % width;\n const y = (i - x) / width;\n const w = where(x, y);\n const key = w.end ?? (w.dy > 0 ? \"below\" : \"above\");\n const g = groups.get(key) ?? { px: [], e: 0, tail: 0 };\n g.px.push(i);\n g.e = Math.max(g.e, w.end ? w.d : w.d - w.half);\n if (w.third) g.tail++;\n groups.set(key, g);\n }\n const [key, g] = [...groups].sort(\n (a, b) => b[1].px.length - a[1].px.length,\n )[0];\n const e = Math.max(1, Math.ceil(g.e));\n const xs = g.px.map((i) => i % width);\n const [xa, xb] = [Math.min(...xs), Math.max(...xs)];\n const span = `x ${xa}..${xb}`;\n const left = `${found.length} px of brow ink (${pct(value)} of the brow) run on`;\n const stays = \"and stay on the face when the brow moves\";\n let hint: string;\n if (key === \"tail\" || key === \"end\") {\n const point = key === \"tail\" ? \"first (tail)\" : \"last (inner)\";\n hint = `${left} past the line's ${key === \"tail\" ? \"tail\" : \"inner end\"} by up to ${e} px at ${span}, ${stays}: extend ${at}.line's ${point} point along the brow by about ${e} px`;\n } else {\n const widen = g.tail * 2 > g.px.length ? \"tailHalfWidth\" : \"halfWidth\";\n // How far the ink's middle lies off the line over the span: the brow's\n // pixels there and the ink past the band, by signed distance.\n const offsets: number[] = [];\n for (const i of [...g.px, ...maskIndices(cut)]) {\n const x = i % width;\n if (x < xa || x > xb) continue;\n const w = where(x, (i - x) / width);\n if (!w.end) offsets.push(w.dy > 0 ? w.d : -w.d);\n }\n const shift = Math.max(1, Math.round(Math.abs(median(offsets))));\n hint = `${left} past the band's ${key === \"below\" ? \"lower\" : \"upper\"} edge by up to ${e} px at ${span}, ${stays}: move ${at}.line's points over ${span} ${key === \"below\" ? \"down\" : \"up\"} by about ${shift} px (onto the ink's middle there), or widen ${at}.${widen} by ${e} (keeping the band no wider than the brow)`;\n }\n return { ...base, pass: false, hint };\n}\n\n// ---- nose and mouth ----\n\n/** What in `box` differs from the skin filled over it (`first`), grown by\n * MARK_EDGE, off `taken`. */\nfunction markIn(\n ctx: CutContext,\n box: Box,\n first: Float32Array,\n same: number,\n taken: Mask,\n): Mask {\n const { pic, labels } = ctx;\n const { width } = pic;\n const b = bounds(pic, box);\n const m = new Uint8Array(width * pic.height);\n for (let y = b.y0; y <= b.y1; y++) {\n for (let x = b.x0; x <= b.x1; x++) {\n const i = y * width + x;\n if (!labels.solid[i] || taken[i] || labels.label[i] === LABEL_HAIR) {\n continue;\n }\n if (dist(labOf(pic.rgb, i), labOf(first, i)) > same) m[i] = 1;\n }\n }\n const box1 = boxMask(pic, box);\n return dilate(pic, m, MARK_EDGE).map((v, i) =>\n v && box1[i] && labels.fg[i] && !taken[i] && labels.label[i] !== LABEL_HAIR\n ? 1\n : 0,\n );\n}\n\n// ---- checks on the brows and the mouth ----\n\n/** Whether a brow's band held its ink: an empty one writes no layer. */\nfunction browCheck(side: \"L\" | \"R\", pixels: number): CutCheck {\n return pixels > 0\n ? {\n id: `brow.${side}`,\n level: \"warn\",\n pass: true,\n value: pixels,\n limit: 1,\n hint: `the brow's band holds ${pixels} px of brow`,\n }\n : {\n id: `brow.${side}`,\n level: \"warn\",\n pass: false,\n value: 0,\n limit: 1,\n hint: `nothing in landmarks.brows.${side}'s band differs from the skin and hair around it, so no brow_${side} is written and the brow stays painted on the face: the line is off the brow; put it along the brow's middle, tail first`,\n };\n}\n\n/**\n * Whether the face has a mouth: the rig needs `mouth` or the lip set. The\n * drawn mouth is what in `mouth.box` differs from the skin; with none, and\n * no lip set to stand for it, the cut fails.\n */\nfunction mouthCheck(pixels: number, lipSet: boolean): CutCheck {\n if (pixels > 0) {\n return {\n id: \"mouth\",\n level: \"fail\",\n pass: true,\n value: pixels,\n limit: 1,\n hint: `the drawn mouth is ${pixels} px${lipSet ? \", lifted off the face under the lip set\" : \"\"}`,\n };\n }\n if (lipSet) {\n return {\n id: \"mouth\",\n level: \"fail\",\n pass: true,\n value: 0,\n limit: 1,\n hint: \"nothing is drawn in landmarks.mouth.box; the lip set stands for the mouth\",\n };\n }\n return {\n id: \"mouth\",\n level: \"fail\",\n pass: false,\n value: 0,\n limit: 1,\n hint: \"nothing in landmarks.mouth.box differs from the skin, so no mouth is written and the rig has none: move the box onto the drawn mouth, or, for a picture with no mouth drawn, give a generated lip set\",\n };\n}\n\n// ---- all of them ----\n\nexport interface FeatureCut {\n /** Each feature layer by role. */\n roles: Map<string, LayerPaint>;\n /** Every pixel a feature takes off the face. */\n holes: Mask;\n /** The skin to fill the holes with: from the skin around, off them. */\n skin: Float32Array;\n /** `skin`'s sources. */\n skinSources: Mask;\n checks: CutCheck[];\n}\n\n/**\n * The eyes, the brows, the nose and the drawn closed mouth as layers, and\n * the skin to fill the face with under them. With `lipSet`, a generated lip\n * set stands for the mouth: the drawn mouth still leaves the face but is\n * written as no layer, and a mouth box with nothing drawn in it is no fault.\n */\nexport function cutFeatures(ctx: CutContext, lipSet = false): FeatureCut {\n const { pic, lm, labels } = ctx;\n const n = pic.width * pic.height;\n const same = samePaint(ctx);\n // A first skin fill with every feature's box open: what the features are\n // told from.\n const boxes = [\n boxMask(pic, lm.eyes.L.box),\n boxMask(pic, lm.eyes.R.box),\n boxMask(pic, lm.mouth.box),\n ...(lm.nose ? [boxMask(pic, lm.nose.box)] : []),\n ...[labels.browBands.L, labels.browBands.R].filter((m) => m !== undefined),\n ].reduce(or);\n const first = fillFrom(pic, skinSources(ctx, boxes));\n\n const roles = new Map<string, LayerPaint>();\n const checks: CutCheck[] = [];\n let holes: Mask = new Uint8Array(n);\n for (const side of [\"L\", \"R\"] as const) {\n const e = cutEye(ctx, side, first, same);\n roles.set(`eye_${side}`, e.sclera);\n if (e.iris) roles.set(`iris_${side}`, e.iris);\n if (count(e.lash) > 0) roles.set(`lash_${side}`, paintOf(pic, e.lash));\n if (count(e.lower) > 0) {\n roles.set(`lash_lower_${side}`, paintOf(pic, e.lower));\n }\n holes = or(holes, e.eye);\n checks.push(...e.checks);\n }\n const brows = cutBrows(ctx, holes, same);\n for (const side of [\"L\", \"R\"] as const) {\n const b = brows[side];\n if (!b) continue;\n const m = b.brow;\n const pixels = count(m);\n checks.push(browCheck(side, pixels));\n if (b.band) checks.push(b.band);\n if (pixels === 0) continue;\n roles.set(`brow_${side}`, paintOf(pic, m));\n holes = or(holes, m);\n }\n if (lm.nose) {\n const nose = markIn(ctx, lm.nose.box, first, same, holes);\n if (count(nose) > 0) {\n roles.set(\"nose\", paintOf(pic, nose));\n holes = or(holes, nose);\n }\n }\n const mouth = markIn(ctx, lm.mouth.box, first, same, holes);\n const mouthPixels = count(mouth);\n checks.push(mouthCheck(mouthPixels, lipSet));\n if (mouthPixels > 0) {\n // The rig refuses `mouth` beside the lip set, which stands for it.\n if (!lipSet) roles.set(\"mouth\", paintOf(pic, mouth));\n holes = or(holes, mouth);\n }\n const sources = skinSources(ctx, holes);\n return {\n roles,\n holes,\n skin: fillFrom(pic, sources),\n skinSources: sources,\n checks,\n };\n}\n","/**\n * The landmarks one finished picture is cut by: where its features sit, the\n * outlines that split its hair, and the points its colours and floods start\n * from, all read off `view_illustration_grid` by an agent.\n *\n * A generator input, not part of the `.iki` contract. `validateLandmarks` is\n * the authoritative check for every caller: it refuses with an\n * `AutoRigInputError` whose message starts at the offending path\n * (`landmarks.eyes.L.iris.rx ...`) and returns the landmarks with every\n * default filled in.\n *\n * Frame: canvas px, origin top-left, x right, y down; a point names a pixel.\n * `L` is the character's left, the viewer's right.\n */\n\nimport { partIdsOfRole } from \"@ikijs/editor\";\nimport { ARM_ROLES } from \"./measure-arms\";\nimport type { Box, CanvasSize, Point } from \"./illustration\";\nimport {\n AutoRigInputError,\n MAX_LANDMARK_BODY_ONLY,\n MAX_LANDMARK_CUSTOM_PARTS,\n MAX_LANDMARK_POINTS,\n MAX_LANDMARK_SAMPLES,\n} from \"./limits\";\n\n/** Where the colour classes come from: each point reads a small patch, and a\n * pixel is hair or skin by which set it is nearer. A missing tone leaves\n * paint in it unclassed or on the wrong side. */\nexport interface IllustrationSamples {\n hair: {\n /** On the hair's main colour, spread over the head; a point on skin or\n * ink makes the face read as hair. */\n base: Point[];\n /** On the hair's shadowed parts; without them shaded strands can fall to\n * the skin. */\n shadow?: Point[];\n /** On the hair's sheen; without them a bright band can read as neither. */\n highlight?: Point[];\n };\n skin: {\n /** On lit skin (cheeks, forehead); a point on hair or a blush makes the\n * face and the hair swap paint. */\n base: Point[];\n /** On shaded skin (under the bangs, the neck); without them shaded skin\n * can fall to the hair. */\n shadow?: Point[];\n };\n}\n\nexport interface IllustrationEye {\n /** The whole drawn eye, lashes included; a box that clips the eye leaves\n * the clipped paint on the face. */\n box: Box;\n /** The iris disc, its centre inside `box`; an ellipse wider than the disc\n * pulls sclera or lash into the iris. */\n iris: { cx: number; cy: number; rx: number; ry: number };\n}\n\nexport interface IllustrationBrow {\n /** The brow's centreline, tail first, 2 or more points; a line off the\n * brow leaves part of it on the face. */\n line: Point[];\n /** Half-width of the band around `line` the brow is cut from (8 when\n * omitted); too narrow leaves the brow's edge behind, too wide takes hair\n * or lash. */\n halfWidth: number;\n /** The band's half-width at the tail, where the brow thins (5 when\n * omitted); too wide takes the hair beside the tail. */\n tailHalfWidth: number;\n}\n\n/** A custom part's cut: the back hair inside a polygon. */\nexport interface IllustrationPolygonCut {\n /** The part's id, also its layer's file name: a plain identifier that no\n * role takes. */\n id: string;\n /** Where the part hangs from the head (a tail's knot); the part swings\n * about it, so a tie off the root tears the part away from the head as it\n * swings. */\n tie: Point;\n /** Everything of the back hair inside it goes to the part; a polygon that\n * misses a strand leaves it in the back hair, where it widens the head\n * the turn is fitted to. */\n polygon: Point[];\n}\n\n/** A custom part's cut: the back hair on one side of a boundary line. */\nexport interface IllustrationSideCut {\n /** The part's id, also its layer's file name: a plain identifier that no\n * role takes. */\n id: string;\n /** Where the part hangs from the head (a tail's knot); the part swings\n * about it, so a tie off the root tears the part away from the head as it\n * swings. */\n tie: Point;\n /** Which side of `line` the part lies on, as the viewer sees it: `left`\n * takes the hair at smaller x. The wrong side takes the head's hair. */\n side: \"left\" | \"right\";\n /** Where the part leaves the head's hair, top to bottom (y strictly\n * ascending), 2 or more points; a line inside the part leaves its root in\n * the back hair. */\n line: Point[];\n /** Under the line's last point, the part is everything on its side of the\n * column x = `below`; set it between the part and the body's hair. */\n below: number;\n /** A box around a ribbon or tie: its strongly coloured paint that is not\n * hair goes with the part instead of staying in the back hair. */\n ribbonBox?: Box;\n}\n\nexport type IllustrationCustomCut =\n | IllustrationPolygonCut\n | IllustrationSideCut;\n\n/** The landmarks with every default applied. */\nexport interface IllustrationLandmarks {\n /** Colour samples for hair and skin; a sample on the wrong paint moves\n * that paint to the other class across the whole picture. */\n samples: IllustrationSamples;\n /** `L` is the character's left eye, on the viewer's right; a swapped pair\n * rigs each eye with the other side's motion. */\n eyes: { L: IllustrationEye; R: IllustrationEye };\n /** Each side optional; a brow left out stays painted on the face and\n * never moves. */\n brows?: { L?: IllustrationBrow; R?: IllustrationBrow };\n /** The drawn nose; left out, it stays on the face. A box that clips it\n * leaves the clipped paint on the face. */\n nose?: { box: Box };\n mouth: {\n /** The whole drawn mouth; a box that clips it leaves paint on the face. */\n box: Box;\n /** The viewer's left end of the drawn mouth line; the lip set's corners\n * land on the two corners, so a corner off the line skews the mouth. */\n cornerL: Point;\n /** The viewer's right end of the drawn mouth line. */\n cornerR: Point;\n };\n /** Polygon, 3 or more points: the bangs and the strands beside the face.\n * Wider than the face, the turn is clamped; narrower, the bangs' edge\n * stays in the back hair. */\n frontHair: Point[];\n /** Polygons, 3 or more points each, round a lock that hangs from under\n * the bangs in front of the ear and the cheek's edge, each side optional\n * (`L` the character's left, on the viewer's right): its hair is\n * `hair_side_<side>`, drawn over the face and under `hair_front`, and\n * rigged to ride the face. Trace the lock's outline from up inside\n * `frontHair` (the two may overlap: the front hair keeps the paint both\n * claim) down round its tip. The lock's root is carried up under the\n * bangs. Under the lock, skin is filled only where it crosses the face's\n * own paint (the ear on one side and the cheek on the other) and inside\n * `skull`; the back hair is filled under it down to `shellLower`, so lower\n * `shellLower` at that side to where the hair behind the lock ends. A top\n * below the front hair leaves a strip of the lock in the back hair and\n * its root showing; a polygon reaching over the eye's outer corner puts it under\n * the lock at rest; one wider than the lock takes the back hair beside\n * it, which then rides the face. */\n sideHair?: { L?: Point[]; R?: Point[] };\n /** Polygon, 3 or more points: the head's skin, the part hidden under the\n * hair included, the ears not; skin is filled in under the bangs and the\n * side locks inside it, so too small shows hair through the forehead on\n * a turn, and one out over an ear lays skin where hair is behind a\n * lock. */\n skull: Point[];\n /** The back hair's lower edge behind the face, left to right (x strictly\n * ascending), 2 or more points; hair is filled in behind the face down to\n * it, so too high shows a gap under the jaw on a turn. */\n shellLower: Point[];\n /** 1 or more, on the face's skin: cheeks, forehead, and one on each ear;\n * skin no seed reaches stays out of the face. */\n skinSeeds: Point[];\n /** 1 or more, on the neck and the chest; paint no seed reaches stays out\n * of the body. */\n bodySeeds: Point[];\n /** Backdrop pockets the figure encloses, which the flood from the border\n * cannot reach; a pocket without one stays painted. Pockets the hair\n * rings (gaps between strands) are keyed without one. Empty when\n * omitted. */\n backgroundSeeds: Point[];\n /** Backdrop-coloured paint the hair rings that is paint, not backdrop (a\n * pale clip between two locks): a pocket holding one is never keyed on\n * its own. Empty when omitted. */\n paintSeeds: Point[];\n /** The row the neck is carried up to behind the chin; too low shows a gap\n * under the jaw when the head turns or nods. */\n neckTopY: number;\n /** Polygons, 3 or more points each, where paint the colour samples call\n * hair belongs to the body: a dark jacket under near-black hair, a\n * hair-coloured bow on the chest. Without one such paint is cut into the\n * hair layers; one over the hair takes it out of them. Empty when\n * omitted. */\n bodyOnly: Point[][];\n /** Parts cut out of the back hair (tails, a ponytail); empty when omitted.\n * A part left in the back hair widens the head the turn is fitted to. */\n customParts: IllustrationCustomCut[];\n}\n\nconst DEFAULT_BROW_HALF_WIDTH = 8;\nconst DEFAULT_BROW_TAIL_HALF_WIDTH = 5;\n\nconst KEYS = {\n root: [\n \"samples\",\n \"eyes\",\n \"brows\",\n \"nose\",\n \"mouth\",\n \"frontHair\",\n \"sideHair\",\n \"skull\",\n \"shellLower\",\n \"skinSeeds\",\n \"bodySeeds\",\n \"backgroundSeeds\",\n \"paintSeeds\",\n \"neckTopY\",\n \"bodyOnly\",\n \"customParts\",\n ],\n samples: [\"hair\", \"skin\"],\n hair: [\"base\", \"shadow\", \"highlight\"],\n skin: [\"base\", \"shadow\"],\n sides: [\"L\", \"R\"],\n eye: [\"box\", \"iris\"],\n iris: [\"cx\", \"cy\", \"rx\", \"ry\"],\n brow: [\"line\", \"halfWidth\", \"tailHalfWidth\"],\n nose: [\"box\"],\n mouth: [\"box\", \"cornerL\", \"cornerR\"],\n custom: [\"id\", \"tie\", \"polygon\", \"side\", \"line\", \"below\", \"ribbonBox\"],\n} as const;\n\n/** The keys of a side cut beyond `id` and `tie`. */\nconst SIDE_CUT_KEYS = [\"side\", \"line\", \"below\", \"ribbonBox\"] as const;\n\n/** The custom-part id rule of `@ikijs/editor`'s `checkCustomParts`\n * (`auto-rig/custom-parts.ts`), which does not export it: mirrored so the\n * cut and the rig tell a user one rule. */\nconst ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nconst fail = (message: string): never => {\n throw new AutoRigInputError(message);\n};\n\n/** A value as a message quotes it. A BigInt is written out by hand: JSON\n * has none, and `JSON.stringify` throws on one. */\nconst show = (v: unknown): string =>\n typeof v === \"bigint\"\n ? `${v}n`\n : (JSON.stringify(v, (_key, x: unknown) =>\n typeof x === \"bigint\" ? `${x}n` : x,\n ) ?? String(v));\n\nconst finite = (v: unknown): v is number =>\n typeof v === \"number\" && Number.isFinite(v);\n\n/** `v` is an array of `n` finite numbers. Read by index: `every` skips the\n * holes of a sparse array. */\nfunction finiteTuple(v: unknown, n: number): v is number[] {\n if (!Array.isArray(v) || v.length !== n) return false;\n for (let i = 0; i < n; i++) if (!finite(v[i])) return false;\n return true;\n}\n\n/** An object whose keys are all among `known`. */\nfunction object(\n path: string,\n v: unknown,\n known: readonly string[],\n): Record<string, unknown> {\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) {\n return fail(`${path} must be a plain object, got ${show(v)}`);\n }\n for (const key of Object.keys(v)) {\n if (!known.includes(key)) {\n fail(`${path}.${key} is not one of ${known.join(\", \")}`);\n }\n }\n return v as Record<string, unknown>;\n}\n\nfunction required(\n path: string,\n o: Record<string, unknown>,\n key: string,\n): unknown {\n const v = o[key];\n return v === undefined ? fail(`${path}.${key} is missing`) : v;\n}\n\nfunction number(path: string, v: unknown): number {\n return finite(v)\n ? v\n : fail(`${path} must be a finite number, got ${show(v)}`);\n}\n\nfunction positive(path: string, v: unknown): number {\n return finite(v) && v > 0\n ? v\n : fail(`${path} must be a positive number, got ${show(v)}`);\n}\n\nfunction canvasBounds({ width, height }: CanvasSize): string {\n return `the ${width}x${height} canvas (0 <= x < ${width}, 0 <= y < ${height})`;\n}\n\nfunction point(path: string, v: unknown, canvas: CanvasSize): Point {\n if (!finiteTuple(v, 2)) {\n return fail(\n `${path} must be an [x, y] pair of finite numbers, got ${show(v)}`,\n );\n }\n const [x, y] = v;\n if (x < 0 || x >= canvas.width || y < 0 || y >= canvas.height) {\n fail(`${path} ${show(v)} is outside ${canvasBounds(canvas)}`);\n }\n return [x, y];\n}\n\nfunction points(\n path: string,\n v: unknown,\n min: number,\n canvas: CanvasSize,\n): Point[] {\n if (!Array.isArray(v)) {\n return fail(`${path} must be an array of [x, y] points, got ${show(v)}`);\n }\n if (v.length < min) {\n fail(\n `${path} must have ${min} or more point${min > 1 ? \"s\" : \"\"}, got ${v.length}`,\n );\n }\n if (v.length > MAX_LANDMARK_POINTS) {\n fail(\n `${path} has ${v.length} points, over the ${MAX_LANDMARK_POINTS} a landmark list may hold`,\n );\n }\n // By index, so a hole in a sparse array is refused rather than skipped.\n const out: Point[] = [];\n for (let i = 0; i < v.length; i++) {\n out.push(point(`${path}[${i}]`, v[i], canvas));\n }\n return out;\n}\n\nfunction box(path: string, v: unknown, canvas: CanvasSize): Box {\n if (!finiteTuple(v, 4)) {\n return fail(\n `${path} must be [x0, y0, x1, y1], four finite numbers, got ${show(v)}`,\n );\n }\n const [x0, y0, x1, y1] = v;\n if (!(x1 > x0 && y1 > y0)) {\n fail(\n `${path} ${show(v)} must span at least two columns and two rows, x1 > x0 and y1 > y0: both corners are inside the box`,\n );\n }\n if (x0 < 0 || y0 < 0 || x1 >= canvas.width || y1 >= canvas.height) {\n fail(`${path} ${show(v)} reaches outside ${canvasBounds(canvas)}`);\n }\n return [x0, y0, x1, y1];\n}\n\nconst inBox = ([x0, y0, x1, y1]: Box, x: number, y: number): boolean =>\n x >= x0 && x <= x1 && y >= y0 && y <= y1;\n\n/** Each point's coordinate `axis` greater than the one before it. */\nfunction ascending(path: string, pts: Point[], axis: 0 | 1): void {\n for (let i = 1; i < pts.length; i++) {\n if (!(pts[i][axis] > pts[i - 1][axis])) {\n const name = axis === 0 ? \"x\" : \"y\";\n fail(\n `${path}[${i}] ${name} ${pts[i][axis]} must be greater than ${path}[${i - 1}] ${name} ${pts[i - 1][axis]}: the points run with ${name} strictly ascending`,\n );\n }\n }\n}\n\nfunction eye(path: string, v: unknown, canvas: CanvasSize): IllustrationEye {\n const o = object(path, v, KEYS.eye);\n const eyeBox = box(`${path}.box`, required(path, o, \"box\"), canvas);\n const ip = `${path}.iris`;\n const i = object(ip, required(path, o, \"iris\"), KEYS.iris);\n const cx = number(`${ip}.cx`, required(ip, i, \"cx\"));\n const cy = number(`${ip}.cy`, required(ip, i, \"cy\"));\n const rx = positive(`${ip}.rx`, required(ip, i, \"rx\"));\n const ry = positive(`${ip}.ry`, required(ip, i, \"ry\"));\n if (!inBox(eyeBox, cx, cy)) {\n fail(`${ip} centre [${cx}, ${cy}] is outside ${path}.box ${show(eyeBox)}`);\n }\n return { box: eyeBox, iris: { cx, cy, rx, ry } };\n}\n\nfunction brow(path: string, v: unknown, canvas: CanvasSize): IllustrationBrow {\n const o = object(path, v, KEYS.brow);\n return {\n line: points(`${path}.line`, required(path, o, \"line\"), 2, canvas),\n halfWidth:\n o.halfWidth === undefined\n ? DEFAULT_BROW_HALF_WIDTH\n : positive(`${path}.halfWidth`, o.halfWidth),\n tailHalfWidth:\n o.tailHalfWidth === undefined\n ? DEFAULT_BROW_TAIL_HALF_WIDTH\n : positive(`${path}.tailHalfWidth`, o.tailHalfWidth),\n };\n}\n\n/** The part ids a role yields besides its own name: only the arms', in\n * `ROLE_TABLE` (`@ikijs/editor`'s `auto-rig/roles.ts`), which the package\n * does not export. */\nconst YIELDED_PART_IDS = new Set(ARM_ROLES.flatMap((r) => partIdsOfRole(r)));\n\n/** A role's name or a part id a role yields: the rig reserves both for\n * roles (`RESERVED` in `@ikijs/editor`'s `auto-rig/custom-parts.ts`), so a\n * custom part named either is refused there. `partIdsOfRole` throws on any\n * name but a role's. */\nfunction isReservedId(id: string): boolean {\n if (YIELDED_PART_IDS.has(id)) return true;\n try {\n partIdsOfRole(id);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction customCut(\n path: string,\n v: unknown,\n canvas: CanvasSize,\n ids: Set<string>,\n): IllustrationCustomCut {\n const o = object(path, v, KEYS.custom);\n const id = required(path, o, \"id\");\n if (typeof id !== \"string\" || !ID_PATTERN.test(id)) {\n fail(\n `${path}.id must be a plain identifier (letters, digits, underscore; not starting with a digit), got ${show(id)}`,\n );\n }\n const name = id as string;\n if (isReservedId(name)) {\n fail(\n `${path}.id \"${name}\" is a role's name or a part id a role yields: a custom part needs a name no role takes`,\n );\n }\n if (ids.has(name)) {\n fail(`${path}.id \"${name}\" repeats an earlier entry's id`);\n }\n ids.add(name);\n const tie = point(`${path}.tie`, required(path, o, \"tie\"), canvas);\n\n const sideKeys = SIDE_CUT_KEYS.filter((k) => o[k] !== undefined);\n if (o.polygon !== undefined) {\n if (sideKeys.length > 0) {\n fail(\n `${path} carries both polygon and ${sideKeys.join(\", \")}: give either polygon, or side, line and below`,\n );\n }\n return {\n id: name,\n tie,\n polygon: points(`${path}.polygon`, o.polygon, 3, canvas),\n };\n }\n if (sideKeys.length === 0) {\n fail(`${path} must carry either polygon, or side, line and below`);\n }\n const side = required(path, o, \"side\");\n if (side !== \"left\" && side !== \"right\") {\n fail(`${path}.side must be \"left\" or \"right\", got ${show(side)}`);\n }\n const line = points(`${path}.line`, required(path, o, \"line\"), 2, canvas);\n ascending(`${path}.line`, line, 1);\n const below = number(`${path}.below`, required(path, o, \"below\"));\n if (below < 0 || below >= canvas.width) {\n fail(\n `${path}.below ${below} must be a column of the canvas, 0 <= x < ${canvas.width}`,\n );\n }\n const cut: IllustrationSideCut = {\n id: name,\n tie,\n side: side as \"left\" | \"right\",\n line,\n below,\n };\n if (o.ribbonBox !== undefined) {\n cut.ribbonBox = box(`${path}.ribbonBox`, o.ribbonBox, canvas);\n }\n return cut;\n}\n\n/**\n * Check `input` against the landmarks schema on a `canvas`-sized picture and\n * return it with the defaults applied. Throws `AutoRigInputError` at the\n * first fault, its message starting at that field's path.\n */\nexport function validateLandmarks(\n input: unknown,\n canvas: CanvasSize,\n): IllustrationLandmarks {\n const at = \"landmarks\";\n const root = object(at, input, KEYS.root);\n\n const sp = `${at}.samples`;\n const s = object(sp, required(at, root, \"samples\"), KEYS.samples);\n const hp = `${sp}.hair`;\n const h = object(hp, required(sp, s, \"hair\"), KEYS.hair);\n const kp = `${sp}.skin`;\n const k = object(kp, required(sp, s, \"skin\"), KEYS.skin);\n const samples: IllustrationSamples = {\n hair: { base: points(`${hp}.base`, required(hp, h, \"base\"), 1, canvas) },\n skin: { base: points(`${kp}.base`, required(kp, k, \"base\"), 1, canvas) },\n };\n if (h.shadow !== undefined) {\n samples.hair.shadow = points(`${hp}.shadow`, h.shadow, 1, canvas);\n }\n if (h.highlight !== undefined) {\n samples.hair.highlight = points(`${hp}.highlight`, h.highlight, 1, canvas);\n }\n if (k.shadow !== undefined) {\n samples.skin.shadow = points(`${kp}.shadow`, k.shadow, 1, canvas);\n }\n for (const [path, set] of [\n [hp, samples.hair],\n [kp, samples.skin],\n ] as const) {\n const total = Object.values(set).reduce((t, list) => t + list.length, 0);\n if (total > MAX_LANDMARK_SAMPLES) {\n fail(\n `${path} has ${total} points, over the ${MAX_LANDMARK_SAMPLES} one set may hold: a few per tone describe it`,\n );\n }\n }\n\n const ep = `${at}.eyes`;\n const e = object(ep, required(at, root, \"eyes\"), KEYS.sides);\n const eyes = {\n L: eye(`${ep}.L`, required(ep, e, \"L\"), canvas),\n R: eye(`${ep}.R`, required(ep, e, \"R\"), canvas),\n };\n const centreX = ([x0, , x1]: Box) => (x0 + x1) / 2;\n if (!(centreX(eyes.L.box) > centreX(eyes.R.box))) {\n fail(\n `${ep}.L.box centre x ${centreX(eyes.L.box)} is not right of ${ep}.R.box centre x ${centreX(eyes.R.box)}: L is the character's left eye, on the viewer's right, so the two look swapped`,\n );\n }\n\n let brows: IllustrationLandmarks[\"brows\"];\n if (root.brows !== undefined) {\n const bp = `${at}.brows`;\n const b = object(bp, root.brows, KEYS.sides);\n brows = {};\n if (b.L !== undefined) brows.L = brow(`${bp}.L`, b.L, canvas);\n if (b.R !== undefined) brows.R = brow(`${bp}.R`, b.R, canvas);\n }\n\n let nose: IllustrationLandmarks[\"nose\"];\n if (root.nose !== undefined) {\n const np = `${at}.nose`;\n const n = object(np, root.nose, KEYS.nose);\n nose = { box: box(`${np}.box`, required(np, n, \"box\"), canvas) };\n }\n\n const mp = `${at}.mouth`;\n const m = object(mp, required(at, root, \"mouth\"), KEYS.mouth);\n const mouthBox = box(`${mp}.box`, required(mp, m, \"box\"), canvas);\n const cornerL = point(`${mp}.cornerL`, required(mp, m, \"cornerL\"), canvas);\n const cornerR = point(`${mp}.cornerR`, required(mp, m, \"cornerR\"), canvas);\n if (!(cornerL[0] < cornerR[0])) {\n fail(\n `${mp}.cornerL x ${cornerL[0]} must be left of ${mp}.cornerR x ${cornerR[0]}: cornerL is the viewer's left end of the mouth line`,\n );\n }\n for (const [name, c] of [\n [\"cornerL\", cornerL],\n [\"cornerR\", cornerR],\n ] as const) {\n if (!inBox(mouthBox, c[0], c[1])) {\n fail(`${mp}.${name} ${show(c)} is outside ${mp}.box ${show(mouthBox)}`);\n }\n }\n\n const list = (key: string, min: number): Point[] =>\n points(`${at}.${key}`, required(at, root, key), min, canvas);\n const frontHair = list(\"frontHair\", 3);\n let sideHair: IllustrationLandmarks[\"sideHair\"];\n if (root.sideHair !== undefined) {\n const shp = `${at}.sideHair`;\n const sh = object(shp, root.sideHair, KEYS.sides);\n sideHair = {};\n if (sh.L !== undefined) sideHair.L = points(`${shp}.L`, sh.L, 3, canvas);\n if (sh.R !== undefined) sideHair.R = points(`${shp}.R`, sh.R, 3, canvas);\n }\n const skull = list(\"skull\", 3);\n const shellLower = list(\"shellLower\", 2);\n ascending(`${at}.shellLower`, shellLower, 0);\n const skinSeeds = list(\"skinSeeds\", 1);\n const bodySeeds = list(\"bodySeeds\", 1);\n const backgroundSeeds =\n root.backgroundSeeds === undefined\n ? []\n : points(`${at}.backgroundSeeds`, root.backgroundSeeds, 0, canvas);\n const paintSeeds =\n root.paintSeeds === undefined\n ? []\n : points(`${at}.paintSeeds`, root.paintSeeds, 0, canvas);\n\n const neckTopY = number(`${at}.neckTopY`, required(at, root, \"neckTopY\"));\n if (neckTopY < 0 || neckTopY >= canvas.height) {\n fail(\n `${at}.neckTopY ${neckTopY} must be a row of the canvas, 0 <= y < ${canvas.height}`,\n );\n }\n\n const op = `${at}.bodyOnly`;\n const bodyOnlyInput = root.bodyOnly === undefined ? [] : root.bodyOnly;\n if (!Array.isArray(bodyOnlyInput)) {\n return fail(\n `${op} must be an array of polygons, got ${show(bodyOnlyInput)}`,\n );\n }\n if (bodyOnlyInput.length > MAX_LANDMARK_BODY_ONLY) {\n fail(\n `${op} has ${bodyOnlyInput.length} polygons, over the ${MAX_LANDMARK_BODY_ONLY} one picture may hold`,\n );\n }\n const bodyOnly: Point[][] = [];\n for (let i = 0; i < bodyOnlyInput.length; i++) {\n bodyOnly.push(points(`${op}[${i}]`, bodyOnlyInput[i], 3, canvas));\n }\n\n const cp = `${at}.customParts`;\n const customInput = root.customParts === undefined ? [] : root.customParts;\n if (!Array.isArray(customInput)) {\n return fail(`${cp} must be an array, got ${show(customInput)}`);\n }\n if (customInput.length > MAX_LANDMARK_CUSTOM_PARTS) {\n fail(\n `${cp} has ${customInput.length} entries, over the ${MAX_LANDMARK_CUSTOM_PARTS} custom parts one picture may cut`,\n );\n }\n const ids = new Set<string>();\n const customParts: IllustrationCustomCut[] = [];\n for (let i = 0; i < customInput.length; i++) {\n customParts.push(customCut(`${cp}[${i}]`, customInput[i], canvas, ids));\n }\n\n return {\n samples,\n eyes,\n ...(brows && { brows }),\n ...(nose && { nose }),\n mouth: { box: mouthBox, cornerL, cornerR },\n frontHair,\n ...(sideHair && { sideHair }),\n skull,\n shellLower,\n skinSeeds,\n bodySeeds,\n backgroundSeeds,\n paintSeeds,\n neckTopY,\n bodyOnly,\n customParts,\n };\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport type { PatchReport, RigBakes, RigPatch } from \"@ikijs/editor\";\nimport {\n validateIki,\n describeIki,\n describeIkiAt,\n listStandardParameters,\n describeRigPlan,\n formatRigPlanReport,\n autoRigFromLayers,\n type AutoRigCustomPartInput,\n type CustomPartReport,\n type BakeCheck,\n} from \"./tools\";\nimport { composeLayersFromParts } from \"./compose\";\nimport { formatFoldReport } from \"./fold-report\";\nimport { formatCustomGate } from \"./custom-gate\";\nimport { formatHairSideReport } from \"./hair-side-report\";\nimport { formatPhysicsReport } from \"./physics-report\";\nimport { formatNodReport, formatSweepReport } from \"./sweep-report\";\nimport { SWEEP_PRESETS } from \"./sweep\";\nimport { measureLayers, formatMeasureReport } from \"./measure\";\nimport { measureTurnReference, formatTurnReport } from \"./measure-turn\";\nimport { renderPoses } from \"./render-poses\";\nimport { probeRig, type ProbeInput } from \"./probe\";\nimport { viewIllustrationGrid } from \"./illustration-grid\";\nimport { cutLayersFromIllustration, formatCutReport } from \"./illustration-cut\";\n\n/** Injected by tsup (and vitest) from this package's package.json version. */\ndeclare const __MCP_VERSION__: string;\n\n/** One `PATCH` line per op `auto_rig_from_layers` replayed. */\nfunction formatPatchReports(reports: PatchReport[]): string[] {\n return reports.map((r) => {\n const at = Object.keys(r.at)\n .sort()\n .map((p) => `${p}=${r.at[p]}`)\n .join(\" \");\n const where =\n r.cols !== undefined && r.rows !== undefined\n ? `cols ${r.cols[0]}-${r.cols[1]}, rows ${r.rows[0]}-${r.rows[1]}`\n : \"vertices\";\n return `PATCH ${r.index} ${r.target} at ${at}: ${r.moved} of ${r.of} points (${where}), largest move ${r.maxPx} model px`;\n });\n}\n\n/** One `CUSTOM` line per custom part `auto_rig_from_layers` put in the model. */\nfunction formatCustomPartReports(parts: CustomPartReport[]): string[] {\n return parts.map((p) => {\n const line = `CUSTOM ${p.id}: box ${p.box.x},${p.box.y} ${p.box.w}x${p.box.h} px, mesh ${p.mesh.vertices} vertices ${p.mesh.triangles} triangles, order ${p.order}, atlas page ${p.page}`;\n if (p.occlusion === undefined) return line;\n const { by, parameter, stops } = p.occlusion;\n return `${line}, hidden by ${by.join(\",\")} on ${parameter} at ${stops.map((s) => `${s.value}:${s.amount}`).join(\" \")}`;\n });\n}\n\n/** One `BAKE` line per custom part and parameter a bake moved, after the `CUSTOM` lines. */\nfunction formatBakeChecks(bakes: BakeCheck[]): string[] {\n return bakes.map(\n (b) =>\n `BAKE ${b.part} ${b.param}: ${b.vertices} vertices, stops ${b.stops.join(\",\")}, error ${Math.round(b.errorPx * 1000) / 1000} px`,\n );\n}\n\nexport function createIkiMcpServer(): McpServer {\n const server = new McpServer({ name: \"iki\", version: __MCP_VERSION__ });\n\n server.registerTool(\n \"validate_iki\",\n {\n description:\n \"Validates a raw .iki model (object or JSON string); fail-fast — returns at most ONE error, so fix one, re-run.\",\n inputSchema: {\n model: z\n .unknown()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n },\n },\n async ({ model }) => {\n try {\n const r = validateIki(model);\n const text = r.ok ? \"OK\" : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"describe_iki\",\n {\n description:\n \"Summarizes a valid model's canvas/params/parts/deformers and its expressions and motion clips (with the descriptions a host picks them by); returns an error for an invalid model. It is also the patch writer's view of a rigged model: each part's rest box in model px and in bust-render px, each part's warp stops, each warp2d's stops, and faceWidth, which is what an auto_rig_from_layers `patches` op is aimed with. Pass exactly one of model or modelPath; prefer modelPath for a written rig so a large model never crosses your context.\",\n inputSchema: {\n model: z\n .unknown()\n .optional()\n .describe(\"Raw .iki model JSON (object or JSON string)\"),\n modelPath: z\n .string()\n .optional()\n .describe(\n \"Path to a written .iki model (relative to the working directory, inside it)\",\n ),\n },\n },\n async ({ model, modelPath }) => {\n try {\n if ((model === undefined) === (modelPath === undefined)) {\n const error = \"pass model or modelPath\";\n return {\n content: [{ type: \"text\", text: `INVALID: ${error}` }],\n structuredContent: { ok: false, error },\n };\n }\n const r =\n modelPath !== undefined\n ? describeIkiAt(modelPath)\n : describeIki(model);\n const text = r.ok\n ? JSON.stringify(r.summary, null, 2)\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"list_standard_parameters\",\n {\n description:\n \"Lists the recommended standard parameter ids a host can drive without per-model wiring.\",\n inputSchema: {},\n },\n async () => {\n const params = listStandardParameters();\n const text = params.map((p) => `${p.id} — ${p.description}`).join(\"\\n\");\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { parameters: params },\n };\n },\n );\n\n server.registerTool(\n \"describe_rig_plan\",\n {\n description:\n \"Lists the fields of the `rigPlan` input of auto_rig_from_layers: each one's path, default, range, recommended span, step, unit, the poses it shows at, the report reading that shows it and the `turnTargets` cue that fits it when given. The one source of those numbers.\",\n inputSchema: {},\n },\n async () => {\n const { fields } = describeRigPlan();\n const text = fields\n .map(\n (f) =>\n `${f.path} default ${f.default} range ${f.range[0]}..${f.range[1]} recommended ${f.recommended[0]}..${f.recommended[1]} step ${f.step} ${f.unit} — ${f.what}; shows at ${f.poses.map((p) => JSON.stringify(p)).join(\" \")}; cue ${f.cue ?? \"none\"}; fitted by ${f.fitBy ?? \"none\"}${f.provisional ? \"; provisional\" : \"\"}`,\n )\n .join(\"\\n\");\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { fields },\n };\n },\n );\n\n server.registerTool(\n \"auto_rig_from_layers\",\n {\n description:\n \"Auto-rigs role-named PNG layers (face, eye_L/eye_R and either mouth or the lip set (mouth_inner + lip_lower + lip_upper, a mouth that folds open instead of crossfading) required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, hair_side_L/hair_side_R, mouth_tongue/mouth_teeth (only with the lip set: drawn under its lips and clipped to mouth_inner), etc. optional; an arm needs the body, a pose forearm needs its arm, a side lock needs hair_front, and a partial lip set, one mixed with mouth/mouth_open, or mouth_tongue/mouth_teeth without it is refused) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given. The result's `folds` is the written rig's fold report, printed after the path the way render_poses prints it, and report-only: a fold never refuses the rig. The `RIGPLAN:` line (the result's `rigPlan`: `effective`, `clamped`, `overriddenBy`) follows the path and precedes the `PATCH` lines. The `PHYSICS` lines follow the fold report (the result's `physics`), one per physics rig output — a spring's, or each chain segment's — reading ok, frozen or unstable with the step and idle amplitudes, or `PHYSICS: no rigs`; report-only too. With side locks and a `nose` (which `turn` needs) the `HAIRSIDE` lines follow the `PHYSICS` lines (the result's `turn.hairSide`), each naming the lock's role, report-only as well. `patches` (see its field) adds displacements to existing keyform stops of the freshly generated rig; each op then prints one line between the path and the fold report — `PATCH <i> <target> at <Param=v …>: <moved> of <of> points (cols a-b, rows c-d), largest move <maxPx> model px`, with `(vertices)` in place of the columns and rows for a mesh part — and the result's `patches` carries the same reports (`index`, `target`, `at`, `moved`, `of`, `cols`/`rows` for a grid, `maxPx`), present whenever `patches` was passed, `[]` included. An op the input schema accepts but the rig refuses comes back as `INVALID: patches[i]…` and nothing is written; an op with a missing field or a field of the wrong type is the SDK's input validation error. `customParts` adds parts the rig has no role for (a twin tail, a hairpin), each from a canvas-sized PNG of its own, as an unrigged mesh on `headDeformer` after its `after` role's parts; it needs @ikijs/mcp 0.34.0, and an older server drops the field and returns no `customParts`. A part can declare `occlusion` (hidden where named roles' paint covers it, by an amount keyed on a parameter; it needs 0.35.0, and an older server refuses the key as `INVALID: customParts[i]…`); its `CUSTOM <id>:` line then ends `, hidden by <id>,<id>… on <parameter> at <value>:<amount> <value>:<amount>…`, and the result's part carries `occlusion` (`by` as the part ids written, `parameter`, `stops`). The result's `customParts` (`parts`: `id`, rest `box`, `mesh`, `order`, atlas `page`) is present whenever the input was passed, `[]` included, and one `CUSTOM <id>: …` line per part follows the `HAIRSIDE` lines. `bakes` (see its field) moves the custom parts with a parameter and needs `customParts`; each part and parameter it moves then prints one `BAKE <part> <param>: <n> vertices, stops <values>, error <px> px` line after the `CUSTOM` lines (the result's `customParts.bakes`: `part`, `param`, `vertices`, `stops`, `errorPx`), the written model having been landed through the engine, and a stop off by 0.1 px or more comes back as `INVALID: BAKE ERROR <part> <param>=<value>: …`, and a part the bake moves at rest as `INVALID: BAKE ERROR <part> at rest: …`, with nothing written (the rig and the engine disagree: report it as a bug in the packages). Whenever `customParts` was passed, the written model is also measured per custom part (the result's `customParts.gate`: `ok`, `limits`, `parts`, `failed`) and the text ends with its lines, `CUSTOM <id> FOLDS|TIE|SLIDE|EXPOSED|RIGID|TIP: …` then `CUSTOM GATE pass` or `CUSTOM GATE FAIL: <part LINE, …>`, always the last line: a part's least triangle area ratio, its tie's displacement against the anchor where the head does not turn and where it does, the hidden art showing, how far a rigid part bends and where its free end lands, each in px and face widths with its worst pose; `TIP` never fails the gate and the other lines do. The model is written either way; from 0.34.0 on `customParts` always carries `gate` (a gate that throws still writes the file and ends the text `CUSTOM GATE FAIL: gate error: <message>`), so a result without `customParts` is from an older server and was never gated. The custom layers are not role layers: they are left out of the head's width and turn measurements, and an empty or wrong-size one, or an entry the rig refuses, comes back as `INVALID: customParts[i]…` with nothing written. A missing field or one of the wrong type (a `tie` that is not two numbers, say) is refused by the schema itself, as the SDK's input validation error.\",\n inputSchema: {\n layers: z\n .array(\n z.object({\n fileName: z\n .string()\n .optional()\n .describe(\n \"Role-bearing filename; defaults to the basename of `path`.\",\n ),\n path: z\n .string()\n .describe(\"PNG file path (resolved against cwd).\"),\n }),\n )\n .describe(\"Full-canvas PNG layers; all must share the same size.\"),\n outputPath: z\n .string()\n .optional()\n .describe(\n \"Output .iki path (resolved against cwd; parent dir must exist).\",\n ),\n quantizeColors: z\n .number()\n .int()\n .min(2)\n .max(256)\n .optional()\n .describe(\n \"Palette-quantize the atlas PNG to this many colours (2..256). Flat-shaded art keeps its look at 256 and the model shrinks to about a quarter; omit for lossless. A `nose` layer stays lossless on a second atlas page of its own, since the palette rims a soft-shaded nose's feather; the nose's own lossless page adds a content-dependent amount, since splitting it off also changes how page 0 re-quantizes without it; the result's `atlasBytes` sums both pages.\",\n ),\n turnTargets: z\n .object({\n eyeShift: z.number().optional(),\n farEyeRatio: z.number().optional(),\n silhouetteRatio: z.number().optional(),\n noseShift: z.number().optional(),\n mouthShift: z.number().optional(),\n })\n .passthrough()\n .optional()\n .describe(\n \"What the head turn is fitted to, as `measure_turn_reference` reports it off a front/turned reference pair. `eyeShift` (and the optional `noseShift`/`mouthShift`) is how far that feature slides across the head at full turn, as a fraction of the head's half-width — a MAGNITUDE: the rig turns both ways, so the sign is ignored. `farEyeRatio` is the far/near eye width at full turn over that same ratio at rest, `silhouetteRatio` the head's half-width turned over at rest. The half-width the shifts are fractions of is measured off the layers themselves, so it is not an input. An omitted field leaves that part of the turn at the profile the rig defaults to. A passed `eyeShift` is fitted by the turn's amount and clamped to the room the art leaves the far eye — the face plate's edge, or the bangs' side strand over the far iris (the result's `turn.clamped` lists every clamped field, `turn.achieved` what the rig reaches, and `turn.strandOverlap` how much of a far iris the bangs still cover). A passed `silhouetteRatio` is clamped too, only on a face drawn without hair and with ear islands, where narrowing the head that far would no longer cover the far ear's slide. Any other passed target this layer set cannot reach comes back as `INVALID: …` naming the field and the attainable range, since it is a measurement rather than a preference. A field not named here is refused the same way. A pair that shows a custom part crossing the eye row reads a wider head than the rig fits to, since the rig measures the role layers alone: measure a pair drawn without the custom parts.\",\n ),\n style: z\n .unknown()\n .optional()\n .describe(\n \"Removed in @ikijs/mcp 0.30.0: pass `rigPlan`. Any value here is refused with the field map.\",\n ),\n rigPlan: z\n .object({\n turn: z\n .object({\n amount: z.number().optional(),\n featureLead: z.number().optional(),\n eyeForeshorten: z.number().optional(),\n noseLead: z.number().optional(),\n farEar: z.number().optional(),\n })\n .passthrough()\n .optional(),\n hair: z\n .object({\n follow: z.number().optional(),\n outlineFollow: z.number().optional(),\n sway: z.number().optional(),\n })\n .passthrough()\n .optional(),\n eyes: z\n .object({ blink: z.number().optional() })\n .passthrough()\n .optional(),\n })\n .passthrough()\n .optional()\n .describe(\n \"Per-character tuning from the profile the rig defaults to, in three groups: `turn` (`amount`, `featureLead`, `eyeForeshorten`, `noseLead`: the last two turn only, the nod untouched, and fitted by `turnTargets.farEyeRatio` / `turnTargets.noseShift` when those are given, which the `RIGPLAN:` line then reports as overridden; `farEar`: how far the far ear's outer edge follows the face on the turn), `hair` (`follow`, `outlineFollow`, `sway`) and `eyes` (`blink`). `describe_rig_plan` lists every field's default, range, recommended span, step and poses. A value out of range, or a group or key not named there, comes back as `INVALID: rigPlan.<path> …`; an object left out or `{}` is the profile. The result reports what the rig built with as `rigPlan` and a `RIGPLAN:` line.\",\n ),\n customParts: z\n .array(\n z\n .object({\n id: z\n .string()\n .describe(\n \"The part's id: a plain identifier, not a role's name or a part id.\",\n ),\n path: z\n .string()\n .describe(\n \"The part's own PNG, the same size as the role layers (resolved against cwd), drawn alone and whole on a transparent ground.\",\n ),\n anchor: z\n .string()\n .describe(\"The role whose layer the part is fixed against.\"),\n tie: z\n .array(z.number())\n .length(2)\n .describe(\n \"[x, y] in canvas px where the part meets the anchor: inside both the part's alpha box and the anchor layer's.\",\n ),\n after: z\n .string()\n .describe(\n \"A role of the set: the part is drawn right after that role's last part.\",\n ),\n deformer: z\n .string()\n .optional()\n .describe(\n \"The matrix deformer it hangs on; only `headDeformer` (the default) is accepted.\",\n ),\n rigid: z\n .boolean()\n .optional()\n .describe(\n \"The art does not bend (a hairpin, a ribbon): a bake that bends it by more than 0.0025 face widths at a stop, from its best-fit rotation and translation, is refused as `INVALID: bakes…` with nothing written. Give a rigid part one displacement for every control point, or a rotation.\",\n ),\n occlusion: z\n .object({\n by: z\n .array(z.string())\n .describe(\n \"Roles of the set whose paint hides the part (an arm role is its three parts); a non-empty list with no role repeated, each a role of the set. A role with a clipped or meshless part (`iris_L`, `forearm_pose_L`) is refused.\",\n ),\n parameter: z\n .string()\n .describe(\n \"Any declared parameter but a physics output (a spring's or a chain segment's).\",\n ),\n stops: z\n .array(\n z\n .object({\n value: z.number(),\n amount: z\n .number()\n .describe(\n \"0 to 1: 1 hides the part wherever the roles' paint lies over it.\",\n ),\n })\n .passthrough(),\n )\n .describe(\n \"At least one, `value` strictly ascending and inside the parameter's range. The amount is linear between stops and held before the first and after the last.\",\n ),\n })\n .passthrough()\n .optional()\n .describe(\n \"Hide the part where the named roles' paint covers it, by an amount keyed on a parameter: `{ by, parameter, stops: [{ value, amount }] }`. Cover is where a role's drawn alpha at that pose is at least 0.5, a hard edge; a role that fades (`mouth_open`, a blush, a pose forearm) covers only while drawn at half strength or more. Use the stops as a short switch starting a degree or more off rest (so the rest pose never sits on it; the idle turns the head through the switch), the hiding's progress coming from the part's baked motion. Needs @ikijs/mcp 0.35.0; an older server refuses the key as an unknown key (`INVALID: customParts[i]…`). An unknown key, a bad stop or a part the key cannot be written for comes back as `INVALID: customParts[i].occlusion…` with nothing written.\",\n ),\n })\n .passthrough(),\n )\n .optional()\n .describe(\n \"Parts the auto-rigger has no role for, each `{ id, path, anchor, tie, after, deformer?, rigid?, occlusion? }`. A custom layer is read apart from `layers`: never role-parsed or measured, so its name is free and it does not widen the head the turn is fitted to; it counts toward the layer and pixel limits. All custom parts share one extra atlas page, the last, quantized on a palette of its own, so the other pages keep their bytes. An entry the rig refuses (an unknown key, a bad tie) comes back as `INVALID: customParts[i]…` with nothing written; a missing field or one of the wrong type (a `tie` that is not two numbers, say) is refused by the schema itself, as the SDK's input validation error. `[]` is the same rig as leaving the field out, plus an empty `customParts` in the result.\",\n ),\n bakes: z\n .object({\n targets: z.array(\n z\n .object({\n id: z.string().optional(),\n param: z.string(),\n parts: z.array(z.string()),\n box: z\n .object({\n x: z.number(),\n y: z.number(),\n w: z.number(),\n h: z.number(),\n })\n .passthrough()\n .optional(),\n grid: z\n .object({ cols: z.number(), rows: z.number() })\n .passthrough(),\n stops: z.record(\n z.string(),\n z.array(z.array(z.number()).length(2)),\n ),\n mirror: z.boolean().optional(),\n why: z.string().optional(),\n })\n .passthrough(),\n ),\n meshes: z\n .record(\n z.string(),\n z\n .object({\n rows: z.array(z.number()).optional(),\n cols: z.number().optional(),\n cellPx: z.number().optional(),\n })\n .passthrough(),\n )\n .optional(),\n })\n .passthrough()\n .optional()\n .describe(\n \"Lattices that move the CUSTOM parts when a parameter does, which an unrigged custom part otherwise does not: `{ targets, meshes? }`; it needs `customParts` and names no other part. A target `{ id?, param, parts, box?, grid: { cols, rows }, stops, mirror?, why? }` is `(cols + 1) x (rows + 1)` control points laid evenly over `box` (canvas px; absent, the union of the parts' rest boxes grown by 2 px), listed row-major from the top-left; `stops` is `{ \\\"<value>\\\": [[dx, dy], … one per control point] }`. FRAME: every position and displacement is in canvas px, origin top-left, x right, y DOWN, the frame of the layer PNGs and of `describe_iki`'s boxes and `probe_rig`. A STOP is the part's TOTAL landed displacement from rest when `param` alone is at that value and every other parameter is at its default: the head's own carry is inside it, so a neighbour's displacement as `probe_rig` measures it is written as it is. Stop keys are values of `param` inside its range, never its default (rest is implicit). The landing is exact at rest, at each stop and at one end key at the range end on a side whose outermost stop is inside the range (it holds that stop's displacement); a side with no stop is not moved by the target. Between keys the offsets blend linearly, so under the head's roll (ParamAngleZ) the path bows off the line, about 1 px midway over 15°: put a stop where the path matters. Each vertex takes the bilinear value of the lattice at its REST position, and a vertex outside `box` takes the nearest edge's value. `mirror: true` fills a missing stop from the one at the value mirrored about the rest value, when that value is inside the parameter's range: the lattice reflected about the box's vertical centre line, `dx` negated; a stop you wrote is never overwritten. Targets that name the same part and parameter SUM; a part in targets on two parameters gets one warp per parameter, and the two add in the head's frame, so under a roll a sway tilts with the head. `meshes` re-meshes a custom part before the bake, `{ <id>: { rows: [canvas-px y, …], cols } }` (the first row at the part's top and the last at its bottom, within 0.5 px) or `{ <id>: { cellPx } }`; the rest picture is unchanged. The written model is then landed through the engine at every stop and at the range end each side holds its outermost stop to, and refused when one is off by 0.1 px or more. An input the rig refuses comes back as `INVALID: bakes…` (`bakes.targets[2].stops[\\\"30\\\"][7]…`) and nothing is written; a field of the wrong type is refused by the schema itself, as the SDK's input validation error. A bake is measured on one rig: after a retune of the layout or `rigPlan`, a regenerated anchor, a changed custom layer or an accepted patch batch, measure the stops again.\",\n ),\n patches: z\n .array(\n z\n .object({\n target: z.string(),\n at: z.record(z.string(), z.number()),\n region: z\n .object({\n role: z.string(),\n // Not z.tuple: its JSON Schema is the array-form `items`\n // draft 2020-12 forbids. The rig checks the pair's order.\n x: z.array(z.number()).length(2),\n y: z.array(z.number()).length(2),\n })\n .passthrough(),\n by: z.object({ dx: z.number(), dy: z.number() }).passthrough(),\n falloff: z.number().optional(),\n why: z.string().optional(),\n })\n .passthrough(),\n )\n .optional()\n .describe(\n \"Displacements ADDED to EXISTING keyform stops of the freshly generated rig, each op `{ target, at, region, by, falloff?, why? }`. They are replayed on every rig of these inputs, over whatever the rig now bakes, so they hold through a layout or `rigPlan` retune; ops on one stop add up, whatever their order. `target` is a feature grid — `eyeWarp_L`, `eyeWarp_R`, `browWarp_L`, `browWarp_R`, `noseWarp`, `mouthWarp`, whose `at` names both `ParamAngleX` and `ParamAngleY`, each -30, 0 or 30, never both 0 — or a mesh part with warps (`face`, `hair_front`, …), whose `at` names exactly one parameter at one of that part's warp keyform values, never the parameter's default nor the stop where the rig shuts the part on purpose (`eye_*` and `lash_lower_*` at their `ParamEye*Open` 0, the lip set and its tongue and teeth at `ParamMouthOpenY` 0), which the fold check exempts, nor a `ParamAngleZ` or `ParamBodyAngleZ` stop (they roll the deformers the part hangs under, so a displacement there is turned off the screen axes). The rest pose is the drawn art and no patch changes it. `bodyWarp` and the matrix deformers are not targets, and a patch adds no stop and changes no parameter range. `region` `{ role, x: [from, to], y: [from, to] }` is a rectangle in fractions of the REST layer box (the opaque crop) of `role`, origin top-left, x right, y DOWN, and may reach past the box: the target's points whose REST position lies inside take the whole of `by`, those within `falloff` of it a smooth share, the rest nothing. `by` `{ dx, dy }` and `falloff` are in face widths (the `face` layer's crop width), on screen axes: +dx toward the viewer's right (a character's `_L` side), +dy DOWN. Between stops the engine blends linearly, so a fix at ParamAngleX -30 shows at half strength at -15 and none at rest. `why` is a note the rig ignores. An op this schema accepts but the rig refuses — an unknown key, target, role or stop, the rest stop or a shut stop, a region running backwards or catching none of the target's points — comes back as `INVALID: patches[i]…`, listing the keys, targets, stops or roles there are, or where the target's points lie in the role's box, and nothing is written; a missing field or one of the wrong type is refused by the schema itself, as the SDK's input validation error.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await autoRigFromLayers({\n ...args,\n // `.length(2)` makes each region span a pair, which its inferred\n // `number[]` cannot say.\n patches: args.patches as RigPatch[] | undefined,\n customParts: args.customParts as AutoRigCustomPartInput[] | undefined,\n // Each stop's `.length(2)` makes it a pair, which its inferred\n // `number[]` cannot say.\n bakes: args.bakes as RigBakes | undefined,\n });\n const text = r.ok\n ? [\n r.path,\n formatRigPlanReport(r.rigPlan),\n ...formatPatchReports(r.patches ?? []),\n ...formatFoldReport(r.folds, r.canvas),\n ...formatPhysicsReport(r.physics),\n ...formatHairSideReport(r.turn?.hairSide, r.canvas),\n ...formatCustomPartReports(r.customParts?.parts ?? []),\n ...formatBakeChecks(r.customParts?.bakes ?? []),\n ...(r.customParts ? formatCustomGate(r.customParts.gate) : []),\n ].join(\"\\n\")\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"compose_layers_from_parts\",\n {\n description:\n \"Composes AI-generated part PNGs into canvas-aligned, role-named PNG layers on disk, ready for auto_rig_from_layers (the eyewhite split, alpha-trim/white-key, and placement pipeline the character-generation skill needs), with the same geometry report measure_layers returns standalone included inline. face, eyewhite, iris, brow, hair_front are required, with mouth.png — or the lip set's mouth_keyed.png (the open mouth, its inside painted flat #00FF00) + mouth_interior.png (the cavity, teeth and tongue alone), which the composer keys and splits into mouth_inner / lip_lower / lip_upper on one frame so auto_rig_from_layers folds the mouth open like the eyelid, the interior's light paint (luma 100 and over) written as mouth_tongue and mouth_teeth on the same frame, riding the opening's bottom and the upper line and clipped to the cavity (listed in `skipped` when the interior has none); the two routes cannot be mixed, one keyed file without the other is refused, and a key that fails (no green, green outside the opening, an outline not closed round it, more than one opening, no skin under the opening, an interior that is only lips, or one drawn opaque on a non-white or noisy ground) is refused naming the regeneration; with the lip set neither mouth nor mouth_open is written and preview.png shows the mouth closed, as the rig draws the rest pose. hair_back, body, mouth_open (legacy route only), blush (one blush.png makes the blush_L/blush_R pair), hair_side (one hair_side.png makes the hair_side_L/hair_side_R pair) and nose are optional — without a nose layer the head still turns on the rig's default profile, but it has no nose to lead the turn, and `auto_rig_from_layers` fits no turn to the art (`turnTargets` is inert, no `turn` report). The hair_side.png is the front side lock on the screen LEFT, hanging beside the ear with its root at the image's top: hair_side_R is as drawn and hair_side_L mirrored, both drawn over the face, brows and lashes and under hair_front, and without the file both are listed in `skipped`. One arm.png — the arm on the screen LEFT, drawn hanging with its shoulder at the top — makes both arms of a full body: arm_R takes it as drawn and arm_L mirrored. The arms are opt-in: without arm.png the compose is a bust's and `skipped` never lists them. arm.png needs body.png, and each arm is hung on the body's shoulder by default (see `layout`). One forearm_pose.png — the arm's forearm raised, on the screen LEFT, standing up from its elbow with the hand at the top — makes both pose forearms (forearm_pose_R as drawn, forearm_pose_L mirrored): each is scaled so its elbow end is as wide as its arm's elbow run and pinned on that arm's elbow (see `layout`), and it needs arm.png. With one, preview-pose.png shows the switch at 1 as the rig draws it (the hanging forearms hidden below the elbow, the pose forearms over everything) while preview.png stays the rest pose; without one it is removed. The inline report carries the full-body checks too: a body whose feet a tall canvas's bottom cuts off, an arm without a body, an arm whose shoulder cap does not reach under the torso's edge, and a pose forearm without its arm or off its arm's elbow in pivot, width or length. A nose whose dense core is a speck — under a quarter of its trimmed part's width or height, such as a lone nostril mark or highlight — is sized and placed whole, and the inline report warns of it. A light mark drawn detached above the eye white, such as a double-eyelid crease, is dropped from the sclera (the iris's clip); dark strokes there stay lash ink. The eyewhite's dark lower lid — its line and lashes — becomes lash_lower_L/lash_lower_R, drawn over the iris; a white with none writes none and lists them in `skipped`.\",\n inputSchema: {\n partsDir: z\n .string()\n .describe(\n \"Directory of the source part PNGs (resolved against cwd).\",\n ),\n outDir: z\n .string()\n .describe(\n \"Existing directory to write the role layer PNGs + preview.png (and preview-pose.png when there is a forearm_pose.png) into (resolved against cwd; must already exist; confined to the working directory). Reused across runs: a role this run does not write — one it skips, or an arm or pose forearm once arm.png or forearm_pose.png is gone, preview-pose.png included — has its stale PNG from an earlier run deleted.\",\n ),\n layout: z\n .record(\n z.string(),\n z\n .object({\n cx: z.number(),\n cy: z.number(),\n w: z.number(),\n h: z.number(),\n })\n .partial(),\n )\n .optional()\n .describe(\n \"Per-role override merged over the built-in defaults, keyed by role — hair_back, body, arm_L, arm_R, face, blush_L, blush_R, nose, mouth, mouth_open, mouth_inner, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_side_L, hair_side_R, hair_front, forearm_pose_L, forearm_pose_R — e.g. `{ eye_L: { cx: 660 } }`. `w` is an integer in 1..1100 (the canvas width) and `h` in 1..canvasHeight; omit `h` to keep the part's own aspect, set it to stretch. The defaults of the face's features — blush, nose, mouth, mouth_open, mouth_inner, eyes, irises, lashes, brows, side locks — are proportions of the face: an override of face.cx, face.cy or face.w carries them with it (scaled by the width; face.h stretches the face alone), while a feature's own override names canvas px. The nose is sized and placed by its dense core (its pixels at alpha >= 128, the drawing inside a soft nose's feather), not its whole part: `w`/`h` size the core, `cx` centres it, and a set `cy` centres its rows. A nose whose core is a speck — under a quarter of the trimmed part's width or height, such as a lone nostril mark or highlight — is sized and placed whole instead, and the report warns of it. Its `cy` defaults to unset, which lands the core's bottom row (the tip) 0.66 of the way from the eye row down to the mouth's, so the nose follows a retuned eye or mouth row. eye_L/lash_L and eye_R/lash_R are cut from one eyewhite into one frame, so each pair must land on the same frame — a pair set to land apart is rejected. lash_lower_L/lash_lower_R are cut from it too and have no key: they land on their eye's frame. mouth_inner is the lip set's one frame (mouth_open's place by default; lip_lower, lip_upper, mouth_tongue and mouth_teeth have no key and land on it, so a retune moves them together), and with the lip set the nose's tip rule reads layout.mouth_inner.cy. arm_L/arm_R have no cx/cy/w defaults: an unset `w` is 0.4 of the placed body's width, and an unset `cx` or `cy` hangs the arm's shoulder pivot — the one auto_rig_from_layers turns it about — on the body box's shoulder corner on that axis: its left edge for arm_R, its right edge for arm_L, 0.12 of its height under its top. A set one centres the arm as for every other role. forearm_pose_L/forearm_pose_R have no cx/cy/w defaults either: an unset `w` scales the forearm so its elbow end (the shoulder rule run from its bottom) is as wide as the placed arm's elbow run, and an unset `cx` or `cy` pins that elbow end's pivot on the arm's elbow — the one auto_rig_from_layers hangs it from.\",\n ),\n mirrorParts: z\n .array(z.string())\n .optional()\n .describe(\n \"Part files to flip left-right as they are read, e.g. `[\\\"eyewhite.png\\\"]`. The composer reads eyewhite.png as the eye on the screen LEFT (lash wing at the image's left end, lash-free tear duct at its right), brow.png as the brow on the screen RIGHT (thick head at the image's left end, tail at its right), blush.png as the blush on the screen LEFT (outer end, toward the face's edge, at the image's left end, inner end at its right), hair_side.png as the front side lock on the screen LEFT (hanging, its root at the image's top), arm.png as the arm on the screen LEFT (the character's right, hanging, its shoulder at the image's top), and forearm_pose.png as the raised forearm on the screen LEFT (standing up from its elbow, the hand at the image's top, the thumb toward the body at the image's right); a part drawn the other way round is fixed here for free. It flips the source, so every role cut from it flips together and an eye's sclera and lash stay in one frame.\",\n ),\n canvasHeight: z\n .number()\n .optional()\n .describe(\n \"The canvas's height in px: an even integer in 1100..4096, default 1100 (a square bust canvas; at 1100 every output is byte-identical to leaving it out). The width stays 1100. The canvas grows downward: every default and every override keeps its canvas px from the top-left, so the head lands where it does on a bust and a full body gets room below. An odd height is refused — model space is centred on the canvas, so it would put the head on a half pixel — and it is checked before any part decodes.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await composeLayersFromParts(args);\n const text = r.ok\n ? [\n ...r.layers.map((l) => l.path),\n formatMeasureReport({ ...r.measure, layersDir: r.outDir }),\n ].join(\"\\n\")\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"measure_layers\",\n {\n description:\n \"Reports read-only geometry checks over an already-composed layers directory — the same checks compose_layers_from_parts returns inline (iris ratio/offset, eye aspect, cropped/cut edges, a nose whose dense core is a speck of its crop, missing optional roles, a body whose feet a tall canvas's bottom cuts off, an arm without a body, an arm whose shoulder cap does not reach under the torso's edge on its shoulder pivot's row, a pose forearm without its arm or whose elbow end is off its arm's elbow in pivot, width or length, a front side lock without hair_front, one whose top row shows past the bangs at rest, one covering the eye white's outer corner at rest, one whose lean on the turn away from it would bare columns neither hair_back nor the face paints, a hair_side.png drawing two locks, and the lip set: a partial one or one beside mouth/mouth_open, the fold's contract per column of the opening, an opening too narrow or short, a line too thin, green left, an interior with holes, and of mouth_tongue/mouth_teeth: one with no lip set, one on another canvas, one whose box leaves mouth_inner's — with the opening's size and the MouthOpen below which no slit shows). Every preview*.png is skipped. Use to re-check a layers dir without recomposing. Its nose check reads the composed file against its crop, which is what auto_rig_from_layers acts on. Compose's inline report does the same unless the composer found the source part's core a speck, which it reports instead — so a speck that resampling erased from the layer shows there and not here.\",\n inputSchema: {\n layersDir: z\n .string()\n .describe(\n \"Directory of role-named layer PNGs (resolved against cwd).\",\n ),\n },\n },\n async ({ layersDir }) => {\n try {\n const r = await measureLayers({ layersDir });\n const text = r.ok ? formatMeasureReport(r) : `INVALID: ${r.error}`;\n // Spread into a fresh object: MeasureResult's ok:true arm is an\n // intersection with the MeasureReport interface, which TS won't accept\n // directly against the SDK's `Record<string, unknown>` structuredContent\n // — spreading drops that nominal interface identity, same value.\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { ...r },\n };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"measure_turn_reference\",\n {\n description:\n \"Measures how far a head turns between two images of the same character — a front view and a turned one, at the SAME scale — as three ratios, so a rigged turn can be compared to a reference turn (or to an earlier rig) without registering the images: farEyeRatio (turned far/near iris width over the same ratio at rest), eyeShift (how far the eye pair slides across the head, in units of the FRONT head half-width; NEGATIVE = toward the image's left), silhouetteRatio (head half-width, turned over front). The ratios divide out crop and position, not scale, so the pair must already share framing and head size; since a yaw never changes iris height, a pair whose mean iris height differs by more than 10% is refused instead of measured as a turn. Reads engine renders (transparent backdrop) and opaque reference art alike. A pair that shows a custom part crossing the eye row reads a wider head than the rig fits to, so measure a pair drawn without the custom parts.\",\n inputSchema: {\n front: z\n .string()\n .describe(\"Front-facing PNG file path (resolved against cwd).\"),\n turned: z\n .string()\n .describe(\"The same character turned, as a PNG file path.\"),\n iris: z\n .object({\n hueMin: z.number().min(0).max(360),\n hueMax: z.number().min(0).max(360),\n satMin: z.number().min(0).max(1),\n })\n .partial()\n .optional()\n .describe(\n \"Iris colour window override merged over the violet default (hue 230..300, sat > 0.22) — set it for a character whose eyes are another colour.\",\n ),\n debugDir: z\n .string()\n .optional()\n .describe(\n \"Existing directory (resolved against cwd; confined to the working directory) to write `front-<name>.debug.png` / `turned-<name>.debug.png` overlays into, with the iris boxes and head edges drawn.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await measureTurnReference(args);\n const text = r.ok ? formatTurnReport(r) : `INVALID: ${r.error}`;\n // Spread into a fresh object: the ok:true arm is an intersection with\n // the TurnMeasurement interface, which TS won't accept directly against\n // the SDK's Record<string, unknown> structuredContent.\n return {\n content: [{ type: \"text\", text }],\n structuredContent: { ...r },\n };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"render_poses\",\n {\n description:\n \"Renders a rigged .iki into the character loop's pose PNGs with the real engine, through the installed Chrome, Edge or Chromium run headless (set CHROME_PATH to pick one). The model decides the set: a bust gets 560x560 shots (rest, turns, nod, blinks, gaze, combined — ParamAngleX/Y/Z all at 30 — and stress: ParamAngleX/Y/Z all at -30, ParamMouthOpenY 1, both eyes at 0.5, the brows at opposite extremes (ParamBrowLY -1, ParamBrowRY 1, ParamBrowLAngle 1, ParamBrowRAngle -1) and each body angle the model declares at -10); a mouth adds 720x480 mouth crops; a full body (taller than wide) adds the full-canvas body, arm and elbow poses on a 1400-wide canvas, and a model with a pose forearm adds the full-pose-* shots. Given `poses` (see its field), the standard set is not rendered: only those poses are, each crop clamped to the model's canvas. Writes <pose>.png files into outDir, overwriting same-named files in place; returns the written paths one per line, then the model's fold report (the result's `folds`), checked by the engine over its own pose set plus any `poses`, each of which a `FOLD` line names by its settings, not its PNG name: a `FOLD` line per warp deformer or mesh part that flips (ratio <= 0) or collapses (under 0.1) at some pose — its cell or triangle, the ratio of its area there to at rest, the pose as its parameter settings (`rest` for none) and where it rests, in model space and in model px from the top-left (the layer PNGs' own pixels, not a render's) — or `FOLDS: none over N poses`, then a `FOLDS expected:` line naming the closures the rig draws on purpose (an eye or the mouth shut), each by part id, ratio and the parameter that shuts it. Report-only: a fold never fails the render. The `PHYSICS` lines follow the fold report (the result's `physics`), one per physics rig output of the model's own rigs — `poses` do not enter it — reading ok, frozen or unstable with the step and idle amplitudes, or `PHYSICS: no rigs`; report-only too. Given `sweep`, also renders an eased turn of the head (see its field) and prints its paths and `SWEEP` lines (and, with `sweeps`, the turn-and-nod box). Fails with INVALID when no browser is found or an input is refused; a browser that cannot start is a tool error.\",\n inputSchema: {\n modelPath: z\n .string()\n .describe(\n \"Rigged .iki file path (resolved against cwd; must sit under the working directory).\",\n ),\n outDir: z\n .string()\n .describe(\n \"Existing directory to write the pose PNGs into (resolved against cwd; must already exist; confined to the working directory).\",\n ),\n poses: z\n .array(\n z.object({\n name: z.string(),\n values: z.record(z.string(), z.number()),\n crop: z\n .object({\n x: z.number(),\n y: z.number(),\n w: z.number(),\n h: z.number(),\n })\n .optional(),\n }),\n )\n .optional()\n .describe(\n \"Caller-named poses rendered INSTEAD of the standard set, each `{ name, values, crop? }`, in order. `name` becomes `<outDir>/<name>.png` and the result's pose name: letters, digits, `_`, `.` and `-` only, unique in the list ignoring case. `values` are parameter settings (every other parameter at its default; an id the model lacks is ignored). `crop` `{ x, y, w, h }` is a rectangle in model px from the top-left — the frame of describe_iki's boxes and of the `FOLD` lines — clamped to the model's canvas, then drawn 720 px wide at its own aspect; without one a pose is framed as the standard shots (560x560, the middle square on a full body). Each pose is also added to the fold sweep, after the engine's own poses. An empty list, a bad or repeated name, a non-finite value, or a crop that misses the canvas or would draw under 1 or over 8192 px tall comes back as `INVALID: poses…` and nothing is rendered.\",\n ),\n sweep: z\n .object({\n name: z.string(),\n preset: z.literal(\"turn\"),\n crop: z\n .object({\n x: z.number(),\n y: z.number(),\n w: z.number(),\n h: z.number(),\n })\n .optional(),\n })\n .optional()\n .describe(\n \"A turn sweep rendered IN ADDITION to the poses, `{ name, preset: \\\"turn\\\", crop? }`: an eased `ParamAngleX` turn (0 to -30 to +30 to 0 over 3 s, sinusoidal) at 30 fps on a 60 Hz physics clock, with the hair physics running and the idle off, every other parameter at its default. `crop` is a rectangle in model px as a pose's, fixed for every frame; without one the frames are framed as the standard shots. Written into `<outDir>/<name>/` (created; `name` starts with a letter or digit, then letters, digits, `_`, `.`, `-`): `fNNN.png` (90 frames), `manifest.json` (each frame's time, angle and effective values), `sheet.png` (nine frames of the -30 to +30 leg, labelled with angle and time, at most 2000 px a side), `kymograph.png` (the eye row of every frame stacked over time), `index.html` (a flipbook to open from disk; add `?b=<relative dir of another sweep>` for two side by side). The text then lists the paths and, after the `PHYSICS` lines, a `SWEEP turn` line per landmark (eyes, nose) from the engine's geometry: amplitude in face widths, the kink of x and of the eye width through angle 0, the lead over the local face plate at each end, and the pop — report-only, like `FOLD` and `PHYSICS`. `sweeps` renders more sweeps beside this one. The `SWEEP nod` and `SWEEP corner` lines follow the `SWEEP turn` ones.\",\n ),\n sweeps: z\n .array(\n z.object({\n name: z.string(),\n preset: z.enum(SWEEP_PRESETS),\n crop: z\n .object({\n x: z.number(),\n y: z.number(),\n w: z.number(),\n h: z.number(),\n })\n .optional(),\n }),\n )\n .optional()\n .describe(\n \"More sweeps rendered after `sweep`, each `{ name, preset, crop? }` into its own `<outDir>/<name>/` (files and `crop` as `sweep`'s). Names are distinct from `sweep`'s and from each other's ignoring case, and presets are distinct (at most one of each). `turn` is `sweep`'s. `roll` is the same eased curve on `ParamAngleZ` (0 to -30 to +30 to 0 over 3 s, 90 frames, physics running, idle off); its `sheet.png` is the nine frames nearest the turn sheet's angles on the -30 to +30 leg, labelled with the angle (Z) and time, and it has no kymograph (the eye row moves with the roll). `turn-nod` is the box (0,0) -> (0,-30) -> (-30,-30) -> (-30,+30) -> (+30,+30) -> (+30,-30) -> (0,-30) -> (0,0) of `ParamAngleX` x `ParamAngleY`, each leg eased, 6 s, 180 frames; its `sheet.png` is a 3 x 3 grid BY ANGLE (columns AngleX -30/0/+30, rows AngleY +30/0/-30, rest in the centre, cells labelled X, Y and t) and it has no kymograph. `manifest.json` is version 2 (`parameters`, and per frame `t` and `values`). A sweep dir's earlier frames, sheet, kymograph, manifest and flipbook are cleared first. An empty list, a repeated name or preset, or a bad crop comes back as `INVALID: sweeps...`. A server before 0.32.0 strips `sweeps` and renders the rest. The `SWEEP nod` lines (the eye-pair and iris-pair gap range and the mouth width range along the nod at each turn, in face widths) and `SWEEP corner` lines (the additivity residual per landmark at the four corners, the rest term included; 0 on an additive rig) print once per call whenever `sweep` or `sweeps` was asked for, report-only like `FOLD` and `PHYSICS`. A `roll` adds no `SWEEP` line of its own and changes none: they are read from the model. `roll` needs @ikijs/mcp 0.34.0; an older server refuses it as an input validation error.\",\n ),\n hideParts: z\n .array(z.string())\n .optional()\n .describe(\n \"Part ids left out of the drawn frames (poses and sweeps); the fold, physics and sweep reports still read the whole model. Use it to render a character without its custom parts, so `measure_turn_reference` reads the rig's own head (a custom part crossing the eye row widens the head it measures, as it does on a drawn reference). An id the model lacks, or one that is the clip mask of a part that stays, or one a part that stays names in its `occlusion.by` (hide that part too), comes back as `INVALID: hideParts[i] …` and nothing is rendered. Needs @ikijs/mcp 0.34.0; an older server drops the field and draws every part.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await renderPoses(args);\n const text = r.ok\n ? [\n ...r.poses.map((p) => p.path),\n ...[...(r.sweep ? [r.sweep] : []), ...(r.sweeps ?? [])].flatMap(\n (w) => [\n w.dir,\n w.sheet,\n ...(w.kymograph ? [w.kymograph] : []),\n w.flipbook,\n w.manifest,\n ],\n ),\n ...formatFoldReport(r.folds, r.modelCanvas),\n ...formatPhysicsReport(r.physics),\n ...((r.sweep ?? r.sweeps?.[0])\n ? [\n ...formatSweepReport((r.sweep ?? r.sweeps![0]).report),\n ...formatNodReport((r.sweep ?? r.sweeps![0]).nod),\n ]\n : []),\n ].join(\"\\n\")\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"probe_rig\",\n {\n description:\n \"Measures a rigged .iki without rendering it, through the engine's own landing. Each query is one of: `paint` (the opaque runs, alpha 128 and over, of a layer PNG, per canvas row, as `{ y0, rows }` with `[x0, x1)` runs; read from the PNG you give, not the atlas, so a quantized model reads the same, and the PNG must be the model's canvas size), `land` (where each canvas-px point of a part lands in a pose) or `displacement` (the landing minus the point). The frame is canvas px, origin top-left, x right, y down — the frame of the layer PNGs and describe_iki's boxes. A point is `[x, y]` and must lie on the part at rest, inside one of its mesh triangles (a part without a mesh, its unit quad); its landing is then found by barycentric interpolation inside that triangle. A point outside the part's mesh comes back as `null`, never an extrapolation. `pose` is parameter settings: every parameter it does not name is at its default, a value outside the parameter's range is clamped as the player does, and an id the model does not declare or a non-finite value is refused. The text is the results as JSON, one entry per query in order. With `outputPath` (a `.probe.json` under the working directory, its folder existing) the results are written there as the same JSON and the text is the path and one line per query, so a part's paint stays out of your context for a rigging program to read. A query's refusal comes back as `INVALID: queries[i].<field> …`, any refusal writes nothing.\",\n inputSchema: {\n modelPath: z\n .string()\n .describe(\n \"Rigged .iki file path (resolved against cwd; must sit under the working directory).\",\n ),\n queries: z\n .array(\n z.discriminatedUnion(\"op\", [\n z.object({\n op: z.literal(\"paint\"),\n path: z\n .string()\n .describe(\n \"Canvas-sized layer PNG (resolved against cwd), the drawing the part was built from.\",\n ),\n }),\n z.object({\n op: z.enum([\"land\", \"displacement\"]),\n part: z.string().describe(\"A part id of the model.\"),\n points: z\n .array(z.array(z.number()).length(2))\n .describe(\n \"Canvas-px points `[x, y]`, at most 5000, each on the part at rest.\",\n ),\n pose: z\n .record(z.string(), z.number())\n .optional()\n .describe(\n \"Parameter id to value; the others stay at their defaults.\",\n ),\n }),\n ]),\n )\n .describe(\"The queries, answered in order; at most 64 per call.\"),\n outputPath: z\n .string()\n .optional()\n .describe(\n \"A path ending in `.probe.json` (resolved against cwd, under it; its folder must exist) to write the results to.\",\n ),\n },\n },\n async (args) => {\n try {\n // `points` is a plain number array in the schema (no tuple, see the\n // patches'); probeRig checks each is a [x, y] pair.\n const r = await probeRig(args as ProbeInput);\n const text = !r.ok\n ? `INVALID: ${r.error}`\n : \"results\" in r\n ? JSON.stringify(r.results)\n : [r.outputPath, ...r.lines].join(\"\\n\");\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"view_illustration_grid\",\n {\n description:\n \"Writes a PNG of one finished character picture (PNG, JPEG or WebP) for reading coordinates off it: the picture scaled to the 1100 px wide layer canvas (height by its aspect, Lanczos), the same canvas the in-place cut works on, cropped, zoomed by an integer factor nearest-neighbour so the pixels stay readable, with a grid line every `step` canvas px labelled along the top and left edges. FRAME: canvas px, origin top-left, x right, y down; a line labelled v sits on the left (top) edge of canvas pixel v, and a landmark coordinate v names that pixel, drawn through its centre. A picture is turned upright by its EXIF orientation first. The picture is shown as given, its backdrop included; only real transparency shows the view's green. With `landmarks`, each shape in it is drawn over the picture, in its key's colour between a dark and a light stroke so it reads over any paint, and labelled with its key path (`eyes.L.iris`, `skinSeeds[2]`): a 4-number array is a box `[x0, y0, x1, y1]`, `{ cx, cy, rx, ry }` an ellipse, a list of `[x, y]` a polyline (closed under `frontHair`, `skull`, `polygon`, `bodyOnly` and `sideHair`), a lone `[x, y]` or a list under a key ending in `Seeds` or anywhere under `samples` point markers; anything else is walked into or skipped, never refused. Defaults: the whole canvas, zoom 1, step 50. Returns the written path, the crop used (whole pixels, clamped to the canvas), zoom, step and the canvas size. A zoom outside 1..8 or not an integer, a step under 5 or not an integer, a crop with no size or missing the canvas, a view over 16,777,216 px, an output path not ending in `.png` or outside the working directory (its folder must exist), a missing, unsupported or corrupt picture, or one over 16,777,216 px or whose canvas would be over 4096 px tall comes back as `INVALID: …` and nothing is written.\",\n inputSchema: {\n imagePath: z\n .string()\n .describe(\"The picture (PNG, JPEG or WebP; resolved against cwd).\"),\n outputPath: z\n .string()\n .describe(\n \"A `.png` path (resolved against cwd, under it; its folder must exist). Overwritten if present.\",\n ),\n crop: z\n .object({\n x: z.number(),\n y: z.number(),\n w: z.number(),\n h: z.number(),\n })\n .optional()\n .describe(\n \"The rectangle to show, in canvas px; clamped to the canvas. The whole canvas when omitted.\",\n ),\n zoom: z\n .number()\n .optional()\n .describe(\n \"Output px per canvas px, an integer 1..8; 1 when omitted.\",\n ),\n step: z\n .number()\n .optional()\n .describe(\n \"Grid spacing in canvas px, an integer of at least 5; 50 when omitted.\",\n ),\n landmarks: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n \"Shapes to draw over the picture, by shape (see the description); unknown shapes are skipped.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await viewIllustrationGrid(args);\n const text = r.ok\n ? `${r.path}\\ncrop ${r.crop.x},${r.crop.y} ${r.crop.w}x${r.crop.h} on the ${r.canvas.width}x${r.canvas.height} canvas, zoom ${r.zoom}, step ${r.step}`\n : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"cut_layers_from_illustration\",\n {\n description:\n \"Cuts ONE finished front-facing character picture (PNG, JPEG or WebP) into in-place role layers for auto_rig_from_layers, from landmarks you read off `view_illustration_grid` (no ML: every part is found from your landmarks and colour samples). The picture is scaled to the 1100 px wide layer canvas (height by its aspect), the canvas `view_illustration_grid` shows; a transparent picture is used as is, an opaque one has its flat backdrop keyed from the border's colour (a border that is not one flat colour is refused). FRAME: canvas px, origin top-left, x right, y down; a coordinate names a pixel; `L` is the character's left, the viewer's right (but `mouth.cornerL` is the viewer's left end). Writes into `outputDir`, every layer a canvas-sized PNG with the paint where the picture has it: hair_back, body, face, nose, mouth, eye_L/eye_R (the sclera), iris_L/iris_R, lash_lower_L/lash_lower_R, lash_L/lash_R, brow_L/brow_R, hair_side_L/hair_side_R (a side lock per `sideHair` polygon holding hair) and hair_front (a feature that is not found writes no layer), each custom part as `custom/<id>.png` (never a role layer: pass them as auto_rig_from_layers' `customParts`, tied at their `tie`), and preview-labels.png (the labels over the picture) and preview-landmarks.png (the landmarks over it), which measure_layers skips. What a layer hides when the rig moves it (the forehead under the bangs, the hair behind the face, the neck behind the chin, the skin under each feature, the cheek and the back hair under a side lock, a side lock's root under the bangs) is filled from the paint around it. A role this cut does not write is removed from `outputDir` if an earlier run left it. With `mouthKeyed` + `mouthInterior` (the composer's lip-set inputs) the lip set is written instead of `mouth`: mouth_inner, lip_lower, lip_upper, and mouth_teeth / mouth_tongue when the interior has light paint, scaled uniformly so the set's own corners (its line's ends) are as far apart as `mouth.cornerL` and `mouth.cornerR` and centred on their midpoint, not turned; the drawn mouth still leaves the face. Text result: the written files one per line, then one line per check, `CHECK <id>: pass|WARN|FAIL <value> (limit <limit>) <hint>` (WARN a warn-level check that did not pass, FAIL a fail-level one; `none` for no value or no limit; the hint names the landmark to move), then measure_layers' checks on the written directory that a cut can act on, as `MEASURE:` lines: what auto_rig_from_layers refuses (a lip set partial, mixed with `mouth` or on another canvas, the lip layers' opening unreadable, a lash whose top row is off its sclera's), a missing optional role (body, hair_back, nose), the side locks' checks naming the landmark to move (a lock without hair_front, a root showing past the bangs, the strip its lean on the turn bares with nothing painted behind), and with a lip set its opening's facts (`lips: opening …`); the checks whose only remedy is re-laying-out or regenerating a generated part (art edges and straight cuts, eye aspect, iris size and place, an eyewhite to mirror, a speck nose, the lip set's own art, a hair_side.png drawing two locks, and a side lock over its eye's corner, which the cut checks against the declared eye box) are left out, the parts being as drawn; and last `CUT pass` or `CUT FAIL: <failed check ids>`. The checks: `stack` (fail): the layers stacked in role order against the picture, the share of canvas pixels off by more than 24 levels outside the mouth's box, limit 0.003, the box's own share counted apart since the mouth is replaced; `seeds` (fail): seeds and samples on the backdrop or on the wrong class, limit 0; `opening.L|R` (fail when the eye box clips the drawn eye, saying how far to grow it to leave 2 to 4 px to spare; warn when the paint the box cuts runs on past it as a stroke it cannot tell from a lash wing, saying what it sees, or when the eye covers under 0.2 of a loose box; a stroke crossing into the box apart from the eye is left out of the eye); `iris.L|R` (warn): the iris ellipse against the coloured disc found by the iris's own colour, their overlap (intersection over union) with limit 0.7 and their centres' offset; `eye.L|R` (warn): the eye's share of white, limit 0.06, under which it is cut as drawn closed (lash over the sclera, no iris); `brow.L|R` (warn): a brow band that holds no brow; `browBand.L|R` (warn): the share of the brow's ink left on the face past its band, limit 0.05, saying which way to move the line and by how much or how far to widen the band; `mouth` (fail): nothing drawn in `mouth.box` and no lip set; `fills.<region>` (warn): per fill, the share made up over 40 px from any paint it is filled from, limit 0.25, or no limit for the fills made up by construction; `frontHairWidth` (warn): hair_front's width over the face's on the eye row, limit 1 (wider clamps the turn; the side locks are not counted); `sideHair.L|R` (warn, per polygon given): its value the number of problems, limit 0: a polygon that holds no hair, a lock whose top row has no hair_front right above it (its root shows at rest and is not carried under the bangs; it names the columns and how far up the front hair ends), or a lock whose paint on the eye's rows reaches into `eyes.<side>.box` past its 4 px of spare and the lock's 4 px outline (the rig slides the eye's corner under the lock on the turn; hair really drawn over the eye cannot be split from it), and a polygon whose hair the front hair or the other side's polygon took, each saying which way to move the polygon; `pockets` (warn): the gaps between strands keyed as backdrop on their own and the backdrop-coloured regions the border's flood cannot reach, each named at a point backgroundSeeds accepts, its value how many of both; a region near the backdrop's colour where backgroundSeeds would accept no point is said to be pale paint that needs nothing, and not counted. Limits: a picture over 16,777,216 px or whose canvas would be over 4096 px tall, a landmark list over 2000 points, over 32 samples per class, over 16 custom parts or 16 bodyOnly polygons. A refusal writes nothing and comes back as `INVALID: …`: bad landmarks as `INVALID: landmarks.<path> …`, an output dir that is missing or outside the working directory, a missing or corrupt picture or lip-set file, one of `mouthKeyed` / `mouthInterior` without the other, a lip set whose key fails (named as the composer names it), corners too close for the lip set's outline to close (naming the least distance that cuts), or a lip set placed past the canvas's edge. A write that fails once writing has begun comes back as `INVALID: write: … the cut stopped part-way …`: the files written before it replace an earlier cut's of the same name, and the rest of the earlier cut's files are still there (a role this cut does not write is removed only after every file is written), so `outputDir` is a mix of the two until the cut is run again.\",\n inputSchema: {\n imagePath: z\n .string()\n .describe(\n \"The finished picture (PNG, JPEG or WebP; resolved against cwd).\",\n ),\n outputDir: z\n .string()\n .describe(\n \"Existing directory to write the layers into (resolved against cwd; confined to the working directory). Reused across rounds: same-named files are overwritten.\",\n ),\n landmarks: z\n .object({\n samples: z\n .unknown()\n .optional()\n .describe(\n \"Required. `{ hair: { base, shadow?, highlight? }, skin: { base, shadow? } }`, each a list of PTS (base 1 or more): points on flat patches of each tone. A pixel is hair or skin by which set it is nearer in colour; a sample on a line or on the other class's paint moves that paint across the whole picture. At most 32 points per class.\",\n ),\n eyes: z\n .unknown()\n .optional()\n .describe(\n \"Required. `{ L, R }`, each `{ box: [x0, y0, x1, y1], iris: { cx, cy, rx, ry } }`: `box` the whole drawn eye, lashes included (inclusive corners; one that clips the eye fails `opening`), `iris` the drawn disc as an ellipse, its centre inside the box (one wider than the disc pulls white or lash into the iris). L is the character's left eye, on the viewer's right.\",\n ),\n brows: z\n .unknown()\n .optional()\n .describe(\n \"Optional, each side optional: `{ L?, R? }`, each `{ line, halfWidth?, tailHalfWidth? }`: `line` the brow's centreline as PTS, tail first, 2 or more; `halfWidth` the band's half-width (8 when omitted), `tailHalfWidth` at the tail (5). A brow left out stays painted on the face; a brow drawn through the bangs passes under the strand.\",\n ),\n nose: z\n .unknown()\n .optional()\n .describe(\n \"Optional: `{ box: [x0, y0, x1, y1] }` around the drawn nose; left out, the nose stays on the face.\",\n ),\n mouth: z\n .unknown()\n .optional()\n .describe(\n \"Required: `{ box: [x0, y0, x1, y1], cornerL: [x, y], cornerR: [x, y] }`: `box` the whole drawn mouth, `cornerL` the VIEWER's left end of the mouth line and `cornerR` its right end (cornerL's x the smaller), both inside the box. A lip set's corners land on them.\",\n ),\n frontHair: z\n .unknown()\n .optional()\n .describe(\n \"Required: polygon PTS, 3 or more, round the bangs and the strands beside the face: its hair is hair_front. Keep it to the face's width (wider warns `frontHairWidth`); the hair outside it is hair_back, or a side lock's inside `sideHair`.\",\n ),\n sideHair: z\n .unknown()\n .optional()\n .describe(\n \"Optional, each side optional: `{ L?, R? }`, each a polygon PTS, 3 or more, round a lock that hangs from under the bangs in front of the ear and the cheek's edge (L the character's left, on the viewer's right): its hair is hair_side_<side>, drawn over the face and under hair_front, riding the face on the turn instead of staying behind it. Trace the lock's outline from up inside `frontHair` (they may overlap; the front hair keeps the paint both take) down round its tip, close to the lock: a polygon wider than it takes the back hair beside it. The lock's root is carried up to 12 px under the bangs from its top edge, wherever hair_front is opaque above it; skin is filled under the lock only where it crosses the face's own paint (the ear on one side and the cheek on the other: the ear then joins the face) and inside `skull`, which is the head's skin, not the ears; the back hair is filled under it down to `shellLower`, so lower `shellLower` at that side to where the hair behind the lock ends. Checked by `sideHair.L|R`.\",\n ),\n skull: z\n .unknown()\n .optional()\n .describe(\n \"Required: polygon PTS, 3 or more, round the head's skin, the part under the hair included, the ears not: skin is filled under the bangs and the side locks inside it.\",\n ),\n shellLower: z\n .unknown()\n .optional()\n .describe(\n \"Required: PTS, 2 or more, x strictly ascending: the back hair's lower edge behind the face; hair is filled behind the face and the bangs down to it.\",\n ),\n skinSeeds: z\n .unknown()\n .optional()\n .describe(\n \"Required: PTS, 1 or more, on the face's skin (cheeks, forehead, one on each ear): the face is flooded from them over skin, stopped by lines.\",\n ),\n bodySeeds: z\n .unknown()\n .optional()\n .describe(\n \"Required: PTS, 1 or more, on the neck and the clothes: the body is flooded from them.\",\n ),\n backgroundSeeds: z\n .unknown()\n .optional()\n .describe(\n \"Optional PTS: backdrop the figure encloses (a gap between the neck and a tail), which the border's flood cannot reach; the `pockets` check names them.\",\n ),\n paintSeeds: z\n .unknown()\n .optional()\n .describe(\n \"Optional PTS: backdrop-coloured paint the hair rings that is paint (a pale clip between two locks), never keyed as a gap.\",\n ),\n neckTopY: z\n .unknown()\n .optional()\n .describe(\n \"Required: the canvas row the neck is carried up to behind the chin (a little above the jaw's lowest row).\",\n ),\n bodyOnly: z\n .unknown()\n .optional()\n .describe(\n \"Optional: polygons (PTS, 3 or more each, at most 16) where paint the samples call hair belongs to the body: a dark jacket under near-black hair.\",\n ),\n customParts: z\n .unknown()\n .optional()\n .describe(\n \"Optional, at most 16: parts cut out of the back hair as `custom/<id>.png` (twin tails, a ponytail). Each `{ id, tie, polygon }` (the back hair inside the polygon) or `{ id, tie, side, line, below, ribbonBox? }` (the back hair on `side` (`left` or `right`, as the viewer sees it) of `line`, PTS top to bottom with y strictly ascending, where the part leaves the head's hair; under the line's last point, everything on that side of the column x = `below`; `ribbonBox` [x0, y0, x1, y1] around a ribbon or tie goes with the part). `id` a plain identifier no role takes, nor a part id a role yields (`elbow_L`, `forearm_R`); `tie` [x, y] where the part hangs from the head. A part left in the back hair widens the head the turn is fitted to.\",\n ),\n })\n .passthrough()\n .describe(\n \"Where the picture's parts are, in canvas px read off `view_illustration_grid` (PTS: a list of [x, y] points, each a pixel on the canvas, at most 2000 per list). Required keys: samples, eyes, mouth, frontHair, skull, shellLower, skinSeeds, bodySeeds, neckTopY; optional: brows, nose, sideHair, backgroundSeeds, paintSeeds, bodyOnly, customParts. Checked as a whole by the tool, which refuses the first fault as `INVALID: landmarks.<path> …`, the path to the field (an unknown key included).\",\n ),\n mouthKeyed: z\n .string()\n .optional()\n .describe(\n \"The lip set's open mouth, its inside painted flat #00FF00 (the composer's mouth_keyed.png; resolved against cwd). Needs `mouthInterior`.\",\n ),\n mouthInterior: z\n .string()\n .optional()\n .describe(\n \"The lip set's cavity, teeth and tongue alone (the composer's mouth_interior.png; resolved against cwd). Needs `mouthKeyed`.\",\n ),\n },\n },\n async (args) => {\n try {\n const r = await cutLayersFromIllustration(args);\n const text = r.ok ? formatCutReport(r) : `INVALID: ${r.error}`;\n return { content: [{ type: \"text\", text }], structuredContent: r };\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n return {\n content: [{ type: \"text\", text: `Unexpected error: ${error}` }],\n structuredContent: { ok: false, error },\n isError: true,\n };\n }\n },\n );\n\n return server;\n}\n"],"mappings":";AAMA,SAAS,eAAe;;;ACEjB,SAAS,MAAM,OAAe,KAAa,KAAqB;AACrE,SAAO,KAAK,IAAI,KAAK,KAAK,IAAI,KAAK,KAAK,CAAC;AAC3C;AAMO,SAAS,KAAK,GAAW,GAAW,GAAmB;AAC5D,SAAO,KAAK,IAAI,KAAK;AACvB;AAOO,SAAS,WAAW,GAAmB;AAC5C,QAAM,IAAI,MAAM,GAAG,GAAG,CAAC;AACvB,SAAO,IAAI,KAAK,IAAI,IAAI;AAC1B;;;ACpBO,IAAM,iBAAN,MAAqB;AAAA,EACT,SAAS,oBAAI,IAA0B;AAAA,EACvC,SAAS,oBAAI,IAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMjC,WAAW,oBAAI,IAAoB;AAAA,EAEpD,YAAY,YAA4B;AACtC,eAAW,SAAS,YAAY;AAC9B,WAAK,OAAO,IAAI,MAAM,IAAI,KAAK;AAK/B,UAAI,CAAC,OAAO,SAAS,MAAM,OAAO,GAAG;AACnC,gBAAQ;AAAA,UACN,mBAAmB,MAAM,EAAE;AAAA,QAC7B;AAAA,MACF;AACA,YAAM,OAAO,OAAO,SAAS,MAAM,OAAO,IAAI,MAAM,UAAU;AAC9D,WAAK,SAAS,IAAI,MAAM,IAAI,MAAM,MAAM,MAAM,KAAK,MAAM,GAAG,CAAC;AAAA,IAC/D;AACA,eAAW,CAAC,IAAI,KAAK,KAAK,KAAK,SAAU,MAAK,OAAO,IAAI,IAAI,KAAK;AAAA,EACpE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,IAAI,IAAY,OAAqB;AACnC,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,eAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,KAAK,CAAC,GAAG,mBAAmB,EAAE;AAAA,MACnE,SAAS,KAAK;AACZ,cAAM,QAAQ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC7D,eAAO;AAAA,UACL,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,qBAAqB,KAAK,GAAG,CAAC;AAAA,UAC9D,mBAAmB,EAAE,IAAI,OAAO,MAAM;AAAA,UACtC,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["points","xRight","yBottom","px","target","target","finite","flat","finite","StandardParameter","DEFAULT_FADE_SECONDS","StandardParameter","points","target","physicsInputs","physicsInputs","px","target","placement","points","px","StandardParameter","px","bounds","points","run","scale","StandardParameter","px2","s","_","plateIndex","fs","path","readFileSync","path","IkiFormatError","StandardParameter","loadIkiModel","fs","path","fs","path","poses","StandardParameter","readFileSync","path","loadIkiModel","sweep","sweeps","IkiFormatError","target","scale","path","fs","readFileSync","path","loadIkiModel","IkiFormatError","StandardParameter","detectAlphaBbox","partIdsOfRole","loadIkiModel","IkiFormatError","box","readFileSync","StandardParameter","clamp","path","detectAlphaBbox","strandEdges","placement","partIdsOfRole","path","headHalfOf","count","box","path","fs","path","path","LayerGeometryError","createLayerSetMeasurer","path","createLayerSetMeasurer","LayerGeometryError","createLayerSetMeasurer","runsAt","createLayerSetMeasurer","eye","LayerGeometryError","armGeometry","createLayerSetMeasurer","k","createLayerSetMeasurer","armGeometry","LayerGeometryError","path","ALPHA_OPAQUE","LayerGeometryError","columnRuns","createLayerSetMeasurer","mouthOpening","sharp","ALPHA_OPAQUE","createLayerSetMeasurer","ALPHA_OPAQUE","px","components","box","px","dilate","ALPHA_OPAQUE","median","from","count","sharp","createLayerSetMeasurer","z","box","createLayerSetMeasurer","path","ALPHA_OPAQUE","mouthOpening","LayerGeometryError","columnRuns","run","eye","fs","path","fs","path","sharp","ALPHA_OPAQUE","isLipInsideRole","scanAlphaBbox","sharp","LayerGeometryError","armGeometry","createLayerSetMeasurer","forearmPoseGeometry","sharp","createLayerSetMeasurer","armGeometry","LayerGeometryError","forearmPoseGeometry","scale","sharp","scanAlphaBbox","bounds","path","fs","box","placement","ALPHA_OPAQUE","px","cfg","part","split","left","top","isLipInsideRole","eye","input","px","px","sharp","sharp","sharp","toCanvas","dist","toCanvas","px","shareOf","dilate","points","run","erode","path","px","columns","sharp","fs","path","sharp","point","path","px","classify","erode","PAINT_ALPHA","brow","dilate","box","px","erode","face","NOISE_SCALE","pct","box","isSkin","px","dilate","eye","r","y","run","erode","sclera","covers","brow","key","g","point","partIdsOfRole","path","box","partIdsOfRole","list","fmt","pct","dilate","erode","sharp","w","part","show","path","box","eye","px","pic","classifier","reads","PAINT_ALPHA","labels","fs"]}