@ikijs/mcp 0.33.1 → 0.34.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.
@@ -1728,6 +1728,989 @@ function ratioText(ratio) {
1728
1728
  return Math.abs(ratio) < 0.01 ? ratio.toExponential(1) : ratio.toFixed(2);
1729
1729
  }
1730
1730
 
1731
+ // src/probe.ts
1732
+ import { readFileSync } from "fs";
1733
+ import { IkiFormatError, loadIkiModel } from "@ikijs/format";
1734
+
1735
+ // src/limits.ts
1736
+ import fs from "fs";
1737
+ import path from "path";
1738
+ var MAX_LAYERS = 64;
1739
+ var MAX_LAYER_DIM = 4096;
1740
+ var MAX_CANVAS_DIM = 4096;
1741
+ var MAX_ATLAS_SIDE = 4096;
1742
+ var MAX_INPUT_PIXELS = 4096 * 4096;
1743
+ var MAX_TOTAL_PIXELS = 128 * 1024 * 1024;
1744
+ var MAX_OUTPUT_BYTES = 12 * 1024 * 1024;
1745
+ var MAX_PROBE_QUERIES = 64;
1746
+ var MAX_PROBE_POINTS = 5e3;
1747
+ var AutoRigInputError = class extends Error {
1748
+ constructor(message) {
1749
+ super(message);
1750
+ this.name = "AutoRigInputError";
1751
+ }
1752
+ };
1753
+ function rejectEmptyOrUrl(inputPath, noun, kind) {
1754
+ if (typeof inputPath !== "string" || inputPath.trim() === "") {
1755
+ throw new AutoRigInputError(`${noun} is empty`);
1756
+ }
1757
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(inputPath)) {
1758
+ throw new AutoRigInputError(
1759
+ `${noun} must be a ${kind}, not a URL: ${inputPath}`
1760
+ );
1761
+ }
1762
+ }
1763
+ function resolveInputPath(inputPath, what = "layer") {
1764
+ rejectEmptyOrUrl(inputPath, `${what} path`, "file path");
1765
+ const resolved = path.resolve(process.cwd(), inputPath);
1766
+ let stat;
1767
+ try {
1768
+ stat = fs.statSync(resolved);
1769
+ } catch {
1770
+ throw new AutoRigInputError(`${what} file not found: ${resolved}`);
1771
+ }
1772
+ if (stat.isDirectory()) {
1773
+ throw new AutoRigInputError(
1774
+ `${what} path is a directory, not a file: ${resolved}`
1775
+ );
1776
+ }
1777
+ return resolved;
1778
+ }
1779
+ function resolveInputDir(dirPath) {
1780
+ rejectEmptyOrUrl(dirPath, "layers dir", "directory path");
1781
+ const resolved = path.resolve(process.cwd(), dirPath);
1782
+ let stat;
1783
+ try {
1784
+ stat = fs.statSync(resolved);
1785
+ } catch {
1786
+ throw new AutoRigInputError(`layers dir not found: ${resolved}`);
1787
+ }
1788
+ if (!stat.isDirectory()) {
1789
+ throw new AutoRigInputError(`layers path is not a directory: ${resolved}`);
1790
+ }
1791
+ return resolved;
1792
+ }
1793
+ function confineToWorkingDirectory(root, dir, label, original) {
1794
+ const realRoot = fs.realpathSync(root);
1795
+ const realDir = fs.realpathSync(dir);
1796
+ if (realDir !== realRoot && !realDir.startsWith(realRoot + path.sep)) {
1797
+ throw new AutoRigInputError(
1798
+ `${label} escapes the working directory: ${original}`
1799
+ );
1800
+ }
1801
+ return realDir;
1802
+ }
1803
+ function resolveOutputPath(outputPath, extension = ".iki") {
1804
+ if (typeof outputPath !== "string" || outputPath.trim() === "") {
1805
+ throw new AutoRigInputError("output path is empty");
1806
+ }
1807
+ if (!outputPath.toLowerCase().endsWith(extension)) {
1808
+ throw new AutoRigInputError(
1809
+ `output path must end in ${extension}: ${outputPath}`
1810
+ );
1811
+ }
1812
+ const root = process.cwd();
1813
+ const resolved = path.resolve(root, outputPath);
1814
+ const dir = path.dirname(resolved);
1815
+ let stat;
1816
+ try {
1817
+ stat = fs.statSync(dir);
1818
+ } catch {
1819
+ throw new AutoRigInputError(`output directory does not exist: ${dir}`);
1820
+ }
1821
+ if (!stat.isDirectory()) {
1822
+ throw new AutoRigInputError(`output parent is not a directory: ${dir}`);
1823
+ }
1824
+ const realDir = confineToWorkingDirectory(
1825
+ root,
1826
+ dir,
1827
+ "output path",
1828
+ outputPath
1829
+ );
1830
+ return path.join(realDir, path.basename(resolved));
1831
+ }
1832
+ function resolveOutputDir(dirPath) {
1833
+ if (typeof dirPath !== "string" || dirPath.trim() === "") {
1834
+ throw new AutoRigInputError("output dir is empty");
1835
+ }
1836
+ const root = process.cwd();
1837
+ const resolved = path.resolve(root, dirPath);
1838
+ let stat;
1839
+ try {
1840
+ stat = fs.statSync(resolved);
1841
+ } catch {
1842
+ throw new AutoRigInputError(`output dir not found: ${resolved}`);
1843
+ }
1844
+ if (!stat.isDirectory()) {
1845
+ throw new AutoRigInputError(`output dir is not a directory: ${resolved}`);
1846
+ }
1847
+ return confineToWorkingDirectory(root, resolved, "output dir", dirPath);
1848
+ }
1849
+ function writeFileAtomic(outPath, data) {
1850
+ const tmp = `${outPath}.${process.pid}.${Date.now()}.tmp`;
1851
+ try {
1852
+ fs.writeFileSync(tmp, data);
1853
+ try {
1854
+ fs.renameSync(tmp, outPath);
1855
+ } catch (e) {
1856
+ try {
1857
+ fs.rmSync(tmp, { force: true });
1858
+ } catch {
1859
+ }
1860
+ throw e;
1861
+ }
1862
+ } catch (e) {
1863
+ throw new AutoRigInputError(
1864
+ `write: ${e instanceof Error ? e.message : String(e)}`
1865
+ );
1866
+ }
1867
+ }
1868
+
1869
+ // src/node-images.ts
1870
+ import sharp from "sharp";
1871
+ import { detectAlphaBbox as scanAlphaBbox } from "@ikijs/editor";
1872
+ async function decodePng(filePath) {
1873
+ try {
1874
+ const pipeline = sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS });
1875
+ const metadata = await pipeline.metadata();
1876
+ if (metadata.format !== "png") {
1877
+ throw new AutoRigInputError(
1878
+ `non-PNG image (${metadata.format ?? "unknown"}): ${filePath}`
1879
+ );
1880
+ }
1881
+ const { data, info } = await pipeline.ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1882
+ return {
1883
+ width: info.width,
1884
+ height: info.height,
1885
+ rgba: data,
1886
+ hasAlpha: metadata.hasAlpha ?? false
1887
+ };
1888
+ } catch (e) {
1889
+ if (e instanceof AutoRigInputError) throw e;
1890
+ const msg = e instanceof Error ? e.message : String(e);
1891
+ throw new AutoRigInputError(`failed to decode PNG ${filePath}: ${msg}`);
1892
+ }
1893
+ }
1894
+ function detectAlphaBbox(rgba, width, height) {
1895
+ const bbox = scanAlphaBbox(rgba, width, height);
1896
+ if (bbox === null) {
1897
+ throw new AutoRigInputError("layer is empty after alpha threshold");
1898
+ }
1899
+ return bbox;
1900
+ }
1901
+ function cropToBuffer(rgba, width, height, bbox) {
1902
+ return sharp(rgba, { raw: { width, height, channels: 4 } }).extract({ left: bbox.x, top: bbox.y, width: bbox.w, height: bbox.h }).png().toBuffer();
1903
+ }
1904
+ function encodeOverlayPng(filePath, svg) {
1905
+ return sharp(filePath, { limitInputPixels: MAX_INPUT_PIXELS }).composite([{ input: Buffer.from(svg) }]).png().toBuffer();
1906
+ }
1907
+ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
1908
+ const byId = /* @__PURE__ */ new Map();
1909
+ for (const crop of crops) byId.set(crop.id, crop);
1910
+ const pad = layout.padding;
1911
+ const composites = await Promise.all(
1912
+ layout.placements.map(async (placement3) => {
1913
+ const crop = byId.get(placement3.id);
1914
+ if (crop === void 0) {
1915
+ throw new AutoRigInputError(
1916
+ `no crop for atlas placement "${placement3.id}"`
1917
+ );
1918
+ }
1919
+ const input = pad > 0 ? await sharp(crop.buffer).extend({ right: pad, bottom: pad, extendWith: "copy" }).png().toBuffer() : crop.buffer;
1920
+ return { input, left: placement3.x, top: placement3.y };
1921
+ })
1922
+ );
1923
+ const page = await sharp({
1924
+ create: {
1925
+ width: layout.pageWidth,
1926
+ height: layout.pageHeight,
1927
+ channels: 4,
1928
+ background: { r: 0, g: 0, b: 0, alpha: 0 }
1929
+ }
1930
+ }).composite(composites).png(
1931
+ quantizeColors === void 0 ? {} : { palette: true, colours: quantizeColors, dither: 0.5, effort: 10 }
1932
+ ).toBuffer();
1933
+ return `data:image/png;base64,${page.toString("base64")}`;
1934
+ }
1935
+
1936
+ // src/probe.ts
1937
+ var OUTPUT_SUFFIX = ".probe.json";
1938
+ var OPAQUE = 128;
1939
+ function paintRuns(png) {
1940
+ const { width, height, rgba } = png;
1941
+ const rows = [];
1942
+ let y0 = -1;
1943
+ for (let y = 0; y < height; y++) {
1944
+ const runs = [];
1945
+ let start = -1;
1946
+ for (let x = 0; x < width; x++) {
1947
+ const on = rgba[(y * width + x) * 4 + 3] >= OPAQUE;
1948
+ if (on && start < 0) start = x;
1949
+ if (!on && start >= 0) {
1950
+ runs.push([start, x]);
1951
+ start = -1;
1952
+ }
1953
+ }
1954
+ if (start >= 0) runs.push([start, width]);
1955
+ if (runs.length > 0 && y0 < 0) y0 = y;
1956
+ if (y0 >= 0) rows.push(runs);
1957
+ }
1958
+ while (rows.length > 0 && rows[rows.length - 1].length === 0) rows.pop();
1959
+ return rows.length === 0 ? { y0: 0, rows: [] } : { y0, rows };
1960
+ }
1961
+ function toCanvas(model, pts) {
1962
+ const hw = model.canvas.width / 2;
1963
+ const hh = model.canvas.height / 2;
1964
+ const out = new Float64Array(pts.length);
1965
+ for (let i = 0; i < pts.length; i += 2) {
1966
+ out[i] = hw + pts[i];
1967
+ out[i + 1] = hh - pts[i + 1];
1968
+ }
1969
+ return out;
1970
+ }
1971
+ var round = (v) => Math.round(v * 1e3) / 1e3 + 0;
1972
+ function locate(vertices, tri, x, y) {
1973
+ const [a, b, c] = tri;
1974
+ const ax = vertices[a * 2];
1975
+ const ay = vertices[a * 2 + 1];
1976
+ const bx = vertices[b * 2];
1977
+ const by = vertices[b * 2 + 1];
1978
+ const cx = vertices[c * 2];
1979
+ const cy = vertices[c * 2 + 1];
1980
+ const d = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy);
1981
+ if (Math.abs(d) < 1e-12) return null;
1982
+ const l1 = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / d;
1983
+ const l2 = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / d;
1984
+ const l3 = 1 - l1 - l2;
1985
+ const eps = 1e-9;
1986
+ return l1 >= -eps && l2 >= -eps && l3 >= -eps ? [l1, l2, l3] : null;
1987
+ }
1988
+ var QUAD_INDICES = [0, 1, 2, 1, 3, 2];
1989
+ function restMesh(model, cache, partId) {
1990
+ let m = cache.get(partId);
1991
+ if (m) return m;
1992
+ const part = model.parts.find((p) => p.id === partId);
1993
+ const indices = part.mesh ? part.mesh.indices : QUAD_INDICES;
1994
+ const rest = toCanvas(model, landParts(model, {}, [partId]).get(partId));
1995
+ const boxes = new Float64Array(indices.length / 3 * 4);
1996
+ for (let t = 0; t < indices.length / 3; t++) {
1997
+ let x0 = Infinity;
1998
+ let y0 = Infinity;
1999
+ let x1 = -Infinity;
2000
+ let y1 = -Infinity;
2001
+ for (let k = 0; k < 3; k++) {
2002
+ const v = indices[t * 3 + k];
2003
+ x0 = Math.min(x0, rest[v * 2]);
2004
+ x1 = Math.max(x1, rest[v * 2]);
2005
+ y0 = Math.min(y0, rest[v * 2 + 1]);
2006
+ y1 = Math.max(y1, rest[v * 2 + 1]);
2007
+ }
2008
+ boxes.set([x0, y0, x1, y1], t * 4);
2009
+ }
2010
+ m = { indices, rest, boxes };
2011
+ cache.set(partId, m);
2012
+ return m;
2013
+ }
2014
+ function locatePoints(mesh, points) {
2015
+ const { indices, rest, boxes } = mesh;
2016
+ const slack = 1e-6;
2017
+ return points.map(([x, y]) => {
2018
+ for (let t = 0; t < indices.length / 3; t++) {
2019
+ const b = t * 4;
2020
+ if (x < boxes[b] - slack || x > boxes[b + 2] + slack || y < boxes[b + 1] - slack || y > boxes[b + 3] + slack) {
2021
+ continue;
2022
+ }
2023
+ const tri = [
2024
+ indices[t * 3],
2025
+ indices[t * 3 + 1],
2026
+ indices[t * 3 + 2]
2027
+ ];
2028
+ const w = locate(rest, tri, x, y);
2029
+ if (w) return { tri, w };
2030
+ }
2031
+ return null;
2032
+ });
2033
+ }
2034
+ function landLocated(posed, at) {
2035
+ if (at === null) return null;
2036
+ let px2 = 0;
2037
+ let py = 0;
2038
+ for (let k = 0; k < 3; k++) {
2039
+ px2 += at.w[k] * posed[at.tri[k] * 2];
2040
+ py += at.w[k] * posed[at.tri[k] * 2 + 1];
2041
+ }
2042
+ return [px2, py];
2043
+ }
2044
+ function landPoints(model, cache, partId, points, pose) {
2045
+ const located = locatePoints(restMesh(model, cache, partId), points);
2046
+ const posed = toCanvas(model, landParts(model, pose, [partId]).get(partId));
2047
+ return located.map((at) => landLocated(posed, at));
2048
+ }
2049
+ function invalid(i, field, what) {
2050
+ return new AutoRigInputError(`queries[${i}].${field} ${what}`);
2051
+ }
2052
+ function checkPoints(i, points) {
2053
+ if (!Array.isArray(points) || points.length === 0) {
2054
+ throw invalid(i, "points", "must be a non-empty list of [x, y]");
2055
+ }
2056
+ if (points.length > MAX_PROBE_POINTS) {
2057
+ throw invalid(
2058
+ i,
2059
+ "points",
2060
+ `has ${points.length} points; at most ${MAX_PROBE_POINTS} per query`
2061
+ );
2062
+ }
2063
+ points.forEach((pt, k) => {
2064
+ if (!Array.isArray(pt) || pt.length !== 2 || !pt.every((v) => Number.isFinite(v))) {
2065
+ throw invalid(i, `points[${k}]`, "must be [x, y] with finite numbers");
2066
+ }
2067
+ });
2068
+ return points;
2069
+ }
2070
+ function checkPose(model, i, pose) {
2071
+ const declared = new Set(model.parameters.map((p) => p.id));
2072
+ for (const [id, v] of Object.entries(pose ?? {})) {
2073
+ if (!declared.has(id)) {
2074
+ throw invalid(i, `pose.${id}`, "is not a parameter the model declares");
2075
+ }
2076
+ if (typeof v !== "number" || !Number.isFinite(v)) {
2077
+ throw invalid(i, `pose.${id}`, "must be a finite number");
2078
+ }
2079
+ }
2080
+ return pose ?? {};
2081
+ }
2082
+ function checkQuery(model, q, i) {
2083
+ if (q.op === "paint") return { op: "paint", path: q.path };
2084
+ if (q.op !== "land" && q.op !== "displacement") {
2085
+ throw invalid(i, "op", `must be paint, land or displacement`);
2086
+ }
2087
+ if (!model.parts.some((p) => p.id === q.part)) {
2088
+ throw invalid(i, "part", `names no part of the model: ${String(q.part)}`);
2089
+ }
2090
+ return {
2091
+ op: q.op,
2092
+ part: q.part,
2093
+ points: checkPoints(i, q.points),
2094
+ pose: checkPose(model, i, q.pose)
2095
+ };
2096
+ }
2097
+ async function runQuery(model, cache, q, i) {
2098
+ if (q.op === "paint") {
2099
+ const file = resolveInputPath(q.path, `queries[${i}].path`);
2100
+ let png;
2101
+ try {
2102
+ png = await decodePng(file);
2103
+ } catch (e) {
2104
+ if (e instanceof AutoRigInputError) throw invalid(i, "path", e.message);
2105
+ throw e;
2106
+ }
2107
+ const { width, height } = model.canvas;
2108
+ if (png.width !== width || png.height !== height) {
2109
+ throw invalid(
2110
+ i,
2111
+ "path",
2112
+ `is ${png.width}x${png.height}, not the model's canvas ${width}x${height}: ${q.path}`
2113
+ );
2114
+ }
2115
+ return { op: "paint", ...paintRuns(png) };
2116
+ }
2117
+ const { points } = q;
2118
+ const landed = landPoints(model, cache, q.part, points, q.pose);
2119
+ return {
2120
+ op: q.op,
2121
+ part: q.part,
2122
+ points: landed.map(
2123
+ (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])]
2124
+ )
2125
+ };
2126
+ }
2127
+ function summarize(r, i) {
2128
+ if (r.op === "paint") {
2129
+ return `${i} paint: ${r.rows.length} rows from y ${r.y0}`;
2130
+ }
2131
+ const off = r.points.filter((p) => p === null).length;
2132
+ return `${i} ${r.op} ${r.part}: ${r.points.length} points, ${off} off the mesh`;
2133
+ }
2134
+ async function probeRig(input) {
2135
+ try {
2136
+ const outFile = input.outputPath !== void 0 ? resolveOutputPath(input.outputPath, OUTPUT_SUFFIX) : void 0;
2137
+ const modelFile = confineToWorkingDirectory(
2138
+ process.cwd(),
2139
+ resolveInputPath(input.modelPath, "model"),
2140
+ "model path",
2141
+ input.modelPath
2142
+ );
2143
+ const model = loadIkiModel(readFileSync(modelFile, "utf8"));
2144
+ if (!Array.isArray(input.queries) || input.queries.length === 0) {
2145
+ throw new AutoRigInputError("queries must be a non-empty list");
2146
+ }
2147
+ if (input.queries.length > MAX_PROBE_QUERIES) {
2148
+ throw new AutoRigInputError(
2149
+ `queries has ${input.queries.length} entries; at most ${MAX_PROBE_QUERIES} per call`
2150
+ );
2151
+ }
2152
+ const checked = input.queries.map((q, i) => checkQuery(model, q, i));
2153
+ const cache = /* @__PURE__ */ new Map();
2154
+ const results = [];
2155
+ for (const [i, q] of checked.entries()) {
2156
+ results.push(await runQuery(model, cache, q, i));
2157
+ }
2158
+ if (outFile === void 0) return { ok: true, results };
2159
+ writeFileAtomic(outFile, JSON.stringify(results));
2160
+ return {
2161
+ ok: true,
2162
+ outputPath: outFile,
2163
+ lines: results.map(summarize)
2164
+ };
2165
+ } catch (e) {
2166
+ if (e instanceof AutoRigInputError || e instanceof IkiFormatError) {
2167
+ return { ok: false, error: e.message };
2168
+ }
2169
+ throw e;
2170
+ }
2171
+ }
2172
+
2173
+ // src/custom-gate.ts
2174
+ import { partIdsOfRole, rigidResidual } from "@ikijs/editor";
2175
+ import { StandardParameter as StandardParameter3 } from "@ikijs/format";
2176
+ var CUSTOM_GATE_LIMITS = {
2177
+ tie: 5e-3,
2178
+ slide: 0.1,
2179
+ onAnchor: 0.015,
2180
+ exposed: 9e-4,
2181
+ rigid: 25e-4
2182
+ };
2183
+ function foldLimit(model) {
2184
+ return checkFolds(model, { poses: [] }).thresholds.collapse;
2185
+ }
2186
+ function failedCustomGate(model, error) {
2187
+ const message = error instanceof Error ? error.message : String(error);
2188
+ return {
2189
+ ok: false,
2190
+ faceWidth: model.parts.find((p) => p.id === "face")?.width ?? 0,
2191
+ limits: { ...CUSTOM_GATE_LIMITS, fold: foldLimit(model) },
2192
+ poses: 0,
2193
+ parts: [],
2194
+ failed: [`gate error: ${message}`]
2195
+ };
2196
+ }
2197
+ function readingOf(faceWidth, amount, dimension, pose, limit, reason) {
2198
+ const value = amount === null ? null : amount / faceWidth ** dimension;
2199
+ const pass = value !== null && value <= limit;
2200
+ return {
2201
+ value,
2202
+ ...dimension === 1 ? { px: amount } : { px2: amount },
2203
+ pose,
2204
+ limit,
2205
+ pass,
2206
+ ...pass ? {} : { reason }
2207
+ };
2208
+ }
2209
+ var TWIN_FACE = 402;
2210
+ var RING_PX = 5;
2211
+ var RING_DIAGONAL_PX = 4;
2212
+ var SAMPLE_REACH_PX = 80;
2213
+ var SAMPLE_STEP_PX = 4;
2214
+ var TIP_INSET_PX = 6;
2215
+ var EXPOSED_REACH = 0.15;
2216
+ var runsAt = (paint, y) => paint.rows[y - paint.y0] ?? [];
2217
+ function paintedAt(paint, x, y) {
2218
+ const px2 = Math.floor(x);
2219
+ return runsAt(paint, Math.floor(y)).some(([a, b]) => px2 >= a && px2 < b);
2220
+ }
2221
+ var GRID_CELLS = 64;
2222
+ function triangleGrid(posed, indices, bounds) {
2223
+ const cell = Math.max(
2224
+ 16,
2225
+ (bounds.x1 - bounds.x0) / GRID_CELLS,
2226
+ (bounds.y1 - bounds.y0) / GRID_CELLS
2227
+ );
2228
+ const cols = Math.floor((bounds.x1 - bounds.x0) / cell) + 1;
2229
+ const rows = Math.floor((bounds.y1 - bounds.y0) / cell) + 1;
2230
+ const bins = /* @__PURE__ */ new Map();
2231
+ for (let t = 0; t < indices.length / 3; t++) {
2232
+ let x0 = Infinity;
2233
+ let y0 = Infinity;
2234
+ let x1 = -Infinity;
2235
+ let y1 = -Infinity;
2236
+ for (let k = 0; k < 3; k++) {
2237
+ const v = indices[t * 3 + k];
2238
+ x0 = Math.min(x0, posed[v * 2]);
2239
+ x1 = Math.max(x1, posed[v * 2]);
2240
+ y0 = Math.min(y0, posed[v * 2 + 1]);
2241
+ y1 = Math.max(y1, posed[v * 2 + 1]);
2242
+ }
2243
+ if (x1 < bounds.x0 || x0 > bounds.x1 || y1 < bounds.y0 || y0 > bounds.y1) {
2244
+ continue;
2245
+ }
2246
+ const cx0 = Math.max(0, Math.floor((x0 - bounds.x0) / cell));
2247
+ const cx1 = Math.min(cols - 1, Math.floor((x1 - bounds.x0) / cell));
2248
+ const cy0 = Math.max(0, Math.floor((y0 - bounds.y0) / cell));
2249
+ const cy1 = Math.min(rows - 1, Math.floor((y1 - bounds.y0) / cell));
2250
+ for (let cy = cy0; cy <= cy1; cy++) {
2251
+ for (let cx = cx0; cx <= cx1; cx++) {
2252
+ const k = cx + cy * cols;
2253
+ const bin = bins.get(k);
2254
+ if (bin) bin.push(t);
2255
+ else bins.set(k, [t]);
2256
+ }
2257
+ }
2258
+ }
2259
+ return (x, y) => x < bounds.x0 || y < bounds.y0 || x > bounds.x1 || y > bounds.y1 ? [] : bins.get(
2260
+ Math.floor((x - bounds.x0) / cell) + Math.floor((y - bounds.y0) / cell) * cols
2261
+ ) ?? [];
2262
+ }
2263
+ function posesOf(model, baked, base) {
2264
+ const byName = new Map(base.map((p) => [p.name, p]));
2265
+ const add = (values) => {
2266
+ const pose = foldPose(values);
2267
+ if (!byName.has(pose.name)) byName.set(pose.name, pose);
2268
+ };
2269
+ const defaults = new Map(model.parameters.map((p) => [p.id, p.default]));
2270
+ for (const [param, stops] of baked) {
2271
+ for (const v of stops) if (v !== defaults.get(param)) add({ [param]: v });
2272
+ }
2273
+ const params = [...baked.keys()];
2274
+ for (let i = 0; i < params.length; i++) {
2275
+ for (let j = i + 1; j < params.length; j++) {
2276
+ for (const a of baked.get(params[i])) {
2277
+ if (a === defaults.get(params[i])) continue;
2278
+ for (const b of baked.get(params[j])) {
2279
+ if (b === defaults.get(params[j])) continue;
2280
+ add({ [params[i]]: a, [params[j]]: b });
2281
+ }
2282
+ }
2283
+ }
2284
+ }
2285
+ return [...byName.values()];
2286
+ }
2287
+ function freeEnd(paint, tie, inset) {
2288
+ if (paint.rows.length === 0) return null;
2289
+ const [top, bottom] = [paint.y0, paint.y0 + paint.rows.length - 1];
2290
+ const y = Math.abs(bottom - tie[1]) > Math.abs(top - tie[1]) ? bottom : top;
2291
+ const runs = runsAt(paint, y);
2292
+ if (runs.length === 0) return null;
2293
+ const widest = runs.reduce((a, b) => b[1] - b[0] > a[1] - a[0] ? b : a);
2294
+ return [(widest[0] + widest[1]) / 2, y > tie[1] ? y - inset : y + inset];
2295
+ }
2296
+ function checkCustomGate(model, parts, paints, options = {}) {
2297
+ const face = model.parts.find((p) => p.id === "face");
2298
+ if (face === void 0) throw new Error("custom gate: the model has no face");
2299
+ const faceWidth = face.width;
2300
+ const limits = {
2301
+ ...CUSTOM_GATE_LIMITS,
2302
+ fold: foldLimit(model)
2303
+ };
2304
+ if (parts.length === 0) {
2305
+ return {
2306
+ ok: true,
2307
+ faceWidth,
2308
+ limits,
2309
+ poses: 0,
2310
+ parts: [],
2311
+ failed: []
2312
+ };
2313
+ }
2314
+ const scale2 = faceWidth / TWIN_FACE;
2315
+ const px2 = (twin) => Math.max(1, Math.round(twin * scale2));
2316
+ const cache = /* @__PURE__ */ new Map();
2317
+ const turnParam = model.parameters.find(
2318
+ (p) => p.id === StandardParameter3.AngleX
2319
+ );
2320
+ const turns = (pose) => turnParam !== void 0 && (pose.values[StandardParameter3.AngleX] ?? turnParam.default) !== turnParam.default;
2321
+ const bakedOf = (id) => {
2322
+ const part = model.parts.find((p) => p.id === id);
2323
+ return new Map(
2324
+ (part.warps ?? []).map((w) => [
2325
+ w.parameter,
2326
+ w.keyforms.map((k) => k.value)
2327
+ ])
2328
+ );
2329
+ };
2330
+ const base = options.poses ?? foldPoses(model);
2331
+ const poseSets = parts.map((part) => {
2332
+ if (!model.parts.some((p) => p.id === part.id)) {
2333
+ throw new Error(`custom gate: the model has no part "${part.id}"`);
2334
+ }
2335
+ return options.poses ?? posesOf(model, bakedOf(part.id), base);
2336
+ });
2337
+ const all = new Map(poseSets.flat().map((p) => [p.name, p]));
2338
+ const reports = parts.map((part, n) => {
2339
+ const poses = poseSets[n];
2340
+ const roleParts = partIdsOfRole(part.anchor).filter(
2341
+ (id) => model.parts.some((p) => p.id === id)
2342
+ );
2343
+ const anchorId = roleParts.find(
2344
+ (id) => locatePoints(restMesh(model, cache, id), [part.tie])[0] !== null
2345
+ ) ?? roleParts[0];
2346
+ const folds = checkFolds(model, { poses });
2347
+ const anchorPart = model.parts.find((p) => p.id === anchorId);
2348
+ if (anchorPart === void 0) {
2349
+ throw new Error(`custom gate: the model has no part "${anchorId}"`);
2350
+ }
2351
+ const ownPaint = paints.get(part.id);
2352
+ const anchorPaint = paints.get(part.anchor);
2353
+ if (ownPaint === void 0 || anchorPaint === void 0) {
2354
+ throw new Error(
2355
+ `custom gate: no paint for "${ownPaint === void 0 ? part.id : part.anchor}"`
2356
+ );
2357
+ }
2358
+ const partMesh = restMesh(model, cache, part.id);
2359
+ const anchorMesh = restMesh(model, cache, anchorId);
2360
+ const length = (amount, pose, limit, reason) => readingOf(faceWidth, amount, 1, pose, limit, reason);
2361
+ const ring = [
2362
+ [0, 0],
2363
+ [px2(RING_PX), 0],
2364
+ [-px2(RING_PX), 0],
2365
+ [0, px2(RING_PX)],
2366
+ [0, -px2(RING_PX)],
2367
+ [px2(RING_DIAGONAL_PX), px2(RING_DIAGONAL_PX)],
2368
+ [-px2(RING_DIAGONAL_PX), px2(RING_DIAGONAL_PX)],
2369
+ [px2(RING_DIAGONAL_PX), -px2(RING_DIAGONAL_PX)],
2370
+ [-px2(RING_DIAGONAL_PX), -px2(RING_DIAGONAL_PX)]
2371
+ ].map(([dx, dy]) => [part.tie[0] + dx, part.tie[1] + dy]);
2372
+ const onPart = locatePoints(partMesh, ring);
2373
+ const onAnchor = locatePoints(anchorMesh, ring);
2374
+ const shared = ring.flatMap(
2375
+ (_, i) => onPart[i] && onAnchor[i] ? [i] : []
2376
+ );
2377
+ const reach = px2(SAMPLE_REACH_PX);
2378
+ const step = px2(SAMPLE_STEP_PX);
2379
+ const samples = [];
2380
+ const cx = Math.round(part.tie[0]);
2381
+ const cy = Math.round(part.tie[1]);
2382
+ for (let y = cy - reach; y <= cy + reach; y += step) {
2383
+ const runs = runsAt(anchorPaint, y);
2384
+ for (let x = cx - reach; x <= cx + reach; x += step) {
2385
+ if (runs.some(([a, b]) => x >= a && x < b))
2386
+ samples.push([x + 0.5, y + 0.5]);
2387
+ }
2388
+ }
2389
+ const samplesOn = locatePoints(anchorMesh, samples).filter(
2390
+ (l) => l !== null
2391
+ );
2392
+ const [tieOnPart] = locatePoints(partMesh, [part.tie]);
2393
+ const partIndex = model.parts.findIndex((p) => p.id === part.id);
2394
+ const anchorIndex = model.parts.indexOf(anchorPart);
2395
+ const ownPart = model.parts[partIndex];
2396
+ const partLower = ownPart.order < anchorPart.order || ownPart.order === anchorPart.order && partIndex < anchorIndex;
2397
+ const [lowerId, upperId] = partLower ? [part.id, anchorId] : [anchorId, part.id];
2398
+ const [lowerMesh, upperMesh] = [
2399
+ restMesh(model, cache, lowerId),
2400
+ restMesh(model, cache, upperId)
2401
+ ];
2402
+ const upperPaint = partLower ? anchorPaint : ownPaint;
2403
+ const exposedReach = Math.round(EXPOSED_REACH * faceWidth);
2404
+ const hidden = [];
2405
+ for (let y = Math.floor(part.tie[1]) - exposedReach; y <= Math.ceil(part.tie[1]) + exposedReach; y++) {
2406
+ for (const [a0, a1] of runsAt(ownPaint, y)) {
2407
+ for (const [b0, b1] of runsAt(anchorPaint, y)) {
2408
+ for (let x = Math.max(a0, b0); x < Math.min(a1, b1); x++) {
2409
+ if (Math.hypot(x + 0.5 - part.tie[0], y + 0.5 - part.tie[1]) <= exposedReach) {
2410
+ hidden.push([x + 0.5, y + 0.5]);
2411
+ }
2412
+ }
2413
+ }
2414
+ }
2415
+ }
2416
+ const onAnchorMesh = locatePoints(anchorMesh, hidden);
2417
+ const hiddenOn = locatePoints(lowerMesh, hidden).filter(
2418
+ (l, i) => l !== null && onAnchorMesh[i] !== null
2419
+ );
2420
+ const stops = bakedOf(part.id);
2421
+ const worstOf = {
2422
+ tie: { v: -1, pose: "rest" },
2423
+ slide: { v: -1, pose: "rest" },
2424
+ onAnchor: { v: -1, pose: "rest" },
2425
+ exposed: { v: -1, pose: "rest" },
2426
+ exposedTurn: { v: -1, pose: "rest" },
2427
+ rigid: { v: -1, pose: "rest" }
2428
+ };
2429
+ const keep = (w, v, pose) => {
2430
+ if (v > w.v) {
2431
+ w.v = v;
2432
+ w.pose = pose;
2433
+ }
2434
+ };
2435
+ let onAnchorNull = null;
2436
+ let turningPoses = 0;
2437
+ const rest = partMesh.rest;
2438
+ const restPoints = [];
2439
+ for (let i = 0; i < rest.length; i += 2)
2440
+ restPoints.push([rest[i], rest[i + 1]]);
2441
+ const measureRigid = (pose, posed) => {
2442
+ const moved = [];
2443
+ for (let i = 0; i < posed.length; i += 2)
2444
+ moved.push([posed[i], posed[i + 1]]);
2445
+ keep(worstOf.rigid, rigidResidual(restPoints, moved), pose.name);
2446
+ };
2447
+ for (const pose of poses) {
2448
+ const landed = landParts(model, pose.values, [part.id, anchorId]);
2449
+ const partPosed = toCanvas(model, landed.get(part.id));
2450
+ const anchorPosed = toCanvas(model, landed.get(anchorId));
2451
+ const turning = turns(pose);
2452
+ if (turning) turningPoses++;
2453
+ let gap = 0;
2454
+ for (const i of shared) {
2455
+ const a = landLocated(partPosed, onPart[i]);
2456
+ const b = landLocated(anchorPosed, onAnchor[i]);
2457
+ gap = Math.max(gap, Math.hypot(a[0] - b[0], a[1] - b[1]));
2458
+ }
2459
+ if (shared.length > 0) {
2460
+ keep(turning ? worstOf.slide : worstOf.tie, gap, pose.name);
2461
+ }
2462
+ if (turning) {
2463
+ const at = landLocated(partPosed, tieOnPart);
2464
+ let nearest = null;
2465
+ if (at !== null) {
2466
+ for (const l of samplesOn) {
2467
+ const q = landLocated(anchorPosed, l);
2468
+ const d = Math.hypot(q[0] - at[0], q[1] - at[1]);
2469
+ if (nearest === null || d < nearest) nearest = d;
2470
+ }
2471
+ }
2472
+ if (nearest === null) onAnchorNull ??= pose.name;
2473
+ else keep(worstOf.onAnchor, nearest, pose.name);
2474
+ }
2475
+ if (hiddenOn.length > 0) {
2476
+ const lowerPosed = lowerId === part.id ? partPosed : anchorPosed;
2477
+ const upperPosed = upperId === part.id ? partPosed : anchorPosed;
2478
+ const upperIndices = upperMesh.indices;
2479
+ const lands = hiddenOn.map((l) => landLocated(lowerPosed, l));
2480
+ const bounds = {
2481
+ x0: Infinity,
2482
+ y0: Infinity,
2483
+ x1: -Infinity,
2484
+ y1: -Infinity
2485
+ };
2486
+ for (const [x, y] of lands) {
2487
+ bounds.x0 = Math.min(bounds.x0, x);
2488
+ bounds.y0 = Math.min(bounds.y0, y);
2489
+ bounds.x1 = Math.max(bounds.x1, x);
2490
+ bounds.y1 = Math.max(bounds.y1, y);
2491
+ }
2492
+ const find = triangleGrid(upperPosed, upperIndices, bounds);
2493
+ let showing = 0;
2494
+ for (const at of lands) {
2495
+ let covered = false;
2496
+ for (const t of find(at[0], at[1])) {
2497
+ const tri = [
2498
+ upperIndices[t * 3],
2499
+ upperIndices[t * 3 + 1],
2500
+ upperIndices[t * 3 + 2]
2501
+ ];
2502
+ const w = locate(upperPosed, tri, at[0], at[1]);
2503
+ if (!w) continue;
2504
+ let rx = 0;
2505
+ let ry = 0;
2506
+ for (let k = 0; k < 3; k++) {
2507
+ rx += w[k] * upperMesh.rest[tri[k] * 2];
2508
+ ry += w[k] * upperMesh.rest[tri[k] * 2 + 1];
2509
+ }
2510
+ covered = paintedAt(upperPaint, rx, ry);
2511
+ break;
2512
+ }
2513
+ if (!covered) showing++;
2514
+ }
2515
+ keep(
2516
+ turning ? worstOf.exposedTurn : worstOf.exposed,
2517
+ showing,
2518
+ pose.name
2519
+ );
2520
+ }
2521
+ if (part.rigid) measureRigid(pose, partPosed);
2522
+ }
2523
+ if (part.rigid) {
2524
+ for (const [param, values] of stops) {
2525
+ const def = model.parameters.find((p) => p.id === param).default;
2526
+ const sorted = [.../* @__PURE__ */ new Set([...values, def])].sort((a, b) => a - b);
2527
+ for (let i = 0; i + 1 < sorted.length; i++) {
2528
+ const mid = foldPose({ [param]: (sorted[i] + sorted[i + 1]) / 2 });
2529
+ const posed = landParts(model, mid.values, [part.id]).get(part.id);
2530
+ measureRigid(mid, toCanvas(model, posed));
2531
+ }
2532
+ }
2533
+ }
2534
+ const tieReading = shared.length === 0 ? length(
2535
+ null,
2536
+ "rest",
2537
+ limits.tie,
2538
+ `no point of the ring around the tie lies on both ${part.id} and ${anchorId}`
2539
+ ) : length(
2540
+ Math.max(0, worstOf.tie.v),
2541
+ worstOf.tie.pose,
2542
+ limits.tie,
2543
+ "the tie comes apart"
2544
+ );
2545
+ const slideReading = length(
2546
+ Math.max(0, worstOf.slide.v),
2547
+ worstOf.slide.pose,
2548
+ limits.slide,
2549
+ "the tie slides too far"
2550
+ );
2551
+ const onAnchorReading = onAnchorNull !== null ? length(
2552
+ null,
2553
+ onAnchorNull,
2554
+ limits.onAnchor,
2555
+ `the tie lands off ${part.id}'s mesh, or no painted point of ${anchorId} near it is on its mesh`
2556
+ ) : length(
2557
+ Math.max(0, worstOf.onAnchor.v),
2558
+ worstOf.onAnchor.pose,
2559
+ limits.onAnchor,
2560
+ `the tie leaves ${anchorId}'s paint`
2561
+ );
2562
+ const exposedReading = readingOf(
2563
+ faceWidth,
2564
+ Math.max(0, worstOf.exposed.v),
2565
+ 2,
2566
+ worstOf.exposed.pose,
2567
+ limits.exposed,
2568
+ "hidden art shows"
2569
+ );
2570
+ const ratioHit = folds.targets.find(
2571
+ (t) => t.target.kind === "part" && t.target.id === part.id
2572
+ )?.worst;
2573
+ const ratio = ratioHit?.ratio ?? 1;
2574
+ const foldsPass = ratio >= limits.fold;
2575
+ const rigidReading = part.rigid ? length(
2576
+ Math.max(0, worstOf.rigid.v),
2577
+ worstOf.rigid.pose,
2578
+ limits.rigid,
2579
+ "the part bends"
2580
+ ) : void 0;
2581
+ const tipAt = freeEnd(ownPaint, part.tie, px2(TIP_INSET_PX));
2582
+ const [tipLoc] = tipAt === null ? [null] : locatePoints(partMesh, [tipAt]);
2583
+ const bareModel = stops.size === 0 ? model : {
2584
+ ...model,
2585
+ parts: model.parts.map(
2586
+ (p) => p.id === part.id ? { ...p, warps: void 0 } : p
2587
+ )
2588
+ };
2589
+ const tip = [...stops.keys()].map((param) => {
2590
+ const def = model.parameters.find((p) => p.id === param);
2591
+ const ends = [def.min, def.max].map((value) => {
2592
+ const at = (m) => landLocated(
2593
+ toCanvas(
2594
+ m,
2595
+ landParts(m, { [param]: value }, [part.id]).get(part.id)
2596
+ ),
2597
+ tipLoc ?? null
2598
+ );
2599
+ const landed = at(model);
2600
+ const bare = at(bareModel);
2601
+ return {
2602
+ value,
2603
+ landed,
2604
+ bare,
2605
+ fromBare: landed && bare ? Math.hypot(landed[0] - bare[0], landed[1] - bare[1]) : null
2606
+ };
2607
+ });
2608
+ const [a, b] = ends;
2609
+ return {
2610
+ param,
2611
+ ends,
2612
+ travel: a.landed && b.landed ? Math.hypot(b.landed[0] - a.landed[0], b.landed[1] - a.landed[1]) : null
2613
+ };
2614
+ });
2615
+ const turningExposed = worstOf.exposedTurn.v < 0 ? null : (({ value, px2: px22, pose }) => ({ value, px2: px22, pose }))(
2616
+ readingOf(
2617
+ faceWidth,
2618
+ worstOf.exposedTurn.v,
2619
+ 2,
2620
+ worstOf.exposedTurn.pose,
2621
+ Infinity,
2622
+ ""
2623
+ )
2624
+ );
2625
+ const slidePass = slideReading.pass && onAnchorReading.pass;
2626
+ const ok = foldsPass && tieReading.pass && slidePass && exposedReading.pass && (rigidReading?.pass ?? true);
2627
+ return {
2628
+ id: part.id,
2629
+ anchor: part.anchor,
2630
+ folds: {
2631
+ ratio,
2632
+ pose: ratioHit?.pose.name ?? "rest",
2633
+ limit: limits.fold,
2634
+ pass: foldsPass,
2635
+ ...foldsPass ? {} : { reason: ratio <= 0 ? "a flip" : "a collapse" }
2636
+ },
2637
+ tie: tieReading,
2638
+ slide: {
2639
+ slide: slideReading,
2640
+ onAnchor: onAnchorReading,
2641
+ turningPoses,
2642
+ pass: slidePass
2643
+ },
2644
+ exposed: {
2645
+ hiddenPx: hiddenOn.length,
2646
+ noTurn: exposedReading,
2647
+ turning: turningExposed,
2648
+ pass: exposedReading.pass
2649
+ },
2650
+ ...rigidReading === void 0 ? {} : { rigid: rigidReading },
2651
+ tip,
2652
+ ok
2653
+ };
2654
+ });
2655
+ const failed = reports.flatMap((r) => [
2656
+ ...r.folds.pass ? [] : [`${r.id} FOLDS`],
2657
+ ...r.tie.pass ? [] : [`${r.id} TIE`],
2658
+ ...r.slide.pass ? [] : [`${r.id} SLIDE`],
2659
+ ...r.exposed.pass ? [] : [`${r.id} EXPOSED`],
2660
+ ...r.rigid === void 0 || r.rigid.pass ? [] : [`${r.id} RIGID`]
2661
+ ]);
2662
+ return {
2663
+ ok: failed.length === 0,
2664
+ faceWidth,
2665
+ limits,
2666
+ poses: all.size,
2667
+ parts: reports,
2668
+ failed
2669
+ };
2670
+ }
2671
+ var both = (faceWidth, px2, digits = 4) => px2 === null ? "off the mesh" : `${px2.toFixed(1)} px (${(px2 / faceWidth).toFixed(digits)} face widths)`;
2672
+ function formatCustomGate(report) {
2673
+ const w = report.faceWidth;
2674
+ const verdict = (pass, reason) => pass ? "pass" : `FAIL: ${reason}`;
2675
+ const limit = (fw) => `${fw} face widths, ${(fw * w).toFixed(1)} px`;
2676
+ const lines = [];
2677
+ for (const r of report.parts) {
2678
+ const at = `CUSTOM ${r.id}`;
2679
+ lines.push(
2680
+ `${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)}`
2681
+ );
2682
+ lines.push(
2683
+ `${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)}`
2684
+ );
2685
+ const s = r.slide;
2686
+ lines.push(
2687
+ s.turningPoses === 0 ? `${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)}`
2688
+ );
2689
+ const e = r.exposed;
2690
+ 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)`;
2691
+ lines.push(
2692
+ `${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}`
2693
+ );
2694
+ if (r.rigid) {
2695
+ lines.push(
2696
+ `${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)}`
2697
+ );
2698
+ }
2699
+ for (const t of r.tip) {
2700
+ const ends = t.ends.map(
2701
+ (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`
2702
+ ).join("; ");
2703
+ lines.push(
2704
+ `${at} TIP ${t.param}: free end ${ends}; travel end to end ${t.travel === null ? "-" : both(w, t.travel)} (reported, no limit)`
2705
+ );
2706
+ }
2707
+ }
2708
+ lines.push(
2709
+ report.ok ? "CUSTOM GATE pass" : `CUSTOM GATE FAIL: ${report.failed.join(", ")}`
2710
+ );
2711
+ return lines;
2712
+ }
2713
+
1731
2714
  // src/sweep-report.ts
