@ikijs/mcp 0.24.0 → 0.25.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.
package/dist/index.js CHANGED
@@ -31,9 +31,11 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
33
  autoRigFromLayers: () => autoRigFromLayers,
34
+ checkModelFolds: () => checkModelFolds,
34
35
  composeLayersFromParts: () => composeLayersFromParts,
35
36
  createIkiMcpServer: () => createIkiMcpServer,
36
37
  describeIki: () => describeIki,
38
+ formatFoldReport: () => formatFoldReport,
37
39
  formatMeasureReport: () => formatMeasureReport,
38
40
  formatTurnReport: () => formatTurnReport,
39
41
  listStandardParameters: () => listStandardParameters,
@@ -50,12 +52,788 @@ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
50
52
 
51
53
  // src/tools.ts
52
54
  var import_node_path2 = __toESM(require("path"));
55
+ var import_format7 = require("@ikijs/format");
56
+ var import_editor3 = require("@ikijs/editor");
57
+
58
+ // src/fold-report.ts
59
+ var import_editor = require("@ikijs/editor");
60
+
61
+ // ../engine/src/math.ts
62
+ function clamp(value, min, max) {
63
+ return Math.max(min, Math.min(max, value));
64
+ }
65
+ function lerp(a, b, t) {
66
+ return a + (b - a) * t;
67
+ }
68
+
69
+ // ../engine/src/parameter-store.ts
70
+ var ParameterStore = class {
71
+ params = /* @__PURE__ */ new Map();
72
+ values = /* @__PURE__ */ new Map();
73
+ /**
74
+ * Resting value per id: the declared default clamped into range, resolved
75
+ * ONCE here so `reset()` is a straight copy and a malformed descriptor is
76
+ * reported once rather than on every reset.
77
+ */
78
+ defaults = /* @__PURE__ */ new Map();
79
+ constructor(parameters) {
80
+ for (const param of parameters) {
81
+ this.params.set(param.id, param);
82
+ if (!Number.isFinite(param.default)) {
83
+ console.error(
84
+ `Iki: parameter "${param.id}" has a non-finite default; resting at the neutral in-range value instead`
85
+ );
86
+ }
87
+ const base = Number.isFinite(param.default) ? param.default : 0;
88
+ this.defaults.set(param.id, clamp(base, param.min, param.max));
89
+ }
90
+ for (const [id, value] of this.defaults) this.values.set(id, value);
91
+ }
92
+ /**
93
+ * Set a parameter's value, clamped to its range. Unknown ids are ignored, as
94
+ * are non-finite values: this is the boundary a host drives with live signals,
95
+ * and `clamp` cannot filter NaN (`Math.max(min, Math.min(max, NaN))` is NaN),
96
+ * so one bad lip-sync/gaze frame would otherwise poison every binding that
97
+ * reads the parameter. A dropped write holds the last good pose.
98
+ */
99
+ set(id, value) {
100
+ const param = this.params.get(id);
101
+ if (!param) return;
102
+ if (!Number.isFinite(value)) return;
103
+ this.values.set(id, clamp(value, param.min, param.max));
104
+ }
105
+ /** Current value, or 0 if the id is unknown. */
106
+ get(id) {
107
+ return this.values.get(id) ?? 0;
108
+ }
109
+ /** Position of a parameter within its range, 0..1. */
110
+ normalized(id) {
111
+ const param = this.params.get(id);
112
+ if (!param || param.max === param.min) return 0;
113
+ return (this.get(id) - param.min) / (param.max - param.min);
114
+ }
115
+ /** Reset every parameter to its resting value (see `defaults`). */
116
+ reset() {
117
+ for (const [id, value] of this.defaults) this.values.set(id, value);
118
+ }
119
+ list() {
120
+ return [...this.params.values()];
121
+ }
122
+ };
123
+
124
+ // ../engine/src/affine.ts
125
+ function translate(tx, ty) {
126
+ return [1, 0, 0, 1, tx, ty];
127
+ }
128
+ function scale(sx, sy) {
129
+ return [sx, 0, 0, sy, 0, 0];
130
+ }
131
+ function rotate(degrees) {
132
+ const r = degrees * Math.PI / 180;
133
+ const c = Math.cos(r);
134
+ const s = Math.sin(r);
135
+ return [c, s, -s, c, 0, 0];
136
+ }
137
+ function multiply(a, b) {
138
+ return [
139
+ a[0] * b[0] + a[2] * b[1],
140
+ a[1] * b[0] + a[3] * b[1],
141
+ a[0] * b[2] + a[2] * b[3],
142
+ a[1] * b[2] + a[3] * b[3],
143
+ a[0] * b[4] + a[2] * b[5] + a[4],
144
+ a[1] * b[4] + a[3] * b[5] + a[5]
145
+ ];
146
+ }
147
+
148
+ // ../engine/src/warp.ts
149
+ function accumulateKeyformOffsets(keyforms, value, out) {
150
+ const ks = keyforms;
151
+ if (value <= ks[0].value) {
152
+ const { offsets } = ks[0];
153
+ for (let i = 0; i < offsets.length; i++) {
154
+ out[i] += offsets[i];
155
+ }
156
+ } else if (value >= ks[ks.length - 1].value) {
157
+ const { offsets } = ks[ks.length - 1];
158
+ for (let i = 0; i < offsets.length; i++) {
159
+ out[i] += offsets[i];
160
+ }
161
+ } else {
162
+ let lo = ks[0];
163
+ let hi = ks[1];
164
+ for (let k = 1; k < ks.length - 1; k++) {
165
+ if (ks[k].value <= value) {
166
+ lo = ks[k];
167
+ hi = ks[k + 1];
168
+ }
169
+ }
170
+ const t = (value - lo.value) / (hi.value - lo.value);
171
+ const loOff = lo.offsets;
172
+ const hiOff = hi.offsets;
173
+ for (let i = 0; i < loOff.length; i++) {
174
+ out[i] += loOff[i] + (hiOff[i] - loOff[i]) * t;
175
+ }
176
+ }
177
+ }
178
+ function accumulate2DKeyformOffsets(valuesX, valuesY, keyforms2d, vx, vy, out) {
179
+ const lastX = valuesX.length - 1;
180
+ const lastY = valuesY.length - 1;
181
+ let ix;
182
+ let tx;
183
+ if (vx <= valuesX[0]) {
184
+ ix = 0;
185
+ tx = 0;
186
+ } else if (vx >= valuesX[lastX]) {
187
+ ix = lastX - 1;
188
+ tx = 1;
189
+ } else {
190
+ ix = 0;
191
+ for (let k = 0; k < lastX - 1; k++) {
192
+ if (valuesX[k + 1] <= vx) ix = k + 1;
193
+ }
194
+ tx = (vx - valuesX[ix]) / (valuesX[ix + 1] - valuesX[ix]);
195
+ }
196
+ let iy;
197
+ let ty;
198
+ if (vy <= valuesY[0]) {
199
+ iy = 0;
200
+ ty = 0;
201
+ } else if (vy >= valuesY[lastY]) {
202
+ iy = lastY - 1;
203
+ ty = 1;
204
+ } else {
205
+ iy = 0;
206
+ for (let k = 0; k < lastY - 1; k++) {
207
+ if (valuesY[k + 1] <= vy) iy = k + 1;
208
+ }
209
+ ty = (vy - valuesY[iy]) / (valuesY[iy + 1] - valuesY[iy]);
210
+ }
211
+ const W = valuesX.length;
212
+ const c00 = keyforms2d[iy * W + ix];
213
+ const c10 = keyforms2d[iy * W + ix + 1];
214
+ const c01 = keyforms2d[(iy + 1) * W + ix];
215
+ const c11 = keyforms2d[(iy + 1) * W + ix + 1];
216
+ const o00 = c00.offsets;
217
+ const o10 = c10.offsets;
218
+ const o01 = c01.offsets;
219
+ const o11 = c11.offsets;
220
+ for (let n = 0; n < o00.length; n++) {
221
+ const top = o00[n] + (o10[n] - o00[n]) * tx;
222
+ const bot = o01[n] + (o11[n] - o01[n]) * tx;
223
+ out[n] += top + (bot - top) * ty;
224
+ }
225
+ }
226
+ function applyWarps(rest, warps, params, out) {
227
+ out.set(rest);
228
+ if (!warps || warps.length === 0) return;
229
+ for (const warp of warps) {
230
+ accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), out);
231
+ }
232
+ }
233
+
234
+ // ../engine/src/warp-grid.ts
235
+ function deformWarpGrid(d, params) {
236
+ const points = Float32Array.from(d.grid.points);
237
+ for (const warp of d.warps ?? []) {
238
+ accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), points);
239
+ }
240
+ if (d.warp2d !== void 0) {
241
+ accumulate2DKeyformOffsets(
242
+ d.warp2d.valuesX,
243
+ d.warp2d.valuesY,
244
+ d.warp2d.keyforms2d,
245
+ params.get(d.warp2d.parameter),
246
+ params.get(d.warp2d.parameterY),
247
+ points
248
+ );
249
+ }
250
+ return points;
251
+ }
252
+ function transformGridPoints(points, affine, out = new Float32Array(points.length)) {
253
+ for (let i = 0; i < points.length; i += 2) {
254
+ const x = points[i];
255
+ const y = points[i + 1];
256
+ out[i] = affine[0] * x + affine[2] * y + affine[4];
257
+ out[i + 1] = affine[1] * x + affine[3] * y + affine[5];
258
+ }
259
+ return out;
260
+ }
261
+ function bindPointToRestGrid(x, y, restGrid) {
262
+ const { cols, rows, points } = restGrid;
263
+ const stride = cols + 1;
264
+ let col = cols - 1;
265
+ for (let c = 0; c < cols; c++) {
266
+ const xRight2 = points[(c + 1) * 2];
267
+ if (x < xRight2) {
268
+ col = c;
269
+ break;
270
+ }
271
+ }
272
+ const xLeft = points[col * 2];
273
+ const xRight = points[(col + 1) * 2];
274
+ const s = clamp((x - xLeft) / (xRight - xLeft), 0, 1);
275
+ let row = rows - 1;
276
+ for (let r = 0; r < rows; r++) {
277
+ const yBottom2 = points[(r + 1) * stride * 2 + 1];
278
+ if (y > yBottom2) {
279
+ row = r;
280
+ break;
281
+ }
282
+ }
283
+ const yTop = points[row * stride * 2 + 1];
284
+ const yBottom = points[(row + 1) * stride * 2 + 1];
285
+ const t = clamp((yTop - y) / (yTop - yBottom), 0, 1);
286
+ return { cell: row * cols + col, s, t };
287
+ }
288
+ function applyWarpToChild(localVerts, partAffine, restGrid, deformedGrid, out) {
289
+ const n = localVerts.length / 2;
290
+ for (let v = 0; v < n; v++) {
291
+ const lx = localVerts[v * 2];
292
+ const ly = localVerts[v * 2 + 1];
293
+ const mx = partAffine[0] * lx + partAffine[2] * ly + partAffine[4];
294
+ const my = partAffine[1] * lx + partAffine[3] * ly + partAffine[5];
295
+ const binding = bindPointToRestGrid(mx, my, restGrid);
296
+ const [sx, sy] = sampleWarpGrid(deformedGrid, binding);
297
+ out[v * 2] = sx;
298
+ out[v * 2 + 1] = sy;
299
+ }
300
+ }
301
+ function sampleWarpGrid(grid, binding) {
302
+ const { cols, points } = grid;
303
+ const stride = cols + 1;
304
+ const row = Math.floor(binding.cell / cols);
305
+ const col = binding.cell % cols;
306
+ const { s, t } = binding;
307
+ const i00 = (row * stride + col) * 2;
308
+ const i10 = (row * stride + col + 1) * 2;
309
+ const i01 = ((row + 1) * stride + col) * 2;
310
+ const i11 = ((row + 1) * stride + col + 1) * 2;
311
+ const topX = points[i00] + (points[i10] - points[i00]) * s;
312
+ const topY = points[i00 + 1] + (points[i10 + 1] - points[i00 + 1]) * s;
313
+ const botX = points[i01] + (points[i11] - points[i01]) * s;
314
+ const botY = points[i01 + 1] + (points[i11 + 1] - points[i01 + 1]) * s;
315
+ return [topX + (botX - topX) * t, topY + (botY - topY) * t];
316
+ }
317
+ function warpRigidFrame(pivot, restGrid, localPoints) {
318
+ const { cols, rows } = restGrid;
319
+ const binding = bindPointToRestGrid(pivot.x, pivot.y, restGrid);
320
+ const [px2, py] = sampleWarpGrid({ cols, rows, points: localPoints }, binding);
321
+ const stride = cols + 1;
322
+ const row = Math.floor(binding.cell / cols);
323
+ const col = binding.cell % cols;
324
+ const { s, t } = binding;
325
+ const i00 = (row * stride + col) * 2;
326
+ const i10 = (row * stride + col + 1) * 2;
327
+ const i01 = ((row + 1) * stride + col) * 2;
328
+ const i11 = ((row + 1) * stride + col + 1) * 2;
329
+ const rest = restGrid.points;
330
+ const cellWidth = rest[(col + 1) * 2] - rest[col * 2];
331
+ const cellHeight = rest[row * stride * 2 + 1] - rest[(row + 1) * stride * 2 + 1];
332
+ const q = localPoints;
333
+ const exX = lerp(q[i10] - q[i00], q[i11] - q[i01], t) / cellWidth;
334
+ const exY = lerp(q[i10 + 1] - q[i00 + 1], q[i11 + 1] - q[i01 + 1], t) / cellWidth;
335
+ const eyX = -lerp(q[i01] - q[i00], q[i11] - q[i10], s) / cellHeight;
336
+ const eyY = -lerp(q[i01 + 1] - q[i00 + 1], q[i11 + 1] - q[i10 + 1], s) / cellHeight;
337
+ const theta = Math.atan2(exY - eyX, exX + eyY);
338
+ const c = Math.cos(theta);
339
+ const sn = Math.sin(theta);
340
+ return [
341
+ c,
342
+ sn,
343
+ -sn,
344
+ c,
345
+ px2 - (c * pivot.x - sn * pivot.y),
346
+ py - (sn * pivot.x + c * pivot.y)
347
+ ];
348
+ }
349
+
350
+ // ../engine/src/deform.ts
351
+ var IDENTITY_TRANSFORM = {
352
+ x: 0,
353
+ y: 0,
354
+ rotation: 0,
355
+ scaleX: 1,
356
+ scaleY: 1,
357
+ opacity: 1
358
+ };
359
+ function evaluateTransform(transform, bindings, params) {
360
+ const base = transform ?? IDENTITY_TRANSFORM;
361
+ const result = {
362
+ x: base.x,
363
+ y: base.y,
364
+ rotation: base.rotation ?? 0,
365
+ scaleX: base.scaleX ?? 1,
366
+ scaleY: base.scaleY ?? 1,
367
+ opacity: base.opacity ?? 1
368
+ };
369
+ for (const binding of bindings ?? []) {
370
+ const t = params.normalized(binding.parameter);
371
+ const value = binding.from + (binding.to - binding.from) * t;
372
+ switch (binding.channel) {
373
+ case "translateX":
374
+ result.x += value;
375
+ break;
376
+ case "translateY":
377
+ result.y += value;
378
+ break;
379
+ case "rotate":
380
+ result.rotation += value;
381
+ break;
382
+ case "scaleX":
383
+ result.scaleX += value;
384
+ break;
385
+ case "scaleY":
386
+ result.scaleY += value;
387
+ break;
388
+ case "opacity":
389
+ result.opacity *= value;
390
+ break;
391
+ }
392
+ }
393
+ return result;
394
+ }
395
+ function deformerLocalMatrix(d, params) {
396
+ const t = evaluateTransform(d.transform, d.bindings, params);
397
+ const trs = multiply(
398
+ multiply(translate(t.x, t.y), rotate(t.rotation)),
399
+ scale(t.scaleX, t.scaleY)
400
+ );
401
+ return multiply(
402
+ multiply(translate(d.pivot.x, d.pivot.y), trs),
403
+ translate(-d.pivot.x, -d.pivot.y)
404
+ );
405
+ }
406
+ function resolveDeformers(deformers, params) {
407
+ const byId = new Map(deformers.map((d) => [d.id, d]));
408
+ const worlds = /* @__PURE__ */ new Map();
409
+ const grids = /* @__PURE__ */ new Map();
410
+ const localWarps = /* @__PURE__ */ new Map();
411
+ function parentOf(d) {
412
+ if (d.parent === void 0) return void 0;
413
+ const parent = byId.get(d.parent);
414
+ if (!parent) {
415
+ throw new Error(
416
+ `unresolved deformer parent "${d.parent}" \u2014 model not validated?`
417
+ );
418
+ }
419
+ return parent;
420
+ }
421
+ function resolveWorld(d) {
422
+ const cached = worlds.get(d.id);
423
+ if (cached) return cached;
424
+ const local = deformerLocalMatrix(d, params);
425
+ const parent = parentOf(d);
426
+ let world;
427
+ if (parent === void 0) {
428
+ world = local;
429
+ } else if (parent.kind === "warp") {
430
+ const warp = resolveWarp(parent);
431
+ const ridden = multiply(
432
+ warpRigidFrame(d.pivot, parent.grid, warp.localGrid),
433
+ local
434
+ );
435
+ world = warp.parentWorld ? multiply(warp.parentWorld, ridden) : ridden;
436
+ } else {
437
+ world = multiply(resolveWorld(parent), local);
438
+ }
439
+ worlds.set(d.id, world);
440
+ return world;
441
+ }
442
+ function resolveWarp(d) {
443
+ const cached = localWarps.get(d.id);
444
+ if (cached) return cached;
445
+ const parent = parentOf(d);
446
+ if (parent?.kind === "warp") {
447
+ throw new Error(
448
+ `warp deformer "${d.id}" hangs from warp "${parent.id}" \u2014 model not validated?`
449
+ );
450
+ }
451
+ const parentWorld = parent && resolveWorld(parent);
452
+ const localGrid = deformWarpGrid(d, params);
453
+ grids.set(d.id, {
454
+ cols: d.grid.cols,
455
+ rows: d.grid.rows,
456
+ points: parentWorld ? transformGridPoints(localGrid, parentWorld) : localGrid
457
+ });
458
+ const resolved = { localGrid, parentWorld };
459
+ localWarps.set(d.id, resolved);
460
+ return resolved;
461
+ }
462
+ for (const d of deformers) {
463
+ if (d.kind === "warp") resolveWarp(d);
464
+ else resolveWorld(d);
465
+ }
466
+ return { worlds, grids };
467
+ }
468
+
469
+ // ../engine/src/idle-motion.ts
53
470
  var import_format = require("@ikijs/format");
