@ikijs/mcp 0.33.1 → 0.35.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.
@@ -413,6 +413,22 @@ function resolveDeformers(deformers, params) {
413
413
  return { worlds, grids };
414
414
  }
415
415
 
416
+ // ../engine/src/occlusion.ts
417
+ function occlusionAmount(occlusion, value) {
418
+ const { stops } = occlusion;
419
+ const first = stops[0];
420
+ if (value <= first.value) return first.amount;
421
+ for (let i = 1; i < stops.length; i++) {
422
+ const hi = stops[i];
423
+ if (value <= hi.value) {
424
+ const lo = stops[i - 1];
425
+ const t = (value - lo.value) / (hi.value - lo.value);
426
+ return lo.amount * (1 - t) + hi.amount * t;
427
+ }
428
+ }
429
+ return stops[stops.length - 1].amount;
430
+ }
431
+
416
432
  // ../engine/src/idle-motion.ts
417
433
  import { StandardParameter } from "@ikijs/format";
418
434
 
@@ -1728,223 +1744,9 @@ function ratioText(ratio) {
1728
1744
  return Math.abs(ratio) < 0.01 ? ratio.toExponential(1) : ratio.toFixed(2);
1729
1745
  }
1730
1746
 
1731
- // src/sweep-report.ts
1732
- var LADDER_MIN = -30;
1733
- var LADDER_MAX = 30;
1734
- var ZERO = -LADDER_MIN;
1735
- var FLAT_SLOPE = 1e-4;
1736
- var PARTS = ["face", "eye_L", "eye_R", "nose"];
1737
- function box(pts, fw) {
1738
- let x0 = Infinity;
1739
- let x1 = -Infinity;
1740
- let y0 = Infinity;
1741
- let y1 = -Infinity;
1742
- for (let i = 0; i < pts.length; i += 2) {
1743
- x0 = Math.min(x0, pts[i]);
1744
- x1 = Math.max(x1, pts[i]);
1745
- y0 = Math.min(y0, pts[i + 1]);
1746
- y1 = Math.max(y1, pts[i + 1]);
1747
- }
1748
- return {
1749
- x: (x0 + x1) / 2 / fw,
1750
- width: (x1 - x0) / fw,
1751
- y: (y0 + y1) / 2 / fw
1752
- };
1753
- }
1754
- function nearestVertex(face, fw, x, y) {
1755
- let best = 0;
1756
- let bestD = Infinity;
1757
- for (let i = 0; i < face.length; i += 2) {
1758
- const d = (face[i] / fw - x) ** 2 + (face[i + 1] / fw - y) ** 2;
1759
- if (d < bestD) {
1760
- bestD = d;
1761
- best = i / 2;
1762
- }
1763
- }
1764
- return best;
1765
- }
1766
- function kink(v) {
1767
- const sMinus = (v[ZERO] - v[ZERO - 5]) / 5;
1768
- const sPlus = (v[ZERO + 5] - v[ZERO]) / 5;
1769
- const big = Math.max(Math.abs(sMinus), Math.abs(sPlus));
1770
- if (big < FLAT_SLOPE) return null;
1771
- return Math.abs(sPlus - sMinus) / big;
1772
- }
1773
- function pop(v) {
1774
- let steps = 0;
1775
- for (let i = 0; i + 1 < v.length; i++) steps += Math.abs(v[i + 1] - v[i]);
1776
- const mean = steps / (v.length - 1);
1777
- if (mean < 1e-9) return null;
1778
- let most = 0;
1779
- for (let i = 1; i + 1 < v.length; i++) {
1780
- if (Math.abs(i - ZERO) <= 1) continue;
1781
- most = Math.max(most, Math.abs(v[i + 1] - 2 * v[i] + v[i - 1]));
1782
- }
1783
- return most / mean;
1784
- }
1785
- var NOD_TURNS = [-30, 0, 30];
1786
- var NOD_PARTS = [
1787
- "face",
1788
- "eye_L",
1789
- "eye_R",
1790
- "iris_L",
1791
- "iris_R",
1792
- "nose",
1793
- "lip_upper",
1794
- "mouth"
1795
- ];
1796
- var NOD_ENDS = [0, -LADDER_MIN, LADDER_MAX - LADDER_MIN];
1797
- function checkNod(model) {
1798
- const face = model.parts.find((p) => p.id === "face");
1799
- if (!face) return { unavailable: "no face part" };
1800
- const hasEyes = ["eye_L", "eye_R"].every(
1801
- (id) => model.parts.some((p) => p.id === id)
1802
- );
1803
- if (!hasEyes) return { unavailable: "no eye_L and eye_R parts" };
1804
- const fw = face.width;
1805
- const ladders = NOD_TURNS.map(
1806
- (x) => Array.from(
1807
- { length: LADDER_MAX - LADDER_MIN + 1 },
1808
- (_, i) => landParts(
1809
- model,
1810
- { ParamAngleX: x, ParamAngleY: LADDER_MIN + i },
1811
- NOD_PARTS
1812
- )
1813
- )
1814
- );
1815
- const has = (id) => ladders[0][0].has(id);
1816
- const boxes = (id) => ladders.map((ladder) => ladder.map((l) => box(l.get(id), fw)));
1817
- const spread = (v) => Math.max(...v) - Math.min(...v);
1818
- const ranges = (values) => {
1819
- const [m30, zero, p30] = NOD_TURNS.map(
1820
- (_, b) => spread(
1821
- Array.from(
1822
- { length: LADDER_MAX - LADDER_MIN + 1 },
1823
- (_2, i) => values(b, i)
1824
- )
1825
- )
1826
- );
1827
- return { m30, zero, p30 };
1828
- };
1829
- const gap = (l, r) => {
1830
- const bl = boxes(l);
1831
- const br = boxes(r);
1832
- return ranges((b, i) => br[b][i].x - bl[b][i].x);
1833
- };
1834
- const nod = [{ id: "eyes", range: gap("eye_L", "eye_R") }];
1835
- if (has("iris_L") && has("iris_R")) {
1836
- nod.push({ id: "irises", range: gap("iris_L", "iris_R") });
1837
- }
1838
- const mouthId = has("lip_upper") ? "lip_upper" : has("mouth") ? "mouth" : null;
1839
- if (mouthId) {
1840
- const bm = boxes(mouthId);
1841
- nod.push({ id: "mouth", range: ranges((b, i) => bm[b][i].width) });
1842
- }
1843
- const corner = ["eye_L", "eye_R", "nose"].filter(has).map((id) => {
1844
- const b = boxes(id);
1845
- const at = (t, j) => b[t][NOD_ENDS[j]];
1846
- const residual = (t, j) => {
1847
- const r = (axis) => at(t, j)[axis] - at(t, 1)[axis] - at(1, j)[axis] + at(1, 1)[axis];
1848
- return Math.max(Math.abs(r("x")), Math.abs(r("y")));
1849
- };
1850
- return {
1851
- id,
1852
- residual: {
1853
- mm: residual(0, 0),
1854
- mp: residual(0, 2),
1855
- pm: residual(2, 0),
1856
- pp: residual(2, 2)
1857
- }
1858
- };
1859
- });
1860
- return { unit: "fw", faceWidth: fw, nod, corner };
1861
- }
1862
- function checkSweep(model) {
1863
- const face = model.parts.find((p) => p.id === "face");
1864
- if (!face) return { preset: "turn", unavailable: "no face part" };
1865
- const hasEyes = ["eye_L", "eye_R"].every(
1866
- (id) => model.parts.some((p) => p.id === id)
1867
- );
1868
- if (!hasEyes) {
1869
- return { preset: "turn", unavailable: "no eye_L and eye_R parts" };
1870
- }
1871
- const fw = face.width;
1872
- const ladder = Array.from(
1873
- { length: LADDER_MAX - LADDER_MIN + 1 },
1874
- (_, i) => landParts(model, { ParamAngleX: LADDER_MIN + i }, PARTS)
1875
- );
1876
- const at = (id, i) => ladder[i].get(id);
1877
- const ids = ["eye_L", "eye_R", ...ladder[0].has("nose") ? ["nose"] : []];
1878
- const landmarks = ids.map((id) => {
1879
- const boxes = ladder.map((_, i) => box(at(id, i), fw));
1880
- const xs = boxes.map((b) => b.x);
1881
- const plateIndex2 = nearestVertex(
1882
- at("face", ZERO),
1883
- fw,
1884
- boxes[ZERO].x,
1885
- boxes[ZERO].y
1886
- );
1887
- const plate = ladder.map((_, i) => at("face", i)[plateIndex2 * 2] / fw);
1888
- const lead = (i) => xs[i] - plate[i] - (xs[ZERO] - plate[ZERO]);
1889
- return {
1890
- id,
1891
- amplitude: xs[xs.length - 1] - xs[0],
1892
- xKink: kink(xs),
1893
- widthKink: id === "nose" ? null : kink(boxes.map((b) => b.width)),
1894
- lead: { m30: lead(0), p30: lead(xs.length - 1) },
1895
- pop: pop(xs)
1896
- };
1897
- });
1898
- const eyes = ["eye_L", "eye_R"].map((id) => box(at(id, ZERO), fw));
1899
- const plateIndex = nearestVertex(
1900
- at("face", ZERO),
1901
- fw,
1902
- (eyes[0].x + eyes[1].x) / 2,
1903
- (eyes[0].y + eyes[1].y) / 2
1904
- );
1905
- const plateX = (i) => at("face", i)[plateIndex * 2] / fw;
1906
- return {
1907
- preset: "turn",
1908
- unit: "fw",
1909
- faceWidth: fw,
1910
- plateAmplitude: plateX(ladder.length - 1) - plateX(0),
1911
- landmarks
1912
- };
1913
- }
1914
- var fw3 = (v) => {
1915
- const s = v.toFixed(3);
1916
- return s === "-0.000" ? "0.000" : s;
1917
- };
1918
- var signed = (v) => fw3(v).startsWith("-") ? fw3(v) : `+${fw3(v)}`;
1919
- var two = (v) => v === null ? "n/a" : v.toFixed(2);
1920
- function formatSweepReport(report) {
1921
- if ("unavailable" in report) {
1922
- return [`SWEEP: unavailable \u2014 ${report.unavailable}`];
1923
- }
1924
- return [
1925
- ...report.landmarks.map(
1926
- (l) => `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)}`
1927
- ),
1928
- `SWEEP turn plate: amplitude ${fw3(report.plateAmplitude)} fw`
1929
- ];
1930
- }
1931
- function formatNodReport(report) {
1932
- if ("unavailable" in report) {
1933
- return [`SWEEP nod: unavailable \u2014 ${report.unavailable}`];
1934
- }
1935
- return [
1936
- ...report.nod.map(
1937
- ({ id, range: r }) => `SWEEP nod ${id}: ${id === "mouth" ? "width" : "gap"} range X -30 ${fw3(r.m30)} / 0 ${fw3(r.zero)} / +30 ${fw3(r.p30)} fw`
1938
- ),
1939
- ...report.corner.map(
1940
- ({ id, residual: r }) => `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`
1941
- )
1942
- ];
1943
- }
1944
-
1945
- // src/sweep.ts
1946
- import fs3 from "fs";
1947
- import path4 from "path";
1747
+ // src/probe.ts
1748
+ import { readFileSync } from "fs";
1749
+ import { IkiFormatError, loadIkiModel } from "@ikijs/format";
1948
1750
 
1949
1751
  // src/limits.ts
1950
1752
  import fs from "fs";
@@ -1956,6 +1758,8 @@ var MAX_ATLAS_SIDE = 4096;
1956
1758
  var MAX_INPUT_PIXELS = 4096 * 4096;
1957
1759
  var MAX_TOTAL_PIXELS = 128 * 1024 * 1024;
1958
1760
  var MAX_OUTPUT_BYTES = 12 * 1024 * 1024;