1732
2715
  var LADDER_MIN = -30;
1733
2716
  var LADDER_MAX = 30;
@@ -1902,187 +2885,57 @@ function checkSweep(model) {
1902
2885
  (eyes[0].x + eyes[1].x) / 2,
1903
2886
  (eyes[0].y + eyes[1].y) / 2
1904
2887
  );
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";
1948
-
1949
- // src/limits.ts
1950
- import fs from "fs";
1951
- import path from "path";
1952
- var MAX_LAYERS = 64;
1953
- var MAX_LAYER_DIM = 4096;
1954
- var MAX_CANVAS_DIM = 4096;
1955
- var MAX_ATLAS_SIDE = 4096;
1956
- var MAX_INPUT_PIXELS = 4096 * 4096;
1957
- var MAX_TOTAL_PIXELS = 128 * 1024 * 1024;
1958
- var MAX_OUTPUT_BYTES = 12 * 1024 * 1024;
1959
- var AutoRigInputError = class extends Error {
1960
- constructor(message) {
1961
- super(message);
1962
- this.name = "AutoRigInputError";
1963
- }
1964
- };
1965
- function rejectEmptyOrUrl(inputPath, noun, kind) {
1966
- if (typeof inputPath !== "string" || inputPath.trim() === "") {
1967
- throw new AutoRigInputError(`${noun} is empty`);
1968
- }
1969
- if (/^[a-z][a-z0-9+.-]*:\/\//i.test(inputPath)) {
1970
- throw new AutoRigInputError(
1971
- `${noun} must be a ${kind}, not a URL: ${inputPath}`
1972
- );
1973
- }
1974
- }
1975
- function resolveInputPath(inputPath, what = "layer") {
1976
- rejectEmptyOrUrl(inputPath, `${what} path`, "file path");
1977
- const resolved = path.resolve(process.cwd(), inputPath);
1978
- let stat;
1979
- try {
1980
- stat = fs.statSync(resolved);
1981
- } catch {
1982
- throw new AutoRigInputError(`${what} file not found: ${resolved}`);
1983
- }
1984
- if (stat.isDirectory()) {
1985
- throw new AutoRigInputError(
1986
- `${what} path is a directory, not a file: ${resolved}`
1987
- );
1988
- }
1989
- return resolved;
1990
- }
1991
- function resolveInputDir(dirPath) {
1992
- rejectEmptyOrUrl(dirPath, "layers dir", "directory path");
1993
- const resolved = path.resolve(process.cwd(), dirPath);
1994
- let stat;
1995
- try {
1996
- stat = fs.statSync(resolved);
1997
- } catch {
1998
- throw new AutoRigInputError(`layers dir not found: ${resolved}`);
1999
- }
2000
- if (!stat.isDirectory()) {
2001
- throw new AutoRigInputError(`layers path is not a directory: ${resolved}`);
2002
- }
2003
- return resolved;
2004
- }
2005
- function confineToWorkingDirectory(root, dir, label, original) {
2006
- const realRoot = fs.realpathSync(root);
2007
- const realDir = fs.realpathSync(dir);
2008
- if (realDir !== realRoot && !realDir.startsWith(realRoot + path.sep)) {
2009
- throw new AutoRigInputError(
2010
- `${label} escapes the working directory: ${original}`
2011
- );
2012
- }
2013
- return realDir;
2014
- }
2015
- function resolveOutputPath(outputPath) {
2016
- if (typeof outputPath !== "string" || outputPath.trim() === "") {
2017
- throw new AutoRigInputError("output path is empty");
2018
- }
2019
- if (!outputPath.toLowerCase().endsWith(".iki")) {
2020
- throw new AutoRigInputError(`output path must end in .iki: ${outputPath}`);
2021
- }
2022
- const root = process.cwd();
2023
- const resolved = path.resolve(root, outputPath);
2024
- const dir = path.dirname(resolved);
2025
- let stat;
2026
- try {
2027
- stat = fs.statSync(dir);
2028
- } catch {
2029
- throw new AutoRigInputError(`output directory does not exist: ${dir}`);
2030
- }
2031
- if (!stat.isDirectory()) {
2032
- throw new AutoRigInputError(`output parent is not a directory: ${dir}`);
2033
- }
2034
- const realDir = confineToWorkingDirectory(
2035
- root,
2036
- dir,
2037
- "output path",
2038
- outputPath
2039
- );
2040
- return path.join(realDir, path.basename(resolved));
2888
+ const plateX = (i) => at("face", i)[plateIndex * 2] / fw;
2889
+ return {
2890
+ preset: "turn",
2891
+ unit: "fw",
2892
+ faceWidth: fw,
2893
+ plateAmplitude: plateX(ladder.length - 1) - plateX(0),
2894
+ landmarks
2895
+ };
2041
2896
  }
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}`);
2897
+ var fw3 = (v) => {
2898
+ const s = v.toFixed(3);
2899
+ return s === "-0.000" ? "0.000" : s;
2900
+ };
2901
+ var signed = (v) => fw3(v).startsWith("-") ? fw3(v) : `+${fw3(v)}`;
2902
+ var two = (v) => v === null ? "n/a" : v.toFixed(2);
2903
+ function formatSweepReport(report) {
2904
+ if ("unavailable" in report) {
2905
+ return [`SWEEP: unavailable \u2014 ${report.unavailable}`];
2056
2906
  }
2057
- return confineToWorkingDirectory(root, resolved, "output dir", dirPath);
2907
+ return [
2908
+ ...report.landmarks.map(
2909
+ (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)}`
2910
+ ),
2911
+ `SWEEP turn plate: amplitude ${fw3(report.plateAmplitude)} fw`
2912
+ ];
2058
2913
  }
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
- );
2914
+ function formatNodReport(report) {
2915
+ if ("unavailable" in report) {
2916
+ return [`SWEEP nod: unavailable \u2014 ${report.unavailable}`];
2076
2917
  }
2918
+ return [
2919
+ ...report.nod.map(
2920
+ ({ 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`
2921
+ ),
2922
+ ...report.corner.map(
2923
+ ({ 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`
2924
+ )
2925
+ ];
2077
2926
  }
2078
2927
 
2928
+ // src/sweep.ts
2929
+ import fs3 from "fs";
2930
+ import path4 from "path";
2931
+
2079
2932
  // src/render-poses.ts
2080
- import { readFileSync } from "fs";
2933
+ import { readFileSync as readFileSync2 } from "fs";
2081
2934
  import path3 from "path";
2082
2935
  import {
2083
- IkiFormatError,
2084
- StandardParameter as StandardParameter3,
2085
- loadIkiModel
2936
+ IkiFormatError as IkiFormatError2,
2937
+ StandardParameter as StandardParameter4,
2938
+ loadIkiModel as loadIkiModel2
2086
2939
  } from "@ikijs/format";
2087
2940
 
2088
2941
  // src/render-browser.ts
@@ -2489,9 +3342,9 @@ function planRenders(model, requested, sweep, sweeps) {
2489
3342
  }
2490
3343
  const bodyAngles = Object.fromEntries(
2491
3344
  [
2492
- StandardParameter3.BodyAngleX,
2493
- StandardParameter3.BodyAngleY,
2494
- StandardParameter3.BodyAngleZ
3345
+ StandardParameter4.BodyAngleX,
3346
+ StandardParameter4.BodyAngleY,
3347
+ StandardParameter4.BodyAngleZ
2495
3348
  ].filter((id) => model.parameters.some((p) => p.id === id)).map((id) => [id, -10])
2496
3349
  );
2497
3350
  const poses = [
@@ -2577,7 +3430,7 @@ function planRenders(model, requested, sweep, sweeps) {
2577
3430
  whole("full-elbow-r-45", { ParamElbowR: 45 }),
2578
3431
  whole("full-elbow-r-90", { ParamElbowR: 90 })
2579
3432
  );
2580
- if (model.parameters.some((p) => p.id === StandardParameter3.ArmPoseRight)) {
3433
+ if (model.parameters.some((p) => p.id === StandardParameter4.ArmPoseRight)) {
2581
3434
  poses.push(
2582
3435
  whole("full-pose-l", { ParamArmPoseL: 1 }),
2583
3436
  whole("full-pose-r", { ParamArmPoseR: 1 }),
@@ -2618,6 +3471,25 @@ function checkRequest(requested, i) {
2618
3471
  }
2619
3472
  }
2620
3473
  }
3474
+ function withoutParts(model, hideParts) {
3475
+ const hidden = new Set(hideParts);
3476
+ hideParts.forEach((id, i) => {
3477
+ if (!model.parts.some((p) => p.id === id)) {
3478
+ throw new AutoRigInputError(
3479
+ `hideParts[${i}] ${JSON.stringify(id)} is not a part of the model`
3480
+ );
3481
+ }
3482
+ const kept = model.parts.find(
3483
+ (p) => !hidden.has(p.id) && p.clip?.masks.includes(id)
3484
+ );
3485
+ if (kept) {
3486
+ throw new AutoRigInputError(
3487
+ `hideParts[${i}] ${JSON.stringify(id)} masks ${JSON.stringify(kept.id)}, which stays; hide ${JSON.stringify(kept.id)} too`
3488
+ );
3489
+ }
3490
+ });
3491
+ return { ...model, parts: model.parts.filter((p) => !hidden.has(p.id)) };
3492
+ }
2621
3493
  var PNG_PREFIX = "data:image/png;base64,";
2622
3494
  var PAGE_SCRIPT_MS = 1e4;
2623
3495
  var LOAD_MS = 6e4;
@@ -2625,7 +3497,7 @@ var CAPTURE_MS = 15e3;
2625
3497
  function readPageScript() {
2626
3498
  const url = new URL("../dist/render-page.global.js", import.meta.url);
2627
3499
  try {
2628
- return readFileSync(url, "utf8");
3500
+ return readFileSync2(url, "utf8");
2629
3501
  } catch (cause) {
2630
3502
  throw new Error(
2631
3503
  "could not read the render page script; run `pnpm build` in packages/mcp",
@@ -2726,8 +3598,9 @@ async function renderPoses(input) {
2726
3598
  input.modelPath
2727
3599
  );
2728
3600
  const outDir = resolveOutputDir(input.outDir);
2729
- const model = loadIkiModel(readFileSync(modelFile, "utf8"));
3601
+ const model = loadIkiModel2(readFileSync2(modelFile, "utf8"));
2730
3602
  const plan = planRenders(model, input.poses, input.sweep, input.sweeps);
3603
+ const drawn = input.hideParts ? withoutParts(model, input.hideParts) : model;
2731
3604
  const browser = findBrowser();
2732
3605
  if (!browser) return { ok: false, error: NO_BROWSER_MESSAGE };
2733
3606
  const pageScript = readPageScript();
@@ -2750,7 +3623,7 @@ async function renderPoses(input) {
2750
3623
  async (evaluate) => {
2751
3624
  await evaluate(pageScript, PAGE_SCRIPT_MS);
2752
3625
  const loaded = await evaluate(
2753
- `window.__ikiRender.load(${JSON.stringify(model)}, ${JSON.stringify({ canvas: plan.canvas, view: plan.view })})`,
3626
+ `window.__ikiRender.load(${JSON.stringify(drawn)}, ${JSON.stringify({ canvas: plan.canvas, view: plan.view })})`,
2754
3627
  LOAD_MS
2755
3628
  );
2756
3629
  const written = [];
@@ -2818,7 +3691,7 @@ async function renderPoses(input) {
2818
3691
  sweeps
2819
3692
  };
2820
3693
  } catch (error) {
2821
- if (error instanceof AutoRigInputError || error instanceof IkiFormatError) {
3694
+ if (error instanceof AutoRigInputError || error instanceof IkiFormatError2) {
2822
3695
  return { ok: false, error: error.message };
2823
3696
  }
2824
3697
  throw error;
@@ -2830,7 +3703,7 @@ var SWEEP_CLOCK_HZ = 60;
2830
3703
  var SWEEP_FPS = 30;
2831
3704
  var SWEEP_DURATION_S = 3;
2832
3705
  var BOX_DURATION_S = 6;
2833
- var SWEEP_PRESETS = ["turn", "turn-nod"];
3706
+ var SWEEP_PRESETS = ["turn", "turn-nod", "roll"];
2834
3707
  var SWEEP_WARMUP_S = 0.5;
2835
3708
  var SWEEP_FRAME_MS = 1e3 / SWEEP_CLOCK_HZ * (1 + 1e-9);
2836
3709
  var SHEET_THETAS = [-30, -20, -10, -5, 0, 5, 10, 20, 30];
@@ -2883,29 +3756,37 @@ function boxAngles(t) {
2883
3756
  }
2884
3757
  return { x: 0, y: 0 };
2885
3758
  }
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);
3759
+ var legSheet = (id) => (steps, n) => turnSheetFrames(steps, n, id);
3760
+ var SHAPES = {
3761
+ turn: {
3762
+ durationS: SWEEP_DURATION_S,
3763
+ angles: (t) => ({ ParamAngleX: turnTheta(t) }),
3764
+ sheetFrames: legSheet("ParamAngleX"),
3765
+ label: (s) => `\u03B8 ${signedDeg(s.ParamAngleX)}\xB0`,
3766
+ kymograph: true
3767
+ },
3768
+ // The roll rides the turn's own curve, so its frames sit at the angles the
3769
+ // turn sheet's do.
3770
+ roll: {
3771
+ durationS: SWEEP_DURATION_S,
3772
+ angles: (t) => ({ ParamAngleZ: turnTheta(t) }),
3773
+ sheetFrames: legSheet("ParamAngleZ"),
3774
+ label: (s) => `Z ${signedDeg(s.ParamAngleZ)}\xB0`,
3775
+ kymograph: false
3776
+ },
3777
+ "turn-nod": {
3778
+ durationS: BOX_DURATION_S,
3779
+ angles: (t) => {
3780
+ const { x, y } = boxAngles(t);
2905
3781
  return { ParamAngleX: x, ParamAngleY: y };
2906
- }),
2907
- durationS
2908
- };
3782
+ },
3783
+ sheetFrames: boxSheetFrames,
3784
+ label: (s) => `X ${signedDeg(s.ParamAngleX)}\xB0 Y ${signedDeg(s.ParamAngleY)}\xB0`,
3785
+ kymograph: false
3786
+ }
3787
+ };
3788
+ function sweepDurationS(preset) {
3789
+ return SHAPES[preset].durationS;
2909
3790
  }
2910
3791
  function eyeRowModelPx(model) {
2911
3792
  const landed = landParts(model, {}, ["eye_L", "eye_R"]);
@@ -2931,13 +3812,13 @@ function physicsOutputIds(model) {
2931
3812
  }
2932
3813
  return [...ids];
2933
3814
  }
2934
- function turnSheetFrames(steps, frames) {
3815
+ function turnSheetFrames(steps, frames, id) {
2935
3816
  const onLeg = [];
2936
3817
  for (let k = 0; k < frames; k++) {
2937
3818
  const t = k / SWEEP_FPS;
2938
3819
  if (t >= LEG_FROM_S && t <= LEG_TO_S) onLeg.push(k);
2939
3820
  }
2940
- const x = (k) => steps[CAPTURE_EVERY * k].ParamAngleX;
3821
+ const x = (k) => steps[CAPTURE_EVERY * k][id];
2941
3822
  const picked = [];
2942
3823
  for (const target2 of SHEET_THETAS) {
2943
3824
  let best = onLeg[0];
@@ -2967,7 +3848,13 @@ function signedDeg(angle) {
2967
3848
  return rounded > 0 ? `+${deg}` : deg.replace("-", "\u2212");
2968
3849
  }
2969
3850
  function sweepSpec(model, preset, crop) {
2970
- const { parameters, steps, durationS } = schedule(preset);
3851
+ const shape = SHAPES[preset];
3852
+ const { durationS } = shape;
3853
+ const steps = Array.from(
3854
+ { length: SWEEP_CLOCK_HZ * durationS },
3855
+ (_, j) => shape.angles(j / SWEEP_CLOCK_HZ)
3856
+ );
3857
+ const parameters = Object.keys(steps[0]);
2971
3858
  const frameCount = durationS * SWEEP_FPS;
2972
3859
  const dw = crop ? crop.dw : BUST_SIZE;
2973
3860
  const dh = crop ? crop.dh : BUST_SIZE;
@@ -2978,15 +3865,11 @@ function sweepSpec(model, preset, crop) {
2978
3865
  (SHEET_MAX_SIDE - 2 * m) / (3 * dw),
2979
3866
  (SHEET_MAX_SIDE - 2 * m - 3 * b) / (3 * dh)
2980
3867
  );
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
- };
3868
+ const frames = shape.sheetFrames(steps, frameCount);
3869
+ const labelOf = (k) => `${shape.label(steps[CAPTURE_EVERY * k])} t ${(k / SWEEP_FPS).toFixed(2)} s`;
2987
3870
  const { width: W, height: H } = model.canvas;
2988
3871
  let kymograph;
2989
- if (preset === "turn") {
3872
+ if (shape.kymograph) {
2990
3873
  const yModel = eyeRowModelPx(model);
2991
3874
  let row = Math.round(dh / 2);
2992
3875
  let at = "middle";
@@ -3066,7 +3949,7 @@ img { max-width: 48vw; height: auto; background: #444; }
3066
3949
  scrub.max = String(n - 1);
3067
3950
  if (b) { bi.style.display = "block"; }
3068
3951
  function short(id) {
3069
- return id === "ParamAngleX" ? "X" : id === "ParamAngleY" ? "Y" : id;
3952
+ return id === "ParamAngleX" ? "X" : id === "ParamAngleY" ? "Y" : id === "ParamAngleZ" ? "Z" : id;
3070
3953
  }
3071
3954
  function show(k) {
3072
3955
  i = k;
@@ -3129,22 +4012,25 @@ function clearSweepDir(real) {
3129
4012
  }
3130
4013
 
3131
4014
  // src/tools.ts
3132
- import { readFileSync as readFileSync2 } from "fs";
4015
+ import { readFileSync as readFileSync3 } from "fs";
3133
4016
  import path5 from "path";
3134
4017
  import {
3135
4018
  parseIkiModel,
3136
- loadIkiModel as loadIkiModel2,
3137
- IkiFormatError as IkiFormatError2,
3138
- StandardParameter as StandardParameter4
4019
+ loadIkiModel as loadIkiModel3,
4020
+ IkiFormatError as IkiFormatError3,
4021
+ StandardParameter as StandardParameter5
3139
4022
  } from "@ikijs/format";
3140
4023
  import {
3141
4024
  EditorDocument,
3142
4025
  packAtlas,
3143
4026
  uvRectFor,
3144
4027
  createLayerSetMeasurer,
4028
+ detectAlphaBbox as detectAlphaBbox2,
3145
4029
  generateIkiFromLayerSet,
3146
4030
  parseLayerRoles,
3147
- partIdsOfRole,
4031
+ partIdsOfRole as partIdsOfRole2,
4032
+ BakeError,
4033
+ CustomPartError,
3148
4034
  LayerGeometryError,
3149
4035
  PatchError,
3150
4036
  RigPlanError,
@@ -3153,80 +4039,81 @@ import {
3153
4039
  TurnTargetError
3154
4040
  } from "@ikijs/editor";
3155
4041
 
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") {
4042
+ // src/bake-report.ts
4043
+ var BAKE_TOLERANCE_PX = 0.1;
4044
+ var BUG = "the rig and the engine disagree; report this as a bug in the packages";
4045
+ function checkBakes(model, reports) {
4046
+ const restOf = /* @__PURE__ */ new Map();
4047
+ for (const id of new Set(reports.map((r) => r.part))) {
4048
+ const rest = landParts(model, {}, [id]).get(id);
4049
+ const bare = landParts(
4050
+ {
4051
+ ...model,
4052
+ parts: model.parts.map(
4053
+ (p) => p.id === id ? { ...p, warps: void 0 } : p
4054
+ )
4055
+ },
4056
+ {},
4057
+ [id]
4058
+ ).get(id);
4059
+ let restGap = 0;
4060
+ for (let i = 0; i < rest.length; i++) {
4061
+ restGap = Math.max(restGap, Math.abs(rest[i] - bare[i]));
4062
+ }
4063
+ if (restGap >= BAKE_TOLERANCE_PX) {
3164
4064
  throw new AutoRigInputError(
3165
- `non-PNG image (${metadata.format ?? "unknown"}): ${filePath}`
4065
+ `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
4066
  );
3167
4067
  }
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");
4068
+ restOf.set(id, rest);
3185
4069
  }
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) {
4070
+ return reports.map((r) => {
4071
+ const rest = restOf.get(r.part);
4072
+ let errorPx = 0;
4073
+ const asked = [
4074
+ ...r.stops.map((value, s) => ({ value, wanted: r.wanted[s] })),
4075
+ ...r.ends
4076
+ ];
4077
+ asked.forEach(({ value, wanted }) => {
4078
+ const posed = landParts(model, { [r.param]: value }, [r.part]).get(
4079
+ r.part
4080
+ );
4081
+ let worst = 0;
4082
+ let worstVertex = 0;
4083
+ for (let v = 0; v < r.vertexCount; v++) {
4084
+ const gap = Math.hypot(
4085
+ posed[v * 2] - rest[v * 2] - wanted[v * 2],
4086
+ -(posed[v * 2 + 1] - rest[v * 2 + 1]) - wanted[v * 2 + 1]
4087
+ );
4088
+ if (gap > worst) {
4089
+ worst = gap;
4090
+ worstVertex = v;
4091
+ }
4092
+ }
4093
+ if (worst >= BAKE_TOLERANCE_PX) {
3202
4094
  throw new AutoRigInputError(
3203
- `no crop for atlas placement "${placement3.id}"`
4095
+ `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
4096
  );
3205
4097
  }
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")}`;
4098
+ errorPx = Math.max(errorPx, worst);
4099
+ });
4100
+ return {
4101
+ part: r.part,
4102
+ param: r.param,
4103
+ vertices: r.vertexCount,
4104
+ stops: r.stops,
4105
+ errorPx
4106
+ };
4107
+ });
3221
4108
  }
3222
4109
 
3223
4110
  // src/tools.ts
3224
4111
  function coerceModel(model) {
3225
4112
  try {
3226
- const parsed = typeof model === "string" ? loadIkiModel2(model) : parseIkiModel(model);
4113
+ const parsed = typeof model === "string" ? loadIkiModel3(model) : parseIkiModel(model);
3227
4114
  return { ok: true, model: parsed };
3228
4115
  } catch (e) {
3229
- if (e instanceof IkiFormatError2) return { ok: false, error: e.message };
4116
+ if (e instanceof IkiFormatError3) return { ok: false, error: e.message };
3230
4117
  throw e;
3231
4118
  }
3232
4119
  }
@@ -3335,7 +4222,7 @@ function describeIkiAt(modelPath) {
3335
4222
  "model path",
3336
4223
  modelPath
3337
4224
  );
3338
- return describeIki(readFileSync2(modelFile, "utf8"));
4225
+ return describeIki(readFileSync3(modelFile, "utf8"));
3339
4226
  } catch (e) {
3340
4227
  if (e instanceof AutoRigInputError) return { ok: false, error: e.message };
3341
4228
  throw e;
@@ -3343,123 +4230,123 @@ function describeIkiAt(modelPath) {
3343
4230
  }
3344
4231
  var STANDARD_PARAMETER_INFO = [
3345
4232
  {
3346
- id: StandardParameter4.MouthOpen,
4233
+ id: StandardParameter5.MouthOpen,
3347
4234
  description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
3348
4235
  },
3349
4236
  {
3350
- id: StandardParameter4.MouthForm,
4237
+ id: StandardParameter5.MouthForm,
3351
4238
  description: "Mouth form / smile (-1 .. 1)."
3352
4239
  },
3353
4240
  {
3354
- id: StandardParameter4.EyeOpenLeft,
4241
+ id: StandardParameter5.EyeOpenLeft,
3355
4242
  description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
3356
4243
  },
3357
4244
  {
3358
- id: StandardParameter4.EyeOpenRight,
4245
+ id: StandardParameter5.EyeOpenRight,
3359
4246
  description: "Right eye open (0 closed .. 1 open)."
3360
4247
  },
3361
4248
  {
3362
- id: StandardParameter4.EyeballX,
4249
+ id: StandardParameter5.EyeballX,
3363
4250
  description: "Eyeball gaze, horizontal (-1 .. 1)."
3364
4251
  },
3365
4252
  {
3366
- id: StandardParameter4.EyeballY,
4253
+ id: StandardParameter5.EyeballY,
3367
4254
  description: "Eyeball gaze, vertical (-1 .. 1)."
3368
4255
  },
3369
4256
  {
3370
- id: StandardParameter4.AngleX,
4257
+ id: StandardParameter5.AngleX,
3371
4258
  description: "Head angle, horizontal degrees."
3372
4259
  },
3373
4260
  {
3374
- id: StandardParameter4.AngleY,
4261
+ id: StandardParameter5.AngleY,
3375
4262
  description: "Head angle, vertical degrees."
3376
4263
  },
3377
4264
  {
3378
- id: StandardParameter4.AngleZ,
4265
+ id: StandardParameter5.AngleZ,
3379
4266
  description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
3380
4267
  },
3381
4268
  {
3382
- id: StandardParameter4.BodyAngleX,
4269
+ id: StandardParameter5.BodyAngleX,
3383
4270
  description: "Body turn, degrees (-10 .. 10); positive turns the body toward the viewer's right, as AngleX does the head."
3384
4271
  },
3385
4272
  {
3386
- id: StandardParameter4.BodyAngleY,
4273
+ id: StandardParameter5.BodyAngleY,
3387
4274
  description: "Body lean, degrees (-10 .. 10); positive moves the upper body up, negative bows."
3388
4275
  },
3389
4276
  {
3390
- id: StandardParameter4.BodyAngleZ,
4277
+ id: StandardParameter5.BodyAngleZ,
3391
4278
  description: "Body tilt, degrees (-10 .. 10); positive tilts the top toward the viewer's right (clockwise), as AngleZ does the head."
3392
4279
  },
3393
4280
  {
3394
- id: StandardParameter4.Breath,
4281
+ id: StandardParameter5.Breath,
3395
4282
  description: "Idle breath (0 .. 1), cycled by the host."
3396
4283
  },
3397
4284
  {
3398
- id: StandardParameter4.AmbientSway,
4285
+ id: StandardParameter5.AmbientSway,
3399
4286
  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
4287
  },
3401
4288
  {
3402
- id: StandardParameter4.BrowLeftY,
4289
+ id: StandardParameter5.BrowLeftY,
3403
4290
  description: "Left brow raise/lower (-1 .. 1)."
3404
4291
  },
3405
4292
  {
3406
- id: StandardParameter4.BrowRightY,
4293
+ id: StandardParameter5.BrowRightY,
3407
4294
  description: "Right brow raise/lower (-1 .. 1)."
3408
4295
  },
3409
4296
  {
3410
- id: StandardParameter4.BrowLeftAngle,
4297
+ id: StandardParameter5.BrowLeftAngle,
3411
4298
  description: "Left brow tilt/angle (-1 .. 1)."
3412
4299
  },
3413
4300
  {
3414
- id: StandardParameter4.BrowRightAngle,
4301
+ id: StandardParameter5.BrowRightAngle,
3415
4302
  description: "Right brow tilt/angle (-1 .. 1)."
3416
4303
  },
3417
4304
  {
3418
- id: StandardParameter4.Cheek,
4305
+ id: StandardParameter5.Cheek,
3419
4306
  description: "Cheek blush strength (0 .. 1), raised by an expression."
3420
4307
  },
3421
4308
  {
3422
- id: StandardParameter4.HairSwayX,
4309
+ id: StandardParameter5.HairSwayX,
3423
4310
  description: "Front hair's horizontal sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
3424
4311
  },
3425
4312
  {
3426
- id: StandardParameter4.HairSwayZ,
4313
+ id: StandardParameter5.HairSwayZ,
3427
4314
  description: "Front hair's sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
3428
4315
  },
3429
4316
  {
3430
- id: StandardParameter4.HairBackSway,
4317
+ id: StandardParameter5.HairBackSway,
3431
4318
  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
4319
  },
3433
4320
  {
3434
- id: StandardParameter4.ArmLeft,
4321
+ id: StandardParameter5.ArmLeft,
3435
4322
  description: "Left shoulder, degrees; positive raises the arm outward (mirrored on the right)."
3436
4323
  },
3437
4324
  {
3438
- id: StandardParameter4.ArmRight,
4325
+ id: StandardParameter5.ArmRight,
3439
4326
  description: "Right shoulder, degrees; positive raises the arm outward (mirrored on the left)."
3440
4327
  },
3441
4328
  {
3442
- id: StandardParameter4.ElbowLeft,
4329
+ id: StandardParameter5.ElbowLeft,
3443
4330
  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
4331
  },
3445
4332
  {
3446
- id: StandardParameter4.ElbowRight,
4333
+ id: StandardParameter5.ElbowRight,
3447
4334
  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
4335
  },
3449
4336
  {
3450
- id: StandardParameter4.ArmPoseLeft,
4337
+ id: StandardParameter5.ArmPoseLeft,
3451
4338
  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
4339
  },
3453
4340
  {
3454
- id: StandardParameter4.ArmPoseRight,
4341
+ id: StandardParameter5.ArmPoseRight,
3455
4342
  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
4343
  },
3457
4344
  {
3458
- id: StandardParameter4.ArmPoseAngleLeft,
4345
+ id: StandardParameter5.ArmPoseAngleLeft,
3459
4346
  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
4347
  },
3461
4348
  {
3462
- id: StandardParameter4.ArmPoseAngleRight,
4349
+ id: StandardParameter5.ArmPoseAngleRight,
3463
4350
  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
4351
  }
3465
4352
  ];
@@ -3516,9 +4403,20 @@ async function autoRigFromLayers(input) {
3516
4403
  if (!Array.isArray(layers) || layers.length === 0) {
3517
4404
  throw new AutoRigInputError("layers must be a non-empty array");
3518
4405
  }
3519
- if (layers.length > MAX_LAYERS) {
4406
+ const customInputs = input.customParts;
4407
+ if (customInputs !== void 0 && !Array.isArray(customInputs)) {
4408
+ throw new AutoRigInputError("customParts must be an array");
4409
+ }
4410
+ const customEntries = customInputs ?? [];
4411
+ customEntries.forEach((entry, i) => {
4412
+ const at = `customParts[${i}]`;
4413
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
4414
+ throw new AutoRigInputError(`${at} must be a plain object`);
4415
+ }
4416
+ });
4417
+ if (layers.length + customEntries.length > MAX_LAYERS) {
3520
4418
  throw new AutoRigInputError(
3521
- `too many layers: ${layers.length} > ${MAX_LAYERS}`
4419
+ `too many layers: ${layers.length + customEntries.length} > ${MAX_LAYERS}`
3522
4420
  );
3523
4421
  }
3524
4422
  const outPath = resolveOutputPath(
@@ -3548,6 +4446,9 @@ async function autoRigFromLayers(input) {
3548
4446
  const resolved = resolveInputPath(layer.path);
3549
4447
  return { resolved, fileName: layer.fileName ?? path5.basename(resolved) };
3550
4448
  });
4449
+ const customPaths = customEntries.map(
4450
+ (entry, i) => resolveInputPath(entry.path, `customParts[${i}].path`)
4451
+ );
3551
4452
  const rolePairs = expectInput(
3552
4453
  "role parsing",
3553
4454
  () => parseLayerRoles(resolvedLayers.map((r) => r.fileName))
@@ -3558,6 +4459,8 @@ async function autoRigFromLayers(input) {
3558
4459
  let totalPixels = 0;
3559
4460
  let measurer;
3560
4461
  const crops = [];
4462
+ const paints = /* @__PURE__ */ new Map();
4463
+ const anchorRoles = new Set(customEntries.map((e) => e.anchor));
3561
4464
  for (let i = 0; i < resolvedLayers.length; i++) {
3562
4465
  const { resolved, fileName } = resolvedLayers[i];
3563
4466
  const png = await decodePng(resolved);
@@ -3597,9 +4500,48 @@ async function autoRigFromLayers(input) {
3597
4500
  );
3598
4501
  }
3599
4502
  const { bbox } = layer;
4503
+ if (anchorRoles.has(role)) paints.set(role, paintRuns(png));
3600
4504
  const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);
3601
4505
  crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
3602
4506
  }
4507
+ const customLayers = [];
4508
+ const customCrops = [];
4509
+ for (let i = 0; i < customEntries.length; i++) {
4510
+ const at = `customParts[${i}]`;
4511
+ const { id } = customEntries[i];
4512
+ const resolved = customPaths[i];
4513
+ const png = await decodePng(resolved);
4514
+ if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {
4515
+ throw new AutoRigInputError(
4516
+ `${at}.path ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`
4517
+ );
4518
+ }
4519
+ totalPixels += png.width * png.height;
4520
+ if (totalPixels > MAX_TOTAL_PIXELS) {
4521
+ throw new AutoRigInputError(
4522
+ `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`
4523
+ );
4524
+ }
4525
+ if (png.width !== canvasW || png.height !== canvasH) {
4526
+ throw new AutoRigInputError(
4527
+ `${at}.path size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
4528
+ );
4529
+ }
4530
+ const bbox = detectAlphaBbox2(png.rgba, png.width, png.height);
4531
+ if (bbox === null) {
4532
+ throw new AutoRigInputError(
4533
+ `${at}.path "${path5.basename(resolved)}": layer is empty after alpha threshold`
4534
+ );
4535
+ }
4536
+ customLayers.push({ fileName: path5.basename(resolved), bbox });
4537
+ paints.set(id, paintRuns(png));
4538
+ customCrops.push({
4539
+ id,
4540
+ buffer: await cropToBuffer(png.rgba, png.width, png.height, bbox),
4541
+ width: bbox.w,
4542
+ height: bbox.h
4543
+ });
4544
+ }
3603
4545
  const measurement = measurer.finish();
3604
4546
  const { headHalfWidth, headHalfWidthApplied, turnOptions } = measurement;
3605
4547
  const { headEdges, strandEdges } = turnOptions;
@@ -3609,6 +4551,7 @@ async function autoRigFromLayers(input) {
3609
4551
  let turn;
3610
4552
  let patches;
3611
4553
  let rigPlan;
4554
+ let bakeReports;
3612
4555
  let model;
3613
4556
  try {
3614
4557
  model = generateIkiFromLayerSet(
@@ -3633,11 +4576,25 @@ async function autoRigFromLayers(input) {
3633
4576
  }
3634
4577
  },
3635
4578
  ...headEdges === void 0 ? {} : { headEdges },
3636
- ...strandEdges === void 0 ? {} : { strandEdges }
4579
+ ...strandEdges === void 0 ? {} : { strandEdges },
4580
+ ...input.customParts === void 0 ? {} : {
4581
+ customParts: customEntries.map(
4582
+ ({ path: _path, ...rest }, i) => ({
4583
+ ...rest,
4584
+ layer: customLayers[i]
4585
+ })
4586
+ )
4587
+ },
4588
+ ...input.bakes === void 0 ? {} : {
4589
+ bakes: input.bakes,
4590
+ onBakesApplied: (reports) => {
4591
+ bakeReports = reports;
4592
+ }
4593
+ }
3637
4594
  }
3638
4595
  );
3639
4596
  } catch (e) {
3640
- if (!(e instanceof TurnTargetError || e instanceof LayerGeometryError || e instanceof PatchError || e instanceof RigPlanError)) {
4597
+ if (!(e instanceof TurnTargetError || e instanceof LayerGeometryError || e instanceof PatchError || e instanceof RigPlanError || e instanceof CustomPartError || e instanceof BakeError)) {
3641
4598
  throw e;
3642
4599
  }
3643
4600
  throw new AutoRigInputError(e.message);
@@ -3651,7 +4608,9 @@ async function autoRigFromLayers(input) {
3651
4608
  ),
3652
4609
  await renderAtlasPage([losslessCrop], void 0)
3653
4610
  ];
3654
- const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);
4611
+ const customPage = customCrops.length === 0 ? void 0 : await renderAtlasPage(customCrops, quantizeColors);
4612
+ const allPages = customPage === void 0 ? pages : [...pages, customPage];
4613
+ const atlasBytes = allPages.reduce((sum, p) => sum + p.dataUri.length, 0);
3655
4614
  if (atlasBytes > MAX_OUTPUT_BYTES) {
3656
4615
  throw new AutoRigInputError(
3657
4616
  `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`
@@ -3667,25 +4626,64 @@ async function autoRigFromLayers(input) {
3667
4626
  width: layout.pageWidth,
3668
4627
  height: layout.pageHeight
3669
4628
  });
3670
- return partIdsOfRole(crop.id).map((partId) => ({ partId, uv }));
4629
+ return partIdsOfRole2(crop.id).map((partId) => ({ partId, uv }));
3671
4630
  })
3672
4631
  );
4632
+ if (customPage !== void 0) {
4633
+ partTextureAssignments.push(
4634
+ ...customPage.crops.map((crop) => {
4635
+ const placement3 = customPage.layout.placements.find(
4636
+ (p) => p.id === crop.id
4637
+ );
4638
+ return {
4639
+ partId: crop.id,
4640
+ uv: uvRectFor(placement3, {
4641
+ width: customPage.layout.pageWidth,
4642
+ height: customPage.layout.pageHeight
4643
+ })
4644
+ };
4645
+ })
4646
+ );
4647
+ }
3673
4648
  doc.applyAtlas({
3674
4649
  textures: [{ source: pages[0].dataUri }],
3675
4650
  partTextureAssignments
3676
4651
  });
3677
4652
  let patched = doc.getModel();
3678
- if (losslessCrop !== void 0) {
4653
+ if (losslessCrop !== void 0 || customPage !== void 0) {
3679
4654
  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;
4655
+ patched.textures = allPages.map((p) => ({ source: p.dataUri }));
4656
+ if (losslessCrop !== void 0) {
4657
+ for (const partId of partIdsOfRole2(losslessCrop.id)) {
4658
+ patched.parts.find((p) => p.id === partId).texture.index = 1;
4659
+ }
4660
+ }
4661
+ for (const crop of customCrops) {
4662
+ patched.parts.find((p) => p.id === crop.id).texture.index = pages.length;
3683
4663
  }
3684
4664
  }
3685
4665
  const finalModel = parseIkiModel(patched);
4666
+ const bakes = bakeReports === void 0 ? void 0 : checkBakes(finalModel, bakeReports);
3686
4667
  writeFileAtomic(outPath, JSON.stringify(finalModel));
3687
4668
  const folds = checkModelFolds(finalModel);
3688
4669
  const physics = checkPhysics(finalModel);
4670
+ let gate;
4671
+ if (input.customParts !== void 0) {
4672
+ try {
4673
+ gate = checkCustomGate(
4674
+ finalModel,
4675
+ customEntries.map(({ id, anchor, tie, rigid }) => ({
4676
+ id,
4677
+ anchor,
4678
+ tie,
4679
+ ...rigid === void 0 ? {} : { rigid }
4680
+ })),
4681
+ paints
4682
+ );
4683
+ } catch (e) {
4684
+ gate = failedCustomGate(finalModel, e);
4685
+ }
4686
+ }
3689
4687
  return {
3690
4688
  ok: true,
3691
4689
  path: outPath,
@@ -3701,7 +4699,26 @@ async function autoRigFromLayers(input) {
3701
4699
  folds,
3702
4700
  physics,
3703
4701
  ...patches === void 0 ? {} : { patches },
3704
- rigPlan
4702
+ rigPlan,
4703
+ ...input.customParts === void 0 ? {} : {
4704
+ customParts: {
4705
+ parts: customCrops.map((crop, i) => {
4706
+ const part = finalModel.parts.find((p) => p.id === crop.id);
4707
+ return {
4708
+ id: crop.id,
4709
+ box: customLayers[i].bbox,
4710
+ mesh: {
4711
+ vertices: part.mesh.vertices.length / 2,
4712
+ triangles: part.mesh.indices.length / 3
4713
+ },
4714
+ order: part.order,
4715
+ page: part.texture.index
4716
+ };
4717
+ }),
4718
+ ...bakes === void 0 ? {} : { bakes },
4719
+ gate
4720
+ }
4721
+ }
3705
4722
  };
3706
4723
  } catch (err) {
3707
4724
  if (err instanceof AutoRigInputError)
@@ -4166,7 +5183,7 @@ function covers(runs, x) {
4166
5183
  }
4167
5184
  return false;
4168
5185
  }
4169
- function runsAt(layer, y) {
5186
+ function runsAt2(layer, y) {
4170
5187
  return layer?.rowRuns?.[y - layer.bbox.y] ?? [];
4171
5188
  }
4172
5189
  function opaqueRows(layer) {
@@ -4242,8 +5259,8 @@ async function hairSideWarnings(absDir, layers) {
4242
5259
  function rootWarning(role, lock, front) {
4243
5260
  const y = opaqueRows(lock)?.top;
4244
5261
  if (y === void 0) return void 0;
4245
- const frontRuns = runsAt(front, y);
4246
- const lockRuns = runsAt(lock, y);
5262
+ const frontRuns = runsAt2(front, y);
5263
+ const lockRuns = runsAt2(lock, y);
4247
5264
  let shown = 0;
4248
5265
  for (let i = 0; i + 1 < lockRuns.length; i += 2) {
4249
5266
  let stretch = 0;
@@ -4262,7 +5279,7 @@ function rootWarning(role, lock, front) {
4262
5279
  function eyeCornerWarning(role, lock, side, eyeRole, eye) {
4263
5280
  const row = Math.floor(eye.bboxCy);
4264
5281
  const corner = side < 0 ? eye.marginLeft : eye.marginLeft + eye.w - 1;
4265
- const runs = runsAt(lock, row);
5282
+ const runs = runsAt2(lock, row);
4266
5283
  let overlap = 0;
4267
5284
  for (let i = 0; i + 1 < runs.length; i += 2) {
4268
5285
  if (corner < runs[i] || corner >= runs[i + 1]) continue;
@@ -4281,14 +5298,14 @@ function leanWarning(role, lock, side, face, back, eye) {
4281
5298
  const bare = /* @__PURE__ */ new Set();
4282
5299
  const rows = /* @__PURE__ */ new Set();
4283
5300
  for (let y = lockRows.top; y <= Math.min(lockRows.bottom, faceBottom); y++) {
4284
- const runs = runsAt(lock, y);
5301
+ const runs = runsAt2(lock, y);
4285
5302
  if (runs.length === 0) continue;
4286
5303
  const from = side < 0 ? runs[0] : runs[runs.length - 2];
4287
5304
  const to = side < 0 ? runs[1] : runs[runs.length - 1];
4288
5305
  const start = side < 0 ? from : Math.max(from, to - lean);
4289
5306
  const end = side < 0 ? Math.min(to, from + lean) : to;
4290
- const faceRuns = runsAt(face, y);
4291
- const backRuns = runsAt(back, y);
5307
+ const faceRuns = runsAt2(face, y);
5308
+ const backRuns = runsAt2(back, y);
4292
5309
  for (let x = start; x < end; x++) {
4293
5310
  if (covers(faceRuns, x) || covers(backRuns, x)) continue;
4294
5311
  bare.add(x);
@@ -6682,8 +7699,18 @@ function formatPatchReports(reports) {
6682
7699
  return `PATCH ${r.index} ${r.target} at ${at}: ${r.moved} of ${r.of} points (${where}), largest move ${r.maxPx} model px`;
6683
7700
  });
6684
7701
  }
7702
+ function formatCustomPartReports(parts) {
7703
+ return parts.map(
7704
+ (p) => `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}`
7705
+ );
7706
+ }
7707
+ function formatBakeChecks(bakes) {
7708
+ return bakes.map(
7709
+ (b) => `BAKE ${b.part} ${b.param}: ${b.vertices} vertices, stops ${b.stops.join(",")}, error ${Math.round(b.errorPx * 1e3) / 1e3} px`
7710
+ );
7711
+ }
6685
7712
  function createIkiMcpServer() {
6686
- const server = new McpServer({ name: "iki", version: "0.33.1" });
7713
+ const server = new McpServer({ name: "iki", version: "0.34.0" });
6687
7714
  server.registerTool(
6688
7715
  "validate_iki",
6689
7716
  {
@@ -6775,7 +7802,7 @@ function createIkiMcpServer() {
6775
7802
  server.registerTool(
6776
7803
  "auto_rig_from_layers",
6777
7804
  {
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.",
7805
+ 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`. 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
7806
  inputSchema: {
6780
7807
  layers: z.array(
6781
7808
  z.object({
@@ -6798,7 +7825,7 @@ function createIkiMcpServer() {
6798
7825
  noseShift: z.number().optional(),
6799
7826
  mouthShift: z.number().optional()
6800
7827
  }).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."
7828
+ "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
7829
  ),
6803
7830
  style: z.unknown().optional().describe(
6804
7831
  "Removed in @ikijs/mcp 0.30.0: pass `rigPlan`. Any value here is refused with the field map."
@@ -6819,6 +7846,63 @@ function createIkiMcpServer() {
6819
7846
  }).passthrough().optional().describe(
6820
7847
  "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
7848
  ),
7849
+ customParts: z.array(
7850
+ z.object({
7851
+ id: z.string().describe(
7852
+ "The part's id: a plain identifier, not a role's name or a part id."
7853
+ ),
7854
+ path: z.string().describe(
7855
+ "The part's own PNG, the same size as the role layers (resolved against cwd), drawn alone and whole on a transparent ground."
7856
+ ),
7857
+ anchor: z.string().describe("The role whose layer the part is fixed against."),
7858
+ tie: z.array(z.number()).length(2).describe(
7859
+ "[x, y] in canvas px where the part meets the anchor: inside both the part's alpha box and the anchor layer's."
7860
+ ),
7861
+ after: z.string().describe(
7862
+ "A role of the set: the part is drawn right after that role's last part."
7863
+ ),
7864
+ deformer: z.string().optional().describe(
7865
+ "The matrix deformer it hangs on; only `headDeformer` (the default) is accepted."
7866
+ ),
7867
+ rigid: z.boolean().optional().describe(
7868
+ "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."
7869
+ )
7870
+ }).passthrough()
7871
+ ).optional().describe(
7872
+ "Parts the auto-rigger has no role for, each `{ id, path, anchor, tie, after, deformer?, rigid? }`. 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."
7873
+ ),
7874
+ bakes: z.object({
7875
+ targets: z.array(
7876
+ z.object({
7877
+ id: z.string().optional(),
7878
+ param: z.string(),
7879
+ parts: z.array(z.string()),
7880
+ box: z.object({
7881
+ x: z.number(),
7882
+ y: z.number(),
7883
+ w: z.number(),
7884
+ h: z.number()
7885
+ }).passthrough().optional(),
7886
+ grid: z.object({ cols: z.number(), rows: z.number() }).passthrough(),
7887
+ stops: z.record(
7888
+ z.string(),
7889
+ z.array(z.array(z.number()).length(2))
7890
+ ),
7891
+ mirror: z.boolean().optional(),
7892
+ why: z.string().optional()
7893
+ }).passthrough()
7894
+ ),
7895
+ meshes: z.record(
7896
+ z.string(),
7897
+ z.object({
7898
+ rows: z.array(z.number()).optional(),
7899
+ cols: z.number().optional(),
7900
+ cellPx: z.number().optional()
7901
+ }).passthrough()
7902
+ ).optional()
7903
+ }).passthrough().optional().describe(
7904
+ "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."
7905
+ ),
6822
7906
  patches: z.array(
6823
7907
  z.object({
6824
7908
  target: z.string(),
@@ -6845,7 +7929,11 @@ function createIkiMcpServer() {
6845
7929
  ...args,
6846
7930
  // `.length(2)` makes each region span a pair, which its inferred
6847
7931
  // `number[]` cannot say.
6848
- patches: args.patches
7932
+ patches: args.patches,
7933
+ customParts: args.customParts,
7934
+ // Each stop's `.length(2)` makes it a pair, which its inferred
7935
+ // `number[]` cannot say.
7936
+ bakes: args.bakes
6849
7937
  });
6850
7938
  const text = r.ok ? [
6851
7939
  r.path,
@@ -6853,7 +7941,10 @@ function createIkiMcpServer() {
6853
7941
  ...formatPatchReports(r.patches ?? []),
6854
7942
  ...formatFoldReport(r.folds, r.canvas),
6855
7943
  ...formatPhysicsReport(r.physics),
6856
- ...formatHairSideReport(r.turn?.hairSide, r.canvas)
7944
+ ...formatHairSideReport(r.turn?.hairSide, r.canvas),
7945
+ ...formatCustomPartReports(r.customParts?.parts ?? []),
7946
+ ...formatBakeChecks(r.customParts?.bakes ?? []),
7947
+ ...r.customParts ? formatCustomGate(r.customParts.gate) : []
6857
7948
  ].join("\n") : `INVALID: ${r.error}`;
6858
7949
  return { content: [{ type: "text", text }], structuredContent: r };
6859
7950
  } catch (err) {
@@ -6945,7 +8036,7 @@ function createIkiMcpServer() {
6945
8036
  server.registerTool(
6946
8037
  "measure_turn_reference",
6947
8038
  {
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.",
8039
+ 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
8040
  inputSchema: {
6950
8041
  front: z.string().describe("Front-facing PNG file path (resolved against cwd)."),
6951
8042
  turned: z.string().describe("The same character turned, as a PNG file path."),
@@ -7028,7 +8119,10 @@ function createIkiMcpServer() {
7028
8119
  }).optional()
7029
8120
  })
7030
8121
  ).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`."
8122
+ "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."
8123
+ ),
8124
+ hideParts: z.array(z.string()).optional().describe(
8125
+ "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, 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
8126
  )
7033
8127
  }
7034
8128
  },
@@ -7064,12 +8158,65 @@ function createIkiMcpServer() {
7064
8158
  }
7065
8159
  }
7066
8160
  );
8161
+ server.registerTool(
8162
+ "probe_rig",
8163
+ {
8164
+ 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.",
8165
+ inputSchema: {
8166
+ modelPath: z.string().describe(
8167
+ "Rigged .iki file path (resolved against cwd; must sit under the working directory)."
8168
+ ),
8169
+ queries: z.array(
8170
+ z.discriminatedUnion("op", [
8171
+ z.object({
8172
+ op: z.literal("paint"),
8173
+ path: z.string().describe(
8174
+ "Canvas-sized layer PNG (resolved against cwd), the drawing the part was built from."
8175
+ )
8176
+ }),
8177
+ z.object({
8178
+ op: z.enum(["land", "displacement"]),
8179
+ part: z.string().describe("A part id of the model."),
8180
+ points: z.array(z.array(z.number()).length(2)).describe(
8181
+ "Canvas-px points `[x, y]`, at most 5000, each on the part at rest."
8182
+ ),
8183
+ pose: z.record(z.string(), z.number()).optional().describe(
8184
+ "Parameter id to value; the others stay at their defaults."
8185
+ )
8186
+ })
8187
+ ])
8188
+ ).describe("The queries, answered in order; at most 64 per call."),
8189
+ outputPath: z.string().optional().describe(
8190
+ "A path ending in `.probe.json` (resolved against cwd, under it; its folder must exist) to write the results to."
8191
+ )
8192
+ }
8193
+ },
8194
+ async (args) => {
8195
+ try {
8196
+ const r = await probeRig(args);
8197
+ const text = !r.ok ? `INVALID: ${r.error}` : "results" in r ? JSON.stringify(r.results) : [r.outputPath, ...r.lines].join("\n");
8198
+ return { content: [{ type: "text", text }], structuredContent: r };
8199
+ } catch (err) {
8200
+ const error = err instanceof Error ? err.message : String(err);
8201
+ return {
8202
+ content: [{ type: "text", text: `Unexpected error: ${error}` }],
8203
+ structuredContent: { ok: false, error },
8204
+ isError: true
8205
+ };
8206
+ }
8207
+ }
8208
+ );
7067
8209
  return server;
7068
8210
  }
7069
8211
 
7070
8212
  export {
7071
8213
  checkModelFolds,
7072
8214
  formatFoldReport,
8215
+ probeRig,
8216
+ CUSTOM_GATE_LIMITS,
8217
+ failedCustomGate,
8218
+ checkCustomGate,
8219
+ formatCustomGate,
7073
8220
  checkNod,
7074
8221
  checkSweep,
7075
8222
  formatSweepReport,
@@ -7092,4 +8239,4 @@ export {
7092
8239
  formatPhysicsReport,
7093
8240
  createIkiMcpServer
7094
8241
  };
7095
- //# sourceMappingURL=chunk-VTJEYDRK.mjs.map
8242
+ //# sourceMappingURL=chunk-HKJT3Q6G.mjs.map