54
- var import_editor2 = require("@ikijs/editor");
471
+
472
+ // ../engine/src/frame-clock.ts
473
+ var FIXED_DT_S = 1 / 60;
474
+
475
+ // ../engine/src/idle-motion.ts
476
+ var BLINK_CLOSE_MS = 60;
477
+ var BLINK_HOLD_MS = 20;
478
+ var BLINK_OPEN_MS = 100;
479
+ var BLINK_DURATION_MS = BLINK_CLOSE_MS + BLINK_HOLD_MS + BLINK_OPEN_MS;
480
+
481
+ // ../engine/src/hair-chain-motion.ts
482
+ var DEG2RAD = Math.PI / 180;
483
+ var RAD2DEG = 180 / Math.PI;
484
+
485
+ // ../engine/src/iki-motion.ts
486
+ var import_format4 = require("@ikijs/format");
487
+
488
+ // ../engine/src/clip-player.ts
489
+ var import_format2 = require("@ikijs/format");
490
+
491
+ // ../engine/src/expression-player.ts
492
+ var import_format3 = require("@ikijs/format");
493
+
494
+ // ../engine/src/iki-motion.ts
495
+ var HEAD_AND_GAZE = /* @__PURE__ */ new Set([
496
+ import_format4.StandardParameter.AngleX,
497
+ import_format4.StandardParameter.AngleY,
498
+ import_format4.StandardParameter.AngleZ,
499
+ import_format4.StandardParameter.EyeballX,
500
+ import_format4.StandardParameter.EyeballY
501
+ ]);
502
+
503
+ // ../engine/src/folds.ts
504
+ var import_format5 = require("@ikijs/format");
505
+ var FLIP = 0;
506
+ var COLLAPSE = 0.1;
507
+ var ANGLES = [
508
+ import_format5.StandardParameter.AngleX,
509
+ import_format5.StandardParameter.AngleY,
510
+ import_format5.StandardParameter.AngleZ,
511
+ import_format5.StandardParameter.BodyAngleX,
512
+ import_format5.StandardParameter.BodyAngleY,
513
+ import_format5.StandardParameter.BodyAngleZ
514
+ ];
515
+ var CROSSES = [
516
+ [import_format5.StandardParameter.EyeOpenLeft],
517
+ [import_format5.StandardParameter.EyeOpenRight],
518
+ [import_format5.StandardParameter.MouthOpen],
519
+ [import_format5.StandardParameter.ArmLeft, import_format5.StandardParameter.ArmRight],
520
+ [import_format5.StandardParameter.ElbowLeft, import_format5.StandardParameter.ElbowRight]
521
+ ];
522
+ function foldPoses(model) {
523
+ const byId = new Map(
524
+ model.parameters.filter((p) => p.min !== p.max).map((p) => [p.id, p])
525
+ );
526
+ const declared = (ids) => ids.flatMap((id) => byId.get(id) ?? []);
527
+ const poses = [];
528
+ const names = /* @__PURE__ */ new Set();
529
+ const add = (values) => {
530
+ const name = poseName(values);
531
+ if (names.has(name)) return;
532
+ names.add(name);
533
+ poses.push({ name, values });
534
+ };
535
+ add({});
536
+ for (const p of byId.values()) {
537
+ add({ [p.id]: p.min });
538
+ add({ [p.id]: p.max });
539
+ }
540
+ const angles = declared(ANGLES);
541
+ if (angles.length === 0) return poses;
542
+ const expand = (corners, groups) => {
543
+ for (const group of groups) {
544
+ corners = corners.flatMap(
545
+ (values) => ["min", "max"].map((end) => {
546
+ const next = { ...values };
547
+ for (const p of group) next[p.id] = p[end];
548
+ return next;
549
+ })
550
+ );
551
+ }
552
+ return corners;
553
+ };
554
+ const angleCorners = expand(
555
+ [{}],
556
+ angles.map((p) => [p])
557
+ );
558
+ for (const values of angleCorners) add(values);
559
+ const crosses = CROSSES.map(declared).filter((g) => g.length > 0);
560
+ for (const values of expand(angleCorners, crosses)) add(values);
561
+ return poses;
562
+ }
563
+ function poseName(values) {
564
+ const ids = Object.keys(values).sort();
565
+ if (ids.length === 0) return "rest";
566
+ return ids.map((id) => `${id}=${values[id]}`).join(" ");
567
+ }
568
+ function staticDeformers(model) {
569
+ return (model.deformers ?? []).map(
570
+ (d) => d.kind === "warp" ? { ...d, warps: void 0, warp2d: void 0 } : { ...d, bindings: void 0 }
571
+ );
572
+ }
573
+ function cornerAreas(points, cols, rows) {
574
+ const stride = cols + 1;
575
+ const out = new Float64Array(cols * rows * 4);
576
+ for (let r = 0; r < rows; r++) {
577
+ for (let c = 0; c < cols; c++) {
578
+ const tl = r * stride + c;
579
+ const [tr, bl, br] = [tl + 1, tl + stride, tl + stride + 1];
580
+ const i = (r * cols + c) * 4;
581
+ out[i] = doubledArea(points, bl, br, tl);
582
+ out[i + 1] = doubledArea(points, br, tr, bl);
583
+ out[i + 2] = doubledArea(points, tr, tl, br);
584
+ out[i + 3] = doubledArea(points, tl, bl, tr);
585
+ }
586
+ }
587
+ return out;
588
+ }
589
+ function doubledArea(points, p, q, s) {
590
+ const ax = points[q * 2] - points[p * 2];
591
+ const ay = points[q * 2 + 1] - points[p * 2 + 1];
592
+ const bx = points[s * 2] - points[p * 2];
593
+ const by = points[s * 2 + 1] - points[p * 2 + 1];
594
+ return ax * by - ay * bx;
595
+ }
596
+ function triangleAreas(points, indices) {
597
+ const out = new Float64Array(indices.length / 3);
598
+ for (let t = 0; t < out.length; t++) {
599
+ const i = t * 3;
600
+ out[t] = doubledArea(points, indices[i], indices[i + 1], indices[i + 2]);
601
+ }
602
+ return out;
603
+ }
604
+ function placement(part, t) {
605
+ return multiply(
606
+ multiply(translate(t.x, t.y), rotate(t.rotation)),
607
+ scale(part.width * t.scaleX, part.height * t.scaleY)
608
+ );
609
+ }
610
+ function keepLeast(sweep, areas, pose, expected) {
611
+ const slot = expected(sweep.target) ? "expected" : "worst";
612
+ for (let i = 0; i < areas.length; i++) {
613
+ const rest = sweep.restAreas[i];
614
+ if (Math.abs(rest) < sweep.tiny) continue;
615
+ const ratio = areas[i] / rest;
616
+ if (ratio < (sweep[slot]?.ratio ?? Infinity)) {
617
+ sweep[slot] = { ratio, at: i, pose };
618
+ }
619
+ }
620
+ }
621
+ function partSweep(part, mesh, deformers, worlds, store) {
622
+ const warpDeformer = deformers.find(
623
+ (d) => d.kind === "warp" && d.id === part.deformer
624
+ );
625
+ const frame = warpDeformer ? warpDeformer.parent : part.deformer;
626
+ const placed = placement(
627
+ part,
628
+ evaluateTransform(part.transform, void 0, store)
629
+ );
630
+ const restPoints = transformGridPoints(
631
+ mesh.vertices,
632
+ frame === void 0 ? placed : multiply(worlds.get(frame), placed),
633
+ new Float64Array(mesh.vertices.length)
634
+ );
635
+ return {
636
+ target: { kind: "part", id: part.id },
637
+ restAreas: triangleAreas(restPoints, mesh.indices),
638
+ tiny: 1e-9 * part.width * part.height,
639
+ part,
640
+ indices: mesh.indices,
641
+ warpDeformer,
642
+ vertices: Float32Array.from(mesh.vertices),
643
+ local: new Float32Array(mesh.vertices.length),
644
+ landed: new Float32Array(mesh.vertices.length),
645
+ restPoints
646
+ };
647
+ }
648
+ function landPart(sweep, store, { worlds, grids }) {
649
+ const { part, warpDeformer, local, landed } = sweep;
650
+ applyWarps(sweep.vertices, part.warps, store, local);
651
+ const placed = placement(
652
+ part,
653
+ evaluateTransform(part.transform, part.bindings, store)
654
+ );
655
+ if (warpDeformer) {
656
+ const grid = grids.get(warpDeformer.id);
657
+ applyWarpToChild(local, placed, warpDeformer.grid, grid, landed);
658
+ } else if (part.deformer !== void 0) {
659
+ const world = worlds.get(part.deformer);
660
+ transformGridPoints(local, multiply(world, placed), landed);
661
+ } else {
662
+ transformGridPoints(local, placed, landed);
663
+ }
664
+ return landed;
665
+ }
666
+ function checkFolds(model, options = {}) {
667
+ const poses = options.poses ?? foldPoses(model);
668
+ const deformers = model.deformers ?? [];
669
+ const restStore = new ParameterStore(model.parameters);
670
+ const { worlds } = resolveDeformers(staticDeformers(model), restStore);
671
+ const gridSweeps = [];
672
+ for (const d of deformers) {
673
+ if (d.kind !== "warp") continue;
674
+ const { cols, rows, points } = d.grid;
675
+ const width = points[cols * 2] - points[0];
676
+ const height = points[1] - points[rows * (cols + 1) * 2 + 1];
677
+ gridSweeps.push({
678
+ deformer: d,
679
+ target: { kind: "deformer", id: d.id },
680
+ restAreas: cornerAreas(points, cols, rows),
681
+ // The validator tolerates 1e-6 of jitter, which can zero a corner's area.
682
+ tiny: 1e-9 * width * height
683
+ });
684
+ }
685
+ const partSweeps = model.parts.flatMap(
686
+ (part) => part.mesh ? [partSweep(part, part.mesh, deformers, worlds, restStore)] : []
687
+ );
688
+ for (const pose of poses) {
689
+ const store = new ParameterStore(model.parameters);
690
+ for (const [id, v] of Object.entries(pose.values)) store.set(id, v);
691
+ const value = (id) => store.get(id);
692
+ const expected = (target) => options.expected?.(target, pose, value) === true;
693
+ for (const sweep of gridSweeps) {
694
+ const { cols, rows } = sweep.deformer.grid;
695
+ const areas = cornerAreas(
696
+ deformWarpGrid(sweep.deformer, store),
697
+ cols,
698
+ rows
699
+ );
700
+ keepLeast(sweep, areas, pose, expected);
701
+ }
702
+ const resolved = resolveDeformers(deformers, store);
703
+ for (const sweep of partSweeps) {
704
+ const areas = triangleAreas(
705
+ landPart(sweep, store, resolved),
706
+ sweep.indices
707
+ );
708
+ keepLeast(sweep, areas, pose, expected);
709
+ }
710
+ }
711
+ const targets = [
712
+ ...gridSweeps.map((sweep) => {
713
+ const { parent } = sweep.deformer;
714
+ const world = parent === void 0 ? void 0 : worlds.get(parent);
715
+ return foldTarget(
716
+ sweep,
717
+ (least) => cellHit(sweep.deformer, least, world)
718
+ );
719
+ }),
720
+ ...partSweeps.map(
721
+ (sweep) => foldTarget(sweep, (least) => triangleHit(sweep, least))
722
+ )
723
+ ];
724
+ const offenders = targets.filter((t) => t.kind !== "ok").sort((a, b) => a.worst.ratio - b.worst.ratio);
725
+ return {
726
+ poses: poses.length,
727
+ thresholds: { flip: FLIP, collapse: COLLAPSE },
728
+ targets,
729
+ offenders
730
+ };
731
+ }
732
+ function foldTarget(sweep, hit) {
733
+ const worst = sweep.worst && hit(sweep.worst);
734
+ const expected = sweep.expected && hit(sweep.expected);
735
+ return { target: sweep.target, kind: classify(worst), worst, expected };
736
+ }
737
+ function cellHit(d, least, parent) {
738
+ const { cols, points } = d.grid;
739
+ const cell = Math.floor(least.at / 4);
740
+ const col = cell % cols;
741
+ const row = Math.floor(cell / cols);
742
+ const stride = cols + 1;
743
+ let x = 0;
744
+ let y = 0;
745
+ for (const i of [
746
+ row * stride + col,
747
+ row * stride + col + 1,
748
+ (row + 1) * stride + col,
749
+ (row + 1) * stride + col + 1
750
+ ]) {
751
+ x += points[i * 2] / 4;
752
+ y += points[i * 2 + 1] / 4;
753
+ }
754
+ const rest = parent ? {
755
+ x: parent[0] * x + parent[2] * y + parent[4],
756
+ y: parent[1] * x + parent[3] * y + parent[5]
757
+ } : { x, y };
758
+ return { ratio: least.ratio, where: { col, row }, pose: least.pose, rest };
759
+ }
760
+ function triangleHit(sweep, least) {
761
+ const { indices, restPoints } = sweep;
762
+ let x = 0;
763
+ let y = 0;
764
+ for (let k = 0; k < 3; k++) {
765
+ const i = indices[least.at * 3 + k];
766
+ x += restPoints[i * 2] / 3;
767
+ y += restPoints[i * 2 + 1] / 3;
768
+ }
769
+ return {
770
+ ratio: least.ratio,
771
+ where: { triangle: least.at },
772
+ pose: least.pose,
773
+ rest: { x, y }
774
+ };
775
+ }
776
+ function classify(worst) {
777
+ if (worst === void 0) return "ok";
778
+ if (worst.ratio <= FLIP) return "flip";
779
+ if (worst.ratio < COLLAPSE) return "collapse";
780
+ return "ok";
781
+ }
782
+
783
+ // src/fold-report.ts
784
+ var import_format6 = require("@ikijs/format");
785
+ var SHUT_BY = new Map([
786
+ ["eye_L", import_format6.StandardParameter.EyeOpenLeft],
787
+ ["lash_lower_L", import_format6.StandardParameter.EyeOpenLeft],
788
+ ["eye_R", import_format6.StandardParameter.EyeOpenRight],
789
+ ["lash_lower_R", import_format6.StandardParameter.EyeOpenRight],
790
+ ...[...import_editor.LIP_ROLES, ...import_editor.LIP_INSIDE_ROLES].map((id) => [
791
+ id,
792
+ import_format6.StandardParameter.MouthOpen
793
+ ])
794
+ ]);
795
+ function checkModelFolds(model) {
796
+ const declared = new Set(model.parameters.map((p) => p.id));
797
+ return checkFolds(model, {
798
+ // The effective value, not the pose's overrides: the auto-rig's mouth
799
+ // rests shut at its default, so `rest` and the other parameters' singles
800
+ // are shut-mouth poses too.
801
+ expected: (target, _pose, value) => {
802
+ if (target.kind !== "part") return false;
803
+ const shutBy = SHUT_BY.get(target.id);
804
+ return shutBy !== void 0 && declared.has(shutBy) && value(shutBy) === 0;
805
+ }
806
+ });
807
+ }
808
+ function formatFoldReport(report, canvas) {
809
+ const lines = report.offenders.length === 0 ? [`FOLDS: none over ${report.poses} poses`] : report.offenders.map((t) => offenderLine(t, t.worst, canvas));
810
+ const closures = report.targets.flatMap((t) => {
811
+ if (t.expected === void 0) return [];
812
+ if (t.expected.ratio >= report.thresholds.collapse) return [];
813
+ const shutBy = SHUT_BY.get(t.target.id);
814
+ const at = shutBy === void 0 ? "" : ` at ${shutBy}=0`;
815
+ return [`${t.target.id} ${ratioText(t.expected.ratio)}${at}`];
816
+ });
817
+ if (closures.length > 0) {
818
+ lines.push(
819
+ `FOLDS expected: by-design closures, not findings \u2014 ${closures.join(", ")}`
820
+ );
821
+ }
822
+ return lines;
823
+ }
824
+ function offenderLine(t, hit, canvas) {
825
+ const where = "triangle" in hit.where ? `triangle ${hit.where.triangle}` : `cell (${hit.where.col},${hit.where.row})`;
826
+ const { x, y } = hit.rest;
827
+ return `FOLD ${t.kind} ${t.target.kind} ${t.target.id} ${where} ratio ${ratioText(hit.ratio)} pose [${hit.pose.name}] rest at (${x.toFixed(1)}, ${y.toFixed(1)}) model space, (${(canvas.width / 2 + x).toFixed(0)}, ${(canvas.height / 2 - y).toFixed(0)}) model px from the top-left`;
828
+ }
829
+ function ratioText(ratio) {
830
+ if (ratio === 0) return "0";
831
+ return Math.abs(ratio) < 0.01 ? ratio.toExponential(1) : ratio.toFixed(2);
832
+ }
55
833
 