1761
+ var MAX_PROBE_QUERIES = 64;
1762
+ var MAX_PROBE_POINTS = 5e3;
1959
1763
  var AutoRigInputError = class extends Error {
1960
1764
  constructor(message) {
1961
1765
  super(message);
@@ -2012,12 +1816,14 @@ function confineToWorkingDirectory(root, dir, label, original) {
2012
1816
  }
2013
1817
  return realDir;
2014
1818
  }
2015
- function resolveOutputPath(outputPath) {
1819
+ function resolveOutputPath(outputPath, extension = ".iki") {
2016
1820
  if (typeof outputPath !== "string" || outputPath.trim() === "") {
2017
1821
  throw new AutoRigInputError("output path is empty");
2018
1822
  }
2019
- if (!outputPath.toLowerCase().endsWith(".iki")) {
2020
- throw new AutoRigInputError(`output path must end in .iki: ${outputPath}`);
1823
+ if (!outputPath.toLowerCase().endsWith(extension)) {
1824
+ throw new AutoRigInputError(
1825
+ `output path must end in ${extension}: ${outputPath}`
1826
+ );
2021
1827
  }
2022
1828
  const root = process.cwd();
2023
1829
  const resolved = path.resolve(root, outputPath);
@@ -2039,50 +1845,1235 @@ function resolveOutputPath(outputPath) {
2039
1845
  );
2040
1846
  return path.join(realDir, path.basename(resolved));
2041
1847
  }
2042
- function resolveOutputDir(dirPath) {
2043
- if (typeof dirPath !== "string" || dirPath.trim() === "") {
2044
- throw new AutoRigInputError("output dir is empty");
2045
- }
2046
- const root = process.cwd();
2047
- const resolved = path.resolve(root, dirPath);
2048
- let stat;
2049
- try {
2050
- stat = fs.statSync(resolved);
2051
- } catch {
2052
- throw new AutoRigInputError(`output dir not found: ${resolved}`);
2053
- }
2054
- if (!stat.isDirectory()) {
2055
- throw new AutoRigInputError(`output dir is not a directory: ${resolved}`);
1848
+ function resolveOutputDir(dirPath) {
1849
+ if (typeof dirPath !== "string" || dirPath.trim() === "") {
1850
+ throw new AutoRigInputError("output dir is empty");
1851
+ }
1852
+ const root = process.cwd();
1853
+ const resolved = path.resolve(root, dirPath);
1854
+ let stat;
1855
+ try {
1856
+ stat = fs.statSync(resolved);
1857
+ } catch {
1858
+ throw new AutoRigInputError(`output dir not found: ${resolved}`);
1859
+ }
1860
+ if (!stat.isDirectory()) {
1861
+ throw new AutoRigInputError(`output dir is not a directory: ${resolved}`);
1862
+ }
1863
+ return confineToWorkingDirectory(root, resolved, "output dir", dirPath);
1864
+ }
1865
+ function writeFileAtomic(outPath, data) {
1866
+ const tmp = `${outPath}.${process.pid}.${Date.now()}.tmp`;
1867
+ try {
1868
+ fs.writeFileSync(tmp, data);
1869
+ try {
1870
+ fs.renameSync(tmp, outPath);
1871
+ } catch (e) {
1872
+ try {
1873
+ fs.rmSync(tmp, { force: true });
1874
+ } catch {
1875
+ }
1876
+ throw e;
1877
+ }
1878
+ } catch (e) {
1879
+ throw new AutoRigInputError(
1880
+ `write: ${e instanceof Error ? e.message : String(e)}`
1881
+ );
1882
+ }
1883
+ }
1884
+
1885
+ // src/node-images.ts
1886
+ import sharp from "sharp";
1887
+ import { detectAlphaBbox as scanAlphaBbox } from "@ikijs/editor";
1888
+ async function decodePng(filePath) {
1889
+ try {
1890
+ const pipeline = sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS });
1891
+ const metadata = await pipeline.metadata();
1892
+ if (metadata.format !== "png") {
1893
+ throw new AutoRigInputError(
1894
+ `non-PNG image (${metadata.format ?? "unknown"}): ${filePath}`
1895
+ );
1896
+ }
1897
+ const { data, info } = await pipeline.ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1898
+ return {
1899
+ width: info.width,
1900
+ height: info.height,
1901
+ rgba: data,
1902
+ hasAlpha: metadata.hasAlpha ?? false
1903
+ };
1904
+ } catch (e) {
1905
+ if (e instanceof AutoRigInputError) throw e;
1906
+ const msg = e instanceof Error ? e.message : String(e);
1907
+ throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);
1908
+ }
1909
+ }
1910
+ function detectAlphaBbox(rgba, width, height) {
1911
+ const bbox = scanAlphaBbox(rgba, width, height);
1912
+ if (bbox === null) {
1913
+ throw new AutoRigInputError("layer is empty after alpha threshold");
1914
+ }
1915
+ return bbox;
1916
+ }
1917
+ function cropToBuffer(rgba, width, height, bbox) {
1918
+ return sharp(rgba, { raw: { width, height, channels: 4 } }).extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h }).png().toBuffer();
1919
+ }
1920
+ function encodeOverlayPng(filePath, svg) {
1921
+ return sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS }).composite([{ input: Buffer.from(svg) }]).png().toBuffer();
1922
+ }
1923
+ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
1924
+ const byId = /* @__PURE__ */ new Map();
1925
+ for (const crop of crops) byId.set(crop.id, crop);
1926
+ const pad = layout.padding;
1927
+ const composites = await Promise.all(
1928
+ layout.placements.map(async (placement3) => {
1929
+ const crop = byId.get(placement3.id);
1930
+ if (crop === void 0) {
1931
+ throw new AutoRigInputError(
1932
+ `no crop for atlas placement "${placement3.id}"`
1933
+ );
1934
+ }
1935
+ const input = pad > 0 ? await sharp(crop.buffer).extend({ right: pad, bottom: pad, extendWith: "copy" }).png().toBuffer() : crop.buffer;
1936
+ return { input, left: placement3.x, top: placement3.y };
1937
+ })
1938
+ );
1939
+ const page = await sharp({
1940
+ create: {
1941
+ width: layout.pageWidth,
1942
+ height: layout.pageHeight,
1943
+ channels: 4,
1944
+ background: { r: 0, g: 0, b: 0, alpha: 0 }
1945
+ }
1946
+ }).composite(composites).png(
1947
+ quantizeColors === void 0 ? {} : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 }
1948
+ ).toBuffer();
1949
+ return `data:image/png;base64,${page.toString("base64")}`;
1950
+ }
1951
+
1952
+ // src/probe.ts
1953
+ var OUTPUT_SUFFIX = ".probe.json";
1954
+ var OPAQUE = 128;
1955
+ function paintRuns(png) {
1956
+ const { width, height, rgba } = png;
1957
+ const rows = [];
1958
+ let y0 = -1;
1959
+ for (let y = 0; y < height; y++) {
1960
+ const runs = [];
1961
+ let start = -1;
1962
+ for (let x = 0; x < width; x++) {
1963
+ const on = rgba[(y * width + x) * 4 + 3] >= OPAQUE;
1964
+ if (on && start < 0) start = x;
1965
+ if (!on && start >= 0) {
1966
+ runs.push([start, x]);
1967
+ start = -1;
1968
+ }
1969
+ }
1970
+ if (start >= 0) runs.push([start, width]);
1971
+ if (runs.length > 0 && y0 < 0) y0 = y;
1972
+ if (y0 >= 0) rows.push(runs);
1973
+ }
1974
+ while (rows.length > 0 && rows[rows.length - 1].length === 0) rows.pop();
1975
+ return rows.length === 0 ? { y0: 0, rows: [] } : { y0, rows };
1976
+ }
1977
+ function toCanvas(model, pts) {
1978
+ const hw = model.canvas.width / 2;
1979
+ const hh = model.canvas.height / 2;
1980
+ const out = new Float64Array(pts.length);
1981
+ for (let i = 0; i < pts.length; i += 2) {
1982
+ out[i] = hw + pts[i];
1983
+ out[i + 1] = hh - pts[i + 1];
1984
+ }
1985
+ return out;
1986
+ }
1987
+ var round = (v) => Math.round(v * 1e3) / 1e3 + 0;
1988
+ function locate(vertices, tri, x, y) {
1989
+ const [a, b, c] = tri;
1990
+ const ax = vertices[a * 2];
1991
+ const ay = vertices[a * 2 + 1];
1992
+ const bx = vertices[b * 2];
1993
+ const by = vertices[b * 2 + 1];
1994
+ const cx = vertices[c * 2];
1995
+ const cy = vertices[c * 2 + 1];
1996
+ const d = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy);
1997
+ if (Math.abs(d) < 1e-12) return null;
1998
+ const l1 = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / d;
1999
+ const l2 = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / d;
2000
+ const l3 = 1 - l1 - l2;
2001
+ const eps = 1e-9;
2002
+ return l1 >= -eps && l2 >= -eps && l3 >= -eps ? [l1, l2, l3] : null;
2003
+ }
2004
+ var QUAD_INDICES = [0, 1, 2, 1, 3, 2];
2005
+ function restMesh(model, cache, partId) {
2006
+ let m = cache.get(partId);
2007
+ if (m) return m;
2008
+ const part = model.parts.find((p) => p.id === partId);
2009
+ const indices = part.mesh ? part.mesh.indices : QUAD_INDICES;
2010
+ const rest = toCanvas(model, landParts(model, {}, [partId]).get(partId));
2011
+ const boxes = new Float64Array(indices.length / 3 * 4);
2012
+ for (let t = 0; t < indices.length / 3; t++) {
2013
+ let x0 = Infinity;
2014
+ let y0 = Infinity;
2015
+ let x1 = -Infinity;
2016
+ let y1 = -Infinity;
2017
+ for (let k = 0; k < 3; k++) {
2018
+ const v = indices[t * 3 + k];
2019
+ x0 = Math.min(x0, rest[v * 2]);
2020
+ x1 = Math.max(x1, rest[v * 2]);
2021
+ y0 = Math.min(y0, rest[v * 2 + 1]);
2022
+ y1 = Math.max(y1, rest[v * 2 + 1]);
2023
+ }
2024
+ boxes.set([x0, y0, x1, y1], t * 4);
2025
+ }
2026
+ m = { indices, rest, boxes };
2027
+ cache.set(partId, m);
2028
+ return m;
2029
+ }
2030
+ function locatePoints(mesh, points) {
2031
+ const { indices, rest, boxes } = mesh;
2032
+ const slack = 1e-6;
2033
+ return points.map(([x, y]) => {
2034
+ for (let t = 0; t < indices.length / 3; t++) {
2035
+ const b = t * 4;
2036
+ if (x < boxes[b] - slack || x > boxes[b + 2] + slack || y < boxes[b + 1] - slack || y > boxes[b + 3] + slack) {
2037
+ continue;
2038
+ }
2039
+ const tri = [
2040
+ indices[t * 3],
2041
+ indices[t * 3 + 1],
2042
+ indices[t * 3 + 2]
2043
+ ];
2044
+ const w = locate(rest, tri, x, y);
2045
+ if (w) return { tri, w };
2046
+ }
2047
+ return null;
2048
+ });
2049
+ }
2050
+ function landLocated(posed, at) {
2051
+ if (at === null) return null;
2052
+ let px2 = 0;
2053
+ let py = 0;
2054
+ for (let k = 0; k < 3; k++) {
2055
+ px2 += at.w[k] * posed[at.tri[k] * 2];
2056
+ py += at.w[k] * posed[at.tri[k] * 2 + 1];
2057
+ }
2058
+ return [px2, py];
2059
+ }
2060
+ function landPoints(model, cache, partId, points, pose) {
2061
+ const located = locatePoints(restMesh(model, cache, partId), points);
2062
+ const posed = toCanvas(model, landParts(model, pose, [partId]).get(partId));
2063
+ return located.map((at) => landLocated(posed, at));
2064
+ }
2065
+ function invalid(i, field, what) {
2066
+ return new AutoRigInputError(`queries[${i}].${field} ${what}`);
2067
+ }
2068
+ function checkPoints(i, points) {
2069
+ if (!Array.isArray(points) || points.length === 0) {
2070
+ throw invalid(i, "points", "must be a non-empty list of [x, y]");
2071
+ }
2072
+ if (points.length > MAX_PROBE_POINTS) {
2073
+ throw invalid(
2074
+ i,
2075
+ "points",
2076
+ `has ${points.length} points; at most ${MAX_PROBE_POINTS} per query`
2077
+ );
2078
+ }
2079
+ points.forEach((pt, k) => {
2080
+ if (!Array.isArray(pt) || pt.length !== 2 || !pt.every((v) => Number.isFinite(v))) {
2081
+ throw invalid(i, `points[${k}]`, "must be [x, y] with finite numbers");
2082
+ }
2083
+ });
2084
+ return points;
2085
+ }
2086
+ function checkPose(model, i, pose) {
2087
+ const declared = new Set(model.parameters.map((p) => p.id));
2088
+ for (const [id, v] of Object.entries(pose ?? {})) {
2089
+ if (!declared.has(id)) {
2090
+ throw invalid(i, `pose.${id}`, "is not a parameter the model declares");
2091
+ }
2092
+ if (typeof v !== "number" || !Number.isFinite(v)) {
2093
+ throw invalid(i, `pose.${id}`, "must be a finite number");
2094
+ }
2095
+ }
2096
+ return pose ?? {};
2097
+ }
2098
+ function checkQuery(model, q, i) {
2099
+ if (q.op === "paint") return { op: "paint", path: q.path };
2100
+ if (q.op !== "land" && q.op !== "displacement") {
2101
+ throw invalid(i, "op", `must be paint, land or displacement`);
2102
+ }
2103
+ if (!model.parts.some((p) => p.id === q.part)) {
2104
+ throw invalid(i, "part", `names no part of the model: ${String(q.part)}`);
2105
+ }
2106
+ return {
2107
+ op: q.op,
2108
+ part: q.part,
2109
+ points: checkPoints(i, q.points),
2110
+ pose: checkPose(model, i, q.pose)
2111
+ };
2112
+ }
2113
+ async function runQuery(model, cache, q, i) {
2114
+ if (q.op === "paint") {
2115
+ const file = resolveInputPath(q.path, `queries[${i}].path`);
2116
+ let png;
2117
+ try {
2118
+ png = await decodePng(file);
2119
+ } catch (e) {
2120
+ if (e instanceof AutoRigInputError) throw invalid(i, "path", e.message);
2121
+ throw e;
2122
+ }
2123
+ const { width, height } = model.canvas;
2124
+ if (png.width !== width || png.height !== height) {
2125
+ throw invalid(
2126
+ i,
2127
+ "path",
2128
+ `is ${png.width}x${png.height}, not the model's canvas ${width}x${height}: ${q.path}`
2129
+ );
2130
+ }
2131
+ return { op: "paint", ...paintRuns(png) };
2132
+ }
2133
+ const { points } = q;
2134
+ const landed = landPoints(model, cache, q.part, points, q.pose);
2135
+ return {
2136
+ op: q.op,
2137
+ part: q.part,
2138
+ points: landed.map(
2139
+ (l, k) => l === null ? null : q.op === "land" ? [round(l[0]), round(l[1])] : [round(l[0] - points[k][0]), round(l[1] - points[k][1])]
2140
+ )
2141
+ };
2142
+ }
2143
+ function summarize(r, i) {
2144
+ if (r.op === "paint") {
2145
+ return `${i} paint: ${r.rows.length} rows from y ${r.y0}`;
2146
+ }
2147
+ const off = r.points.filter((p) => p === null).length;
2148
+ return `${i} ${r.op} ${r.part}: ${r.points.length} points, ${off} off the mesh`;
2149
+ }
2150
+ async function probeRig(input) {
2151
+ try {
2152
+ const outFile = input.outputPath !== void 0 ? resolveOutputPath(input.outputPath, OUTPUT_SUFFIX) : void 0;
2153
+ const modelFile = confineToWorkingDirectory(
2154
+ process.cwd(),
2155
+ resolveInputPath(input.modelPath, "model"),
2156
+ "model path",
2157
+ input.modelPath
2158
+ );
2159
+ const model = loadIkiModel(readFileSync(modelFile, "utf8"));
2160
+ if (!Array.isArray(input.queries) || input.queries.length === 0) {
2161
+ throw new AutoRigInputError("queries must be a non-empty list");
2162
+ }
2163
+ if (input.queries.length > MAX_PROBE_QUERIES) {
2164
+ throw new AutoRigInputError(
2165
+ `queries has ${input.queries.length} entries; at most ${MAX_PROBE_QUERIES} per call`
2166
+ );
2167
+ }
2168
+ const checked = input.queries.map((q, i) => checkQuery(model, q, i));
2169
+ const cache = /* @__PURE__ */ new Map();
2170
+ const results = [];
2171
+ for (const [i, q] of checked.entries()) {
2172
+ results.push(await runQuery(model, cache, q, i));
2173
+ }
2174
+ if (outFile === void 0) return { ok: true, results };
2175
+ writeFileAtomic(outFile, JSON.stringify(results));
2176
+ return {
2177
+ ok: true,
2178
+ outputPath: outFile,
2179
+ lines: results.map(summarize)
2180
+ };
2181
+ } catch (e) {
2182
+ if (e instanceof AutoRigInputError || e instanceof IkiFormatError) {
2183
+ return { ok: false, error: e.message };
2184
+ }
2185
+ throw e;
2186
+ }
2187
+ }
2188
+
2189
+ // src/custom-gate.ts
2190
+ import { partIdsOfRole, rigidResidual } from "@ikijs/editor";
2191
+ import { StandardParameter as StandardParameter3 } from "@ikijs/format";
2192
+ var CUSTOM_GATE_LIMITS = {
2193
+ tie: 5e-3,
2194
+ slide: 0.1,
2195
+ onAnchor: 0.015,
2196
+ exposed: 9e-4,
2197
+ rigid: 25e-4
2198
+ };
2199
+ function foldLimit(model) {
2200
+ return checkFolds(model, { poses: [] }).thresholds.collapse;
2201
+ }
2202
+ function failedCustomGate(model, error) {
2203
+ const message = error instanceof Error ? error.message : String(error);
2204
+ return {
2205
+ ok: false,
2206
+ faceWidth: model.parts.find((p) => p.id === "face")?.width ?? 0,
2207
+ limits: { ...CUSTOM_GATE_LIMITS, fold: foldLimit(model) },
2208
+ poses: 0,
2209
+ parts: [],
2210
+ failed: [`gate error: ${message}`]
2211
+ };
2212
+ }
2213
+ function readingOf(faceWidth, amount, dimension, pose, limit, reason) {
2214
+ const value = amount === null ? null : amount / faceWidth ** dimension;
2215
+ const pass = value !== null && value <= limit;
2216
+ return {
2217
+ value,
2218
+ ...dimension === 1 ? { px: amount } : { px2: amount },
2219
+ pose,
2220
+ limit,
2221
+ pass,
2222
+ ...pass ? {} : { reason }
2223
+ };
2224
+ }
2225
+ var TWIN_FACE = 402;
2226
+ var RING_PX = 5;
2227
+ var RING_DIAGONAL_PX = 4;
2228
+ var SAMPLE_REACH_PX = 80;
2229
+ var SAMPLE_STEP_PX = 4;
2230
+ var TIP_INSET_PX = 6;
2231
+ var EXPOSED_REACH = 0.15;
2232
+ var runsAt = (paint, y) => paint.rows[y - paint.y0] ?? [];
2233
+ function paintedAt(paint, x, y) {
2234
+ const px2 = Math.floor(x);
2235
+ return runsAt(paint, Math.floor(y)).some(([a, b]) => px2 >= a && px2 < b);
2236
+ }
2237
+ var GRID_CELLS = 64;
2238
+ function triangleGrid(posed, indices, bounds) {
2239
+ const cell = Math.max(
2240
+ 16,
2241
+ (bounds.x1 - bounds.x0) / GRID_CELLS,
2242
+ (bounds.y1 - bounds.y0) / GRID_CELLS
2243
+ );
2244
+ const cols = Math.floor((bounds.x1 - bounds.x0) / cell) + 1;
2245
+ const rows = Math.floor((bounds.y1 - bounds.y0) / cell) + 1;
2246
+ const bins = /* @__PURE__ */ new Map();
2247
+ for (let t = 0; t < indices.length / 3; t++) {
2248
+ let x0 = Infinity;
2249
+ let y0 = Infinity;
2250
+ let x1 = -Infinity;
2251
+ let y1 = -Infinity;
2252
+ for (let k = 0; k < 3; k++) {
2253
+ const v = indices[t * 3 + k];
2254
+ x0 = Math.min(x0, posed[v * 2]);
2255
+ x1 = Math.max(x1, posed[v * 2]);
2256
+ y0 = Math.min(y0, posed[v * 2 + 1]);
2257
+ y1 = Math.max(y1, posed[v * 2 + 1]);
2258
+ }
2259
+ if (x1 < bounds.x0 || x0 > bounds.x1 || y1 < bounds.y0 || y0 > bounds.y1) {
2260
+ continue;
2261
+ }
2262
+ const cx0 = Math.max(0, Math.floor((x0 - bounds.x0) / cell));
2263
+ const cx1 = Math.min(cols - 1, Math.floor((x1 - bounds.x0) / cell));
2264
+ const cy0 = Math.max(0, Math.floor((y0 - bounds.y0) / cell));
2265
+ const cy1 = Math.min(rows - 1, Math.floor((y1 - bounds.y0) / cell));
2266
+ for (let cy = cy0; cy <= cy1; cy++) {
2267
+ for (let cx = cx0; cx <= cx1; cx++) {
2268
+ const k = cx + cy * cols;
2269
+ const bin = bins.get(k);
2270
+ if (bin) bin.push(t);
2271
+ else bins.set(k, [t]);
2272
+ }
2273
+ }
2274
+ }
2275
+ return (x, y) => x < bounds.x0 || y < bounds.y0 || x > bounds.x1 || y > bounds.y1 ? [] : bins.get(
2276
+ Math.floor((x - bounds.x0) / cell) + Math.floor((y - bounds.y0) / cell) * cols
2277
+ ) ?? [];
2278
+ }
2279
+ function paintedUnder(posed, mesh, paint, points) {
2280
+ if (points.length === 0) return [];
2281
+ const bounds = { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity };
2282
+ for (const [x, y] of points) {
2283
+ bounds.x0 = Math.min(bounds.x0, x);
2284
+ bounds.y0 = Math.min(bounds.y0, y);
2285
+ bounds.x1 = Math.max(bounds.x1, x);
2286
+ bounds.y1 = Math.max(bounds.y1, y);
2287
+ }
2288
+ const find = triangleGrid(posed, mesh.indices, bounds);
2289
+ return points.map(([x, y]) => {
2290
+ for (const t of find(x, y)) {
2291
+ const tri = [
2292
+ mesh.indices[t * 3],
2293
+ mesh.indices[t * 3 + 1],
2294
+ mesh.indices[t * 3 + 2]
2295
+ ];
2296
+ const w = locate(posed, tri, x, y);
2297
+ if (!w) continue;
2298
+ let rx = 0;
2299
+ let ry = 0;
2300
+ for (let k = 0; k < 3; k++) {
2301
+ rx += w[k] * mesh.rest[tri[k] * 2];
2302
+ ry += w[k] * mesh.rest[tri[k] * 2 + 1];
2303
+ }
2304
+ return paintedAt(paint, rx, ry);
2305
+ }
2306
+ return false;
2307
+ });
2308
+ }
2309
+ function hiddenSide(occlusion, from, direction) {
2310
+ const at = (v) => occlusionAmount(occlusion, v);
2311
+ const rest = at(from);
2312
+ const marks = occlusion.stops.map((s) => s.value).filter((v) => (v - from) * direction > 0).sort((a, b) => (a - b) * direction);
2313
+ const run2 = [from, ...marks];
2314
+ let leaves = null;
2315
+ let full = rest === 1 ? from : null;
2316
+ for (let i = 0; i + 1 < run2.length; i++) {
2317
+ if (leaves === null && at(run2[i + 1]) !== rest) leaves = run2[i];
2318
+ if (full === null && at(run2[i + 1]) === 1) full = run2[i + 1];
2319
+ }
2320
+ return { leaves, full };
2321
+ }
2322
+ function posesOf(model, baked, base) {
2323
+ const byName = new Map(base.map((p) => [p.name, p]));
2324
+ const add = (values) => {
2325
+ const pose = foldPose(values);
2326
+ if (!byName.has(pose.name)) byName.set(pose.name, pose);
2327
+ };
2328
+ const defaults = new Map(model.parameters.map((p) => [p.id, p.default]));
2329
+ for (const [param, stops] of baked) {
2330
+ for (const v of stops) if (v !== defaults.get(param)) add({ [param]: v });
2331
+ }
2332
+ const params = [...baked.keys()];
2333
+ for (let i = 0; i < params.length; i++) {
2334
+ for (let j = i + 1; j < params.length; j++) {
2335
+ for (const a of baked.get(params[i])) {
2336
+ if (a === defaults.get(params[i])) continue;
2337
+ for (const b of baked.get(params[j])) {
2338
+ if (b === defaults.get(params[j])) continue;
2339
+ add({ [params[i]]: a, [params[j]]: b });
2340
+ }
2341
+ }
2342
+ }
2343
+ }
2344
+ return [...byName.values()];
2345
+ }
2346
+ function freeEnd(paint, tie, inset) {
2347
+ if (paint.rows.length === 0) return null;
2348
+ const [top, bottom] = [paint.y0, paint.y0 + paint.rows.length - 1];
2349
+ const y = Math.abs(bottom - tie[1]) > Math.abs(top - tie[1]) ? bottom : top;
2350
+ const runs = runsAt(paint, y);
2351
+ if (runs.length === 0) return null;
2352
+ const widest = runs.reduce((a, b) => b[1] - b[0] > a[1] - a[0] ? b : a);
2353
+ return [(widest[0] + widest[1]) / 2, y > tie[1] ? y - inset : y + inset];
2354
+ }
2355
+ function checkCustomGate(model, parts, paints, options = {}) {
2356
+ const face = model.parts.find((p) => p.id === "face");
2357
+ if (face === void 0) throw new Error("custom gate: the model has no face");
2358
+ const faceWidth = face.width;
2359
+ const limits = {
2360
+ ...CUSTOM_GATE_LIMITS,
2361
+ fold: foldLimit(model)
2362
+ };
2363
+ if (parts.length === 0) {
2364
+ return {
2365
+ ok: true,
2366
+ faceWidth,
2367
+ limits,
2368
+ poses: 0,
2369
+ parts: [],
2370
+ failed: []
2371
+ };
2372
+ }
2373
+ const scale2 = faceWidth / TWIN_FACE;
2374
+ const px2 = (twin) => Math.max(1, Math.round(twin * scale2));
2375
+ const cache = /* @__PURE__ */ new Map();
2376
+ const turnParam = model.parameters.find(
2377
+ (p) => p.id === StandardParameter3.AngleX
2378
+ );
2379
+ const turns = (pose) => turnParam !== void 0 && (pose.values[StandardParameter3.AngleX] ?? turnParam.default) !== turnParam.default;
2380
+ const bakedOf = (id) => {
2381
+ const part = model.parts.find((p) => p.id === id);
2382
+ return new Map(
2383
+ (part.warps ?? []).map((w) => [
2384
+ w.parameter,
2385
+ w.keyforms.map((k) => k.value)
2386
+ ])
2387
+ );
2388
+ };
2389
+ const base = options.poses ?? foldPoses(model);
2390
+ const poseSets = parts.map((part) => {
2391
+ if (!model.parts.some((p) => p.id === part.id)) {
2392
+ throw new Error(`custom gate: the model has no part "${part.id}"`);
2393
+ }
2394
+ if (options.poses) return options.poses;
2395
+ const sampledOf = bakedOf(part.id);
2396
+ const occ = model.parts.find((p) => p.id === part.id).occlusion;
2397
+ if (occ !== void 0) {
2398
+ const at = sampledOf.get(occ.parameter) ?? [];
2399
+ sampledOf.set(occ.parameter, [
2400
+ .../* @__PURE__ */ new Set([...at, ...occ.stops.map((s) => s.value)])
2401
+ ]);
2402
+ }
2403
+ return posesOf(model, sampledOf, base);
2404
+ });
2405
+ const all = new Map(poseSets.flat().map((p) => [p.name, p]));
2406
+ const reports = parts.map((part, n) => {
2407
+ const poses = poseSets[n];
2408
+ const roleParts = partIdsOfRole(part.anchor).filter(
2409
+ (id) => model.parts.some((p) => p.id === id)
2410
+ );
2411
+ const anchorId = roleParts.find(
2412
+ (id) => locatePoints(restMesh(model, cache, id), [part.tie])[0] !== null
2413
+ ) ?? roleParts[0];
2414
+ const folds = checkFolds(model, { poses });
2415
+ const anchorPart = model.parts.find((p) => p.id === anchorId);
2416
+ if (anchorPart === void 0) {
2417
+ throw new Error(`custom gate: the model has no part "${anchorId}"`);
2418
+ }
2419
+ const ownPaint = paints.get(part.id);
2420
+ const anchorPaint = paints.get(part.anchor);
2421
+ if (ownPaint === void 0 || anchorPaint === void 0) {
2422
+ throw new Error(
2423
+ `custom gate: no paint for "${ownPaint === void 0 ? part.id : part.anchor}"`
2424
+ );
2425
+ }
2426
+ const partMesh = restMesh(model, cache, part.id);
2427
+ const anchorMesh = restMesh(model, cache, anchorId);
2428
+ const length = (amount, pose, limit, reason) => readingOf(faceWidth, amount, 1, pose, limit, reason);
2429
+ const ring = [
2430
+ [0, 0],
2431
+ [px2(RING_PX), 0],
2432
+ [-px2(RING_PX), 0],
2433
+ [0, px2(RING_PX)],
2434
+ [0, -px2(RING_PX)],
2435
+ [px2(RING_DIAGONAL_PX), px2(RING_DIAGONAL_PX)],
2436
+ [-px2(RING_DIAGONAL_PX), px2(RING_DIAGONAL_PX)],
2437
+ [px2(RING_DIAGONAL_PX), -px2(RING_DIAGONAL_PX)],
2438
+ [-px2(RING_DIAGONAL_PX), -px2(RING_DIAGONAL_PX)]
2439
+ ].map(([dx, dy]) => [part.tie[0] + dx, part.tie[1] + dy]);
2440
+ const onPart = locatePoints(partMesh, ring);
2441
+ const onAnchor = locatePoints(anchorMesh, ring);
2442
+ const shared = ring.flatMap(
2443
+ (_, i) => onPart[i] && onAnchor[i] ? [i] : []
2444
+ );
2445
+ const reach = px2(SAMPLE_REACH_PX);
2446
+ const step = px2(SAMPLE_STEP_PX);
2447
+ const samples = [];
2448
+ const cx = Math.round(part.tie[0]);
2449
+ const cy = Math.round(part.tie[1]);
2450
+ for (let y = cy - reach; y <= cy + reach; y += step) {
2451
+ const runs = runsAt(anchorPaint, y);
2452
+ for (let x = cx - reach; x <= cx + reach; x += step) {
2453
+ if (runs.some(([a, b]) => x >= a && x < b))
2454
+ samples.push([x + 0.5, y + 0.5]);
2455
+ }
2456
+ }
2457
+ const samplesOn = locatePoints(anchorMesh, samples).filter(
2458
+ (l) => l !== null
2459
+ );
2460
+ const [tieOnPart] = locatePoints(partMesh, [part.tie]);
2461
+ const partIndex = model.parts.findIndex((p) => p.id === part.id);
2462
+ const anchorIndex = model.parts.indexOf(anchorPart);
2463
+ const ownPart = model.parts[partIndex];
2464
+ const partLower = ownPart.order < anchorPart.order || ownPart.order === anchorPart.order && partIndex < anchorIndex;
2465
+ const [lowerId, upperId] = partLower ? [part.id, anchorId] : [anchorId, part.id];
2466
+ const [lowerMesh, upperMesh] = [
2467
+ restMesh(model, cache, lowerId),
2468
+ restMesh(model, cache, upperId)
2469
+ ];
2470
+ const upperPaint = partLower ? anchorPaint : ownPaint;
2471
+ const exposedReach = Math.round(EXPOSED_REACH * faceWidth);
2472
+ const hidden = [];
2473
+ for (let y = Math.floor(part.tie[1]) - exposedReach; y <= Math.ceil(part.tie[1]) + exposedReach; y++) {
2474
+ for (const [a0, a1] of runsAt(ownPaint, y)) {
2475
+ for (const [b0, b1] of runsAt(anchorPaint, y)) {
2476
+ for (let x = Math.max(a0, b0); x < Math.min(a1, b1); x++) {
2477
+ if (Math.hypot(x + 0.5 - part.tie[0], y + 0.5 - part.tie[1]) <= exposedReach) {
2478
+ hidden.push([x + 0.5, y + 0.5]);
2479
+ }
2480
+ }
2481
+ }
2482
+ }
2483
+ }
2484
+ const onAnchorMesh = locatePoints(anchorMesh, hidden);
2485
+ const hiddenOn = locatePoints(lowerMesh, hidden).filter(
2486
+ (l, i) => l !== null && onAnchorMesh[i] !== null
2487
+ );
2488
+ const occlusion = ownPart.occlusion;
2489
+ const coverParts = [];
2490
+ if (occlusion !== void 0) {
2491
+ for (const role of part.occludedBy ?? []) {
2492
+ for (const id of partIdsOfRole(role)) {
2493
+ const o = model.parts.find((p) => p.id === id);
2494
+ if (o === void 0 || !occlusion.by.includes(id)) continue;
2495
+ const steady = o.color[3] === 1 && (o.transform.opacity ?? 1) >= 1 && !(o.bindings ?? []).some((b) => b.channel === "opacity");
2496
+ if (!steady) continue;
2497
+ const paint = paints.get(role);
2498
+ if (paint === void 0) {
2499
+ throw new Error(`custom gate: no paint for "${role}"`);
2500
+ }
2501
+ coverParts.push({ id, mesh: restMesh(model, cache, id), paint });
2502
+ }
2503
+ }
2504
+ }
2505
+ const coverIds = new Set(coverParts.map((c) => c.id));
2506
+ const keyParam = occlusion === void 0 ? void 0 : model.parameters.find((p) => p.id === occlusion.parameter);
2507
+ const keyOf = (values) => Math.min(
2508
+ keyParam.max,
2509
+ Math.max(keyParam.min, values[keyParam.id] ?? keyParam.default)
2510
+ );
2511
+ const sampled = keyParam === void 0 ? [] : [
2512
+ .../* @__PURE__ */ new Set([
2513
+ keyParam.default,
2514
+ ...poses.map((p) => keyOf(p.values))
2515
+ ])
2516
+ ].sort((a, b) => a - b);
2517
+ const fullyHidden = (lo, hi) => occlusion.stops.every(
2518
+ (st) => st.value <= lo || st.value >= hi || st.amount === 1
2519
+ ) && occlusionAmount(occlusion, lo) === 1 && occlusionAmount(occlusion, hi) === 1;
2520
+ const hiddenAt = (v) => fullyHidden(
2521
+ sampled.filter((x) => x < v).at(-1) ?? v,
2522
+ sampled.find((x) => x > v) ?? v
2523
+ );
2524
+ let leftOut = 0;
2525
+ let leftOutTurning = 0;
2526
+ let readNoTurn = 0;
2527
+ const stops = bakedOf(part.id);
2528
+ const worstOf = {
2529
+ tie: { v: -1, pose: "rest" },
2530
+ slide: { v: -1, pose: "rest" },
2531
+ onAnchor: { v: -1, pose: "rest" },
2532
+ exposed: { v: -1, pose: "rest" },
2533
+ exposedTurn: { v: -1, pose: "rest" },
2534
+ rigid: { v: -1, pose: "rest" }
2535
+ };
2536
+ const keep = (w, v, pose) => {
2537
+ if (v > w.v) {
2538
+ w.v = v;
2539
+ w.pose = pose;
2540
+ }
2541
+ };
2542
+ let onAnchorNull = null;
2543
+ let turningPoses = 0;
2544
+ const rest = partMesh.rest;
2545
+ const restPoints = [];
2546
+ for (let i = 0; i < rest.length; i += 2)
2547
+ restPoints.push([rest[i], rest[i + 1]]);
2548
+ const measureRigid = (pose, posed) => {
2549
+ const moved = [];
2550
+ for (let i = 0; i < posed.length; i += 2)
2551
+ moved.push([posed[i], posed[i + 1]]);
2552
+ keep(worstOf.rigid, rigidResidual(restPoints, moved), pose.name);
2553
+ };
2554
+ for (const pose of poses) {
2555
+ const hiding = occlusion !== void 0 && hiddenAt(keyOf(pose.values));
2556
+ const landed = landParts(model, pose.values, [
2557
+ .../* @__PURE__ */ new Set([
2558
+ part.id,
2559
+ anchorId,
2560
+ ...hiding && coverIds.size > 0 ? coverIds : []
2561
+ ])
2562
+ ]);
2563
+ const partPosed = toCanvas(model, landed.get(part.id));
2564
+ const anchorPosed = toCanvas(model, landed.get(anchorId));
2565
+ const canvasOf = /* @__PURE__ */ new Map();
2566
+ const underCover = (points, skip) => {
2567
+ const covered = points.map(() => false);
2568
+ if (!hiding) return covered;
2569
+ for (const c of coverParts) {
2570
+ if (c.id === skip) continue;
2571
+ let posed = canvasOf.get(c.id);
2572
+ if (posed === void 0) {
2573
+ posed = toCanvas(model, landed.get(c.id));
2574
+ canvasOf.set(c.id, posed);
2575
+ }
2576
+ const under = paintedUnder(posed, c.mesh, c.paint, points);
2577
+ under.forEach((u, i) => {
2578
+ if (u) covered[i] = true;
2579
+ });
2580
+ }
2581
+ return covered;
2582
+ };
2583
+ const turning = turns(pose);
2584
+ const ringLands = onPart.map(
2585
+ (l) => l === null ? null : landLocated(partPosed, l)
2586
+ );
2587
+ const ringHidden = hiding && ringLands.every((p) => p !== null) && underCover(ringLands).every(Boolean);
2588
+ if (ringHidden) {
2589
+ leftOut++;
2590
+ if (turning) leftOutTurning++;
2591
+ } else if (turning) turningPoses++;
2592
+ else readNoTurn++;
2593
+ let gap = 0;
2594
+ for (const i of shared) {
2595
+ const a = landLocated(partPosed, onPart[i]);
2596
+ const b = landLocated(anchorPosed, onAnchor[i]);
2597
+ gap = Math.max(gap, Math.hypot(a[0] - b[0], a[1] - b[1]));
2598
+ }
2599
+ if (shared.length > 0 && !ringHidden) {
2600
+ keep(turning ? worstOf.slide : worstOf.tie, gap, pose.name);
2601
+ }
2602
+ if (turning && !ringHidden) {
2603
+ const at = landLocated(partPosed, tieOnPart);
2604
+ let nearest = null;
2605
+ if (at !== null) {
2606
+ for (const l of samplesOn) {
2607
+ const q = landLocated(anchorPosed, l);
2608
+ const d = Math.hypot(q[0] - at[0], q[1] - at[1]);
2609
+ if (nearest === null || d < nearest) nearest = d;
2610
+ }
2611
+ }
2612
+ if (nearest === null) onAnchorNull ??= pose.name;
2613
+ else keep(worstOf.onAnchor, nearest, pose.name);
2614
+ }
2615
+ if (hiddenOn.length > 0) {
2616
+ const lowerPosed = lowerId === part.id ? partPosed : anchorPosed;
2617
+ const upperPosed = upperId === part.id ? partPosed : anchorPosed;
2618
+ const lands = hiddenOn.map((l) => landLocated(lowerPosed, l));
2619
+ const underUpper = paintedUnder(
2620
+ upperPosed,
2621
+ upperMesh,
2622
+ upperPaint,
2623
+ lands
2624
+ );
2625
+ const underHider = coverIds.has(lowerId) ? lands.map(() => hiding) : underCover(lands, upperId);
2626
+ let showing = 0;
2627
+ lands.forEach((_, i) => {
2628
+ if (!underUpper[i] && !underHider[i]) showing++;
2629
+ });
2630
+ keep(
2631
+ turning ? worstOf.exposedTurn : worstOf.exposed,
2632
+ showing,
2633
+ pose.name
2634
+ );
2635
+ }
2636
+ if (part.rigid) measureRigid(pose, partPosed);
2637
+ }
2638
+ if (part.rigid) {
2639
+ for (const [param, values] of stops) {
2640
+ const def = model.parameters.find((p) => p.id === param).default;
2641
+ const sorted = [.../* @__PURE__ */ new Set([...values, def])].sort((a, b) => a - b);
2642
+ for (let i = 0; i + 1 < sorted.length; i++) {
2643
+ const mid = foldPose({ [param]: (sorted[i] + sorted[i + 1]) / 2 });
2644
+ const posed = landParts(model, mid.values, [part.id]).get(part.id);
2645
+ measureRigid(mid, toCanvas(model, posed));
2646
+ }
2647
+ }
2648
+ }
2649
+ const tieReading = shared.length === 0 ? length(
2650
+ null,
2651
+ "rest",
2652
+ limits.tie,
2653
+ `no point of the ring around the tie lies on both ${part.id} and ${anchorId}`
2654
+ ) : length(
2655
+ Math.max(0, worstOf.tie.v),
2656
+ worstOf.tie.pose,
2657
+ limits.tie,
2658
+ "the tie comes apart"
2659
+ );
2660
+ const slideReading = length(
2661
+ Math.max(0, worstOf.slide.v),
2662
+ worstOf.slide.pose,
2663
+ limits.slide,
2664
+ "the tie slides too far"
2665
+ );
2666
+ const onAnchorReading = onAnchorNull !== null ? length(
2667
+ null,
2668
+ onAnchorNull,
2669
+ limits.onAnchor,
2670
+ `the tie lands off ${part.id}'s mesh, or no painted point of ${anchorId} near it is on its mesh`
2671
+ ) : length(
2672
+ Math.max(0, worstOf.onAnchor.v),
2673
+ worstOf.onAnchor.pose,
2674
+ limits.onAnchor,
2675
+ `the tie leaves ${anchorId}'s paint`
2676
+ );
2677
+ const exposedReading = readingOf(
2678
+ faceWidth,
2679
+ Math.max(0, worstOf.exposed.v),
2680
+ 2,
2681
+ worstOf.exposed.pose,
2682
+ limits.exposed,
2683
+ "hidden art shows"
2684
+ );
2685
+ const ratioHit = folds.targets.find(
2686
+ (t) => t.target.kind === "part" && t.target.id === part.id
2687
+ )?.worst;
2688
+ const ratio = ratioHit?.ratio ?? 1;
2689
+ const foldsPass = ratio >= limits.fold;
2690
+ const rigidReading = part.rigid ? length(
2691
+ Math.max(0, worstOf.rigid.v),
2692
+ worstOf.rigid.pose,
2693
+ limits.rigid,
2694
+ "the part bends"
2695
+ ) : void 0;
2696
+ const tipAt = freeEnd(ownPaint, part.tie, px2(TIP_INSET_PX));
2697
+ const [tipLoc] = tipAt === null ? [null] : locatePoints(partMesh, [tipAt]);
2698
+ const bareModel = stops.size === 0 ? model : {
2699
+ ...model,
2700
+ parts: model.parts.map(
2701
+ (p) => p.id === part.id ? { ...p, warps: void 0 } : p
2702
+ )
2703
+ };
2704
+ const tip = [...stops.keys()].map((param) => {
2705
+ const def = model.parameters.find((p) => p.id === param);
2706
+ const ends = [def.min, def.max].map((value) => {
2707
+ const at = (m) => landLocated(
2708
+ toCanvas(
2709
+ m,
2710
+ landParts(m, { [param]: value }, [part.id]).get(part.id)
2711
+ ),
2712
+ tipLoc ?? null
2713
+ );
2714
+ const landed = at(model);
2715
+ const bare = at(bareModel);
2716
+ return {
2717
+ value,
2718
+ landed,
2719
+ bare,
2720
+ fromBare: landed && bare ? Math.hypot(landed[0] - bare[0], landed[1] - bare[1]) : null
2721
+ };
2722
+ });
2723
+ const [a, b] = ends;
2724
+ return {
2725
+ param,
2726
+ ends,
2727
+ travel: a.landed && b.landed ? Math.hypot(b.landed[0] - a.landed[0], b.landed[1] - a.landed[1]) : null
2728
+ };
2729
+ });
2730
+ const turningExposed = worstOf.exposedTurn.v < 0 ? null : (({ value, px2: px22, pose }) => ({ value, px2: px22, pose }))(
2731
+ readingOf(
2732
+ faceWidth,
2733
+ worstOf.exposedTurn.v,
2734
+ 2,
2735
+ worstOf.exposedTurn.pose,
2736
+ Infinity,
2737
+ ""
2738
+ )
2739
+ );
2740
+ const slidePass = slideReading.pass && onAnchorReading.pass;
2741
+ const ok = foldsPass && tieReading.pass && slidePass && exposedReading.pass && (rigidReading?.pass ?? true);
2742
+ return {
2743
+ id: part.id,
2744
+ anchor: part.anchor,
2745
+ folds: {
2746
+ ratio,
2747
+ pose: ratioHit?.pose.name ?? "rest",
2748
+ limit: limits.fold,
2749
+ pass: foldsPass,
2750
+ ...foldsPass ? {} : { reason: ratio <= 0 ? "a flip" : "a collapse" }
2751
+ },
2752
+ tie: tieReading,
2753
+ slide: {
2754
+ slide: slideReading,
2755
+ onAnchor: onAnchorReading,
2756
+ turningPoses,
2757
+ pass: slidePass
2758
+ },
2759
+ exposed: {
2760
+ hiddenPx: hiddenOn.length,
2761
+ noTurn: exposedReading,
2762
+ turning: turningExposed,
2763
+ pass: exposedReading.pass
2764
+ },
2765
+ ...rigidReading === void 0 ? {} : { rigid: rigidReading },
2766
+ tip,
2767
+ ...occlusion === void 0 ? {} : {
2768
+ hidden: {
2769
+ by: occlusion.by,
2770
+ cover: [...coverIds],
2771
+ parameter: occlusion.parameter,
2772
+ default: keyParam.default,
2773
+ atRest: occlusionAmount(occlusion, keyParam.default),
2774
+ below: hiddenSide(occlusion, keyParam.default, -1),
2775
+ above: hiddenSide(occlusion, keyParam.default, 1),
2776
+ leftOut,
2777
+ leftOutTurning,
2778
+ readNoTurn,
2779
+ poses: poses.length
2780
+ }
2781
+ },
2782
+ ok
2783
+ };
2784
+ });
2785
+ const failed = reports.flatMap((r) => [
2786
+ ...r.folds.pass ? [] : [`${r.id} FOLDS`],
2787
+ ...r.tie.pass ? [] : [`${r.id} TIE`],
2788
+ ...r.slide.pass ? [] : [`${r.id} SLIDE`],
2789
+ ...r.exposed.pass ? [] : [`${r.id} EXPOSED`],
2790
+ ...r.rigid === void 0 || r.rigid.pass ? [] : [`${r.id} RIGID`]
2791
+ ]);
2792
+ return {
2793
+ ok: failed.length === 0,
2794
+ faceWidth,
2795
+ limits,
2796
+ poses: all.size,
2797
+ parts: reports,
2798
+ failed
2799
+ };
2800
+ }
2801
+ var both = (faceWidth, px2, digits = 4) => px2 === null ? "off the mesh" : `${px2.toFixed(1)} px (${(px2 / faceWidth).toFixed(digits)} face widths)`;
2802
+ function formatCustomGate(report) {
2803
+ const w = report.faceWidth;
2804
+ const verdict = (pass, reason) => pass ? "pass" : `FAIL: ${reason}`;
2805
+ const limit = (fw) => `${fw} face widths, ${(fw * w).toFixed(1)} px`;
2806
+ const lines = [];
2807
+ for (const r of report.parts) {
2808
+ const at = `CUSTOM ${r.id}`;
2809
+ lines.push(
2810
+ `${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)}`
2811
+ );
2812
+ const noTurnLeftOut = r.hidden !== void 0 && r.hidden.readNoTurn === 0 && r.hidden.leftOut > r.hidden.leftOutTurning;
2813
+ lines.push(
2814
+ noTurnLeftOut ? `${at} TIE: every pose that does not turn the head is left out as hidden (see HIDDEN) ${verdict(r.tie.pass, r.tie.reason)}` : `${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)}`
2815
+ );
2816
+ const s = r.slide;
2817
+ lines.push(
2818
+ s.turningPoses === 0 ? r.hidden !== void 0 && r.hidden.leftOutTurning > 0 ? `${at} SLIDE: every pose that turns the head is left out as hidden (see HIDDEN) pass` : `${at} SLIDE: no pose turns the head pass` : `${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)}`
2819
+ );
2820
+ const e = r.exposed;
2821
+ const turnText = e.turning === null ? "no pose turns the head" : `max ${e.turning.px2.toFixed(0)} px\xB2 (${e.turning.value.toFixed(5)} face widths\xB2) at [${e.turning.pose}] (reported, no limit)`;
2822
+ lines.push(
2823
+ `${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\xB2 (${(e.noTurn.value ?? 0).toFixed(5)} face widths\xB2) at [${e.noTurn.pose}] (limit <= ${e.noTurn.limit} face widths\xB2, ${(e.noTurn.limit * w * w).toFixed(0)} px\xB2) ${verdict(e.pass, e.noTurn.reason)}; where it turns: ${turnText}`
2824
+ );
2825
+ if (r.hidden) {
2826
+ const h = r.hidden;
2827
+ const side = (name, s2) => h.atRest === 1 ? `${name} ${h.default} the amount is 1 at rest and ${s2.leaves === null ? "stays 1" : `leaves it at ${s2.leaves}`}` : `${name} ${h.default} the amount ${s2.leaves === null ? `never leaves ${h.atRest}` : `leaves ${h.atRest} at ${s2.leaves}`} and ${s2.full === null ? "never reaches 1" : `reaches 1 at ${s2.full}`}`;
2828
+ lines.push(
2829
+ `${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)`
2830
+ );
2831
+ }
2832
+ if (r.rigid) {
2833
+ lines.push(
2834
+ `${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)}`
2835
+ );
2836
+ }
2837
+ for (const t of r.tip) {
2838
+ const ends = t.ends.map(
2839
+ (x) => `${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`
2840
+ ).join("; ");
2841
+ lines.push(
2842
+ `${at} TIP ${t.param}: free end ${ends}; travel end to end ${t.travel === null ? "-" : both(w, t.travel)} (reported, no limit)`
2843
+ );
2844
+ }
2845
+ }
2846
+ lines.push(
2847
+ report.ok ? "CUSTOM GATE pass" : `CUSTOM GATE FAIL: ${report.failed.join(", ")}`
2848
+ );
2849
+ return lines;
2850
+ }
2851
+
2852
+ // src/sweep-report.ts
2853
+ var LADDER_MIN = -30;
2854
+ var LADDER_MAX = 30;
2855
+ var ZERO = -LADDER_MIN;
2856
+ var FLAT_SLOPE = 1e-4;
2857
+ var PARTS = ["face", "eye_L", "eye_R", "nose"];
2858
+ function box(pts, fw) {
2859
+ let x0 = Infinity;
2860
+ let x1 = -Infinity;
2861
+ let y0 = Infinity;
2862
+ let y1 = -Infinity;
2863
+ for (let i = 0; i < pts.length; i += 2) {
2864
+ x0 = Math.min(x0, pts[i]);
2865
+ x1 = Math.max(x1, pts[i]);
2866
+ y0 = Math.min(y0, pts[i + 1]);
2867
+ y1 = Math.max(y1, pts[i + 1]);
2868
+ }
2869
+ return {
2870
+ x: (x0 + x1) / 2 / fw,
2871
+ width: (x1 - x0) / fw,
2872
+ y: (y0 + y1) / 2 / fw
2873
+ };
2874
+ }
2875
+ function nearestVertex(face, fw, x, y) {
2876
+ let best = 0;
2877
+ let bestD = Infinity;
2878
+ for (let i = 0; i < face.length; i += 2) {
2879
+ const d = (face[i] / fw - x) ** 2 + (face[i + 1] / fw - y) ** 2;
2880
+ if (d < bestD) {
2881
+ bestD = d;
2882
+ best = i / 2;
2883
+ }
2884
+ }
2885
+ return best;
2886
+ }
2887
+ function kink(v) {
2888
+ const sMinus = (v[ZERO] - v[ZERO - 5]) / 5;
2889
+ const sPlus = (v[ZERO + 5] - v[ZERO]) / 5;
2890
+ const big = Math.max(Math.abs(sMinus), Math.abs(sPlus));
2891
+ if (big < FLAT_SLOPE) return null;
2892
+ return Math.abs(sPlus - sMinus) / big;
2893
+ }
2894
+ function pop(v) {
2895
+ let steps = 0;
2896
+ for (let i = 0; i + 1 < v.length; i++) steps += Math.abs(v[i + 1] - v[i]);
2897
+ const mean = steps / (v.length - 1);
2898
+ if (mean < 1e-9) return null;
2899
+ let most = 0;
2900
+ for (let i = 1; i + 1 < v.length; i++) {
2901
+ if (Math.abs(i - ZERO) <= 1) continue;
2902
+ most = Math.max(most, Math.abs(v[i + 1] - 2 * v[i] + v[i - 1]));
2903
+ }
2904
+ return most / mean;
2905
+ }
2906
+ var NOD_TURNS = [-30, 0, 30];
2907
+ var NOD_PARTS = [
2908
+ "face",
2909
+ "eye_L",
2910
+ "eye_R",
2911
+ "iris_L",
2912
+ "iris_R",
2913
+ "nose",
2914
+ "lip_upper",
2915
+ "mouth"
2916
+ ];
2917
+ var NOD_ENDS = [0, -LADDER_MIN, LADDER_MAX - LADDER_MIN];
2918
+ function checkNod(model) {
2919
+ const face = model.parts.find((p) => p.id === "face");
2920
+ if (!face) return { unavailable: "no face part" };
2921
+ const hasEyes = ["eye_L", "eye_R"].every(
2922
+ (id) => model.parts.some((p) => p.id === id)
2923
+ );
2924
+ if (!hasEyes) return { unavailable: "no eye_L and eye_R parts" };
2925
+ const fw = face.width;
2926
+ const ladders = NOD_TURNS.map(
2927
+ (x) => Array.from(
2928
+ { length: LADDER_MAX - LADDER_MIN + 1 },
2929
+ (_, i) => landParts(
2930
+ model,
2931
+ { ParamAngleX: x, ParamAngleY: LADDER_MIN + i },
2932
+ NOD_PARTS
2933
+ )
2934
+ )
2935
+ );
2936
+ const has = (id) => ladders[0][0].has(id);
2937
+ const boxes = (id) => ladders.map((ladder) => ladder.map((l) => box(l.get(id), fw)));
2938
+ const spread = (v) => Math.max(...v) - Math.min(...v);
2939
+ const ranges = (values) => {
2940
+ const [m30, zero, p30] = NOD_TURNS.map(
2941
+ (_, b) => spread(
2942
+ Array.from(
2943
+ { length: LADDER_MAX - LADDER_MIN + 1 },
2944
+ (_2, i) => values(b, i)
2945
+ )
2946
+ )
2947
+ );
2948
+ return { m30, zero, p30 };
2949
+ };
2950
+ const gap = (l, r) => {
2951
+ const bl = boxes(l);
2952
+ const br = boxes(r);
2953
+ return ranges((b, i) => br[b][i].x - bl[b][i].x);
2954
+ };
2955
+ const nod = [{ id: "eyes", range: gap("eye_L", "eye_R") }];
2956
+ if (has("iris_L") && has("iris_R")) {
2957
+ nod.push({ id: "irises", range: gap("iris_L", "iris_R") });
2958
+ }
2959
+ const mouthId = has("lip_upper") ? "lip_upper" : has("mouth") ? "mouth" : null;
2960
+ if (mouthId) {
2961
+ const bm = boxes(mouthId);
2962
+ nod.push({ id: "mouth", range: ranges((b, i) => bm[b][i].width) });
2963
+ }
2964
+ const corner = ["eye_L", "eye_R", "nose"].filter(has).map((id) => {
2965
+ const b = boxes(id);
2966
+ const at = (t, j) => b[t][NOD_ENDS[j]];
2967
+ const residual = (t, j) => {
2968
+ const r = (axis) => at(t, j)[axis] - at(t, 1)[axis] - at(1, j)[axis] + at(1, 1)[axis];
2969
+ return Math.max(Math.abs(r("x")), Math.abs(r("y")));
2970
+ };
2971
+ return {
2972
+ id,
2973
+ residual: {
2974
+ mm: residual(0, 0),
2975
+ mp: residual(0, 2),
2976
+ pm: residual(2, 0),
2977
+ pp: residual(2, 2)
2978
+ }
2979
+ };
2980
+ });
2981
+ return { unit: "fw", faceWidth: fw, nod, corner };
2982
+ }
2983
+ function checkSweep(model) {
2984
+ const face = model.parts.find((p) => p.id === "face");
2985
+ if (!face) return { preset: "turn", unavailable: "no face part" };
2986
+ const hasEyes = ["eye_L", "eye_R"].every(
2987
+ (id) => model.parts.some((p) => p.id === id)
2988
+ );
2989
+ if (!hasEyes) {
2990
+ return { preset: "turn", unavailable: "no eye_L and eye_R parts" };
2991
+ }
2992
+ const fw = face.width;
2993
+ const ladder = Array.from(
2994
+ { length: LADDER_MAX - LADDER_MIN + 1 },
2995
+ (_, i) => landParts(model, { ParamAngleX: LADDER_MIN + i }, PARTS)
2996
+ );
2997
+ const at = (id, i) => ladder[i].get(id);
2998
+ const ids = ["eye_L", "eye_R", ...ladder[0].has("nose") ? ["nose"] : []];
2999
+ const landmarks = ids.map((id) => {
3000
+ const boxes = ladder.map((_, i) => box(at(id, i), fw));
3001
+ const xs = boxes.map((b) => b.x);
3002
+ const plateIndex2 = nearestVertex(
3003
+ at("face", ZERO),
3004
+ fw,
3005
+ boxes[ZERO].x,
3006
+ boxes[ZERO].y
3007
+ );
3008
+ const plate = ladder.map((_, i) => at("face", i)[plateIndex2 * 2] / fw);
3009
+ const lead = (i) => xs[i] - plate[i] - (xs[ZERO] - plate[ZERO]);
3010
+ return {
3011
+ id,
3012
+ amplitude: xs[xs.length - 1] - xs[0],
3013
+ xKink: kink(xs),
3014
+ widthKink: id === "nose" ? null : kink(boxes.map((b) => b.width)),
3015
+ lead: { m30: lead(0), p30: lead(xs.length - 1) },
3016
+ pop: pop(xs)
3017
+ };
3018
+ });
3019
+ const eyes = ["eye_L", "eye_R"].map((id) => box(at(id, ZERO), fw));
3020
+ const plateIndex = nearestVertex(
3021
+ at("face", ZERO),
3022
+ fw,
3023
+ (eyes[0].x + eyes[1].x) / 2,
3024
+ (eyes[0].y + eyes[1].y) / 2
3025
+ );
3026
+ const plateX = (i) => at("face", i)[plateIndex * 2] / fw;
3027
+ return {
3028
+ preset: "turn",
3029
+ unit: "fw",
3030
+ faceWidth: fw,
3031
+ plateAmplitude: plateX(ladder.length - 1) - plateX(0),
3032
+ landmarks
3033
+ };
3034
+ }
3035
+ var fw3 = (v) => {
3036
+ const s = v.toFixed(3);
3037
+ return s === "-0.000" ? "0.000" : s;
3038
+ };
3039
+ var signed = (v) => fw3(v).startsWith("-") ? fw3(v) : `+${fw3(v)}`;
3040
+ var two = (v) => v === null ? "n/a" : v.toFixed(2);
3041
+ function formatSweepReport(report) {
3042
+ if ("unavailable" in report) {
3043
+ return [`SWEEP: unavailable \u2014 ${report.unavailable}`];
2056
3044
  }
2057
- return confineToWorkingDirectory(root, resolved, "output dir", dirPath);
3045
+ return [
3046
+ ...report.landmarks.map(
3047
+ (l) => `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)}`
3048
+ ),
3049
+ `SWEEP turn plate: amplitude ${fw3(report.plateAmplitude)} fw`
3050
+ ];
2058
3051
  }
