@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.
@@ -1,10 +1,793 @@
1
+ // src/fold-report.ts
2
+ import { LIP_INSIDE_ROLES, LIP_ROLES } from "@ikijs/editor";
3
+
4
+ // ../engine/src/math.ts
5
+ function clamp(value, min, max) {
6
+ return Math.max(min, Math.min(max, value));
7
+ }
8
+ function lerp(a, b, t) {
9
+ return a + (b - a) * t;
10
+ }
11
+
12
+ // ../engine/src/parameter-store.ts
13
+ var ParameterStore = class {
14
+ params = /* @__PURE__ */ new Map();
15
+ values = /* @__PURE__ */ new Map();
16
+ /**
17
+ * Resting value per id: the declared default clamped into range, resolved
18
+ * ONCE here so `reset()` is a straight copy and a malformed descriptor is
19
+ * reported once rather than on every reset.
20
+ */
21
+ defaults = /* @__PURE__ */ new Map();
22
+ constructor(parameters) {
23
+ for (const param of parameters) {
24
+ this.params.set(param.id, param);
25
+ if (!Number.isFinite(param.default)) {
26
+ console.error(
27
+ `Iki: parameter "${param.id}" has a non-finite default; resting at the neutral in-range value instead`
28
+ );
29
+ }
30
+ const base = Number.isFinite(param.default) ? param.default : 0;
31
+ this.defaults.set(param.id, clamp(base, param.min, param.max));
32
+ }
33
+ for (const [id, value] of this.defaults) this.values.set(id, value);
34
+ }
35
+ /**
36
+ * Set a parameter's value, clamped to its range. Unknown ids are ignored, as
37
+ * are non-finite values: this is the boundary a host drives with live signals,
38
+ * and `clamp` cannot filter NaN (`Math.max(min, Math.min(max, NaN))` is NaN),
39
+ * so one bad lip-sync/gaze frame would otherwise poison every binding that
40
+ * reads the parameter. A dropped write holds the last good pose.
41
+ */
42
+ set(id, value) {
43
+ const param = this.params.get(id);
44
+ if (!param) return;
45
+ if (!Number.isFinite(value)) return;
46
+ this.values.set(id, clamp(value, param.min, param.max));
47
+ }
48
+ /** Current value, or 0 if the id is unknown. */
49
+ get(id) {
50
+ return this.values.get(id) ?? 0;
51
+ }
52
+ /** Position of a parameter within its range, 0..1. */
53
+ normalized(id) {
54
+ const param = this.params.get(id);
55
+ if (!param || param.max === param.min) return 0;
56
+ return (this.get(id) - param.min) / (param.max - param.min);
57
+ }
58
+ /** Reset every parameter to its resting value (see `defaults`). */
59
+ reset() {
60
+ for (const [id, value] of this.defaults) this.values.set(id, value);
61
+ }
62
+ list() {
63
+ return [...this.params.values()];
64
+ }
65
+ };
66
+
67
+ // ../engine/src/affine.ts
68
+ function translate(tx, ty) {
69
+ return [1, 0, 0, 1, tx, ty];
70
+ }
71
+ function scale(sx, sy) {
72
+ return [sx, 0, 0, sy, 0, 0];
73
+ }
74
+ function rotate(degrees) {
75
+ const r = degrees * Math.PI / 180;
76
+ const c = Math.cos(r);
77
+ const s = Math.sin(r);
78
+ return [c, s, -s, c, 0, 0];
79
+ }
80
+ function multiply(a, b) {
81
+ return [
82
+ a[0] * b[0] + a[2] * b[1],
83
+ a[1] * b[0] + a[3] * b[1],
84
+ a[0] * b[2] + a[2] * b[3],
85
+ a[1] * b[2] + a[3] * b[3],
86
+ a[0] * b[4] + a[2] * b[5] + a[4],
87
+ a[1] * b[4] + a[3] * b[5] + a[5]
88
+ ];
89
+ }
90
+
91
+ // ../engine/src/warp.ts
92
+ function accumulateKeyformOffsets(keyforms, value, out) {
93
+ const ks = keyforms;
94
+ if (value <= ks[0].value) {
95
+ const { offsets } = ks[0];
96
+ for (let i = 0; i < offsets.length; i++) {
97
+ out[i] += offsets[i];
98
+ }
99
+ } else if (value >= ks[ks.length - 1].value) {
100
+ const { offsets } = ks[ks.length - 1];
101
+ for (let i = 0; i < offsets.length; i++) {
102
+ out[i] += offsets[i];
103
+ }
104
+ } else {
105
+ let lo = ks[0];
106
+ let hi = ks[1];
107
+ for (let k = 1; k < ks.length - 1; k++) {
108
+ if (ks[k].value <= value) {
109
+ lo = ks[k];
110
+ hi = ks[k + 1];
111
+ }
112
+ }
113
+ const t = (value - lo.value) / (hi.value - lo.value);
114
+ const loOff = lo.offsets;
115
+ const hiOff = hi.offsets;
116
+ for (let i = 0; i < loOff.length; i++) {
117
+ out[i] += loOff[i] + (hiOff[i] - loOff[i]) * t;
118
+ }
119
+ }
120
+ }
121
+ function accumulate2DKeyformOffsets(valuesX, valuesY, keyforms2d, vx, vy, out) {
122
+ const lastX = valuesX.length - 1;
123
+ const lastY = valuesY.length - 1;
124
+ let ix;
125
+ let tx;
126
+ if (vx <= valuesX[0]) {
127
+ ix = 0;
128
+ tx = 0;
129
+ } else if (vx >= valuesX[lastX]) {
130
+ ix = lastX - 1;
131
+ tx = 1;
132
+ } else {
133
+ ix = 0;
134
+ for (let k = 0; k < lastX - 1; k++) {
135
+ if (valuesX[k + 1] <= vx) ix = k + 1;
136
+ }
137
+ tx = (vx - valuesX[ix]) / (valuesX[ix + 1] - valuesX[ix]);
138
+ }
139
+ let iy;
140
+ let ty;
141
+ if (vy <= valuesY[0]) {
142
+ iy = 0;
143
+ ty = 0;
144
+ } else if (vy >= valuesY[lastY]) {
145
+ iy = lastY - 1;
146
+ ty = 1;
147
+ } else {
148
+ iy = 0;
149
+ for (let k = 0; k < lastY - 1; k++) {
150
+ if (valuesY[k + 1] <= vy) iy = k + 1;
151
+ }
152
+ ty = (vy - valuesY[iy]) / (valuesY[iy + 1] - valuesY[iy]);
153
+ }
154
+ const W = valuesX.length;
155
+ const c00 = keyforms2d[iy * W + ix];
156
+ const c10 = keyforms2d[iy * W + ix + 1];
157
+ const c01 = keyforms2d[(iy + 1) * W + ix];
158
+ const c11 = keyforms2d[(iy + 1) * W + ix + 1];
159
+ const o00 = c00.offsets;
160
+ const o10 = c10.offsets;
161
+ const o01 = c01.offsets;
162
+ const o11 = c11.offsets;
163
+ for (let n = 0; n < o00.length; n++) {
164
+ const top = o00[n] + (o10[n] - o00[n]) * tx;
165
+ const bot = o01[n] + (o11[n] - o01[n]) * tx;
166
+ out[n] += top + (bot - top) * ty;
167
+ }
168
+ }
169
+ function applyWarps(rest, warps, params, out) {
170
+ out.set(rest);
171
+ if (!warps || warps.length === 0) return;
172
+ for (const warp of warps) {
173
+ accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), out);
174
+ }
175
+ }
176
+
177
+ // ../engine/src/warp-grid.ts
178
+ function deformWarpGrid(d, params) {
179
+ const points = Float32Array.from(d.grid.points);
180
+ for (const warp of d.warps ?? []) {
181
+ accumulateKeyformOffsets(warp.keyforms, params.get(warp.parameter), points);
182
+ }
183
+ if (d.warp2d !== void 0) {
184
+ accumulate2DKeyformOffsets(
185
+ d.warp2d.valuesX,
186
+ d.warp2d.valuesY,
187
+ d.warp2d.keyforms2d,
188
+ params.get(d.warp2d.parameter),
189
+ params.get(d.warp2d.parameterY),
190
+ points
191
+ );
192
+ }
193
+ return points;
194
+ }
195
+ function transformGridPoints(points, affine, out = new Float32Array(points.length)) {
196
+ for (let i = 0; i < points.length; i += 2) {
197
+ const x = points[i];
198
+ const y = points[i + 1];
199
+ out[i] = affine[0] * x + affine[2] * y + affine[4];
200
+ out[i + 1] = affine[1] * x + affine[3] * y + affine[5];
201
+ }
202
+ return out;
203
+ }
204
+ function bindPointToRestGrid(x, y, restGrid) {
205
+ const { cols, rows, points } = restGrid;
206
+ const stride = cols + 1;
207
+ let col = cols - 1;
208
+ for (let c = 0; c < cols; c++) {
209
+ const xRight2 = points[(c + 1) * 2];
210
+ if (x < xRight2) {
211
+ col = c;
212
+ break;
213
+ }
214
+ }
215
+ const xLeft = points[col * 2];
216
+ const xRight = points[(col + 1) * 2];
217
+ const s = clamp((x - xLeft) / (xRight - xLeft), 0, 1);
218
+ let row = rows - 1;
219
+ for (let r = 0; r < rows; r++) {
220
+ const yBottom2 = points[(r + 1) * stride * 2 + 1];
221
+ if (y > yBottom2) {
222
+ row = r;
223
+ break;
224
+ }
225
+ }
226
+ const yTop = points[row * stride * 2 + 1];
227
+ const yBottom = points[(row + 1) * stride * 2 + 1];
228
+ const t = clamp((yTop - y) / (yTop - yBottom), 0, 1);
229
+ return { cell: row * cols + col, s, t };
230
+ }
231
+ function applyWarpToChild(localVerts, partAffine, restGrid, deformedGrid, out) {
232
+ const n = localVerts.length / 2;
233
+ for (let v = 0; v < n; v++) {
234
+ const lx = localVerts[v * 2];
235
+ const ly = localVerts[v * 2 + 1];
236
+ const mx = partAffine[0] * lx + partAffine[2] * ly + partAffine[4];
237
+ const my = partAffine[1] * lx + partAffine[3] * ly + partAffine[5];
238
+ const binding = bindPointToRestGrid(mx, my, restGrid);
239
+ const [sx, sy] = sampleWarpGrid(deformedGrid, binding);
240
+ out[v * 2] = sx;
241
+ out[v * 2 + 1] = sy;
242
+ }
243
+ }
244
+ function sampleWarpGrid(grid, binding) {
245
+ const { cols, points } = grid;
246
+ const stride = cols + 1;
247
+ const row = Math.floor(binding.cell / cols);
248
+ const col = binding.cell % cols;
249
+ const { s, t } = binding;
250
+ const i00 = (row * stride + col) * 2;
251
+ const i10 = (row * stride + col + 1) * 2;
252
+ const i01 = ((row + 1) * stride + col) * 2;
253
+ const i11 = ((row + 1) * stride + col + 1) * 2;
254
+ const topX = points[i00] + (points[i10] - points[i00]) * s;
255
+ const topY = points[i00 + 1] + (points[i10 + 1] - points[i00 + 1]) * s;
256
+ const botX = points[i01] + (points[i11] - points[i01]) * s;
257
+ const botY = points[i01 + 1] + (points[i11 + 1] - points[i01 + 1]) * s;
258
+ return [topX + (botX - topX) * t, topY + (botY - topY) * t];
259
+ }
260
+ function warpRigidFrame(pivot, restGrid, localPoints) {
261
+ const { cols, rows } = restGrid;
262
+ const binding = bindPointToRestGrid(pivot.x, pivot.y, restGrid);
263
+ const [px2, py] = sampleWarpGrid({ cols, rows, points: localPoints }, binding);
264
+ const stride = cols + 1;
265
+ const row = Math.floor(binding.cell / cols);
266
+ const col = binding.cell % cols;
267
+ const { s, t } = binding;
268
+ const i00 = (row * stride + col) * 2;
269
+ const i10 = (row * stride + col + 1) * 2;
270
+ const i01 = ((row + 1) * stride + col) * 2;
271
+ const i11 = ((row + 1) * stride + col + 1) * 2;
272
+ const rest = restGrid.points;
273
+ const cellWidth = rest[(col + 1) * 2] - rest[col * 2];
274
+ const cellHeight = rest[row * stride * 2 + 1] - rest[(row + 1) * stride * 2 + 1];
275
+ const q = localPoints;
276
+ const exX = lerp(q[i10] - q[i00], q[i11] - q[i01], t) / cellWidth;
277
+ const exY = lerp(q[i10 + 1] - q[i00 + 1], q[i11 + 1] - q[i01 + 1], t) / cellWidth;
278
+ const eyX = -lerp(q[i01] - q[i00], q[i11] - q[i10], s) / cellHeight;
279
+ const eyY = -lerp(q[i01 + 1] - q[i00 + 1], q[i11 + 1] - q[i10 + 1], s) / cellHeight;
280
+ const theta = Math.atan2(exY - eyX, exX + eyY);
281
+ const c = Math.cos(theta);
282
+ const sn = Math.sin(theta);
283
+ return [
284
+ c,
285
+ sn,
286
+ -sn,
287
+ c,
288
+ px2 - (c * pivot.x - sn * pivot.y),
289
+ py - (sn * pivot.x + c * pivot.y)
290
+ ];
291
+ }
292
+
293
+ // ../engine/src/deform.ts
294
+ var IDENTITY_TRANSFORM = {
295
+ x: 0,
296
+ y: 0,
297
+ rotation: 0,
298
+ scaleX: 1,
299
+ scaleY: 1,
300
+ opacity: 1
301
+ };
302
+ function evaluateTransform(transform, bindings, params) {
303
+ const base = transform ?? IDENTITY_TRANSFORM;
304
+ const result = {
305
+ x: base.x,
306
+ y: base.y,
307
+ rotation: base.rotation ?? 0,
308
+ scaleX: base.scaleX ?? 1,
309
+ scaleY: base.scaleY ?? 1,
310
+ opacity: base.opacity ?? 1
311
+ };
312
+ for (const binding of bindings ?? []) {
313
+ const t = params.normalized(binding.parameter);
314
+ const value = binding.from + (binding.to - binding.from) * t;
315
+ switch (binding.channel) {
316
+ case "translateX":
317
+ result.x += value;
318
+ break;
319
+ case "translateY":
320
+ result.y += value;
321
+ break;
322
+ case "rotate":
323
+ result.rotation += value;
324
+ break;
325
+ case "scaleX":
326
+ result.scaleX += value;
327
+ break;
328
+ case "scaleY":
329
+ result.scaleY += value;
330
+ break;
331
+ case "opacity":
332
+ result.opacity *= value;
333
+ break;
334
+ }
335
+ }
336
+ return result;
337
+ }
338
+ function deformerLocalMatrix(d, params) {
339
+ const t = evaluateTransform(d.transform, d.bindings, params);
340
+ const trs = multiply(
341
+ multiply(translate(t.x, t.y), rotate(t.rotation)),
342
+ scale(t.scaleX, t.scaleY)
343
+ );
344
+ return multiply(
345
+ multiply(translate(d.pivot.x, d.pivot.y), trs),
346
+ translate(-d.pivot.x, -d.pivot.y)
347
+ );
348
+ }
349
+ function resolveDeformers(deformers, params) {
350
+ const byId = new Map(deformers.map((d) => [d.id, d]));
351
+ const worlds = /* @__PURE__ */ new Map();
352
+ const grids = /* @__PURE__ */ new Map();
353
+ const localWarps = /* @__PURE__ */ new Map();
354
+ function parentOf(d) {
355
+ if (d.parent === void 0) return void 0;
356
+ const parent = byId.get(d.parent);
357
+ if (!parent) {
358
+ throw new Error(
359
+ `unresolved deformer parent "${d.parent}" \u2014 model not validated?`
360
+ );
361
+ }
362
+ return parent;
363
+ }
364
+ function resolveWorld(d) {
365
+ const cached = worlds.get(d.id);
366
+ if (cached) return cached;
367
+ const local = deformerLocalMatrix(d, params);
368
+ const parent = parentOf(d);
369
+ let world;
370
+ if (parent === void 0) {
371
+ world = local;
372
+ } else if (parent.kind === "warp") {
373
+ const warp = resolveWarp(parent);
374
+ const ridden = multiply(
375
+ warpRigidFrame(d.pivot, parent.grid, warp.localGrid),
376
+ local
377
+ );
378
+ world = warp.parentWorld ? multiply(warp.parentWorld, ridden) : ridden;
379
+ } else {
380
+ world = multiply(resolveWorld(parent), local);
381
+ }
382
+ worlds.set(d.id, world);
383
+ return world;
384
+ }
385
+ function resolveWarp(d) {
386
+ const cached = localWarps.get(d.id);
387
+ if (cached) return cached;
388
+ const parent = parentOf(d);
389
+ if (parent?.kind === "warp") {
390
+ throw new Error(
391
+ `warp deformer "${d.id}" hangs from warp "${parent.id}" \u2014 model not validated?`
392
+ );
393
+ }
394
+ const parentWorld = parent && resolveWorld(parent);
395
+ const localGrid = deformWarpGrid(d, params);
396
+ grids.set(d.id, {
397
+ cols: d.grid.cols,
398
+ rows: d.grid.rows,
399
+ points: parentWorld ? transformGridPoints(localGrid, parentWorld) : localGrid
400
+ });
401
+ const resolved = { localGrid, parentWorld };
402
+ localWarps.set(d.id, resolved);
403
+ return resolved;
404
+ }
405
+ for (const d of deformers) {
406
+ if (d.kind === "warp") resolveWarp(d);
407
+ else resolveWorld(d);
408
+ }
409
+ return { worlds, grids };
410
+ }
411
+
412
+ // ../engine/src/idle-motion.ts
413
+ import { StandardParameter } from "@ikijs/format";
414
+
415
+ // ../engine/src/frame-clock.ts
416
+ var FIXED_DT_S = 1 / 60;
417
+
418
+ // ../engine/src/idle-motion.ts
419
+ var BLINK_CLOSE_MS = 60;
420
+ var BLINK_HOLD_MS = 20;
421
+ var BLINK_OPEN_MS = 100;
422
+ var BLINK_DURATION_MS = BLINK_CLOSE_MS + BLINK_HOLD_MS + BLINK_OPEN_MS;
423
+
424
+ // ../engine/src/hair-chain-motion.ts
425
+ var DEG2RAD = Math.PI / 180;
426
+ var RAD2DEG = 180 / Math.PI;
427
+
428
+ // ../engine/src/iki-motion.ts
429
+ import { StandardParameter as StandardParameter2 } from "@ikijs/format";
430
+
431
+ // ../engine/src/clip-player.ts
432
+ import {
433
+ DEFAULT_FADE_SECONDS,
434
+ IDLE_MOTION_GROUP
435
+ } from "@ikijs/format";
436
+
437
+ // ../engine/src/expression-player.ts
438
+ import {
439
+ DEFAULT_FADE_SECONDS as DEFAULT_FADE_SECONDS2
440
+ } from "@ikijs/format";
441
+
442
+ // ../engine/src/iki-motion.ts
443
+ var HEAD_AND_GAZE = /* @__PURE__ */ new Set([
444
+ StandardParameter2.AngleX,
445
+ StandardParameter2.AngleY,
446
+ StandardParameter2.AngleZ,
447
+ StandardParameter2.EyeballX,
448
+ StandardParameter2.EyeballY
449
+ ]);
450
+
451
+ // ../engine/src/folds.ts
452
+ import {
453
+ StandardParameter as P
454
+ } from "@ikijs/format";
455
+ var FLIP = 0;
456
+ var COLLAPSE = 0.1;
457
+ var ANGLES = [
458
+ P.AngleX,
459
+ P.AngleY,
460
+ P.AngleZ,
461
+ P.BodyAngleX,
462
+ P.BodyAngleY,
463
+ P.BodyAngleZ
464
+ ];
465
+ var CROSSES = [
466
+ [P.EyeOpenLeft],
467
+ [P.EyeOpenRight],
468
+ [P.MouthOpen],
469
+ [P.ArmLeft, P.ArmRight],
470
+ [P.ElbowLeft, P.ElbowRight]
471
+ ];
472
+ function foldPoses(model) {
473
+ const byId = new Map(
474
+ model.parameters.filter((p) => p.min !== p.max).map((p) => [p.id, p])
475
+ );
476
+ const declared = (ids) => ids.flatMap((id) => byId.get(id) ?? []);
477
+ const poses = [];
478
+ const names = /* @__PURE__ */ new Set();
479
+ const add = (values) => {
480
+ const name = poseName(values);
481
+ if (names.has(name)) return;
482
+ names.add(name);
483
+ poses.push({ name, values });
484
+ };
485
+ add({});
486
+ for (const p of byId.values()) {
487
+ add({ [p.id]: p.min });
488
+ add({ [p.id]: p.max });
489
+ }
490
+ const angles = declared(ANGLES);
491
+ if (angles.length === 0) return poses;
492
+ const expand = (corners, groups) => {
493
+ for (const group of groups) {
494
+ corners = corners.flatMap(
495
+ (values) => ["min", "max"].map((end) => {
496
+ const next = { ...values };
497
+ for (const p of group) next[p.id] = p[end];
498
+ return next;
499
+ })
500
+ );
501
+ }
502
+ return corners;
503
+ };
504
+ const angleCorners = expand(
505
+ [{}],
506
+ angles.map((p) => [p])
507
+ );
508
+ for (const values of angleCorners) add(values);
509
+ const crosses = CROSSES.map(declared).filter((g) => g.length > 0);
510
+ for (const values of expand(angleCorners, crosses)) add(values);
511
+ return poses;
512
+ }
513
+ function poseName(values) {
514
+ const ids = Object.keys(values).sort();
515
+ if (ids.length === 0) return "rest";
516
+ return ids.map((id) => `${id}=${values[id]}`).join(" ");
517
+ }
518
+ function staticDeformers(model) {
519
+ return (model.deformers ?? []).map(
520
+ (d) => d.kind === "warp" ? { ...d, warps: void 0, warp2d: void 0 } : { ...d, bindings: void 0 }
521
+ );
522
+ }
523
+ function cornerAreas(points, cols, rows) {
524
+ const stride = cols + 1;
525
+ const out = new Float64Array(cols * rows * 4);
526
+ for (let r = 0; r < rows; r++) {
527
+ for (let c = 0; c < cols; c++) {
528
+ const tl = r * stride + c;
529
+ const [tr, bl, br] = [tl + 1, tl + stride, tl + stride + 1];
530
+ const i = (r * cols + c) * 4;
531
+ out[i] = doubledArea(points, bl, br, tl);
532
+ out[i + 1] = doubledArea(points, br, tr, bl);
533
+ out[i + 2] = doubledArea(points, tr, tl, br);
534
+ out[i + 3] = doubledArea(points, tl, bl, tr);
535
+ }
536
+ }
537
+ return out;
538
+ }
539
+ function doubledArea(points, p, q, s) {
540
+ const ax = points[q * 2] - points[p * 2];
541
+ const ay = points[q * 2 + 1] - points[p * 2 + 1];
542
+ const bx = points[s * 2] - points[p * 2];
543
+ const by = points[s * 2 + 1] - points[p * 2 + 1];
544
+ return ax * by - ay * bx;
545
+ }
546
+ function triangleAreas(points, indices) {
547
+ const out = new Float64Array(indices.length / 3);
548
+ for (let t = 0; t < out.length; t++) {
549
+ const i = t * 3;
550
+ out[t] = doubledArea(points, indices[i], indices[i + 1], indices[i + 2]);
551
+ }
552
+ return out;
553
+ }
554
+ function placement(part, t) {
555
+ return multiply(
556
+ multiply(translate(t.x, t.y), rotate(t.rotation)),
557
+ scale(part.width * t.scaleX, part.height * t.scaleY)
558
+ );
559
+ }
560
+ function keepLeast(sweep, areas, pose, expected) {
561
+ const slot = expected(sweep.target) ? "expected" : "worst";
562
+ for (let i = 0; i < areas.length; i++) {
563
+ const rest = sweep.restAreas[i];
564
+ if (Math.abs(rest) < sweep.tiny) continue;
565
+ const ratio = areas[i] / rest;
566
+ if (ratio < (sweep[slot]?.ratio ?? Infinity)) {
567
+ sweep[slot] = { ratio, at: i, pose };
568
+ }
569
+ }
570
+ }
571
+ function partSweep(part, mesh, deformers, worlds, store) {
572
+ const warpDeformer = deformers.find(
573
+ (d) => d.kind === "warp" && d.id === part.deformer
574
+ );
575
+ const frame = warpDeformer ? warpDeformer.parent : part.deformer;
576
+ const placed = placement(
577
+ part,
578
+ evaluateTransform(part.transform, void 0, store)
579
+ );
580
+ const restPoints = transformGridPoints(
581
+ mesh.vertices,
582
+ frame === void 0 ? placed : multiply(worlds.get(frame), placed),
583
+ new Float64Array(mesh.vertices.length)
584
+ );
585
+ return {
586
+ target: { kind: "part", id: part.id },
587
+ restAreas: triangleAreas(restPoints, mesh.indices),
588
+ tiny: 1e-9 * part.width * part.height,
589
+ part,
590
+ indices: mesh.indices,
591
+ warpDeformer,
592
+ vertices: Float32Array.from(mesh.vertices),
593
+ local: new Float32Array(mesh.vertices.length),
594
+ landed: new Float32Array(mesh.vertices.length),
595
+ restPoints
596
+ };
597
+ }
598
+ function landPart(sweep, store, { worlds, grids }) {
599
+ const { part, warpDeformer, local, landed } = sweep;
600
+ applyWarps(sweep.vertices, part.warps, store, local);
601
+ const placed = placement(
602
+ part,
603
+ evaluateTransform(part.transform, part.bindings, store)
604
+ );
605
+ if (warpDeformer) {
606
+ const grid = grids.get(warpDeformer.id);
607
+ applyWarpToChild(local, placed, warpDeformer.grid, grid, landed);
608
+ } else if (part.deformer !== void 0) {
609
+ const world = worlds.get(part.deformer);
610
+ transformGridPoints(local, multiply(world, placed), landed);
611
+ } else {
612
+ transformGridPoints(local, placed, landed);
613
+ }
614
+ return landed;
615
+ }
616
+ function checkFolds(model, options = {}) {
617
+ const poses = options.poses ?? foldPoses(model);
618
+ const deformers = model.deformers ?? [];
619
+ const restStore = new ParameterStore(model.parameters);
620
+ const { worlds } = resolveDeformers(staticDeformers(model), restStore);
621
+ const gridSweeps = [];
622
+ for (const d of deformers) {
623
+ if (d.kind !== "warp") continue;
624
+ const { cols, rows, points } = d.grid;
625
+ const width = points[cols * 2] - points[0];
626
+ const height = points[1] - points[rows * (cols + 1) * 2 + 1];
627
+ gridSweeps.push({
628
+ deformer: d,
629
+ target: { kind: "deformer", id: d.id },
630
+ restAreas: cornerAreas(points, cols, rows),
631
+ // The validator tolerates 1e-6 of jitter, which can zero a corner's area.
632
+ tiny: 1e-9 * width * height
633
+ });
634
+ }
635
+ const partSweeps = model.parts.flatMap(
636
+ (part) => part.mesh ? [partSweep(part, part.mesh, deformers, worlds, restStore)] : []
637
+ );
638
+ for (const pose of poses) {
639
+ const store = new ParameterStore(model.parameters);
640
+ for (const [id, v] of Object.entries(pose.values)) store.set(id, v);
641
+ const value = (id) => store.get(id);
642
+ const expected = (target) => options.expected?.(target, pose, value) === true;
643
+ for (const sweep of gridSweeps) {
644
+ const { cols, rows } = sweep.deformer.grid;
645
+ const areas = cornerAreas(
646
+ deformWarpGrid(sweep.deformer, store),
647
+ cols,
648
+ rows
649
+ );
650
+ keepLeast(sweep, areas, pose, expected);
651
+ }
652
+ const resolved = resolveDeformers(deformers, store);
653
+ for (const sweep of partSweeps) {
654
+ const areas = triangleAreas(
655
+ landPart(sweep, store, resolved),
656
+ sweep.indices
657
+ );
658
+ keepLeast(sweep, areas, pose, expected);
659
+ }
660
+ }
661
+ const targets = [
662
+ ...gridSweeps.map((sweep) => {
663
+ const { parent } = sweep.deformer;
664
+ const world = parent === void 0 ? void 0 : worlds.get(parent);
665
+ return foldTarget(
666
+ sweep,
667
+ (least) => cellHit(sweep.deformer, least, world)
668
+ );
669
+ }),
670
+ ...partSweeps.map(
671
+ (sweep) => foldTarget(sweep, (least) => triangleHit(sweep, least))
672
+ )
673
+ ];
674
+ const offenders = targets.filter((t) => t.kind !== "ok").sort((a, b) => a.worst.ratio - b.worst.ratio);
675
+ return {
676
+ poses: poses.length,
677
+ thresholds: { flip: FLIP, collapse: COLLAPSE },
678
+ targets,
679
+ offenders
680
+ };
681
+ }
682
+ function foldTarget(sweep, hit) {
683
+ const worst = sweep.worst && hit(sweep.worst);
684
+ const expected = sweep.expected && hit(sweep.expected);
685
+ return { target: sweep.target, kind: classify(worst), worst, expected };
686
+ }
687
+ function cellHit(d, least, parent) {
688
+ const { cols, points } = d.grid;
689
+ const cell = Math.floor(least.at / 4);
690
+ const col = cell % cols;
691
+ const row = Math.floor(cell / cols);
692
+ const stride = cols + 1;
693
+ let x = 0;
694
+ let y = 0;
695
+ for (const i of [
696
+ row * stride + col,
697
+ row * stride + col + 1,
698
+ (row + 1) * stride + col,
699
+ (row + 1) * stride + col + 1
700
+ ]) {
701
+ x += points[i * 2] / 4;
702
+ y += points[i * 2 + 1] / 4;
703
+ }
704
+ const rest = parent ? {
705
+ x: parent[0] * x + parent[2] * y + parent[4],
706
+ y: parent[1] * x + parent[3] * y + parent[5]
707
+ } : { x, y };
708
+ return { ratio: least.ratio, where: { col, row }, pose: least.pose, rest };
709
+ }
710
+ function triangleHit(sweep, least) {
711
+ const { indices, restPoints } = sweep;
712
+ let x = 0;
713
+ let y = 0;
714
+ for (let k = 0; k < 3; k++) {
715
+ const i = indices[least.at * 3 + k];
716
+ x += restPoints[i * 2] / 3;
717
+ y += restPoints[i * 2 + 1] / 3;
718
+ }
719
+ return {
720
+ ratio: least.ratio,
721
+ where: { triangle: least.at },
722
+ pose: least.pose,
723
+ rest: { x, y }
724
+ };
725
+ }
726
+ function classify(worst) {
727
+ if (worst === void 0) return "ok";
728
+ if (worst.ratio <= FLIP) return "flip";
729
+ if (worst.ratio < COLLAPSE) return "collapse";
730
+ return "ok";
731
+ }
732
+
733
+ // src/fold-report.ts
734
+ import { StandardParameter as P2 } from "@ikijs/format";
735
+ var SHUT_BY = new Map([
736
+ ["eye_L", P2.EyeOpenLeft],
737
+ ["lash_lower_L", P2.EyeOpenLeft],
738
+ ["eye_R", P2.EyeOpenRight],
739
+ ["lash_lower_R", P2.EyeOpenRight],
740
+ ...[...LIP_ROLES, ...LIP_INSIDE_ROLES].map((id) => [
741
+ id,
742
+ P2.MouthOpen
743
+ ])
744
+ ]);
745
+ function checkModelFolds(model) {
746
+ const declared = new Set(model.parameters.map((p) => p.id));
747
+ return checkFolds(model, {
748
+ // The effective value, not the pose's overrides: the auto-rig's mouth
749
+ // rests shut at its default, so `rest` and the other parameters' singles
750
+ // are shut-mouth poses too.
751
+ expected: (target, _pose, value) => {
752
+ if (target.kind !== "part") return false;
753
+ const shutBy = SHUT_BY.get(target.id);
754
+ return shutBy !== void 0 && declared.has(shutBy) && value(shutBy) === 0;
755
+ }
756
+ });
757
+ }
758
+ function formatFoldReport(report, canvas) {
759
+ const lines = report.offenders.length === 0 ? [`FOLDS: none over ${report.poses} poses`] : report.offenders.map((t) => offenderLine(t, t.worst, canvas));
760
+ const closures = report.targets.flatMap((t) => {
761
+ if (t.expected === void 0) return [];
762
+ if (t.expected.ratio >= report.thresholds.collapse) return [];
763
+ const shutBy = SHUT_BY.get(t.target.id);
764
+ const at = shutBy === void 0 ? "" : ` at ${shutBy}=0`;
765
+ return [`${t.target.id} ${ratioText(t.expected.ratio)}${at}`];
766
+ });
767
+ if (closures.length > 0) {
768
+ lines.push(
769
+ `FOLDS expected: by-design closures, not findings \u2014 ${closures.join(", ")}`
770
+ );
771
+ }
772
+ return lines;
773
+ }
774
+ function offenderLine(t, hit, canvas) {
775
+ const where = "triangle" in hit.where ? `triangle ${hit.where.triangle}` : `cell (${hit.where.col},${hit.where.row})`;
776
+ const { x, y } = hit.rest;
777
+ 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`;
778
+ }
779
+ function ratioText(ratio) {
780
+ if (ratio === 0) return "0";
781
+ return Math.abs(ratio) < 0.01 ? ratio.toExponential(1) : ratio.toFixed(2);
782
+ }
783
+
1
784
  // src/tools.ts
2
785
  import path2 from "path";
3
786
  import {
4
787
  parseIkiModel,
5
788
  loadIkiModel,
6
789
  IkiFormatError,
7
- StandardParameter
790
+ StandardParameter as StandardParameter3
8
791
  } from "@ikijs/format";
9
792
  import {
10
793
  EditorDocument,
@@ -193,15 +976,15 @@ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
193
976
  for (const crop of crops) byId.set(crop.id, crop);
194
977
  const pad = layout.padding;
195
978
  const composites = await Promise.all(
196
- layout.placements.map(async (placement2) => {
197
- const crop = byId.get(placement2.id);
979
+ layout.placements.map(async (placement3) => {
980
+ const crop = byId.get(placement3.id);
198
981
  if (crop === void 0) {
199
982
  throw new AutoRigInputError(
200
- `no crop for atlas placement "${placement2.id}"`
983
+ `no crop for atlas placement "${placement3.id}"`
201
984
  );
202
985
  }
203
986
  const input = pad > 0 ? await sharp(crop.buffer).extend({ right: pad, bottom: pad, extendWith: "copy" }).png().toBuffer() : crop.buffer;
204
- return { input, left: placement2.x, top: placement2.y };
987
+ return { input, left: placement3.x, top: placement3.y };
205
988
  })
206
989
  );
207
990
  const page = await sharp({
@@ -297,115 +1080,115 @@ function describeIki(model) {
297
1080
  }
298
1081
  var STANDARD_PARAMETER_INFO = [
299
1082
  {
300
- id: StandardParameter.MouthOpen,
1083
+ id: StandardParameter3.MouthOpen,
301
1084
  description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
302
1085
  },
303
1086
  {
304
- id: StandardParameter.MouthForm,
1087
+ id: StandardParameter3.MouthForm,
305
1088
  description: "Mouth form / smile (-1 .. 1)."
306
1089
  },
307
1090
  {
308
- id: StandardParameter.EyeOpenLeft,
1091
+ id: StandardParameter3.EyeOpenLeft,
309
1092
  description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
310
1093
  },
311
1094
  {
312
- id: StandardParameter.EyeOpenRight,
1095
+ id: StandardParameter3.EyeOpenRight,
313
1096
  description: "Right eye open (0 closed .. 1 open)."
314
1097
  },
315
1098
  {
316
- id: StandardParameter.EyeballX,
1099
+ id: StandardParameter3.EyeballX,
317
1100
  description: "Eyeball gaze, horizontal (-1 .. 1)."
318
1101
  },
319
1102
  {
320
- id: StandardParameter.EyeballY,
1103
+ id: StandardParameter3.EyeballY,
321
1104
  description: "Eyeball gaze, vertical (-1 .. 1)."
322
1105
  },
323
1106
  {
324
- id: StandardParameter.AngleX,
1107
+ id: StandardParameter3.AngleX,
325
1108
  description: "Head angle, horizontal degrees."
326
1109
  },
327
1110
  {
328
- id: StandardParameter.AngleY,
1111
+ id: StandardParameter3.AngleY,
329
1112
  description: "Head angle, vertical degrees."
330
1113
  },
331
1114
  {
332
- id: StandardParameter.AngleZ,
1115
+ id: StandardParameter3.AngleZ,
333
1116
  description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
334
1117
  },
335
1118
  {
336
- id: StandardParameter.BodyAngleX,
1119
+ id: StandardParameter3.BodyAngleX,
337
1120
  description: "Body turn, degrees (-10 .. 10); positive turns the body toward the viewer's right, as AngleX does the head."
338
1121
  },
339
1122
  {
340
- id: StandardParameter.BodyAngleY,
1123
+ id: StandardParameter3.BodyAngleY,
341
1124
  description: "Body lean, degrees (-10 .. 10); positive moves the upper body up, negative bows."
342
1125
  },
343
1126
  {
344
- id: StandardParameter.BodyAngleZ,
1127
+ id: StandardParameter3.BodyAngleZ,
345
1128
  description: "Body tilt, degrees (-10 .. 10); positive tilts the top toward the viewer's right (clockwise), as AngleZ does the head."
346
1129
  },
347
1130
  {
348
- id: StandardParameter.Breath,
1131
+ id: StandardParameter3.Breath,
349
1132
  description: "Idle breath (0 .. 1), cycled by the host."
350
1133
  },
351
1134
  {
352
- id: StandardParameter.BrowLeftY,
1135
+ id: StandardParameter3.BrowLeftY,
353
1136
  description: "Left brow raise/lower (-1 .. 1)."
354
1137
  },
355
1138
  {
356
- id: StandardParameter.BrowRightY,
1139
+ id: StandardParameter3.BrowRightY,
357
1140
  description: "Right brow raise/lower (-1 .. 1)."
358
1141
  },
359
1142
  {
360
- id: StandardParameter.BrowLeftAngle,
1143
+ id: StandardParameter3.BrowLeftAngle,
361
1144
  description: "Left brow tilt/angle (-1 .. 1)."
362
1145
  },
363
1146
  {
364
- id: StandardParameter.BrowRightAngle,
1147
+ id: StandardParameter3.BrowRightAngle,
365
1148
  description: "Right brow tilt/angle (-1 .. 1)."
366
1149
  },
367
1150
  {
368
- id: StandardParameter.Cheek,
1151
+ id: StandardParameter3.Cheek,
369
1152
  description: "Cheek blush strength (0 .. 1), raised by an expression."
370
1153
  },
371
1154
  {
372
- id: StandardParameter.HairSwayX,
1155
+ id: StandardParameter3.HairSwayX,
373
1156
  description: "Horizontal hair-sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
374
1157
  },
375
1158
  {
376
- id: StandardParameter.HairSwayZ,
1159
+ id: StandardParameter3.HairSwayZ,
377
1160
  description: "Hair-sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
378
1161
  },
379
1162
  {
380
- id: StandardParameter.ArmLeft,
1163
+ id: StandardParameter3.ArmLeft,
381
1164
  description: "Left shoulder, degrees; positive raises the arm outward (mirrored on the right)."
382
1165
  },
383
1166
  {
384
- id: StandardParameter.ArmRight,
1167
+ id: StandardParameter3.ArmRight,
385
1168
  description: "Right shoulder, degrees; positive raises the arm outward (mirrored on the left)."
386
1169
  },
387
1170
  {
388
- id: StandardParameter.ElbowLeft,
1171
+ id: StandardParameter3.ElbowLeft,
389
1172
  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)."
390
1173
  },
391
1174
  {
392
- id: StandardParameter.ElbowRight,
1175
+ id: StandardParameter3.ElbowRight,
393
1176
  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)."
394
1177
  },
395
1178
  {
396
- id: StandardParameter.ArmPoseLeft,
1179
+ id: StandardParameter3.ArmPoseLeft,
397
1180
  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."
398
1181
  },
399
1182
  {
400
- id: StandardParameter.ArmPoseRight,
1183
+ id: StandardParameter3.ArmPoseRight,
401
1184
  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."
402
1185
  },
403
1186
  {
404
- id: StandardParameter.ArmPoseAngleLeft,
1187
+ id: StandardParameter3.ArmPoseAngleLeft,
405
1188
  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)."
406
1189
  },
407
1190
  {
408
- id: StandardParameter.ArmPoseAngleRight,
1191
+ id: StandardParameter3.ArmPoseAngleRight,
409
1192
  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)."
410
1193
  }
411
1194
  ];
@@ -575,11 +1358,11 @@ async function autoRigFromLayers(input) {
575
1358
  }
576
1359
  const partTextureAssignments = pages.flatMap(
577
1360
  ({ crops: pageCrops, layout }) => pageCrops.flatMap((crop) => {
578
- const placement2 = layout.placements.find((p) => p.id === crop.id);
579
- if (placement2 === void 0) {
1361
+ const placement3 = layout.placements.find((p) => p.id === crop.id);
1362
+ if (placement3 === void 0) {
580
1363
  throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
581
1364
  }
582
- const uv = uvRectFor(placement2, {
1365
+ const uv = uvRectFor(placement3, {
583
1366
  width: layout.pageWidth,
584
1367
  height: layout.pageHeight
585
1368
  });
@@ -600,6 +1383,7 @@ async function autoRigFromLayers(input) {
600
1383
  }
601
1384
  const finalModel = parseIkiModel(patched);
602
1385
  writeFileAtomic(outPath, JSON.stringify(finalModel));
1386
+ const folds = checkModelFolds(finalModel);
603
1387
  return {
604
1388
  ok: true,
605
1389
  path: outPath,
@@ -611,7 +1395,8 @@ async function autoRigFromLayers(input) {
611
1395
  ...headEdges === void 0 ? {} : { headEdges },
612
1396
  ...strandEdges === void 0 ? {} : { strandEdges },
613
1397
  ...noseCore === void 0 ? {} : { noseCore },
614
- ...turn === void 0 ? {} : { turn }
1398
+ ...turn === void 0 ? {} : { turn },
1399
+ folds
615
1400
  };
616
1401
  } catch (err) {
617
1402
  if (err instanceof AutoRigInputError)
@@ -1156,8 +1941,8 @@ function jointWarnings(pose, arm, stats, a, armLayer, b) {
1156
1941
  import path5 from "path";
1157
1942
  import {
1158
1943
  ALPHA_OPAQUE as ALPHA_OPAQUE4,
1159
- LIP_INSIDE_ROLES,
1160
- LIP_ROLES,
1944
+ LIP_INSIDE_ROLES as LIP_INSIDE_ROLES2,
1945
+ LIP_ROLES as LIP_ROLES2,
1161
1946
  LayerGeometryError as LayerGeometryError4,
1162
1947
  columnRuns as columnRuns2,
1163
1948
  createLayerSetMeasurer as createLayerSetMeasurer5,
@@ -1837,7 +2622,7 @@ async function closedLips(upper, lower, shift, left, top) {
1837
2622
  }
1838
2623
 
1839
2624
  // src/measure-lips.ts
1840
- var isLipLayerRole = (role) => LIP_ROLES.includes(role) || isLipInsideRole(role);
2625
+ var isLipLayerRole = (role) => LIP_ROLES2.includes(role) || isLipInsideRole(role);
1841
2626
  var MIN_OPENING_ROWS = 8;
1842
2627
  var MIN_LINE_ROWS = 2;
1843
2628
  var GREEN_EXCESS = 40;
@@ -1845,8 +2630,8 @@ var INTERIOR_GAP_FRACTION = 0.05;
1845
2630
  var columns = (cols) => `${cols.length} column${cols.length === 1 ? "" : "s"} (first at x=${cols[0]})`;
1846
2631
  async function lipWarnings(absDir, layers) {
1847
2632
  const warnings = [];
1848
- const present = LIP_ROLES.filter((role) => layers[role] !== void 0);
1849
- const inside = LIP_INSIDE_ROLES.filter((role) => layers[role] !== void 0);
2633
+ const present = LIP_ROLES2.filter((role) => layers[role] !== void 0);
2634
+ const inside = LIP_INSIDE_ROLES2.filter((role) => layers[role] !== void 0);
1850
2635
  if (present.length === 0) {
1851
2636
  if (inside.length > 0) {
1852
2637
  warnings.push(
@@ -1863,8 +2648,8 @@ async function lipWarnings(absDir, layers) {
1863
2648
  `${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.`
1864
2649
  );
1865
2650
  }
1866
- if (present.length < LIP_ROLES.length) {
1867
- const missing = LIP_ROLES.filter((role) => layers[role] === void 0);
2651
+ if (present.length < LIP_ROLES2.length) {
2652
+ const missing = LIP_ROLES2.filter((role) => layers[role] === void 0);
1868
2653
  warnings.push(
1869
2654
  `${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.`
1870
2655
  );
@@ -1901,7 +2686,7 @@ async function lipWarnings(absDir, layers) {
1901
2686
  });
1902
2687
  const set = /* @__PURE__ */ new Map();
1903
2688
  const green = [];
1904
- for (const role of LIP_ROLES) {
2689
+ for (const role of LIP_ROLES2) {
1905
2690
  const fileName = `${role}.png`;
1906
2691
  const { rgba } = await decodePng(path5.join(absDir, fileName));
1907
2692
  set.set(role, measurer.add({ role, fileName, rgba }));
@@ -2603,12 +3388,12 @@ function resolveLayout(overrides, canvas) {
2603
3388
  const face = { ...resolved.face, ...sets.get("face") };
2604
3389
  resolved.face = face;
2605
3390
  const base = DEFAULT_LAYOUT.face;
2606
- const scale = face.w / base.w;
2607
- const x = (cx) => face.cx + (cx - base.cx) * scale;
2608
- const w = (width) => Math.max(1, Math.round(width * scale));
3391
+ const scale2 = face.w / base.w;
3392
+ const x = (cx) => face.cx + (cx - base.cx) * scale2;
3393
+ const w = (width) => Math.max(1, Math.round(width * scale2));
2609
3394
  for (const role of FACE_FEATURES) {
2610
3395
  const d = DEFAULT_LAYOUT[role];
2611
- const cy = face.cy + (d.cy - base.cy) * scale;
3396
+ const cy = face.cy + (d.cy - base.cy) * scale2;
2612
3397
  resolved[role] = { ...d, cx: x(d.cx), cy, w: w(d.w), ...sets.get(role) };
2613
3398
  }
2614
3399
  const nose = DEFAULT_LAYOUT.nose;
@@ -2749,7 +3534,7 @@ function assertOnCanvas(source, w, h, left, top, canvas) {
2749
3534
  );
2750
3535
  }
2751
3536
  }
2752
- function placement(role, cfg, w, h, canvas) {
3537
+ function placement2(role, cfg, w, h, canvas) {
2753
3538
  const left = Math.round(cfg.cx - w / 2);
2754
3539
  const top = Math.round(cfg.cy - h / 2);
2755
3540
  assertOnCanvas(`layout.${role}.cx/cy`, w, h, left, top, canvas);
@@ -3019,7 +3804,7 @@ async function composeLayersFromParts(input) {
3019
3804
  part2.h,
3020
3805
  lips.interior
3021
3806
  );
3022
- const { left: left2, top: top2 } = placement(role, cfg2, part2.w, part2.h, canvas);
3807
+ const { left: left2, top: top2 } = placement2(role, cfg2, part2.w, part2.h, canvas);
3023
3808
  lipSplit = { split: split2, w: part2.w, h: part2.h, left: left2, top: top2 };
3024
3809
  placed.push({
3025
3810
  role,
@@ -3176,7 +3961,7 @@ async function composeLayersFromParts(input) {
3176
3961
  canvas
3177
3962
  ));
3178
3963
  } else {
3179
- ({ left, top } = placement(key, layout[key], part.w, part.h, canvas));
3964
+ ({ left, top } = placement2(key, layout[key], part.w, part.h, canvas));
3180
3965
  }
3181
3966
  if (role === "lash_L" || role === "lash_R") {
3182
3967
  const eyeRole = role === "lash_L" ? "eye_L" : "eye_R";
@@ -3305,7 +4090,7 @@ import { readFileSync } from "fs";
3305
4090
  import path9 from "path";
3306
4091
  import {
3307
4092
  IkiFormatError as IkiFormatError2,
3308
- StandardParameter as StandardParameter2,
4093
+ StandardParameter as StandardParameter4,
3309
4094
  loadIkiModel as loadIkiModel2
3310
4095
  } from "@ikijs/format";
3311
4096
 
@@ -3634,6 +4419,13 @@ function planRenders(model) {
3634
4419
  name,
3635
4420
  values
3636
4421
  });
4422
+ const bodyAngles = Object.fromEntries(
4423
+ [
4424
+ StandardParameter4.BodyAngleX,
4425
+ StandardParameter4.BodyAngleY,
4426
+ StandardParameter4.BodyAngleZ
4427
+ ].filter((id) => model.parameters.some((p) => p.id === id)).map((id) => [id, -10])
4428
+ );
3637
4429
  const poses = [
3638
4430
  square("rest"),
3639
4431
  square("turn-m30", { ParamAngleX: -30 }),
@@ -3643,7 +4435,22 @@ function planRenders(model) {
3643
4435
  square("blink", { ParamEyeLOpen: 0 }),
3644
4436
  square("blink-half", { ParamEyeLOpen: 0.5 }),
3645
4437
  square("gaze", { ParamEyeBallX: 1 }),
3646
- square("combined", { ParamAngleX: 30, ParamAngleY: 30, ParamAngleZ: 30 })
4438
+ square("combined", { ParamAngleX: 30, ParamAngleY: 30, ParamAngleZ: 30 }),
4439
+ // Every head angle at its other extreme with the face moving too, where
4440
+ // moves that each look fine alone stack up into a fold.
4441
+ square("stress", {
4442
+ ParamAngleX: -30,
4443
+ ParamAngleY: -30,
4444
+ ParamAngleZ: -30,
4445
+ ParamMouthOpenY: 1,
4446
+ ParamEyeLOpen: 0.5,
4447
+ ParamEyeROpen: 0.5,
4448
+ ParamBrowLY: -1,
4449
+ ParamBrowRY: 1,
4450
+ ParamBrowLAngle: 1,
4451
+ ParamBrowRAngle: -1,
4452
+ ...bodyAngles
4453
+ })
3647
4454
  ];
3648
4455
  if (mouth) {
3649
4456
  const crop = {
@@ -3702,7 +4509,7 @@ function planRenders(model) {
3702
4509
  whole("full-elbow-r-45", { ParamElbowR: 45 }),
3703
4510
  whole("full-elbow-r-90", { ParamElbowR: 90 })
3704
4511
  );
3705
- if (model.parameters.some((p) => p.id === StandardParameter2.ArmPoseRight)) {
4512
+ if (model.parameters.some((p) => p.id === StandardParameter4.ArmPoseRight)) {
3706
4513
  poses.push(
3707
4514
  whole("full-pose-l", { ParamArmPoseL: 1 }),
3708
4515
  whole("full-pose-r", { ParamArmPoseR: 1 }),
@@ -3749,6 +4556,7 @@ async function renderPoses(input) {
3749
4556
  const browser = findBrowser();
3750
4557
  if (!browser) return { ok: false, error: NO_BROWSER_MESSAGE };
3751
4558
  const pageScript = readPageScript();
4559
+ const folds = checkModelFolds(model);
3752
4560
  const { failedTextures, poses } = await withBrowser(
3753
4561
  browser,
3754
4562
  async (evaluate) => {
@@ -3783,7 +4591,9 @@ async function renderPoses(input) {
3783
4591
  fullBody: plan.fullBody,
3784
4592
  mouth: plan.mouth,
3785
4593
  failedTextures,
3786
- poses
4594
+ poses,
4595
+ modelCanvas: model.canvas,
4596
+ folds
3787
4597
  };
3788
4598
  } catch (error) {
3789
4599
  if (error instanceof AutoRigInputError || error instanceof IkiFormatError2) {
@@ -3797,7 +4607,7 @@ async function renderPoses(input) {
3797
4607
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3798
4608
  import { z } from "zod";
3799
4609
  function createIkiMcpServer() {
3800
- const server = new McpServer({ name: "iki", version: "0.24.0" });
4610
+ const server = new McpServer({ name: "iki", version: "0.25.0" });
3801
4611
  server.registerTool(
3802
4612
  "validate_iki",
3803
4613
  {
@@ -3862,7 +4672,7 @@ function createIkiMcpServer() {
3862
4672
  server.registerTool(
3863
4673
  "auto_rig_from_layers",
3864
4674
  {
3865
- 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.",
4675
+ 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.",
3866
4676
  inputSchema: {
3867
4677
  layers: z.array(
3868
4678
  z.object({
@@ -3902,7 +4712,7 @@ function createIkiMcpServer() {
3902
4712
  async (args) => {
3903
4713
  try {
3904
4714
  const r = await autoRigFromLayers(args);
3905
- const text = r.ok ? r.path : `INVALID: ${r.error}`;
4715
+ const text = r.ok ? [r.path, ...formatFoldReport(r.folds, r.canvas)].join("\n") : `INVALID: ${r.error}`;
3906
4716
  return { content: [{ type: "text", text }], structuredContent: r };
3907
4717
  } catch (err) {
3908
4718
  const error = err instanceof Error ? err.message : String(err);
@@ -4030,7 +4840,7 @@ function createIkiMcpServer() {
4030
4840
  server.registerTool(
4031
4841
  "render_poses",
4032
4842
  {
4033
- 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.",
4843
+ 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.",
4034
4844
  inputSchema: {
4035
4845
  modelPath: z.string().describe(
4036
4846
  "Rigged .iki file path (resolved against cwd; must sit under the working directory)."
@@ -4043,7 +4853,10 @@ function createIkiMcpServer() {
4043
4853
  async (args) => {
4044
4854
  try {
4045
4855
  const r = await renderPoses(args);
4046
- const text = r.ok ? r.poses.map((p) => p.path).join("\n") : `INVALID: ${r.error}`;
4856
+ const text = r.ok ? [
4857
+ ...r.poses.map((p) => p.path),
4858
+ ...formatFoldReport(r.folds, r.modelCanvas)
4859
+ ].join("\n") : `INVALID: ${r.error}`;
4047
4860
  return { content: [{ type: "text", text }], structuredContent: r };
4048
4861
  } catch (err) {
4049
4862
  const error = err instanceof Error ? err.message : String(err);
@@ -4059,6 +4872,8 @@ function createIkiMcpServer() {
4059
4872
  }
4060
4873
 
4061
4874
  export {
4875
+ checkModelFolds,
4876
+ formatFoldReport,
4062
4877
  validateIki,
4063
4878
  describeIki,
4064
4879
  listStandardParameters,
@@ -4071,4 +4886,4 @@ export {
4071
4886
  renderPoses,
4072
4887
  createIkiMcpServer
4073
4888
  };
4074
- //# sourceMappingURL=chunk-GEXOSC5O.mjs.map
4889
+ //# sourceMappingURL=chunk-JIVXQW4L.mjs.map