56
834
  // src/node-images.ts
57
835
  var import_sharp = __toESM(require("sharp"));
58
- var import_editor = require("@ikijs/editor");
836
+ var import_editor2 = require("@ikijs/editor");
59
837
 
60
838
  // src/limits.ts
61
839
  var import_node_fs = __toESM(require("fs"));
@@ -211,7 +989,7 @@ async function decodePng(filePath) {
211
989
  }
212
990
  }
213
991
  function detectAlphaBbox(rgba, width, height) {
214
- const bbox = (0, import_editor.detectAlphaBbox)(rgba, width, height);
992
+ const bbox = (0, import_editor2.detectAlphaBbox)(rgba, width, height);
215
993
  if (bbox === null) {
216
994
  throw new AutoRigInputError("layer is empty after alpha threshold");
217
995
  }
@@ -228,15 +1006,15 @@ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
228
1006
  for (const crop of crops) byId.set(crop.id, crop);
229
1007
  const pad = layout.padding;
230
1008
  const composites = await Promise.all(
231
- layout.placements.map(async (placement2) => {
232
- const crop = byId.get(placement2.id);
1009
+ layout.placements.map(async (placement3) => {
1010
+ const crop = byId.get(placement3.id);
233
1011
  if (crop === void 0) {
234
1012
  throw new AutoRigInputError(
235
- `no crop for atlas placement "${placement2.id}"`
1013
+ `no crop for atlas placement "${placement3.id}"`
236
1014
  );
237
1015
  }
238
1016
  const input = pad > 0 ? await (0, import_sharp.default)(crop.buffer).extend({ right: pad, bottom: pad, extendWith: "copy" }).png().toBuffer() : crop.buffer;
239
- return { input, left: placement2.x, top: placement2.y };
1017
+ return { input, left: placement3.x, top: placement3.y };
240
1018
  })
241
1019
  );
242
1020
  const page = await (0, import_sharp.default)({
@@ -255,10 +1033,10 @@ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
255
1033
  // src/tools.ts
256
1034
  function coerceModel(model) {
257
1035
  try {
258
- const parsed = typeof model === "string" ? (0, import_format.loadIkiModel)(model) : (0, import_format.parseIkiModel)(model);
1036
+ const parsed = typeof model === "string" ? (0, import_format7.loadIkiModel)(model) : (0, import_format7.parseIkiModel)(model);
259
1037
  return { ok: true, model: parsed };
260
1038
  } catch (e) {
261
- if (e instanceof import_format.IkiFormatError) return { ok: false, error: e.message };
1039
+ if (e instanceof import_format7.IkiFormatError) return { ok: false, error: e.message };
262
1040
  throw e;
263
1041
  }
264
1042
  }
@@ -332,115 +1110,115 @@ function describeIki(model) {
332
1110
  }
333
1111
  var STANDARD_PARAMETER_INFO = [
334
1112
  {
335
- id: import_format.StandardParameter.MouthOpen,
1113
+ id: import_format7.StandardParameter.MouthOpen,
336
1114
  description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
337
1115
  },
338
1116
  {
339
- id: import_format.StandardParameter.MouthForm,
1117
+ id: import_format7.StandardParameter.MouthForm,
340
1118
  description: "Mouth form / smile (-1 .. 1)."
341
1119
  },
342
1120
  {
343
- id: import_format.StandardParameter.EyeOpenLeft,
1121
+ id: import_format7.StandardParameter.EyeOpenLeft,
344
1122
  description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
345
1123
  },
346
1124
  {
347
- id: import_format.StandardParameter.EyeOpenRight,
1125
+ id: import_format7.StandardParameter.EyeOpenRight,
348
1126
  description: "Right eye open (0 closed .. 1 open)."
349
1127
  },
350
1128
  {
351
- id: import_format.StandardParameter.EyeballX,
1129
+ id: import_format7.StandardParameter.EyeballX,
352
1130
  description: "Eyeball gaze, horizontal (-1 .. 1)."
353
1131
  },
354
1132
  {
355
- id: import_format.StandardParameter.EyeballY,
1133
+ id: import_format7.StandardParameter.EyeballY,
356
1134
  description: "Eyeball gaze, vertical (-1 .. 1)."
357
1135
  },
358
1136
  {
359
- id: import_format.StandardParameter.AngleX,
1137
+ id: import_format7.StandardParameter.AngleX,
360
1138
  description: "Head angle, horizontal degrees."
361
1139
  },
362
1140
  {
363
- id: import_format.StandardParameter.AngleY,
1141
+ id: import_format7.StandardParameter.AngleY,
364
1142
  description: "Head angle, vertical degrees."
365
1143
  },
366
1144
  {
367
- id: import_format.StandardParameter.AngleZ,
1145
+ id: import_format7.StandardParameter.AngleZ,
368
1146
  description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
369
1147
  },
370
1148
  {
371
- id: import_format.StandardParameter.BodyAngleX,
1149
+ id: import_format7.StandardParameter.BodyAngleX,
372
1150
  description: "Body turn, degrees (-10 .. 10); positive turns the body toward the viewer's right, as AngleX does the head."
373
1151
  },
374
1152
  {
375
- id: import_format.StandardParameter.BodyAngleY,
1153
+ id: import_format7.StandardParameter.BodyAngleY,
376
1154
  description: "Body lean, degrees (-10 .. 10); positive moves the upper body up, negative bows."
377
1155
  },
378
1156
  {
379
- id: import_format.StandardParameter.BodyAngleZ,
1157
+ id: import_format7.StandardParameter.BodyAngleZ,
380
1158
  description: "Body tilt, degrees (-10 .. 10); positive tilts the top toward the viewer's right (clockwise), as AngleZ does the head."
381
1159
  },
382
1160
  {
383
- id: import_format.StandardParameter.Breath,
1161
+ id: import_format7.StandardParameter.Breath,
384
1162
  description: "Idle breath (0 .. 1), cycled by the host."
385
1163
  },
386
1164
  {
387
- id: import_format.StandardParameter.BrowLeftY,
1165
+ id: import_format7.StandardParameter.BrowLeftY,
388
1166
  description: "Left brow raise/lower (-1 .. 1)."
389
1167
  },
390
1168
  {
391
- id: import_format.StandardParameter.BrowRightY,
1169
+ id: import_format7.StandardParameter.BrowRightY,
392
1170
  description: "Right brow raise/lower (-1 .. 1)."
393
1171
  },
394
1172
  {
395
- id: import_format.StandardParameter.BrowLeftAngle,
1173
+ id: import_format7.StandardParameter.BrowLeftAngle,
396
1174
  description: "Left brow tilt/angle (-1 .. 1)."
397
1175
  },
398
1176
  {
399
- id: import_format.StandardParameter.BrowRightAngle,
1177
+ id: import_format7.StandardParameter.BrowRightAngle,
400
1178
  description: "Right brow tilt/angle (-1 .. 1)."
401
1179
  },
402
1180
  {
403
- id: import_format.StandardParameter.Cheek,
1181
+ id: import_format7.StandardParameter.Cheek,
404
1182
  description: "Cheek blush strength (0 .. 1), raised by an expression."
405
1183
  },
406
1184
  {
407
- id: import_format.StandardParameter.HairSwayX,
1185
+ id: import_format7.StandardParameter.HairSwayX,
408
1186
  description: "Horizontal hair-sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
409
1187
  },
410
1188
  {
411
- id: import_format.StandardParameter.HairSwayZ,
1189
+ id: import_format7.StandardParameter.HairSwayZ,
412
1190
  description: "Hair-sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
413
1191
  },
414
1192
  {
415
- id: import_format.StandardParameter.ArmLeft,
1193
+ id: import_format7.StandardParameter.ArmLeft,
416
1194
  description: "Left shoulder, degrees; positive raises the arm outward (mirrored on the right)."
417
1195
  },
418
1196
  {
419
- id: import_format.StandardParameter.ArmRight,
1197
+ id: import_format7.StandardParameter.ArmRight,
420
1198
  description: "Right shoulder, degrees; positive raises the arm outward (mirrored on the left)."
421
1199
  },
422
1200
  {
423
- id: import_format.StandardParameter.ElbowLeft,
1201
+ id: import_format7.StandardParameter.ElbowLeft,
424
1202
  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)."
425
1203
  },
426
1204
  {
427
- id: import_format.StandardParameter.ElbowRight,
1205
+ id: import_format7.StandardParameter.ElbowRight,
428
1206
  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)."
429
1207
  },
430
1208
  {
431
- id: import_format.StandardParameter.ArmPoseLeft,
1209
+ id: import_format7.StandardParameter.ArmPoseLeft,
432
1210
  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."
433
1211
  },
434
1212
  {
435
- id: import_format.StandardParameter.ArmPoseRight,
1213
+ id: import_format7.StandardParameter.ArmPoseRight,
436
1214
  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."
437
1215
  },
438
1216
  {
439
- id: import_format.StandardParameter.ArmPoseAngleLeft,
1217
+ id: import_format7.StandardParameter.ArmPoseAngleLeft,
440
1218
  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)."
441
1219
  },
442
1220
  {
443
- id: import_format.StandardParameter.ArmPoseAngleRight,
1221
+ id: import_format7.StandardParameter.ArmPoseAngleRight,
444
1222
  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)."
445
1223
  }
446
1224
  ];
@@ -458,7 +1236,7 @@ function expectInput(label, fn) {
458
1236
  }
459
1237
  var LOSSLESS_PAGE_ROLE = "nose";
460
1238
  async function renderAtlasPage(crops, quantizeColors) {
461
- const layout = (0, import_editor2.packAtlas)(
1239
+ const layout = (0, import_editor3.packAtlas)(
462
1240
  crops.map((c) => ({ id: c.id, width: c.width, height: c.height })),
463
1241
  void 0,
464
1242
  MAX_ATLAS_SIDE
@@ -512,7 +1290,7 @@ async function autoRigFromLayers(input) {
512
1290
  });
513
1291
  const rolePairs = expectInput(
514
1292
  "role parsing",
515
- () => (0, import_editor2.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
1293
+ () => (0, import_editor3.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
516
1294
  );
517
1295
  const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));
518
1296
  let canvasW = 0;
@@ -542,7 +1320,7 @@ async function autoRigFromLayers(input) {
542
1320
  `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`
543
1321
  );
544
1322
  }
545
- measurer = (0, import_editor2.createLayerSetMeasurer)({ width: canvasW, height: canvasH });
1323
+ measurer = (0, import_editor3.createLayerSetMeasurer)({ width: canvasW, height: canvasH });
546
1324
  } else if (png.width !== canvasW || png.height !== canvasH) {
547
1325
  throw new AutoRigInputError(
548
1326
  `layer "${fileName}" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
@@ -571,7 +1349,7 @@ async function autoRigFromLayers(input) {
571
1349
  let turn;
572
1350
  let model;
573
1351
  try {
574
- model = (0, import_editor2.generateIkiFromLayerSet)(
1352
+ model = (0, import_editor3.generateIkiFromLayerSet)(
575
1353
  measurement.layers,
576
1354
  { width: canvasW, height: canvasH },
577
1355
  {
@@ -588,12 +1366,12 @@ async function autoRigFromLayers(input) {
588
1366
  }
589
1367
  );
590
1368
  } catch (e) {
591
- if (!(e instanceof import_editor2.TurnTargetError || e instanceof import_editor2.LayerGeometryError)) {
1369
+ if (!(e instanceof import_editor3.TurnTargetError || e instanceof import_editor3.LayerGeometryError)) {
592
1370
  throw e;
593
1371
  }
594
1372
  throw new AutoRigInputError(e.message);
595
1373
  }
596
- const doc = new import_editor2.EditorDocument(model);
1374
+ const doc = new import_editor3.EditorDocument(model);
597
1375
  const losslessCrop = quantizeColors === void 0 ? void 0 : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);
598
1376
  const pages = losslessCrop === void 0 ? [await renderAtlasPage(crops, quantizeColors)] : [
599
1377
  await renderAtlasPage(
@@ -610,15 +1388,15 @@ async function autoRigFromLayers(input) {
610
1388
  }
611
1389
  const partTextureAssignments = pages.flatMap(
612
1390
  ({ crops: pageCrops, layout }) => pageCrops.flatMap((crop) => {
613
- const placement2 = layout.placements.find((p) => p.id === crop.id);
614
- if (placement2 === void 0) {
1391
+ const placement3 = layout.placements.find((p) => p.id === crop.id);
1392
+ if (placement3 === void 0) {
615
1393
  throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
616
1394
  }
617
- const uv = (0, import_editor2.uvRectFor)(placement2, {
1395
+ const uv = (0, import_editor3.uvRectFor)(placement3, {
618
1396
  width: layout.pageWidth,
619
1397
  height: layout.pageHeight
620
1398
  });
621
- return (0, import_editor2.partIdsOfRole)(crop.id).map((partId) => ({ partId, uv }));
1399
+ return (0, import_editor3.partIdsOfRole)(crop.id).map((partId) => ({ partId, uv }));
622
1400
  })
623
1401
  );
624
1402
  doc.applyAtlas({
@@ -629,12 +1407,13 @@ async function autoRigFromLayers(input) {
629
1407
  if (losslessCrop !== void 0) {
630
1408
  patched = structuredClone(patched);
631
1409
  patched.textures = pages.map((p) => ({ source: p.dataUri }));
632
- for (const partId of (0, import_editor2.partIdsOfRole)(losslessCrop.id)) {
1410
+ for (const partId of (0, import_editor3.partIdsOfRole)(losslessCrop.id)) {
633
1411
  patched.parts.find((p) => p.id === partId).texture.index = 1;
634
1412
  }
635
1413
  }
636
- const finalModel = (0, import_format.parseIkiModel)(patched);
1414
+ const finalModel = (0, import_format7.parseIkiModel)(patched);
637
1415
  writeFileAtomic(outPath, JSON.stringify(finalModel));
1416
+ const folds = checkModelFolds(finalModel);
638
1417
  return {
639
1418
  ok: true,
640
1419
  path: outPath,
@@ -646,7 +1425,8 @@ async function autoRigFromLayers(input) {
646
1425
  ...headEdges === void 0 ? {} : { headEdges },
647
1426
  ...strandEdges === void 0 ? {} : { strandEdges },
648
1427
  ...noseCore === void 0 ? {} : { noseCore },
649
- ...turn === void 0 ? {} : { turn }
1428
+ ...turn === void 0 ? {} : { turn },
1429
+ folds
650
1430
  };
651
1431
  } catch (err) {
652
1432
  if (err instanceof AutoRigInputError)
@@ -659,10 +1439,10 @@ async function autoRigFromLayers(input) {
659
1439
  var import_node_fs3 = __toESM(require("fs"));
660
1440
  var import_node_path7 = __toESM(require("path"));
661
1441
  var import_sharp4 = __toESM(require("sharp"));
662
- var import_editor11 = require("@ikijs/editor");
1442
+ var import_editor12 = require("@ikijs/editor");
663
1443
 
664
1444
  // src/trim.ts
665
- var import_editor3 = require("@ikijs/editor");
1445
+ var import_editor4 = require("@ikijs/editor");
666
1446
  var TRIM_THRESHOLD = 12;
667
1447
  var STRAY_SPECK_FRACTION = 0.01;
668
1448
  function luma(rgba, i) {
@@ -691,7 +1471,7 @@ function boxWithoutStraySpecks(rgba, W, H) {
691
1471
  while (depth > 0) {
692
1472
  const p = stack[--depth];
693
1473
  size++;
694
- if (rgba[p * 4 + 3] >= import_editor3.ALPHA_OPAQUE) opaque = true;
1474
+ if (rgba[p * 4 + 3] >= import_editor4.ALPHA_OPAQUE) opaque = true;
695
1475
  const px2 = p % W;
696
1476
  const py = (p - px2) / W;
697
1477
  setLeft = Math.min(setLeft, px2);
@@ -733,7 +1513,7 @@ var import_node_path6 = __toESM(require("path"));
733
1513
 
734
1514
  // src/measure-arms.ts
735
1515
  var import_node_path3 = __toESM(require("path"));
736
- var import_editor4 = require("@ikijs/editor");
1516
+ var import_editor5 = require("@ikijs/editor");
737
1517
  var ARM_ROLES = ["arm_L", "arm_R"];
738
1518
  var CAP_OVERLAP = 0.5;
739
1519
  var px = (v) => `${Number(v.toFixed(1))}`;
@@ -762,7 +1542,7 @@ async function armWarnings(absDir, layers) {
762
1542
  continue;
763
1543
  }
764
1544
  if (set === void 0) {
765
- const measurer = (0, import_editor4.createLayerSetMeasurer)({
1545
+ const measurer = (0, import_editor5.createLayerSetMeasurer)({
766
1546
  width: body.canvasW,
767
1547
  height: body.canvasH
768
1548
  });
@@ -770,12 +1550,12 @@ async function armWarnings(absDir, layers) {
770
1550
  }
771
1551
  let g;
772
1552
  try {
773
- g = (0, import_editor4.armGeometry)(
1553
+ g = (0, import_editor5.armGeometry)(
774
1554
  await measured(set.measurer, absDir, arm),
775
1555
  set.body.bbox.x + set.body.bbox.w / 2 - body.canvasW / 2
776
1556
  );
777
1557
  } catch (err) {
778
- if (err instanceof import_editor4.LayerGeometryError) {
1558
+ if (err instanceof import_editor5.LayerGeometryError) {
779
1559
  warnings.push(
780
1560
  `${arm}: ${err.message} \u2014 auto_rig_from_layers refuses it. Regenerate arm.png drawn hanging, shoulder at the top. Billed.`
781
1561
  );
@@ -803,7 +1583,7 @@ function capWarning(arm, g, body) {
803
1583
  }
804
1584
 
805
1585
  // src/measure-forearm-pose.ts
806
- var import_editor5 = require("@ikijs/editor");
1586
+ var import_editor6 = require("@ikijs/editor");
807
1587
  var POSE_ROLES = ["forearm_pose_L", "forearm_pose_R"];
808
1588
  var ARM_OF = {
809
1589
  forearm_pose_L: "arm_L",
@@ -837,7 +1617,7 @@ async function forearmPoseWarnings(absDir, layers) {
837
1617
  continue;
838
1618
  }
839
1619
  if (layers.body === void 0) continue;
840
- const measurer = (0, import_editor5.createLayerSetMeasurer)({
1620
+ const measurer = (0, import_editor6.createLayerSetMeasurer)({
841
1621
  width: stats.canvasW,
842
1622
  height: stats.canvasH
843
1623
  });
@@ -845,12 +1625,12 @@ async function forearmPoseWarnings(absDir, layers) {
845
1625
  let armLayer;
846
1626
  try {
847
1627
  armLayer = await measured(measurer, absDir, arm);
848
- a = (0, import_editor5.armGeometry)(armLayer, arm === "arm_R" ? Infinity : -Infinity);
1628
+ a = (0, import_editor6.armGeometry)(armLayer, arm === "arm_R" ? Infinity : -Infinity);
849
1629
  } catch (err) {
850
- if (err instanceof import_editor5.LayerGeometryError) continue;
1630
+ if (err instanceof import_editor6.LayerGeometryError) continue;
851
1631
  throw err;
852
1632
  }
853
- const b = (0, import_editor5.forearmPoseGeometry)(await measured(measurer, absDir, pose));
1633
+ const b = (0, import_editor6.forearmPoseGeometry)(await measured(measurer, absDir, pose));
854
1634
  warnings.push(...jointWarnings(pose, arm, stats, a, armLayer, b));
855
1635
  }
856
1636
  return warnings;
@@ -890,11 +1670,11 @@ function jointWarnings(pose, arm, stats, a, armLayer, b) {
890
1670
 
891
1671
  // src/measure-lips.ts
892
1672
  var import_node_path4 = __toESM(require("path"));
893
- var import_editor7 = require("@ikijs/editor");
1673
+ var import_editor8 = require("@ikijs/editor");
894
1674
 
895
1675
  // src/compose-lips.ts
896
1676
  var import_sharp2 = __toESM(require("sharp"));
897
- var import_editor6 = require("@ikijs/editor");
1677
+ var import_editor7 = require("@ikijs/editor");
898
1678
  var KEYED_SRC = "mouth_keyed.png";
899
1679
  var INTERIOR_SRC = "mouth_interior.png";
900
1680
  var KEY_CANDIDATE = 0.5;
@@ -992,7 +1772,7 @@ function keyGreen(rgba, W, H) {
992
1772
  let candidates = 0;
993
1773
  for (let p = 0; p < n; p++) {
994
1774
  const i = p * 4;
995
- if (rgba[i + 3] < import_editor6.ALPHA_OPAQUE) continue;
1775
+ if (rgba[i + 3] < import_editor7.ALPHA_OPAQUE) continue;
996
1776
  const excess = (rgba[i + 1] - Math.max(rgba[i], rgba[i + 2])) / 255;
997
1777
  if (excess < KEY_CANDIDATE) continue;
998
1778
  candidates++;
@@ -1019,7 +1799,7 @@ function keyGreen(rgba, W, H) {
1019
1799
  const dg = rgba[i + 1] - G[1];
1020
1800
  const db = rgba[i + 2] - G[2];
1021
1801
  const green = dr * dr + dg * dg + db * db <= KEY_FILL_DIST * KEY_FILL_DIST;
1022
- if (rgba[i + 3] < import_editor6.ALPHA_OPAQUE) {
1802
+ if (rgba[i + 3] < import_editor7.ALPHA_OPAQUE) {
1023
1803
  if (green) out[i + 3] = 0;
1024
1804
  } else if (green) {
1025
1805
  fill[p] = 1;
@@ -1195,7 +1975,7 @@ async function prepInterior(rgba, W, H) {
1195
1975
  for (let y = box.y; y < box.y + box.h; y++) {
1196
1976
  for (let x = box.x; x < box.x + box.w; x++) {
1197
1977
  const i = (y * cw + x) * 4;
1198
- if (crop[i + 3] < import_editor6.ALPHA_OPAQUE) continue;
1978
+ if (crop[i + 3] < import_editor7.ALPHA_OPAQUE) continue;
1199
1979
  count++;
1200
1980
  for (let c = 0; c < 3; c++) all[c] += crop[i + c];
1201
1981
  if (luma(crop, i) < CAVITY_LUMA) {
@@ -1218,7 +1998,7 @@ function enclosedHole(frame, w, h) {
1218
1998
  const stack = new Int32Array(n);
1219
1999
  let depth = 0;
1220
2000
  const seed = (p) => {
1221
- if (!outside[p] && alpha(p) < import_editor6.ALPHA_OPAQUE) {
2001
+ if (!outside[p] && alpha(p) < import_editor7.ALPHA_OPAQUE) {
1222
2002
  outside[p] = 1;
1223
2003
  stack[depth++] = p;
1224
2004
  }
@@ -1241,7 +2021,7 @@ function enclosedHole(frame, w, h) {
1241
2021
  }
1242
2022
  const mask = new Uint8Array(n);
1243
2023
  for (let p = 0; p < n; p++) {
1244
- if (alpha(p) < import_editor6.ALPHA_OPAQUE && !outside[p]) mask[p] = 1;
2024
+ if (alpha(p) < import_editor7.ALPHA_OPAQUE && !outside[p]) mask[p] = 1;
1245
2025
  }
1246
2026
  const { label, sizes, boxes } = components(mask, w, h);
1247
2027
  const main = largest(sizes);
@@ -1268,7 +2048,7 @@ function enclosedHole(frame, w, h) {
1268
2048
  return { label, main, box };
1269
2049
  }
1270
2050
  function measureLips(layers, w, h) {
1271
- const measurer = (0, import_editor6.createLayerSetMeasurer)({ width: w, height: h });
2051
+ const measurer = (0, import_editor7.createLayerSetMeasurer)({ width: w, height: h });
1272
2052
  return new Map(
1273
2053
  Object.entries(layers).map(([role, rgba]) => [
1274
2054
  role,
@@ -1286,8 +2066,8 @@ function assertFoldContract(layers, w, h) {
1286
2066
  }
1287
2067
  byRole.set(role, layer);
1288
2068
  }
1289
- const opening = (0, import_editor6.mouthOpening)(byRole);
1290
- const runs = (0, import_editor6.columnRuns)(byRole.get("mouth_inner"));
2069
+ const opening = (0, import_editor7.mouthOpening)(byRole);
2070
+ const runs = (0, import_editor7.columnRuns)(byRole.get("mouth_inner"));
1291
2071
  for (let col = opening.x0; col <= opening.x1; col++) {
1292
2072
  const c = opening.at(col);
1293
2073
  const why = !runs.has(col) ? "has no interior run" : c.Tu > c.T ? `has a gap between the line and the interior (Tu ${c.Tu} > T ${c.T})` : c.T > c.lineTop || c.lineH <= 0 ? `has no line above the interior (T ${c.T}, line top ${c.lineTop})` : c.Bl < c.Bb ? `has a gap between the interior and the skin (Bl ${c.Bl} < Bb ${c.Bb})` : null;
@@ -1317,18 +2097,18 @@ async function splitLipSet(keyedPng, w, h, interior) {
1317
2097
  }
1318
2098
  const centre = Math.round((hb.x0 + hb.x1) / 2);
1319
2099
  let stroke = 0;
1320
- while (top[centre] - 1 - stroke >= 0 && alpha((top[centre] - 1 - stroke) * w + centre) >= import_editor6.ALPHA_OPAQUE)
2100
+ while (top[centre] - 1 - stroke >= 0 && alpha((top[centre] - 1 - stroke) * w + centre) >= import_editor7.ALPHA_OPAQUE)
1321
2101
  stroke++;
1322
2102
  const bandCap = BAND_CAP * Math.max(1, stroke);
1323
2103
  const skinRow = new Int32Array(w).fill(-1);
1324
2104
  const inM = new Uint8Array(n);
1325
2105
  for (let x = hb.x0; x <= hb.x1; x++) {
1326
2106
  let y = bot[x];
1327
- while (y < h && y - bot[x] < bandCap && alpha(y * w + x) >= import_editor6.ALPHA_OPAQUE && luma(frame, (y * w + x) * 4) < BAND_LUMA)
2107
+ while (y < h && y - bot[x] < bandCap && alpha(y * w + x) >= import_editor7.ALPHA_OPAQUE && luma(frame, (y * w + x) * 4) < BAND_LUMA)
1328
2108
  y++;
1329
2109
  for (let k = top[x]; k < y; k++) inM[k * w + x] = 1;
1330
2110
  let r = y;
1331
- while (r < h && alpha(r * w + x) < import_editor6.ALPHA_OPAQUE) r++;
2111
+ while (r < h && alpha(r * w + x) < import_editor7.ALPHA_OPAQUE) r++;
1332
2112
  if (r < h) {
1333
2113
  skinRow[x] = r;
1334
2114
  inM[r * w + x] = 1;
@@ -1338,7 +2118,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
1338
2118
  for (let y = 0; y < h; y++) {
1339
2119
  for (let x = 0; x < w; x++) {
1340
2120
  const p = y * w + x;
1341
- if (inM[p] || alpha(p) < import_editor6.ALPHA_OPAQUE) continue;
2121
+ if (inM[p] || alpha(p) < import_editor7.ALPHA_OPAQUE) continue;
1342
2122
  if (top[x] >= 0 && y < top[x]) continue;
1343
2123
  if (x > 0 && inM[p - 1] || x < w - 1 && inM[p + 1]) grown[p] = 1;
1344
2124
  }
@@ -1348,7 +2128,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
1348
2128
  if (x < 0 || x >= w) continue;
1349
2129
  let first = 0;
1350
2130
  while (first < h && !(grown[first * w + x] && !inM[first * w + x])) first++;
1351
- if (first > 0 && first < h && alpha((first - 1) * w + x) >= import_editor6.ALPHA_OPAQUE)
2131
+ if (first > 0 && first < h && alpha((first - 1) * w + x) >= import_editor7.ALPHA_OPAQUE)
1352
2132
  wall[x] = 1;
1353
2133
  }
1354
2134
  const gx = hb.x0 - 1;
@@ -1375,7 +2155,7 @@ async function splitLipSet(keyedPng, w, h, interior) {
1375
2155
  if (inOpening && skinRow[x] >= 0 && y >= skinRow[x]) copy(lower, p);
1376
2156
  if (!grown[p]) {
1377
2157
  const a = alpha(p);
1378
- if (a >= import_editor6.ALPHA_OPAQUE && a < 255 && besideHole(p, x, y)) {
2158
+ if (a >= import_editor7.ALPHA_OPAQUE && a < 255 && besideHole(p, x, y)) {
1379
2159
  inner.set(interior.cavity, p * 4);
1380
2160
  inner[p * 4 + 3] = 255 - a;
1381
2161
  }
@@ -1440,7 +2220,7 @@ async function restShiftOf(layers, width, height) {
1440
2220
  }
1441
2221
  byRole.set(role, layer);
1442
2222
  }
1443
- return (0, import_editor6.mouthRestShift)(byRole);
2223
+ return (0, import_editor7.mouthRestShift)(byRole);
1444
2224
  }
1445
2225
  async function closedLips(upper, lower, shift, left, top) {
1446
2226
  const shut = async (png, role) => {
@@ -1490,7 +2270,7 @@ async function closedLips(upper, lower, shift, left, top) {
1490
2270
  }
1491
2271
 
1492
2272
  // src/measure-lips.ts
1493
- var isLipLayerRole = (role) => import_editor7.LIP_ROLES.includes(role) || (0, import_editor7.isLipInsideRole)(role);
2273
+ var isLipLayerRole = (role) => import_editor8.LIP_ROLES.includes(role) || (0, import_editor8.isLipInsideRole)(role);
1494
2274
  var MIN_OPENING_ROWS = 8;
1495
2275
  var MIN_LINE_ROWS = 2;
1496
2276
  var GREEN_EXCESS = 40;
@@ -1498,8 +2278,8 @@ var INTERIOR_GAP_FRACTION = 0.05;
1498
2278
  var columns = (cols) => `${cols.length} column${cols.length === 1 ? "" : "s"} (first at x=${cols[0]})`;
1499
2279
  async function lipWarnings(absDir, layers) {
1500
2280
  const warnings = [];
1501
- const present = import_editor7.LIP_ROLES.filter((role) => layers[role] !== void 0);
1502
- const inside = import_editor7.LIP_INSIDE_ROLES.filter((role) => layers[role] !== void 0);
2281
+ const present = import_editor8.LIP_ROLES.filter((role) => layers[role] !== void 0);
2282
+ const inside = import_editor8.LIP_INSIDE_ROLES.filter((role) => layers[role] !== void 0);
1503
2283
  if (present.length === 0) {
1504
2284
  if (inside.length > 0) {
1505
2285
  warnings.push(
@@ -1516,8 +2296,8 @@ async function lipWarnings(absDir, layers) {
1516
2296
  `${present.join("/")}: the lip set cannot be mixed with ${legacy.join("/")} \u2014 auto_rig_from_layers refuses it. Remove one route: compose again with only mouth_keyed.png + mouth_interior.png, or without them.`
1517
2297
  );
1518
2298
  }
1519
- if (present.length < import_editor7.LIP_ROLES.length) {
1520
- const missing = import_editor7.LIP_ROLES.filter((role) => layers[role] === void 0);
2299
+ if (present.length < import_editor8.LIP_ROLES.length) {
2300
+ const missing = import_editor8.LIP_ROLES.filter((role) => layers[role] === void 0);
1521
2301
  warnings.push(
1522
2302
  `${present.join("/")}: partial lip set, missing ${missing.join("/")} \u2014 auto_rig_from_layers refuses it. Compose mouth_keyed.png + mouth_interior.png together, which cuts all three.`
1523
2303
  );
@@ -1548,18 +2328,18 @@ async function lipWarnings(absDir, layers) {
1548
2328
  );
1549
2329
  }
1550
2330
  }
1551
- const measurer = (0, import_editor7.createLayerSetMeasurer)({
2331
+ const measurer = (0, import_editor8.createLayerSetMeasurer)({
1552
2332
  width: inner.canvasW,
1553
2333
  height: inner.canvasH
1554
2334
  });
1555
2335
  const set = /* @__PURE__ */ new Map();
1556
2336
  const green = [];
1557
- for (const role of import_editor7.LIP_ROLES) {
2337
+ for (const role of import_editor8.LIP_ROLES) {
1558
2338
  const fileName = `${role}.png`;
1559
2339
  const { rgba } = await decodePng(import_node_path4.default.join(absDir, fileName));
1560
2340
  set.set(role, measurer.add({ role, fileName, rgba }));
1561
2341
  for (let i = 0; i < rgba.length; i += 4) {
1562
- if (rgba[i + 3] >= import_editor7.ALPHA_OPAQUE && rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS) {
2342
+ if (rgba[i + 3] >= import_editor8.ALPHA_OPAQUE && rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS) {
1563
2343
  green.push(role);
1564
2344
  break;
1565
2345
  }
@@ -1567,15 +2347,15 @@ async function lipWarnings(absDir, layers) {
1567
2347
  }
1568
2348
  let opening;
1569
2349
  try {
1570
- opening = (0, import_editor7.mouthOpening)(set);
2350
+ opening = (0, import_editor8.mouthOpening)(set);
1571
2351
  } catch (err) {
1572
- if (err instanceof import_editor7.LayerGeometryError) {
2352
+ if (err instanceof import_editor8.LayerGeometryError) {
1573
2353
  warnings.push(err.message);
1574
2354
  return { warnings };
1575
2355
  }
1576
2356
  throw err;
1577
2357
  }
1578
- const innerRuns = (0, import_editor7.columnRuns)(set.get("mouth_inner"));
2358
+ const innerRuns = (0, import_editor8.columnRuns)(set.get("mouth_inner"));
1579
2359
  const noInterior = [];
1580
2360
  const gap = [];
1581
2361
  const noLine = [];
@@ -1661,8 +2441,8 @@ async function lipWarnings(absDir, layers) {
1661
2441
 
1662
2442
  // src/measure-turn.ts
1663
2443
  var import_node_path5 = __toESM(require("path"));
1664
- var import_editor8 = require("@ikijs/editor");
1665
2444
  var import_editor9 = require("@ikijs/editor");
2445
+ var import_editor10 = require("@ikijs/editor");
1666
2446
  var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
1667
2447
  var IRIS_V_MIN = 0.18;
1668
2448
  var IRIS_V_MAX = 0.95;
@@ -1812,7 +2592,7 @@ async function measureTurnImage(filePath, iris) {
1812
2592
  let transparent = false;
1813
2593
  if (hasAlpha) {
1814
2594
  for (let i = 0; i < n; i++) {
1815
- if (rgba[i * 4 + 3] < import_editor8.ALPHA_OPAQUE) {
2595
+ if (rgba[i * 4 + 3] < import_editor9.ALPHA_OPAQUE) {
1816
2596
  transparent = true;
1817
2597
  break;
1818
2598
  }
@@ -1823,7 +2603,7 @@ async function measureTurnImage(filePath, iris) {
1823
2603
  const fg = new Uint8Array(n);
1824
2604
  const value = new Float32Array(n);
1825
2605
  for (let i = 0; i < n; i++) {
1826
- if (rgba[i * 4 + 3] < import_editor8.ALPHA_OPAQUE) continue;
2606
+ if (rgba[i * 4 + 3] < import_editor9.ALPHA_OPAQUE) continue;
1827
2607
  const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);
1828
2608
  if (maskMode === "alpha") {
1829
2609
  fg[i] = 1;
@@ -1889,12 +2669,12 @@ async function measureTurnImage(filePath, iris) {
1889
2669
  }
1890
2670
  const [irisL, irisR] = best.pair;
1891
2671
  const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);
1892
- const { left, right } = (0, import_editor8.foregroundSpan)(
2672
+ const { left, right } = (0, import_editor9.foregroundSpan)(
1893
2673
  fg,
1894
2674
  width,
1895
2675
  height,
1896
- eyeRow - import_editor8.HEAD_BAND,
1897
- eyeRow + import_editor8.HEAD_BAND
2676
+ eyeRow - import_editor9.HEAD_BAND,
2677
+ eyeRow + import_editor9.HEAD_BAND
1898
2678
  );
1899
2679
  if (right <= left) {
1900
2680
  throw new AutoRigInputError(
@@ -1918,7 +2698,7 @@ async function measureTurnImage(filePath, iris) {
1918
2698
  left,
1919
2699
  right,
1920
2700
  cx: (left + right) / 2,
1921
- half: (0, import_editor8.headHalfOf)({ left, right })
2701
+ half: (0, import_editor9.headHalfOf)({ left, right })
1922
2702
  },
1923
2703
  pairCx: (irisL.cx + irisR.cx) / 2,
1924
2704
  eyeGap: irisR.cx - irisL.cx
@@ -2109,7 +2889,7 @@ function noseSpeckWarning({ core, part }, source) {
2109
2889
  `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,
2110
2890
  `auto_rig_from_layers turns and tilts the nose about its whole crop instead`
2111
2891
  ];
2112
- return `nose: ${found} \u2014 under ${import_editor9.SPECK_CORE_FRACTION} of its width or height, a speck: a lone nostril mark or highlight at alpha >= 128, not the drawing, so ${consequence}. Regenerate the nose with its shading painted denser, so the drawing itself reaches alpha 128. Billed.`;
2892
+ return `nose: ${found} \u2014 under ${import_editor10.SPECK_CORE_FRACTION} of its width or height, a speck: a lone nostril mark or highlight at alpha >= 128, not the drawing, so ${consequence}. Regenerate the nose with its shading painted denser, so the drawing itself reaches alpha 128. Billed.`;
2113
2893
  }
2114
2894
  async function lashOffSclera(eyePath, lashPath) {
2115
2895
  const eye = await decodePng(eyePath);
@@ -2246,10 +3026,10 @@ async function measureDir(absDir, noseSpeck) {
2246
3026
  warnings.push(noseSpeckWarning(noseSpeck, "compose"));
2247
3027
  } else if (layers.nose !== void 0) {
2248
3028
  const nose = await decodePng(import_node_path6.default.join(absDir, "nose.png"));
2249
- const core = (0, import_editor9.denseCoreOf)(nose.rgba, nose.width, nose.height);
3029
+ const core = (0, import_editor10.denseCoreOf)(nose.rgba, nose.width, nose.height);
2250
3030
  if (core !== null) {
2251
3031
  const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);
2252
- if ((0, import_editor9.isSpeckCore)(core, crop))
3032
+ if ((0, import_editor10.isSpeckCore)(core, crop))
2253
3033
  warnings.push(noseSpeckWarning({ core, part: crop }, "layer"));
2254
3034
  }
2255
3035
  }
@@ -2320,12 +3100,12 @@ function formatMeasureReport(result) {
2320
3100
 
2321
3101
  // src/compose-arms.ts
2322
3102
  var import_sharp3 = __toESM(require("sharp"));
2323
- var import_editor10 = require("@ikijs/editor");
3103
+ var import_editor11 = require("@ikijs/editor");
2324
3104
  var ARM_WIDTH = 0.4;
2325
3105
  var SHOULDER_DROP = 0.12;
2326
3106
  async function armPlacement(role, cfg, part, body) {
2327
3107
  const { data } = await (0, import_sharp3.default)(part.buf).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2328
- const layer = (0, import_editor10.createLayerSetMeasurer)({ width: part.w, height: part.h }).add({
3108
+ const layer = (0, import_editor11.createLayerSetMeasurer)({ width: part.w, height: part.h }).add({
2329
3109
  role,
2330
3110
  fileName: "arm.png",
2331
3111
  rgba: data
@@ -2337,9 +3117,9 @@ async function armPlacement(role, cfg, part, body) {
2337
3117
  }
2338
3118
  let g;
2339
3119
  try {
2340
- g = (0, import_editor10.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
3120
+ g = (0, import_editor11.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
2341
3121
  } catch (err) {
2342
- if (err instanceof import_editor10.LayerGeometryError) {
3122
+ if (err instanceof import_editor11.LayerGeometryError) {
2343
3123
  throw new AutoRigInputError(`layout.${role}: ${err.message}`);
2344
3124
  }
2345
3125
  throw err;
@@ -2366,7 +3146,7 @@ async function armPlacement(role, cfg, part, body) {
2366
3146
  }
2367
3147
  async function poseGeometryOf(role, png, size, when) {
2368
3148
  const { data } = await (0, import_sharp3.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2369
- const layer = (0, import_editor10.createLayerSetMeasurer)({
3149
+ const layer = (0, import_editor11.createLayerSetMeasurer)({
2370
3150
  width: size.w,
2371
3151
  height: size.h
2372
3152
  }).add({ role, fileName: "forearm_pose.png", rgba: data });
@@ -2375,7 +3155,7 @@ async function poseGeometryOf(role, png, size, when) {
2375
3155
  `layout.${role}: forearm_pose.png is empty after alpha threshold${when}`
2376
3156
  );
2377
3157
  }
2378
- return (0, import_editor10.forearmPoseGeometry)(layer);
3158
+ return (0, import_editor11.forearmPoseGeometry)(layer);
2379
3159
  }
2380
3160
  async function forearmPoseWidth(role, trimmed, elbowRun) {
2381
3161
  const g = await poseGeometryOf(role, trimmed.data, trimmed, "");
@@ -2593,12 +3373,12 @@ function resolveLayout(overrides, canvas) {
2593
3373
  const face = { ...resolved.face, ...sets.get("face") };
2594
3374
  resolved.face = face;
2595
3375
  const base = DEFAULT_LAYOUT.face;
2596
- const scale = face.w / base.w;
2597
- const x = (cx) => face.cx + (cx - base.cx) * scale;
2598
- const w = (width) => Math.max(1, Math.round(width * scale));
3376
+ const scale2 = face.w / base.w;
3377
+ const x = (cx) => face.cx + (cx - base.cx) * scale2;
3378
+ const w = (width) => Math.max(1, Math.round(width * scale2));
2599
3379
  for (const role of FACE_FEATURES) {
2600
3380
  const d = DEFAULT_LAYOUT[role];
2601
- const cy = face.cy + (d.cy - base.cy) * scale;
3381
+ const cy = face.cy + (d.cy - base.cy) * scale2;
2602
3382
  resolved[role] = { ...d, cx: x(d.cx), cy, w: w(d.w), ...sets.get(role) };
2603
3383
  }
2604
3384
  const nose = DEFAULT_LAYOUT.nose;
@@ -2651,18 +3431,18 @@ function keyWhiteToAlpha(rgba) {
2651
3431
  async function coreAndBoundsOf(png) {
2652
3432
  const { data, info } = await (0, import_sharp4.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2653
3433
  return {
2654
- core: (0, import_editor9.denseCoreOf)(data, info.width, info.height),
3434
+ core: (0, import_editor10.denseCoreOf)(data, info.width, info.height),
2655
3435
  bounds: { x: 0, y: 0, w: info.width, h: info.height }
2656
3436
  };
2657
3437
  }
2658
3438
  async function hasCoverage(png) {
2659
3439
  const { data, info } = await (0, import_sharp4.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2660
- return (0, import_editor11.detectAlphaBbox)(data, info.width, info.height) !== null;
3440
+ return (0, import_editor12.detectAlphaBbox)(data, info.width, info.height) !== null;
2661
3441
  }
2662
3442
  async function noseSizingOf(png) {
2663
3443
  const { core, bounds } = await coreAndBoundsOf(png);
2664
3444
  if (core === null) return { box: bounds, whole: true };
2665
- if ((0, import_editor9.isSpeckCore)(core, bounds)) {
3445
+ if ((0, import_editor10.isSpeckCore)(core, bounds)) {
2666
3446
  return {
2667
3447
  box: bounds,
2668
3448
  whole: true,
@@ -2739,7 +3519,7 @@ function assertOnCanvas(source, w, h, left, top, canvas) {
2739
3519
  );
2740
3520
  }
2741
3521
  }
2742
- function placement(role, cfg, w, h, canvas) {
3522
+ function placement2(role, cfg, w, h, canvas) {
2743
3523
  const left = Math.round(cfg.cx - w / 2);
2744
3524
  const top = Math.round(cfg.cy - h / 2);
2745
3525
  assertOnCanvas(`layout.${role}.cx/cy`, w, h, left, top, canvas);
@@ -2784,7 +3564,7 @@ function detachedAboveWhite(rgba, W, H) {
2784
3564
  for (let p = 0; p < n; p++) {
2785
3565
  const alpha = rgba[p * 4 + 3];
2786
3566
  if (alpha > 0 && luma(rgba, p * 4) >= EYE_LASH_LUMA)
2787
- ink[p] = alpha >= import_editor11.ALPHA_OPAQUE ? 2 : 1;
3567
+ ink[p] = alpha >= import_editor12.ALPHA_OPAQUE ? 2 : 1;
2788
3568
  }
2789
3569
  const label = new Int32Array(n).fill(-1);
2790
3570
  const stack = new Int32Array(n);
@@ -3009,7 +3789,7 @@ async function composeLayersFromParts(input) {
3009
3789
  part2.h,
3010
3790
  lips.interior
3011
3791
  );
3012
- const { left: left2, top: top2 } = placement(role, cfg2, part2.w, part2.h, canvas);
3792
+ const { left: left2, top: top2 } = placement2(role, cfg2, part2.w, part2.h, canvas);
3013
3793
  lipSplit = { split: split2, w: part2.w, h: part2.h, left: left2, top: top2 };
3014
3794
  placed.push({
3015
3795
  role,
@@ -3028,7 +3808,7 @@ async function composeLayersFromParts(input) {
3028
3808
  lip_lower: split2.lower,
3029
3809
  lip_upper: split2.upper
3030
3810
  }[role];
3031
- if ((0, import_editor11.isLipInsideRole)(role) && !await hasCoverage(buf)) {
3811
+ if ((0, import_editor12.isLipInsideRole)(role) && !await hasCoverage(buf)) {
3032
3812
  skipped.push(role);
3033
3813
  continue;
3034
3814
  }
@@ -3166,7 +3946,7 @@ async function composeLayersFromParts(input) {
3166
3946
  canvas
3167
3947
  ));
3168
3948
  } else {
3169
- ({ left, top } = placement(key, layout[key], part.w, part.h, canvas));
3949
+ ({ left, top } = placement2(key, layout[key], part.w, part.h, canvas));
3170
3950
  }
3171
3951
  if (role === "lash_L" || role === "lash_R") {
3172
3952
  const eyeRole = role === "lash_L" ? "eye_L" : "eye_R";
@@ -3223,7 +4003,7 @@ async function composeLayersFromParts(input) {
3223
4003
  });
3224
4004
  }
3225
4005
  const restInput = (role, buf) => {
3226
- if (role === "mouth_inner" || (0, import_editor11.isLipInsideRole)(role)) return null;
4006
+ if (role === "mouth_inner" || (0, import_editor12.isLipInsideRole)(role)) return null;
3227
4007
  if (closed === void 0) return buf;
3228
4008
  if (role === "lip_upper") return closed.upper;
3229
4009
  if (role === "lip_lower") return closed.lower;
@@ -3293,7 +4073,7 @@ async function composeLayersFromParts(input) {
3293
4073
  // src/render-poses.ts
3294
4074
  var import_node_fs5 = require("fs");
3295
4075
  var import_node_path9 = __toESM(require("path"));
3296
- var import_format2 = require("@ikijs/format");
4076
+ var import_format8 = require("@ikijs/format");
3297
4077
 
3298
4078
  // src/render-browser.ts
3299
4079
  var import_node_child_process = require("child_process");
@@ -3620,6 +4400,13 @@ function planRenders(model) {
3620
4400
  name,
3621
4401
  values
3622
4402
  });
4403
+ const bodyAngles = Object.fromEntries(
4404
+ [
4405
+ import_format8.StandardParameter.BodyAngleX,
4406
+ import_format8.StandardParameter.BodyAngleY,
4407
+ import_format8.StandardParameter.BodyAngleZ
4408
+ ].filter((id) => model.parameters.some((p) => p.id === id)).map((id) => [id, -10])
4409
+ );
3623
4410
  const poses = [
3624
4411
  square("rest"),
3625
4412
  square("turn-m30", { ParamAngleX: -30 }),
@@ -3629,7 +4416,22 @@ function planRenders(model) {
3629
4416
  square("blink", { ParamEyeLOpen: 0 }),
3630
4417
  square("blink-half", { ParamEyeLOpen: 0.5 }),
3631
4418
  square("gaze", { ParamEyeBallX: 1 }),
3632
- square("combined", { ParamAngleX: 30, ParamAngleY: 30, ParamAngleZ: 30 })
4419
+ square("combined", { ParamAngleX: 30, ParamAngleY: 30, ParamAngleZ: 30 }),
4420
+ // Every head angle at its other extreme with the face moving too, where
4421
+ // moves that each look fine alone stack up into a fold.
4422
+ square("stress", {
4423
+ ParamAngleX: -30,
4424
+ ParamAngleY: -30,
4425
+ ParamAngleZ: -30,
4426
+ ParamMouthOpenY: 1,
4427
+ ParamEyeLOpen: 0.5,
4428
+ ParamEyeROpen: 0.5,
4429
+ ParamBrowLY: -1,
4430
+ ParamBrowRY: 1,
4431
+ ParamBrowLAngle: 1,
4432
+ ParamBrowRAngle: -1,
4433
+ ...bodyAngles
4434
+ })
3633
4435
  ];
3634
4436
  if (mouth) {
3635
4437
  const crop = {
@@ -3688,7 +4490,7 @@ function planRenders(model) {
3688
4490
  whole("full-elbow-r-45", { ParamElbowR: 45 }),
3689
4491
  whole("full-elbow-r-90", { ParamElbowR: 90 })
3690
4492
  );
3691
- if (model.parameters.some((p) => p.id === import_format2.StandardParameter.ArmPoseRight)) {
4493
+ if (model.parameters.some((p) => p.id === import_format8.StandardParameter.ArmPoseRight)) {
3692
4494
  poses.push(
3693
4495
  whole("full-pose-l", { ParamArmPoseL: 1 }),
3694
4496
  whole("full-pose-r", { ParamArmPoseR: 1 }),
@@ -3730,11 +4532,12 @@ async function renderPoses(input) {
3730
4532
  input.modelPath
3731
4533
  );
3732
4534
  const outDir = resolveOutputDir(input.outDir);
3733
- const model = (0, import_format2.loadIkiModel)((0, import_node_fs5.readFileSync)(modelFile, "utf8"));
4535
+ const model = (0, import_format8.loadIkiModel)((0, import_node_fs5.readFileSync)(modelFile, "utf8"));
3734
4536
  const plan = planRenders(model);
3735
4537
  const browser = findBrowser();
3736
4538
  if (!browser) return { ok: false, error: NO_BROWSER_MESSAGE };
3737
4539
  const pageScript = readPageScript();
4540
+ const folds = checkModelFolds(model);
3738
4541
  const { failedTextures, poses } = await withBrowser(
3739
4542
  browser,
3740
4543
  async (evaluate) => {
@@ -3769,10 +4572,12 @@ async function renderPoses(input) {
3769
4572
  fullBody: plan.fullBody,
3770
4573
  mouth: plan.mouth,
3771
4574
  failedTextures,
3772
- poses
4575
+ poses,
4576
+ modelCanvas: model.canvas,
4577
+ folds
3773
4578
  };
3774
4579
  } catch (error) {
3775
- if (error instanceof AutoRigInputError || error instanceof import_format2.IkiFormatError) {
4580
+ if (error instanceof AutoRigInputError || error instanceof import_format8.IkiFormatError) {
3776
4581
  return { ok: false, error: error.message };
3777
4582
  }
3778
4583
  throw error;
@@ -3783,7 +4588,7 @@ async function renderPoses(input) {
3783
4588
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
3784
4589
  var import_zod = require("zod");
3785
4590
  function createIkiMcpServer() {
3786
- const server = new import_mcp.McpServer({ name: "iki", version: "0.24.0" });
4591
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.25.0" });
3787
4592
  server.registerTool(
3788
4593
  "validate_iki",
3789
4594
  {
@@ -3848,7 +4653,7 @@ function createIkiMcpServer() {
3848
4653
  server.registerTool(
3849
4654
  "auto_rig_from_layers",
3850
4655
  {
3851
- 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, 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, 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.",
4656
+ 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, 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, 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.",
3852
4657
  inputSchema: {
3853
4658
  layers: import_zod.z.array(
3854
4659
  import_zod.z.object({
@@ -3888,7 +4693,7 @@ function createIkiMcpServer() {
3888
4693
  async (args) => {
3889
4694
  try {
3890
4695
  const r = await autoRigFromLayers(args);
3891
- const text = r.ok ? r.path : `INVALID: ${r.error}`;
4696
+ const text = r.ok ? [r.path, ...formatFoldReport(r.folds, r.canvas)].join("\n") : `INVALID: ${r.error}`;
3892
4697
  return { content: [{ type: "text", text }], structuredContent: r };
3893
4698
  } catch (err) {
3894
4699
  const error = err instanceof Error ? err.message : String(err);
@@ -4016,7 +4821,7 @@ function createIkiMcpServer() {
4016
4821
  server.registerTool(
4017
4822
  "render_poses",
4018
4823
  {
4019
- description: "Renders a rigged .iki into the character loop's pose PNGs with the real engine, through the installed Chrome, Edge or Chromium run headless (set CHROME_PATH to pick one). The model decides the set: a bust gets 560x560 shots (rest, turns, nod, blinks, gaze, combined); a mouth adds 720x480 mouth crops; a full body (taller than wide) adds the full-canvas body, arm and elbow poses on a 1400-wide canvas, and a model with a pose forearm adds the full-pose-* shots. Writes <pose>.png files into outDir, overwriting same-named files in place; returns the written paths one per line. Fails with INVALID when no browser is found or an input is refused; a browser that cannot start is a tool error.",
4824
+ description: "Renders a rigged .iki into the character loop's pose PNGs with the real engine, through the installed Chrome, Edge or Chromium run headless (set CHROME_PATH to pick one). The model decides the set: a bust gets 560x560 shots (rest, turns, nod, blinks, gaze, combined \u2014 ParamAngleX/Y/Z all at 30 \u2014 and stress: ParamAngleX/Y/Z all at -30, ParamMouthOpenY 1, both eyes at 0.5, the brows at opposite extremes (ParamBrowLY -1, ParamBrowRY 1, ParamBrowLAngle 1, ParamBrowRAngle -1) and each body angle the model declares at -10); a mouth adds 720x480 mouth crops; a full body (taller than wide) adds the full-canvas body, arm and elbow poses on a 1400-wide canvas, and a model with a pose forearm adds the full-pose-* shots. Writes <pose>.png files into outDir, overwriting same-named files in place; returns the written paths one per line, then the model's fold report (the result's `folds`), checked by the engine over its own pose set: a `FOLD` line per warp deformer or mesh part that flips (ratio <= 0) or collapses (under 0.1) at some pose \u2014 its cell or triangle, the ratio of its area there to at rest, the pose as its parameter settings (`rest` for none) and where it rests, in model space and in model px from the top-left (the layer PNGs' own pixels, not a render's) \u2014 or `FOLDS: none over N poses`, then a `FOLDS expected:` line naming the closures the rig draws on purpose (an eye or the mouth shut), each by part id, ratio and the parameter that shuts it. Report-only: a fold never fails the render. Fails with INVALID when no browser is found or an input is refused; a browser that cannot start is a tool error.",
4020
4825
  inputSchema: {
4021
4826
  modelPath: import_zod.z.string().describe(
4022
4827
  "Rigged .iki file path (resolved against cwd; must sit under the working directory)."
@@ -4029,7 +4834,10 @@ function createIkiMcpServer() {
4029
4834
  async (args) => {
4030
4835
  try {
4031
4836
  const r = await renderPoses(args);
4032
- const text = r.ok ? r.poses.map((p) => p.path).join("\n") : `INVALID: ${r.error}`;
4837
+ const text = r.ok ? [
4838
+ ...r.poses.map((p) => p.path),
4839
+ ...formatFoldReport(r.folds, r.modelCanvas)
4840
+ ].join("\n") : `INVALID: ${r.error}`;
4033
4841
  return { content: [{ type: "text", text }], structuredContent: r };
4034
4842
  } catch (err) {
4035
4843
  const error = err instanceof Error ? err.message : String(err);
@@ -4046,9 +4854,11 @@ function createIkiMcpServer() {
4046
4854
  // Annotate the CommonJS export names for ESM import in node:
4047
4855
  0 && (module.exports = {
4048
4856
  autoRigFromLayers,
4857
+ checkModelFolds,
4049
4858
  composeLayersFromParts,
4050
4859
  createIkiMcpServer,
4051
4860
  describeIki,
4861
+ formatFoldReport,
4052
4862
  formatMeasureReport,
4053
4863
  formatTurnReport,
4054
4864
  listStandardParameters,