2059
- function writeFileAtomic(outPath, data) {
2060
- const tmp = `${outPath}.${process.pid}.${Date.now()}.tmp`;
2061
- try {
2062
- fs.writeFileSync(tmp, data);
2063
- try {
2064
- fs.renameSync(tmp, outPath);
2065
- } catch (e) {
2066
- try {
2067
- fs.rmSync(tmp, { force: true });
2068
- } catch {
2069
- }
2070
- throw e;
2071
- }
2072
- } catch (e) {
2073
- throw new AutoRigInputError(
2074
- `write: ${e instanceof Error ? e.message : String(e)}`
2075
- );
3052
+ function formatNodReport(report) {
3053
+ if ("unavailable" in report) {
3054
+ return [`SWEEP nod: unavailable \u2014 ${report.unavailable}`];
2076
3055
  }
3056
+ return [
3057
+ ...report.nod.map(
3058
+ ({ id, range: r }) => `SWEEP nod ${id}: ${id === "mouth" ? "width" : "gap"} range X -30 ${fw3(r.m30)} / 0 ${fw3(r.zero)} / +30 ${fw3(r.p30)} fw`
3059
+ ),
3060
+ ...report.corner.map(
3061
+ ({ id, residual: r }) => `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`
3062
+ )
3063
+ ];
2077
3064
  }
2078
3065
 
3066
+ // src/sweep.ts
3067
+ import fs3 from "fs";
3068
+ import path4 from "path";
3069
+
2079
3070
  // src/render-poses.ts
2080
- import { readFileSync } from "fs";
3071
+ import { readFileSync as readFileSync2 } from "fs";
2081
3072
  import path3 from "path";
2082
3073
  import {
2083
- IkiFormatError,
2084
- StandardParameter as StandardParameter3,
2085
- loadIkiModel
3074
+ IkiFormatError as IkiFormatError2,
3075
+ StandardParameter as StandardParameter4,
3076
+ loadIkiModel as loadIkiModel2
2086
3077
  } from "@ikijs/format";
2087
3078
 
2088
3079
  // src/render-browser.ts
@@ -2489,9 +3480,9 @@ function planRenders(model, requested, sweep, sweeps) {
2489
3480
  }
2490
3481
  const bodyAngles = Object.fromEntries(
2491
3482
  [
2492
- StandardParameter3.BodyAngleX,
2493
- StandardParameter3.BodyAngleY,
2494
- StandardParameter3.BodyAngleZ
3483
+ StandardParameter4.BodyAngleX,
3484
+ StandardParameter4.BodyAngleY,
3485
+ StandardParameter4.BodyAngleZ
2495
3486
  ].filter((id) => model.parameters.some((p) => p.id === id)).map((id) => [id, -10])
2496
3487
  );
2497
3488
  const poses = [
@@ -2577,7 +3568,7 @@ function planRenders(model, requested, sweep, sweeps) {
2577
3568
  whole("full-elbow-r-45", { ParamElbowR: 45 }),
2578
3569
  whole("full-elbow-r-90", { ParamElbowR: 90 })
2579
3570
  );
2580
- if (model.parameters.some((p) => p.id === StandardParameter3.ArmPoseRight)) {
3571
+ if (model.parameters.some((p) => p.id === StandardParameter4.ArmPoseRight)) {
2581
3572
  poses.push(
2582
3573
  whole("full-pose-l", { ParamArmPoseL: 1 }),
2583
3574
  whole("full-pose-r", { ParamArmPoseR: 1 }),
@@ -2618,6 +3609,33 @@ function checkRequest(requested, i) {
2618
3609
  }
2619
3610
  }
2620
3611
  }
3612
+ function withoutParts(model, hideParts) {
3613
+ const hidden = new Set(hideParts);
3614
+ hideParts.forEach((id, i) => {
3615
+ if (!model.parts.some((p) => p.id === id)) {
3616
+ throw new AutoRigInputError(
3617
+ `hideParts[${i}] ${JSON.stringify(id)} is not a part of the model`
3618
+ );
3619
+ }
3620
+ const kept = model.parts.find(
3621
+ (p) => !hidden.has(p.id) && p.clip?.masks.includes(id)
3622
+ );
3623
+ if (kept) {
3624
+ throw new AutoRigInputError(
3625
+ `hideParts[${i}] ${JSON.stringify(id)} masks ${JSON.stringify(kept.id)}, which stays; hide ${JSON.stringify(kept.id)} too`
3626
+ );
3627
+ }
3628
+ const occluded = model.parts.find(
3629
+ (p) => !hidden.has(p.id) && p.occlusion?.by.includes(id)
3630
+ );
3631
+ if (occluded) {
3632
+ throw new AutoRigInputError(
3633
+ `hideParts[${i}] ${JSON.stringify(id)} occludes ${JSON.stringify(occluded.id)}, which stays; hide ${JSON.stringify(occluded.id)} too`
3634
+ );
3635
+ }
3636
+ });
3637
+ return { ...model, parts: model.parts.filter((p) => !hidden.has(p.id)) };
3638
+ }
2621
3639
  var PNG_PREFIX = "data:image/png;base64,";
2622
3640
  var PAGE_SCRIPT_MS = 1e4;
2623
3641
  var LOAD_MS = 6e4;
@@ -2625,7 +3643,7 @@ var CAPTURE_MS = 15e3;
2625
3643
  function readPageScript() {
2626
3644
  const url = new URL("../dist/render-page.global.js", import.meta.url);
2627
3645
  try {
2628
- return readFileSync(url, "utf8");
3646
+ return readFileSync2(url, "utf8");
2629
3647
  } catch (cause) {
2630
3648
  throw new Error(
2631
3649
  "could not read the render page script; run `pnpm build` in packages/mcp",
@@ -2726,8 +3744,9 @@ async function renderPoses(input) {
2726
3744
  input.modelPath
2727
3745
  );
2728
3746
  const outDir = resolveOutputDir(input.outDir);
2729
- const model = loadIkiModel(readFileSync(modelFile, "utf8"));
3747
+ const model = loadIkiModel2(readFileSync2(modelFile, "utf8"));
2730
3748
  const plan = planRenders(model, input.poses, input.sweep, input.sweeps);
3749
+ const drawn = input.hideParts ? withoutParts(model, input.hideParts) : model;
2731
3750
  const browser = findBrowser();
2732
3751
  if (!browser) return { ok: false, error: NO_BROWSER_MESSAGE };
2733
3752
  const pageScript = readPageScript();
@@ -2750,7 +3769,7 @@ async function renderPoses(input) {
2750
3769
  async (evaluate) => {
2751
3770
  await evaluate(pageScript, PAGE_SCRIPT_MS);
2752
3771
  const loaded = await evaluate(
2753
- `window.__ikiRender.load(${JSON.stringify(model)}, ${JSON.stringify({ canvas: plan.canvas, view: plan.view })})`,
3772
+ `window.__ikiRender.load(${JSON.stringify(drawn)}, ${JSON.stringify({ canvas: plan.canvas, view: plan.view })})`,
2754
3773
  LOAD_MS
2755
3774
  );
2756
3775
  const written = [];
@@ -2818,7 +3837,7 @@ async function renderPoses(input) {
2818
3837
  sweeps
2819
3838
  };
2820
3839
  } catch (error) {
2821
- if (error instanceof AutoRigInputError || error instanceof IkiFormatError) {
3840
+ if (error instanceof AutoRigInputError || error instanceof IkiFormatError2) {
2822
3841
  return { ok: false, error: error.message };
2823
3842
  }
2824
3843
  throw error;
@@ -2830,7 +3849,7 @@ var SWEEP_CLOCK_HZ = 60;
2830
3849
  var SWEEP_FPS = 30;
2831
3850
  var SWEEP_DURATION_S = 3;
2832
3851
  var BOX_DURATION_S = 6;
2833
- var SWEEP_PRESETS = ["turn", "turn-nod"];
3852
+ var SWEEP_PRESETS = ["turn", "turn-nod", "roll"];
2834
3853
  var SWEEP_WARMUP_S = 0.5;
2835
3854
  var SWEEP_FRAME_MS = 1e3 / SWEEP_CLOCK_HZ * (1 + 1e-9);
2836
3855
  var SHEET_THETAS = [-30, -20, -10, -5, 0, 5, 10, 20, 30];
@@ -2883,29 +3902,37 @@ function boxAngles(t) {
2883
3902
  }
2884
3903
  return { x: 0, y: 0 };
2885
3904
  }
2886
- function sweepDurationS(preset) {
2887
- return preset === "turn" ? SWEEP_DURATION_S : BOX_DURATION_S;
2888
- }
2889
- function schedule(preset) {
2890
- const durationS = sweepDurationS(preset);
2891
- const n = SWEEP_CLOCK_HZ * durationS;
2892
- if (preset === "turn") {
2893
- return {
2894
- parameters: ["ParamAngleX"],
2895
- steps: Array.from({ length: n }, (_, j) => ({
2896
- ParamAngleX: turnTheta(j / SWEEP_CLOCK_HZ)
2897
- })),
2898
- durationS
2899
- };
2900
- }
2901
- return {
2902
- parameters: ["ParamAngleX", "ParamAngleY"],
2903
- steps: Array.from({ length: n }, (_, j) => {
2904
- const { x, y } = boxAngles(j / SWEEP_CLOCK_HZ);
3905
+ var legSheet = (id) => (steps, n) => turnSheetFrames(steps, n, id);
3906
+ var SHAPES = {
3907
+ turn: {
3908
+ durationS: SWEEP_DURATION_S,
3909
+ angles: (t) => ({ ParamAngleX: turnTheta(t) }),
3910
+ sheetFrames: legSheet("ParamAngleX"),
3911
+ label: (s) => `\u03B8 ${signedDeg(s.ParamAngleX)}\xB0`,
3912
+ kymograph: true
3913
+ },
3914
+ // The roll rides the turn's own curve, so its frames sit at the angles the
3915
+ // turn sheet's do.
3916
+ roll: {
3917
+ durationS: SWEEP_DURATION_S,
3918
+ angles: (t) => ({ ParamAngleZ: turnTheta(t) }),
3919
+ sheetFrames: legSheet("ParamAngleZ"),
3920
+ label: (s) => `Z ${signedDeg(s.ParamAngleZ)}\xB0`,
3921
+ kymograph: false
3922
+ },
3923
+ "turn-nod": {
3924
+ durationS: BOX_DURATION_S,
3925
+ angles: (t) => {
3926
+ const { x, y } = boxAngles(t);
2905
3927
  return { ParamAngleX: x, ParamAngleY: y };
2906
- }),
2907
- durationS
2908
- };
3928
+ },
3929
+ sheetFrames: boxSheetFrames,
3930
+ label: (s) => `X ${signedDeg(s.ParamAngleX)}\xB0 Y ${signedDeg(s.ParamAngleY)}\xB0`,
3931
+ kymograph: false
3932
+ }
3933
+ };
3934
+ function sweepDurationS(preset) {
3935
+ return SHAPES[preset].durationS;
2909
3936
  }
2910
3937
  function eyeRowModelPx(model) {
2911
3938
  const landed = landParts(model, {}, ["eye_L", "eye_R"]);
@@ -2931,13 +3958,13 @@ function physicsOutputIds(model) {
2931
3958
  }
2932
3959
  return [...ids];
2933
3960
  }
2934
- function turnSheetFrames(steps, frames) {
3961
+ function turnSheetFrames(steps, frames, id) {
2935
3962
  const onLeg = [];
2936
3963
  for (let k = 0; k < frames; k++) {
2937
3964
  const t = k / SWEEP_FPS;
2938
3965
  if (t >= LEG_FROM_S && t <= LEG_TO_S) onLeg.push(k);
2939
3966
  }
2940
- const x = (k) => steps[CAPTURE_EVERY * k].ParamAngleX;
3967
+ const x = (k) => steps[CAPTURE_EVERY * k][id];
2941
3968
  const picked = [];
2942
3969
  for (const target2 of SHEET_THETAS) {
2943
3970
  let best = onLeg[0];
@@ -2967,7 +3994,13 @@ function signedDeg(angle) {
2967
3994
  return rounded > 0 ? `+${deg}` : deg.replace("-", "\u2212");
2968
3995
  }
2969
3996
  function sweepSpec(model, preset, crop) {
2970
- const { parameters, steps, durationS } = schedule(preset);
3997
+ const shape = SHAPES[preset];
3998
+ const { durationS } = shape;
3999
+ const steps = Array.from(
4000
+ { length: SWEEP_CLOCK_HZ * durationS },
4001
+ (_, j) => shape.angles(j / SWEEP_CLOCK_HZ)
4002
+ );
4003
+ const parameters = Object.keys(steps[0]);
2971
4004
  const frameCount = durationS * SWEEP_FPS;
2972
4005
  const dw = crop ? crop.dw : BUST_SIZE;
2973
4006
  const dh = crop ? crop.dh : BUST_SIZE;
@@ -2978,15 +4011,11 @@ function sweepSpec(model, preset, crop) {
2978
4011
  (SHEET_MAX_SIDE - 2 * m) / (3 * dw),
2979
4012
  (SHEET_MAX_SIDE - 2 * m - 3 * b) / (3 * dh)
2980
4013
  );
2981
- const frames = preset === "turn" ? turnSheetFrames(steps, frameCount) : boxSheetFrames(steps, frameCount);
2982
- const labelOf = (k) => {
2983
- const s = steps[CAPTURE_EVERY * k];
2984
- const t = (k / SWEEP_FPS).toFixed(2);
2985
- return preset === "turn" ? `\u03B8 ${signedDeg(s.ParamAngleX)}\xB0 t ${t} s` : `X ${signedDeg(s.ParamAngleX)}\xB0 Y ${signedDeg(s.ParamAngleY)}\xB0 t ${t} s`;
2986
- };
4014
+ const frames = shape.sheetFrames(steps, frameCount);
4015
+ const labelOf = (k) => `${shape.label(steps[CAPTURE_EVERY * k])} t ${(k / SWEEP_FPS).toFixed(2)} s`;
2987
4016
  const { width: W, height: H } = model.canvas;
2988
4017
  let kymograph;
2989
- if (preset === "turn") {
4018
+ if (shape.kymograph) {
2990
4019
  const yModel = eyeRowModelPx(model);
2991
4020
  let row = Math.round(dh / 2);
2992
4021
  let at = "middle";
@@ -3066,7 +4095,7 @@ img { max-width: 48vw; height: auto; background: #444; }
3066
4095
  scrub.max = String(n - 1);
3067
4096
  if (b) { bi.style.display = "block"; }
3068
4097
  function short(id) {
3069
- return id === "ParamAngleX" ? "X" : id === "ParamAngleY" ? "Y" : id;
4098
+ return id === "ParamAngleX" ? "X" : id === "ParamAngleY" ? "Y" : id === "ParamAngleZ" ? "Z" : id;
3070
4099
  }
3071
4100
  function show(k) {
3072
4101
  i = k;
@@ -3129,22 +4158,25 @@ function clearSweepDir(real) {
3129
4158
  }
3130
4159
 
3131
4160
  // src/tools.ts
3132
- import { readFileSync as readFileSync2 } from "fs";
4161
+ import { readFileSync as readFileSync3 } from "fs";
3133
4162
  import path5 from "path";
3134
4163
  import {
3135
4164
  parseIkiModel,
3136
- loadIkiModel as loadIkiModel2,
3137
- IkiFormatError as IkiFormatError2,
3138
- StandardParameter as StandardParameter4
4165
+ loadIkiModel as loadIkiModel3,
4166
+ IkiFormatError as IkiFormatError3,
4167
+ StandardParameter as StandardParameter5
3139
4168
  } from "@ikijs/format";
3140
4169
  import {
3141
4170
  EditorDocument,
3142
4171
  packAtlas,
3143
4172
  uvRectFor,
3144
4173
  createLayerSetMeasurer,
4174
+ detectAlphaBbox as detectAlphaBbox2,
3145
4175
  generateIkiFromLayerSet,
3146
4176
  parseLayerRoles,
3147
- partIdsOfRole,
4177
+ partIdsOfRole as partIdsOfRole2,
4178
+ BakeError,
4179
+ CustomPartError,
3148
4180
  LayerGeometryError,
3149
4181
  PatchError,
3150
4182
  RigPlanError,
@@ -3153,80 +4185,81 @@ import {
3153
4185
  TurnTargetError
3154
4186
  } from "@ikijs/editor";
3155
4187
 
3156
- // src/node-images.ts
3157
- import sharp from "sharp";
3158
- import { detectAlphaBbox as scanAlphaBbox } from "@ikijs/editor";
3159
- async function decodePng(filePath) {
3160
- try {
3161
- const pipeline = sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS });
3162
- const metadata = await pipeline.metadata();
3163
- if (metadata.format !== "png") {
4188
+ // src/bake-report.ts
4189
+ var BAKE_TOLERANCE_PX = 0.1;
4190
+ var BUG = "the rig and the engine disagree; report this as a bug in the packages";
4191
+ function checkBakes(model, reports) {
4192
+ const restOf = /* @__PURE__ */ new Map();
4193
+ for (const id of new Set(reports.map((r) => r.part))) {
4194
+ const rest = landParts(model, {}, [id]).get(id);
4195
+ const bare = landParts(
4196
+ {
4197
+ ...model,
4198
+ parts: model.parts.map(
4199
+ (p) => p.id === id ? { ...p, warps: void 0 } : p
4200
+ )
4201
+ },
4202
+ {},
4203
+ [id]
4204
+ ).get(id);
4205
+ let restGap = 0;
4206
+ for (let i = 0; i < rest.length; i++) {
4207
+ restGap = Math.max(restGap, Math.abs(rest[i] - bare[i]));
4208
+ }
4209
+ if (restGap >= BAKE_TOLERANCE_PX) {
3164
4210
  throw new AutoRigInputError(
3165
- `non-PNG image (${metadata.format ?? "unknown"}): ${filePath}`
4211
+ `BAKE ERROR ${id} at rest: the part moved ${restGap.toFixed(3)} px, where the bake must leave it (limit ${BAKE_TOLERANCE_PX} px); ${BUG}`
3166
4212
  );
3167
4213
  }
3168
- const { data, info } = await pipeline.ensureAlpha().raw().toBuffer({ resolveWithObject: true });
3169
- return {
3170
- width: info.width,
3171
- height: info.height,
3172
- rgba: data,
3173
- hasAlpha: metadata.hasAlpha ?? false
3174
- };
3175
- } catch (e) {
3176
- if (e instanceof AutoRigInputError) throw e;
3177
- const msg = e instanceof Error ? e.message : String(e);
3178
- throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);
3179
- }
3180
- }
3181
- function detectAlphaBbox(rgba, width, height) {
3182
- const bbox = scanAlphaBbox(rgba, width, height);
3183
- if (bbox === null) {
3184
- throw new AutoRigInputError("layer is empty after alpha threshold");
4214
+ restOf.set(id, rest);
3185
4215
  }
3186
- return bbox;
3187
- }
3188
- function cropToBuffer(rgba, width, height, bbox) {
3189
- return sharp(rgba, { raw: { width, height, channels: 4 } }).extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h }).png().toBuffer();
3190
- }
3191
- function encodeOverlayPng(filePath, svg) {
3192
- return sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS }).composite([{ input: Buffer.from(svg) }]).png().toBuffer();
3193
- }
3194
- async function renderAtlasToDataUri(crops, layout, quantizeColors) {
3195
- const byId = /* @__PURE__ */ new Map();
3196
- for (const crop of crops) byId.set(crop.id, crop);
3197
- const pad = layout.padding;
3198
- const composites = await Promise.all(
3199
- layout.placements.map(async (placement3) => {
3200
- const crop = byId.get(placement3.id);
3201
- if (crop === void 0) {
4216
+ return reports.map((r) => {
4217
+ const rest = restOf.get(r.part);
4218
+ let errorPx = 0;
4219
+ const asked = [
4220
+ ...r.stops.map((value, s) => ({ value, wanted: r.wanted[s] })),
4221
+ ...r.ends
4222
+ ];
4223
+ asked.forEach(({ value, wanted }) => {
4224
+ const posed = landParts(model, { [r.param]: value }, [r.part]).get(
4225
+ r.part
4226
+ );
4227
+ let worst = 0;
4228
+ let worstVertex = 0;
4229
+ for (let v = 0; v < r.vertexCount; v++) {
4230
+ const gap = Math.hypot(
4231
+ posed[v * 2] - rest[v * 2] - wanted[v * 2],
4232
+ -(posed[v * 2 + 1] - rest[v * 2 + 1]) - wanted[v * 2 + 1]
4233
+ );
4234
+ if (gap > worst) {
4235
+ worst = gap;
4236
+ worstVertex = v;
4237
+ }
4238
+ }
4239
+ if (worst >= BAKE_TOLERANCE_PX) {
3202
4240
  throw new AutoRigInputError(
3203
- `no crop for atlas placement "${placement3.id}"`
4241
+ `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}`
3204
4242
  );
3205
4243
  }
3206
- const input = pad > 0 ? await sharp(crop.buffer).extend({ right: pad, bottom: pad, extendWith: "copy" }).png().toBuffer() : crop.buffer;
3207
- return { input, left: placement3.x, top: placement3.y };
3208
- })
3209
- );
3210
- const page = await sharp({
3211
- create: {
3212
- width: layout.pageWidth,
3213
- height: layout.pageHeight,
3214
- channels: 4,
3215
- background: { r: 0, g: 0, b: 0, alpha: 0 }
3216
- }
3217
- }).composite(composites).png(
3218
- quantizeColors === void 0 ? {} : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 }
3219
- ).toBuffer();
3220
- return `data:image/png;base64,${page.toString("base64")}`;
4244
+ errorPx = Math.max(errorPx, worst);
4245
+ });
4246
+ return {
4247
+ part: r.part,
4248
+ param: r.param,
4249
+ vertices: r.vertexCount,
4250
+ stops: r.stops,
4251
+ errorPx
4252
+ };
4253
+ });
3221
4254
  }
3222
4255
 
3223
4256
  // src/tools.ts
3224
4257
  function coerceModel(model) {
3225
4258
  try {
3226
- const parsed = typeof model === "string" ? loadIkiModel2(model) : parseIkiModel(model);
4259
+ const parsed = typeof model === "string" ? loadIkiModel3(model) : parseIkiModel(model);
3227
4260
  return { ok: true, model: parsed };
3228
4261
  } catch (e) {
3229
- if (e instanceof IkiFormatError2) return { ok: false, error: e.message };
4262
+ if (e instanceof IkiFormatError3) return { ok: false, error: e.message };
3230
4263
  throw e;
3231
4264
  }
3232
4265
  }
@@ -3335,7 +4368,7 @@ function describeIkiAt(modelPath) {
3335
4368
  "model path",
3336
4369
  modelPath
3337
4370
  );
3338
- return describeIki(readFileSync2(modelFile, "utf8"));
4371
+ return describeIki(readFileSync3(modelFile, "utf8"));
3339
4372
  } catch (e) {
3340
4373
  if (e instanceof AutoRigInputError) return { ok: false, error: e.message };
3341
4374
  throw e;
@@ -3343,123 +4376,123 @@ function describeIkiAt(modelPath) {
3343
4376
  }
3344
4377
  var STANDARD_PARAMETER_INFO = [
3345
4378
  {
3346
- id: StandardParameter4.MouthOpen,
4379
+ id: StandardParameter5.MouthOpen,
3347
4380
  description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
3348
4381
  },
3349
4382
  {
3350
- id: StandardParameter4.MouthForm,
4383
+ id: StandardParameter5.MouthForm,
3351
4384
  description: "Mouth form / smile (-1 .. 1)."
3352
4385
  },
3353
4386
  {
3354
- id: StandardParameter4.EyeOpenLeft,
4387
+ id: StandardParameter5.EyeOpenLeft,
3355
4388
  description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
3356
4389
  },
3357
4390
  {
3358
- id: StandardParameter4.EyeOpenRight,
4391
+ id: StandardParameter5.EyeOpenRight,
3359
4392
  description: "Right eye open (0 closed .. 1 open)."
3360
4393
  },
3361
4394
  {
3362
- id: StandardParameter4.EyeballX,
4395
+ id: StandardParameter5.EyeballX,
3363
4396
  description: "Eyeball gaze, horizontal (-1 .. 1)."
3364
4397
  },
3365
4398
  {
3366
- id: StandardParameter4.EyeballY,
4399
+ id: StandardParameter5.EyeballY,
3367
4400
  description: "Eyeball gaze, vertical (-1 .. 1)."
3368
4401
  },
3369
4402
  {
3370
- id: StandardParameter4.AngleX,
4403
+ id: StandardParameter5.AngleX,
3371
4404
  description: "Head angle, horizontal degrees."
3372
4405
  },
3373
4406
  {
3374
- id: StandardParameter4.AngleY,
4407
+ id: StandardParameter5.AngleY,
3375
4408
  description: "Head angle, vertical degrees."
3376
4409
  },
3377
4410
  {
3378
- id: StandardParameter4.AngleZ,
4411
+ id: StandardParameter5.AngleZ,
3379
4412
  description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
3380
4413
  },
3381
4414
  {
3382
- id: StandardParameter4.BodyAngleX,
4415
+ id: StandardParameter5.BodyAngleX,
3383
4416
  description: "Body turn, degrees (-10 .. 10); positive turns the body toward the viewer's right, as AngleX does the head."
3384
4417
  },
3385
4418
  {
3386
- id: StandardParameter4.BodyAngleY,
4419
+ id: StandardParameter5.BodyAngleY,
3387
4420
  description: "Body lean, degrees (-10 .. 10); positive moves the upper body up, negative bows."
3388
4421
  },
3389
4422
  {
3390
- id: StandardParameter4.BodyAngleZ,
4423
+ id: StandardParameter5.BodyAngleZ,
3391
4424
  description: "Body tilt, degrees (-10 .. 10); positive tilts the top toward the viewer's right (clockwise), as AngleZ does the head."
3392
4425
  },
3393
4426
  {
3394
- id: StandardParameter4.Breath,
4427
+ id: StandardParameter5.Breath,
3395
4428
  description: "Idle breath (0 .. 1), cycled by the host."
3396
4429
  },
3397
4430
  {
3398
- id: StandardParameter4.AmbientSway,
4431
+ id: StandardParameter5.AmbientSway,
3399
4432
  description: "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."
3400
4433
  },
3401
4434
  {
3402
- id: StandardParameter4.BrowLeftY,
4435
+ id: StandardParameter5.BrowLeftY,
3403
4436
  description: "Left brow raise/lower (-1 .. 1)."
3404
4437
  },
3405
4438
  {
3406
- id: StandardParameter4.BrowRightY,
4439
+ id: StandardParameter5.BrowRightY,
3407
4440
  description: "Right brow raise/lower (-1 .. 1)."
3408
4441
  },
3409
4442
  {
3410
- id: StandardParameter4.BrowLeftAngle,
4443
+ id: StandardParameter5.BrowLeftAngle,
3411
4444
  description: "Left brow tilt/angle (-1 .. 1)."
3412
4445
  },
3413
4446
  {
3414
- id: StandardParameter4.BrowRightAngle,
4447
+ id: StandardParameter5.BrowRightAngle,
3415
4448
  description: "Right brow tilt/angle (-1 .. 1)."
3416
4449
  },
3417
4450
  {
3418
- id: StandardParameter4.Cheek,
4451
+ id: StandardParameter5.Cheek,
3419
4452
  description: "Cheek blush strength (0 .. 1), raised by an expression."
3420
4453
  },
3421
4454
  {
3422
- id: StandardParameter4.HairSwayX,
4455
+ id: StandardParameter5.HairSwayX,
3423
4456
  description: "Front hair's horizontal sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
3424
4457
  },
3425
4458
  {
3426
- id: StandardParameter4.HairSwayZ,
4459
+ id: StandardParameter5.HairSwayZ,
3427
4460
  description: "Front hair's sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
3428
4461
  },
3429
4462
  {
3430
- id: StandardParameter4.HairBackSway,
4463
+ id: StandardParameter5.HairBackSway,
3431
4464
  description: "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 \u2014 driven by the spring, hosts should not set it directly."
3432
4465
  },
3433
4466
  {
3434
- id: StandardParameter4.ArmLeft,
4467
+ id: StandardParameter5.ArmLeft,
3435
4468
  description: "Left shoulder, degrees; positive raises the arm outward (mirrored on the right)."
3436
4469
  },
3437
4470
  {
3438
- id: StandardParameter4.ArmRight,
4471
+ id: StandardParameter5.ArmRight,
3439
4472
  description: "Right shoulder, degrees; positive raises the arm outward (mirrored on the left)."
3440
4473
  },
3441
4474
  {
3442
- id: StandardParameter4.ElbowLeft,
4475
+ id: StandardParameter5.ElbowLeft,
3443
4476
  description: "Left elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the right)."
3444
4477
  },
3445
4478
  {
3446
- id: StandardParameter4.ElbowRight,
4479
+ id: StandardParameter5.ElbowRight,
3447
4480
  description: "Right elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the left)."
3448
4481
  },
3449
4482
  {
3450
- id: StandardParameter4.ArmPoseLeft,
4483
+ id: StandardParameter5.ArmPoseLeft,
3451
4484
  description: "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."
3452
4485
  },
3453
4486
  {
3454
- id: StandardParameter4.ArmPoseRight,
4487
+ id: StandardParameter5.ArmPoseRight,
3455
4488
  description: "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."
3456
4489
  },
3457
4490
  {
3458
- id: StandardParameter4.ArmPoseAngleLeft,
4491
+ id: StandardParameter5.ArmPoseAngleLeft,
3459
4492
  description: "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)."
3460
4493
  },
3461
4494
  {
3462
- id: StandardParameter4.ArmPoseAngleRight,
4495
+ id: StandardParameter5.ArmPoseAngleRight,
3463
4496
  description: "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)."
3464
4497
  }
3465
4498
  ];
@@ -3516,9 +4549,20 @@ async function autoRigFromLayers(input) {
3516
4549
  if (!Array.isArray(layers) || layers.length === 0) {
3517
4550
  throw new AutoRigInputError("layers must be a non-empty array");
3518
4551
  }
3519
- if (layers.length > MAX_LAYERS) {
4552
+ const customInputs = input.customParts;
4553
+ if (customInputs !== void 0 && !Array.isArray(customInputs)) {
4554
+ throw new AutoRigInputError("customParts must be an array");
4555
+ }
4556
+ const customEntries = customInputs ?? [];
4557
+ customEntries.forEach((entry, i) => {
4558
+ const at = `customParts[${i}]`;
4559
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
4560
+ throw new AutoRigInputError(`${at} must be a plain object`);
4561
+ }
4562
+ });
4563
+ if (layers.length + customEntries.length > MAX_LAYERS) {
3520
4564
  throw new AutoRigInputError(
3521
- `too many layers: ${layers.length} > ${MAX_LAYERS}`
4565
+ `too many layers: ${layers.length + customEntries.length} > ${MAX_LAYERS}`
3522
4566
  );
3523
4567
  }
3524
4568
  const outPath = resolveOutputPath(
@@ -3548,6 +4592,9 @@ async function autoRigFromLayers(input) {
3548
4592
  const resolved = resolveInputPath(layer.path);
3549
4593
  return { resolved, fileName: layer.fileName ?? path5.basename(resolved) };
3550
4594
  });
4595
+ const customPaths = customEntries.map(
4596
+ (entry, i) => resolveInputPath(entry.path, `customParts[${i}].path`)
4597
+ );
3551
4598
  const rolePairs = expectInput(
3552
4599
  "role parsing",
3553
4600
  () => parseLayerRoles(resolvedLayers.map((r) => r.fileName))
@@ -3558,6 +4605,10 @@ async function autoRigFromLayers(input) {
3558
4605
  let totalPixels = 0;
3559
4606
  let measurer;
3560
4607
  const crops = [];
4608
+ const paints = /* @__PURE__ */ new Map();
4609
+ const anchorRoles = new Set(
4610
+ customEntries.flatMap((e) => [e.anchor, ...e.occlusion?.by ?? []])
4611
+ );
3561
4612
  for (let i = 0; i < resolvedLayers.length; i++) {
3562
4613
  const { resolved, fileName } = resolvedLayers[i];
3563
4614
  const png = await decodePng(resolved);
@@ -3597,9 +4648,48 @@ async function autoRigFromLayers(input) {
3597
4648
  );
3598
4649
  }
3599
4650
  const { bbox } = layer;
4651
+ if (anchorRoles.has(role)) paints.set(role, paintRuns(png));
3600
4652
  const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);
3601
4653
  crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
3602
4654
  }
4655
+ const customLayers = [];
4656
+ const customCrops = [];
4657
+ for (let i = 0; i < customEntries.length; i++) {
4658
+ const at = `customParts[${i}]`;
4659
+ const { id } = customEntries[i];
4660
+ const resolved = customPaths[i];
4661
+ const png = await decodePng(resolved);
4662
+ if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {
4663
+ throw new AutoRigInputError(
4664
+ `${at}.path ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`
4665
+ );
4666
+ }
4667
+ totalPixels += png.width * png.height;
4668
+ if (totalPixels > MAX_TOTAL_PIXELS) {
4669
+ throw new AutoRigInputError(
4670
+ `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`
4671
+ );
4672
+ }
4673
+ if (png.width !== canvasW || png.height !== canvasH) {
4674
+ throw new AutoRigInputError(
4675
+ `${at}.path size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
4676
+ );
4677
+ }
4678
+ const bbox = detectAlphaBbox2(png.rgba, png.width, png.height);
4679
+ if (bbox === null) {
4680
+ throw new AutoRigInputError(
4681
+ `${at}.path "${path5.basename(resolved)}": layer is empty after alpha threshold`
4682
+ );
4683
+ }
4684
+ customLayers.push({ fileName: path5.basename(resolved), bbox });
4685
+ paints.set(id, paintRuns(png));
4686
+ customCrops.push({
4687
+ id,
4688
+ buffer: await cropToBuffer(png.rgba, png.width, png.height, bbox),
4689
+ width: bbox.w,
4690
+ height: bbox.h
4691
+ });
4692
+ }
3603
4693
  const measurement = measurer.finish();
3604
4694
  const { headHalfWidth, headHalfWidthApplied, turnOptions } = measurement;
3605
4695
  const { headEdges, strandEdges } = turnOptions;
@@ -3609,6 +4699,7 @@ async function autoRigFromLayers(input) {
3609
4699
  let turn;
3610
4700
  let patches;
3611
4701
  let rigPlan;
4702
+ let bakeReports;
3612
4703
  let model;
3613
4704
  try {
3614
4705
  model = generateIkiFromLayerSet(
@@ -3633,11 +4724,25 @@ async function autoRigFromLayers(input) {
3633
4724
  }
3634
4725
  },
3635
4726
  ...headEdges === void 0 ? {} : { headEdges },
3636
- ...strandEdges === void 0 ? {} : { strandEdges }
4727
+ ...strandEdges === void 0 ? {} : { strandEdges },
4728
+ ...input.customParts === void 0 ? {} : {
4729
+ customParts: customEntries.map(
4730
+ ({ path: _path, ...rest }, i) => ({
4731
+ ...rest,
4732
+ layer: customLayers[i]
4733
+ })
4734
+ )
4735
+ },
4736
+ ...input.bakes === void 0 ? {} : {
4737
+ bakes: input.bakes,
4738
+ onBakesApplied: (reports) => {
4739
+ bakeReports = reports;
4740
+ }
4741
+ }
3637
4742
  }
3638
4743
  );
3639
4744
  } catch (e) {
3640
- if (!(e instanceof TurnTargetError || e instanceof LayerGeometryError || e instanceof PatchError || e instanceof RigPlanError)) {
4745
+ if (!(e instanceof TurnTargetError || e instanceof LayerGeometryError || e instanceof PatchError || e instanceof RigPlanError || e instanceof CustomPartError || e instanceof BakeError)) {
3641
4746
  throw e;
3642
4747
  }
3643
4748
  throw new AutoRigInputError(e.message);
@@ -3651,7 +4756,9 @@ async function autoRigFromLayers(input) {
3651
4756
  ),
3652
4757
  await renderAtlasPage([losslessCrop], void 0)
3653
4758
  ];
3654
- const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);
4759
+ const customPage = customCrops.length === 0 ? void 0 : await renderAtlasPage(customCrops, quantizeColors);
4760
+ const allPages = customPage === void 0 ? pages : [...pages, customPage];
4761
+ const atlasBytes = allPages.reduce((sum, p) => sum + p.dataUri.length, 0);
3655
4762
  if (atlasBytes > MAX_OUTPUT_BYTES) {
3656
4763
  throw new AutoRigInputError(
3657
4764
  `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`
@@ -3667,25 +4774,65 @@ async function autoRigFromLayers(input) {
3667
4774
  width: layout.pageWidth,
3668
4775
  height: layout.pageHeight
3669
4776
  });
3670
- return partIdsOfRole(crop.id).map((partId) => ({ partId, uv }));
4777
+ return partIdsOfRole2(crop.id).map((partId) => ({ partId, uv }));
3671
4778
  })
3672
4779
  );
4780
+ if (customPage !== void 0) {
4781
+ partTextureAssignments.push(
4782
+ ...customPage.crops.map((crop) => {
4783
+ const placement3 = customPage.layout.placements.find(
4784
+ (p) => p.id === crop.id
4785
+ );
4786
+ return {
4787
+ partId: crop.id,
4788
+ uv: uvRectFor(placement3, {
4789
+ width: customPage.layout.pageWidth,
4790
+ height: customPage.layout.pageHeight
4791
+ })
4792
+ };
4793
+ })
4794
+ );
4795
+ }
3673
4796
  doc.applyAtlas({
3674
4797
  textures: [{ source: pages[0].dataUri }],
3675
4798
  partTextureAssignments
3676
4799
  });
3677
4800
  let patched = doc.getModel();
3678
- if (losslessCrop !== void 0) {
4801
+ if (losslessCrop !== void 0 || customPage !== void 0) {
3679
4802
  patched = structuredClone(patched);
3680
- patched.textures = pages.map((p) => ({ source: p.dataUri }));
3681
- for (const partId of partIdsOfRole(losslessCrop.id)) {
3682
- patched.parts.find((p) => p.id === partId).texture.index = 1;
4803
+ patched.textures = allPages.map((p) => ({ source: p.dataUri }));
4804
+ if (losslessCrop !== void 0) {
4805
+ for (const partId of partIdsOfRole2(losslessCrop.id)) {
4806
+ patched.parts.find((p) => p.id === partId).texture.index = 1;
4807
+ }
4808
+ }
4809
+ for (const crop of customCrops) {
4810
+ patched.parts.find((p) => p.id === crop.id).texture.index = pages.length;
3683
4811
  }
3684
4812
  }
3685
4813
  const finalModel = parseIkiModel(patched);
4814
+ const bakes = bakeReports === void 0 ? void 0 : checkBakes(finalModel, bakeReports);
3686
4815
  writeFileAtomic(outPath, JSON.stringify(finalModel));
3687
4816
  const folds = checkModelFolds(finalModel);
3688
4817
  const physics = checkPhysics(finalModel);
4818
+ let gate;
4819
+ if (input.customParts !== void 0) {
4820
+ try {
4821
+ gate = checkCustomGate(
4822
+ finalModel,
4823
+ customEntries.map(({ id, anchor, tie, rigid, occlusion }) => ({
4824
+ id,
4825
+ anchor,
4826
+ tie,
4827
+ ...rigid === void 0 ? {} : { rigid },
4828
+ ...occlusion === void 0 ? {} : { occludedBy: occlusion.by }
4829
+ })),
4830
+ paints
4831
+ );
4832
+ } catch (e) {
4833
+ gate = failedCustomGate(finalModel, e);
4834
+ }
4835
+ }
3689
4836
  return {
3690
4837
  ok: true,
3691
4838
  path: outPath,
@@ -3701,7 +4848,27 @@ async function autoRigFromLayers(input) {
3701
4848
  folds,
3702
4849
  physics,
3703
4850
  ...patches === void 0 ? {} : { patches },
3704
- rigPlan
4851
+ rigPlan,
4852
+ ...input.customParts === void 0 ? {} : {
4853
+ customParts: {
4854
+ parts: customCrops.map((crop, i) => {
4855
+ const part = finalModel.parts.find((p) => p.id === crop.id);
4856
+ return {
4857
+ id: crop.id,
4858
+ box: customLayers[i].bbox,
4859
+ mesh: {
4860
+ vertices: part.mesh.vertices.length / 2,
4861
+ triangles: part.mesh.indices.length / 3
4862
+ },
4863
+ order: part.order,
4864
+ page: part.texture.index,
4865
+ ...part.occlusion === void 0 ? {} : { occlusion: part.occlusion }
4866
+ };
4867
+ }),
4868
+ ...bakes === void 0 ? {} : { bakes },
4869
+ gate
4870
+ }
4871
+ }
3705
4872
  };
3706
4873
  } catch (err) {
3707
4874
  if (err instanceof AutoRigInputError)
@@ -4166,7 +5333,7 @@ function covers(runs, x) {
4166
5333
  }
4167
5334
  return false;
4168
5335
  }
4169
- function runsAt(layer, y) {
5336
+ function runsAt2(layer, y) {
4170
5337
  return layer?.rowRuns?.[y - layer.bbox.y] ?? [];
4171
5338
  }
4172
5339
  function opaqueRows(layer) {
@@ -4242,8 +5409,8 @@ async function hairSideWarnings(absDir, layers) {
4242
5409
  function rootWarning(role, lock, front) {
4243
5410
  const y = opaqueRows(lock)?.top;
4244
5411
  if (y === void 0) return void 0;
4245
- const frontRuns = runsAt(front, y);
4246
- const lockRuns = runsAt(lock, y);
5412
+ const frontRuns = runsAt2(front, y);
5413
+ const lockRuns = runsAt2(lock, y);
4247
5414
  let shown = 0;
4248
5415
  for (let i = 0; i + 1 < lockRuns.length; i += 2) {
4249
5416
  let stretch = 0;
@@ -4262,7 +5429,7 @@ function rootWarning(role, lock, front) {
4262
5429
  function eyeCornerWarning(role, lock, side, eyeRole, eye) {
4263
5430
  const row = Math.floor(eye.bboxCy);
4264
5431
  const corner = side < 0 ? eye.marginLeft : eye.marginLeft + eye.w - 1;
4265
- const runs = runsAt(lock, row);
5432
+ const runs = runsAt2(lock, row);
4266
5433
  let overlap = 0;
4267
5434
  for (let i = 0; i + 1 < runs.length; i += 2) {
4268
5435
  if (corner < runs[i] || corner >= runs[i + 1]) continue;
@@ -4281,14 +5448,14 @@ function leanWarning(role, lock, side, face, back, eye) {
4281
5448
  const bare = /* @__PURE__ */ new Set();
4282
5449
  const rows = /* @__PURE__ */ new Set();
4283
5450
  for (let y = lockRows.top; y <= Math.min(lockRows.bottom, faceBottom); y++) {
4284
- const runs = runsAt(lock, y);
5451
+ const runs = runsAt2(lock, y);
4285
5452
  if (runs.length === 0) continue;
4286
5453
  const from = side < 0 ? runs[0] : runs[runs.length - 2];
4287
5454
  const to = side < 0 ? runs[1] : runs[runs.length - 1];
4288
5455
  const start = side < 0 ? from : Math.max(from, to - lean);
4289
5456
  const end = side < 0 ? Math.min(to, from + lean) : to;
4290
- const faceRuns = runsAt(face, y);
4291
- const backRuns = runsAt(back, y);
5457
+ const faceRuns = runsAt2(face, y);
5458
+ const backRuns = runsAt2(back, y);
4292
5459
  for (let x = start; x < end; x++) {
4293
5460
  if (covers(faceRuns, x) || covers(backRuns, x)) continue;
4294
5461
  bare.add(x);
@@ -6682,8 +7849,21 @@ function formatPatchReports(reports) {
6682
7849
  return `PATCH ${r.index} ${r.target} at ${at}: ${r.moved} of ${r.of} points (${where}), largest move ${r.maxPx} model px`;
6683
7850
  });
6684
7851
  }
7852
+ function formatCustomPartReports(parts) {
7853
+ return parts.map((p) => {
7854
+ 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}`;
7855
+ if (p.occlusion === void 0) return line;
7856
+ const { by, parameter, stops } = p.occlusion;
7857
+ return `${line}, hidden by ${by.join(",")} on ${parameter} at ${stops.map((s) => `${s.value}:${s.amount}`).join(" ")}`;
7858
+ });
7859
+ }
7860
+ function formatBakeChecks(bakes) {
7861
+ return bakes.map(
7862
+ (b) => `BAKE ${b.part} ${b.param}: ${b.vertices} vertices, stops ${b.stops.join(",")}, error ${Math.round(b.errorPx * 1e3) / 1e3} px`
7863
+ );
7864
+ }
6685
7865
  function createIkiMcpServer() {
6686
- const server = new McpServer({ name: "iki", version: "0.33.1" });
7866
+ const server = new McpServer({ name: "iki", version: "0.35.0" });
6687
7867
  server.registerTool(
6688
7868
  "validate_iki",
6689
7869
  {
@@ -6775,7 +7955,7 @@ function createIkiMcpServer() {
6775
7955
  server.registerTool(
6776
7956
  "auto_rig_from_layers",
6777
7957
  {
6778
- description: "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 \u2014 a spring's, or each chain segment's \u2014 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 \u2014 `PATCH <i> <target> at <Param=v \u2026>: <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 \u2014 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]\u2026` and nothing is written; an op with a missing field or a field of the wrong type is the SDK's input validation error.",
7958
+ description: "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 \u2014 a spring's, or each chain segment's \u2014 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 \u2014 `PATCH <i> <target> at <Param=v \u2026>: <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 \u2014 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]\u2026` 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]\u2026`); its `CUSTOM <id>:` line then ends `, hidden by <id>,<id>\u2026 on <parameter> at <value>:<amount> <value>:<amount>\u2026`, 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>: \u2026` 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>: \u2026`, and a part the bake moves at rest as `INVALID: BAKE ERROR <part> at rest: \u2026`, 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: \u2026` then `CUSTOM GATE pass` or `CUSTOM GATE FAIL: <part LINE, \u2026>`, 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]\u2026` 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.",
6779
7959
  inputSchema: {
6780
7960
  layers: z.array(
6781
7961
  z.object({
@@ -6798,7 +7978,7 @@ function createIkiMcpServer() {
6798
7978
  noseShift: z.number().optional(),
6799
7979
  mouthShift: z.number().optional()
6800
7980
  }).passthrough().optional().describe(
6801
- "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 \u2014 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 \u2014 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: \u2026` 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."
7981
+ "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 \u2014 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 \u2014 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: \u2026` 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."
6802
7982
  ),
6803
7983
  style: z.unknown().optional().describe(
6804
7984
  "Removed in @ikijs/mcp 0.30.0: pass `rigPlan`. Any value here is refused with the field map."
@@ -6819,6 +7999,83 @@ function createIkiMcpServer() {
6819
7999
  }).passthrough().optional().describe(
6820
8000
  "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), `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> \u2026`; an object left out or `{}` is the profile. The result reports what the rig built with as `rigPlan` and a `RIGPLAN:` line."
6821
8001
  ),
8002
+ customParts: z.array(
8003
+ z.object({
8004
+ id: z.string().describe(
8005
+ "The part's id: a plain identifier, not a role's name or a part id."
8006
+ ),
8007
+ path: z.string().describe(
8008
+ "The part's own PNG, the same size as the role layers (resolved against cwd), drawn alone and whole on a transparent ground."
8009
+ ),
8010
+ anchor: z.string().describe("The role whose layer the part is fixed against."),
8011
+ tie: z.array(z.number()).length(2).describe(
8012
+ "[x, y] in canvas px where the part meets the anchor: inside both the part's alpha box and the anchor layer's."
8013
+ ),
8014
+ after: z.string().describe(
8015
+ "A role of the set: the part is drawn right after that role's last part."
8016
+ ),
8017
+ deformer: z.string().optional().describe(
8018
+ "The matrix deformer it hangs on; only `headDeformer` (the default) is accepted."
8019
+ ),
8020
+ rigid: z.boolean().optional().describe(
8021
+ "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\u2026` with nothing written. Give a rigid part one displacement for every control point, or a rotation."
8022
+ ),
8023
+ occlusion: z.object({
8024
+ by: z.array(z.string()).describe(
8025
+ "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."
8026
+ ),
8027
+ parameter: z.string().describe(
8028
+ "Any declared parameter but a physics output (a spring's or a chain segment's)."
8029
+ ),
8030
+ stops: z.array(
8031
+ z.object({
8032
+ value: z.number(),
8033
+ amount: z.number().describe(
8034
+ "0 to 1: 1 hides the part wherever the roles' paint lies over it."
8035
+ )
8036
+ }).passthrough()
8037
+ ).describe(
8038
+ "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."
8039
+ )
8040
+ }).passthrough().optional().describe(
8041
+ "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 past the idle sway, 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]\u2026`). An unknown key, a bad stop or a part the key cannot be written for comes back as `INVALID: customParts[i].occlusion\u2026` with nothing written."
8042
+ )
8043
+ }).passthrough()
8044
+ ).optional().describe(
8045
+ "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]\u2026` 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."
8046
+ ),
8047
+ bakes: z.object({
8048
+ targets: z.array(
8049
+ z.object({
8050
+ id: z.string().optional(),
8051
+ param: z.string(),
8052
+ parts: z.array(z.string()),
8053
+ box: z.object({
8054
+ x: z.number(),
8055
+ y: z.number(),
8056
+ w: z.number(),
8057
+ h: z.number()
8058
+ }).passthrough().optional(),
8059
+ grid: z.object({ cols: z.number(), rows: z.number() }).passthrough(),
8060
+ stops: z.record(
8061
+ z.string(),
8062
+ z.array(z.array(z.number()).length(2))
8063
+ ),
8064
+ mirror: z.boolean().optional(),
8065
+ why: z.string().optional()
8066
+ }).passthrough()
8067
+ ),
8068
+ meshes: z.record(
8069
+ z.string(),
8070
+ z.object({
8071
+ rows: z.array(z.number()).optional(),
8072
+ cols: z.number().optional(),
8073
+ cellPx: z.number().optional()
8074
+ }).passthrough()
8075
+ ).optional()
8076
+ }).passthrough().optional().describe(
8077
+ "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], \u2026 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\xB0: 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, \u2026], 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\u2026` (`bakes.targets[2].stops[\"30\"][7]\u2026`) 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."
8078
+ ),
6822
8079
  patches: z.array(
6823
8080
  z.object({
6824
8081
  target: z.string(),
@@ -6845,7 +8102,11 @@ function createIkiMcpServer() {
6845
8102
  ...args,
6846
8103
  // `.length(2)` makes each region span a pair, which its inferred
6847
8104
  // `number[]` cannot say.
6848
- patches: args.patches
8105
+ patches: args.patches,
8106
+ customParts: args.customParts,
8107
+ // Each stop's `.length(2)` makes it a pair, which its inferred
8108
+ // `number[]` cannot say.
8109
+ bakes: args.bakes
6849
8110
  });
6850
8111
  const text = r.ok ? [
6851
8112
  r.path,
@@ -6853,7 +8114,10 @@ function createIkiMcpServer() {
6853
8114
  ...formatPatchReports(r.patches ?? []),
6854
8115
  ...formatFoldReport(r.folds, r.canvas),
6855
8116
  ...formatPhysicsReport(r.physics),
6856
- ...formatHairSideReport(r.turn?.hairSide, r.canvas)
8117
+ ...formatHairSideReport(r.turn?.hairSide, r.canvas),
8118
+ ...formatCustomPartReports(r.customParts?.parts ?? []),
8119
+ ...formatBakeChecks(r.customParts?.bakes ?? []),
8120
+ ...r.customParts ? formatCustomGate(r.customParts.gate) : []
6857
8121
  ].join("\n") : `INVALID: ${r.error}`;
6858
8122
  return { content: [{ type: "text", text }], structuredContent: r };
6859
8123
  } catch (err) {
@@ -6945,7 +8209,7 @@ function createIkiMcpServer() {
6945
8209
  server.registerTool(
6946
8210
  "measure_turn_reference",
6947
8211
  {
6948
- description: "Measures how far a head turns between two images of the same character \u2014 a front view and a turned one, at the SAME scale \u2014 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.",
8212
+ description: "Measures how far a head turns between two images of the same character \u2014 a front view and a turned one, at the SAME scale \u2014 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.",
6949
8213
  inputSchema: {
6950
8214
  front: z.string().describe("Front-facing PNG file path (resolved against cwd)."),
6951
8215
  turned: z.string().describe("The same character turned, as a PNG file path."),
@@ -7028,7 +8292,10 @@ function createIkiMcpServer() {
7028
8292
  }).optional()
7029
8293
  })
7030
8294
  ).optional().describe(
7031
- "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. `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`."
8295
+ "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."
8296
+ ),
8297
+ hideParts: z.array(z.string()).optional().describe(
8298
+ "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] \u2026` and nothing is rendered. Needs @ikijs/mcp 0.34.0; an older server drops the field and draws every part."
7032
8299
  )
7033
8300
  }
7034
8301
  },
@@ -7064,12 +8331,65 @@ function createIkiMcpServer() {
7064
8331
  }
7065
8332
  }
7066
8333
  );
8334
+ server.registerTool(
8335
+ "probe_rig",
8336
+ {
8337
+ description: "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 \u2014 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> \u2026`, any refusal writes nothing.",
8338
+ inputSchema: {
8339
+ modelPath: z.string().describe(
8340
+ "Rigged .iki file path (resolved against cwd; must sit under the working directory)."
8341
+ ),
8342
+ queries: z.array(
8343
+ z.discriminatedUnion("op", [
8344
+ z.object({
8345
+ op: z.literal("paint"),
8346
+ path: z.string().describe(
8347
+ "Canvas-sized layer PNG (resolved against cwd), the drawing the part was built from."
8348
+ )
8349
+ }),
8350
+ z.object({
8351
+ op: z.enum(["land", "displacement"]),
8352
+ part: z.string().describe("A part id of the model."),
8353
+ points: z.array(z.array(z.number()).length(2)).describe(
8354
+ "Canvas-px points `[x, y]`, at most 5000, each on the part at rest."
8355
+ ),
8356
+ pose: z.record(z.string(), z.number()).optional().describe(
8357
+ "Parameter id to value; the others stay at their defaults."
8358
+ )
8359
+ })
8360
+ ])
8361
+ ).describe("The queries, answered in order; at most 64 per call."),
8362
+ outputPath: z.string().optional().describe(
8363
+ "A path ending in `.probe.json` (resolved against cwd, under it; its folder must exist) to write the results to."
8364
+ )
8365
+ }
8366
+ },
8367
+ async (args) => {
8368
+ try {
8369
+ const r = await probeRig(args);
8370
+ const text = !r.ok ? `INVALID: ${r.error}` : "results" in r ? JSON.stringify(r.results) : [r.outputPath, ...r.lines].join("\n");
8371
+ return { content: [{ type: "text", text }], structuredContent: r };
8372
+ } catch (err) {
8373
+ const error = err instanceof Error ? err.message : String(err);
8374
+ return {
8375
+ content: [{ type: "text", text: `Unexpected error: ${error}` }],
8376
+ structuredContent: { ok: false, error },
8377
+ isError: true
8378
+ };
8379
+ }
8380
+ }
8381
+ );
7067
8382
  return server;
7068
8383
  }
7069
8384
 
7070
8385
  export {
7071
8386
  checkModelFolds,
7072
8387
  formatFoldReport,
8388
+ probeRig,
8389
+ CUSTOM_GATE_LIMITS,
8390
+ failedCustomGate,
8391
+ checkCustomGate,
8392
+ formatCustomGate,
7073
8393
  checkNod,
7074
8394
  checkSweep,
7075
8395
  formatSweepReport,
@@ -7092,4 +8412,4 @@ export {
7092
8412
  formatPhysicsReport,
7093
8413
  createIkiMcpServer
7094
8414
  };
7095
- //# sourceMappingURL=chunk-VTJEYDRK.mjs.map
8415
+ //# sourceMappingURL=chunk-SNBG5VHS.mjs.map