@ikijs/mcp 0.23.2 → 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,
@@ -48,18 +831,18 @@ function rejectEmptyOrUrl(inputPath, noun, kind) {
48
831
  );
49
832
  }
50
833
  }
51
- function resolveInputPath(inputPath) {
52
- rejectEmptyOrUrl(inputPath, "layer path", "file path");
834
+ function resolveInputPath(inputPath, what = "layer") {
835
+ rejectEmptyOrUrl(inputPath, `${what} path`, "file path");
53
836
  const resolved = path.resolve(process.cwd(), inputPath);
54
837
  let stat;
55
838
  try {
56
839
  stat = fs.statSync(resolved);
57
840
  } catch {
58
- throw new AutoRigInputError(`layer file not found: ${resolved}`);
841
+ throw new AutoRigInputError(`${what} file not found: ${resolved}`);
59
842
  }
60
843
  if (stat.isDirectory()) {
61
844
  throw new AutoRigInputError(
62
- `layer path is a directory, not a file: ${resolved}`
845
+ `${what} path is a directory, not a file: ${resolved}`
63
846
  );
64
847
  }
65
848
  return resolved;
@@ -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";
@@ -3300,11 +4085,529 @@ async function composeLayersFromParts(input) {
3300
4085
  }
3301
4086
  }
3302
4087
 
4088
+ // src/render-poses.ts
4089
+ import { readFileSync } from "fs";
4090
+ import path9 from "path";
4091
+ import {
4092
+ IkiFormatError as IkiFormatError2,
4093
+ StandardParameter as StandardParameter4,
4094
+ loadIkiModel as loadIkiModel2
4095
+ } from "@ikijs/format";
4096
+
4097
+ // src/render-browser.ts
4098
+ import { spawn } from "child_process";
4099
+ import fs4 from "fs";
4100
+ import os from "os";
4101
+ import path8 from "path";
4102
+ var NO_BROWSER_MESSAGE = "render_poses needs a Chromium-based browser and found none. Install Google Chrome, Microsoft Edge or Chromium, or set CHROME_PATH to its executable.";
4103
+ var DARWIN_CANDIDATES = [
4104
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
4105
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
4106
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
4107
+ ];
4108
+ var LINUX_CANDIDATES = [
4109
+ "/usr/bin/google-chrome",
4110
+ "/usr/bin/google-chrome-stable",
4111
+ "/usr/bin/chromium",
4112
+ "/usr/bin/chromium-browser",
4113
+ "/usr/bin/microsoft-edge",
4114
+ "/snap/bin/chromium"
4115
+ ];
4116
+ var WIN32_ROOTS = ["PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"];
4117
+ var WIN32_SUFFIXES = [
4118
+ ["Google", "Chrome", "Application", "chrome.exe"],
4119
+ ["Microsoft", "Edge", "Application", "msedge.exe"]
4120
+ ];
4121
+ var CLOSE_GRACE_MS = 2e3;
4122
+ var DEFAULT_TIMEOUT_MS = 3e4;
4123
+ var BROWSER_CLOSE_MS = 1e3;
4124
+ function isExecutableFile(file) {
4125
+ try {
4126
+ if (!fs4.statSync(file).isFile()) return false;
4127
+ fs4.accessSync(file, fs4.constants.X_OK);
4128
+ return true;
4129
+ } catch {
4130
+ return false;
4131
+ }
4132
+ }
4133
+ function findBrowser({
4134
+ env = process.env,
4135
+ platform = process.platform,
4136
+ isExecutable = isExecutableFile
4137
+ } = {}) {
4138
+ const override = env.CHROME_PATH;
4139
+ if (override) {
4140
+ if (!isExecutable(override)) {
4141
+ throw new AutoRigInputError(
4142
+ `CHROME_PATH is not an executable file: ${override}`
4143
+ );
4144
+ }
4145
+ return override;
4146
+ }
4147
+ let candidates;
4148
+ if (platform === "darwin") candidates = DARWIN_CANDIDATES;
4149
+ else if (platform === "win32") {
4150
+ candidates = [];
4151
+ for (const suffix of WIN32_SUFFIXES) {
4152
+ for (const root of WIN32_ROOTS) {
4153
+ const base = env[root];
4154
+ if (base) candidates.push(path8.win32.join(base, ...suffix));
4155
+ }
4156
+ }
4157
+ } else candidates = LINUX_CANDIDATES;
4158
+ return candidates.find((file) => isExecutable(file));
4159
+ }
4160
+ function within(promise, ms, what, detail) {
4161
+ let timer;
4162
+ const timeout = new Promise((_, reject) => {
4163
+ timer = setTimeout(
4164
+ () => reject(
4165
+ new Error(
4166
+ `${what} timed out after ${ms} ms${detail ? `: ${detail()}` : ""}`
4167
+ )
4168
+ ),
4169
+ ms
4170
+ );
4171
+ });
4172
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
4173
+ }
4174
+ function connectCdp(url, timeoutMs) {
4175
+ const socket = new WebSocket(url);
4176
+ let nextId = 0;
4177
+ let socketClosed = false;
4178
+ const pending = /* @__PURE__ */ new Map();
4179
+ socket.addEventListener("message", (event) => {
4180
+ const message = JSON.parse(String(event.data));
4181
+ const entry = pending.get(message.id);
4182
+ if (!entry) return;
4183
+ pending.delete(message.id);
4184
+ if (message.error) {
4185
+ entry.reject(
4186
+ new Error(`${message.error.message} (${message.error.code})`)
4187
+ );
4188
+ } else entry.resolve(message.result);
4189
+ });
4190
+ socket.addEventListener("close", () => {
4191
+ socketClosed = true;
4192
+ for (const entry of pending.values()) {
4193
+ entry.reject(new Error("DevTools connection closed"));
4194
+ }
4195
+ pending.clear();
4196
+ });
4197
+ const opened = new Promise((resolve, reject) => {
4198
+ socket.addEventListener(
4199
+ "error",
4200
+ () => reject(new Error("DevTools connection failed"))
4201
+ );
4202
+ socket.addEventListener(
4203
+ "open",
4204
+ () => resolve({
4205
+ send(method, callTimeoutMs, params, sessionId) {
4206
+ if (socketClosed) {
4207
+ return Promise.reject(new Error("DevTools connection closed"));
4208
+ }
4209
+ const id = ++nextId;
4210
+ const reply = new Promise((res, rej) => {
4211
+ pending.set(id, {
4212
+ resolve: res,
4213
+ reject: rej
4214
+ });
4215
+ });
4216
+ socket.send(JSON.stringify({ id, method, params, sessionId }));
4217
+ return within(reply, callTimeoutMs, method).finally(
4218
+ () => pending.delete(id)
4219
+ );
4220
+ }
4221
+ })
4222
+ );
4223
+ });
4224
+ return within(opened, timeoutMs, "DevTools connection").catch((error) => {
4225
+ socket.close();
4226
+ throw error;
4227
+ });
4228
+ }
4229
+ function startError(executable, error) {
4230
+ return new Error(
4231
+ `could not start ${executable}: ${error.code ?? error.message}`
4232
+ );
4233
+ }
4234
+ function waitForDevTools(child, closed, getSpawnError, executable, timeoutMs) {
4235
+ let tail = "";
4236
+ return within(
4237
+ new Promise((resolve, reject) => {
4238
+ child.stderr.on("data", (chunk) => {
4239
+ tail = (tail + chunk).slice(-2e3);
4240
+ const match = /DevTools listening on (ws:\/\/\S+)/.exec(tail);
4241
+ if (match) resolve(match[1]);
4242
+ });
4243
+ void closed.then(() => {
4244
+ const spawnError = getSpawnError();
4245
+ reject(
4246
+ spawnError ? startError(executable, spawnError) : new Error(
4247
+ `${executable} exited before DevTools was ready: ${tail.trim()}`
4248
+ )
4249
+ );
4250
+ });
4251
+ }),
4252
+ timeoutMs,
4253
+ "browser startup",
4254
+ () => tail.trim() || "no output"
4255
+ );
4256
+ }
4257
+ async function openPage(cdp, timeoutMs) {
4258
+ const { targetId } = await cdp.send(
4259
+ "Target.createTarget",
4260
+ timeoutMs,
4261
+ { url: "about:blank" }
4262
+ );
4263
+ const { sessionId } = await cdp.send(
4264
+ "Target.attachToTarget",
4265
+ timeoutMs,
4266
+ { targetId, flatten: true }
4267
+ );
4268
+ return async (expression, evalTimeoutMs) => {
4269
+ const { result, exceptionDetails } = await cdp.send(
4270
+ "Runtime.evaluate",
4271
+ evalTimeoutMs,
4272
+ { expression, awaitPromise: true, returnByValue: true },
4273
+ sessionId
4274
+ );
4275
+ if (exceptionDetails) {
4276
+ const thrown = exceptionDetails.exception;
4277
+ throw new Error(
4278
+ thrown?.description ?? (thrown && "value" in thrown ? String(thrown.value) : exceptionDetails.text)
4279
+ );
4280
+ }
4281
+ return result.value;
4282
+ };
4283
+ }
4284
+ function removeProfile(profile) {
4285
+ try {
4286
+ fs4.rmSync(profile, {
4287
+ recursive: true,
4288
+ force: true,
4289
+ maxRetries: 5,
4290
+ retryDelay: 100
4291
+ });
4292
+ } catch (error) {
4293
+ console.error(`could not remove browser profile ${profile}:`, error);
4294
+ }
4295
+ }
4296
+ async function launchBrowser(executable, timeoutMs) {
4297
+ if (typeof globalThis.WebSocket === "undefined") {
4298
+ throw new AutoRigInputError(
4299
+ "render_poses needs Node 22 or newer (the global WebSocket is missing)."
4300
+ );
4301
+ }
4302
+ const profile = fs4.mkdtempSync(path8.join(os.tmpdir(), "iki-render-"));
4303
+ let child;
4304
+ try {
4305
+ child = spawn(
4306
+ executable,
4307
+ [
4308
+ "--headless=new",
4309
+ "--remote-debugging-port=0",
4310
+ `--user-data-dir=${profile}`,
4311
+ "--no-first-run",
4312
+ "--no-default-browser-check",
4313
+ // Output pixel sizes must equal the plan's, whatever the display.
4314
+ "--force-device-scale-factor=1",
4315
+ // WebGL without a GPU; recent Chrome no longer falls back by itself.
4316
+ "--enable-unsafe-swiftshader",
4317
+ "about:blank"
4318
+ ],
4319
+ { stdio: ["ignore", "ignore", "pipe"] }
4320
+ );
4321
+ } catch (error) {
4322
+ fs4.rmSync(profile, { recursive: true, force: true });
4323
+ throw startError(executable, error);
4324
+ }
4325
+ let spawnError;
4326
+ child.on("error", (error) => {
4327
+ spawnError = error;
4328
+ });
4329
+ let exited = false;
4330
+ const closed = new Promise((resolve) => {
4331
+ child.on("close", () => {
4332
+ exited = true;
4333
+ resolve();
4334
+ });
4335
+ });
4336
+ const settle = (ms) => within(closed, ms, "browser close").catch(() => {
4337
+ });
4338
+ const onProcessExit = () => {
4339
+ child.kill("SIGKILL");
4340
+ removeProfile(profile);
4341
+ };
4342
+ process.once("exit", onProcessExit);
4343
+ let shutdownPromise;
4344
+ const shutdown = () => shutdownPromise ??= (async () => {
4345
+ if (!exited) {
4346
+ child.kill();
4347
+ await settle(CLOSE_GRACE_MS);
4348
+ if (!exited) {
4349
+ child.kill("SIGKILL");
4350
+ await settle(CLOSE_GRACE_MS);
4351
+ }
4352
+ }
4353
+ process.removeListener("exit", onProcessExit);
4354
+ removeProfile(profile);
4355
+ })();
4356
+ let cdp;
4357
+ try {
4358
+ const endpoint = await waitForDevTools(
4359
+ child,
4360
+ closed,
4361
+ () => spawnError,
4362
+ executable,
4363
+ timeoutMs
4364
+ );
4365
+ cdp = await connectCdp(endpoint, timeoutMs);
4366
+ } catch (error) {
4367
+ await shutdown();
4368
+ throw error;
4369
+ }
4370
+ return {
4371
+ openPage: () => openPage(cdp, timeoutMs),
4372
+ async close() {
4373
+ if (!exited) {
4374
+ await cdp.send("Browser.close", BROWSER_CLOSE_MS).catch(() => {
4375
+ });
4376
+ }
4377
+ await shutdown();
4378
+ }
4379
+ };
4380
+ }
4381
+ async function withBrowser(executable, fn) {
4382
+ const browser = await launchBrowser(executable, DEFAULT_TIMEOUT_MS);
4383
+ try {
4384
+ return await fn(await browser.openPage());
4385
+ } finally {
4386
+ await browser.close();
4387
+ }
4388
+ }
4389
+
4390
+ // src/render-poses.ts
4391
+ var FULL_BODY_VIEW_WIDTH = 2.5;
4392
+ var BUST_SIZE = 560;
4393
+ function planRenders(model) {
4394
+ const { width: W, height: H } = model.canvas;
4395
+ const fullBody = H > W;
4396
+ const canvas = fullBody ? {
4397
+ width: FULL_BODY_VIEW_WIDTH * BUST_SIZE,
4398
+ height: Math.ceil(BUST_SIZE * H / W)
4399
+ } : { width: BUST_SIZE, height: BUST_SIZE };
4400
+ const view = fullBody ? { x: 0, y: 0, width: FULL_BODY_VIEW_WIDTH * W, height: H } : void 0;
4401
+ const x0 = (canvas.width - BUST_SIZE) / 2;
4402
+ const s = BUST_SIZE / W;
4403
+ const mouthPart = model.parts.find((p) => p.id === "mouth_inner") ?? model.parts.find((p) => p.id === "mouth");
4404
+ const mouth = mouthPart ? { cx: W / 2 + mouthPart.transform.x, cy: H / 2 - mouthPart.transform.y } : void 0;
4405
+ const squareCrop = fullBody ? {
4406
+ sx: x0,
4407
+ sy: 0,
4408
+ sw: BUST_SIZE,
4409
+ sh: BUST_SIZE,
4410
+ dw: BUST_SIZE,
4411
+ dh: BUST_SIZE
4412
+ } : void 0;
4413
+ const square = (name, values = {}) => ({
4414
+ name,
4415
+ values,
4416
+ crop: squareCrop
4417
+ });
4418
+ const whole = (name, values = {}) => ({
4419
+ name,
4420
+ values
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
+ );
4429
+ const poses = [
4430
+ square("rest"),
4431
+ square("turn-m30", { ParamAngleX: -30 }),
4432
+ square("turn-p30", { ParamAngleX: 30 }),
4433
+ square("turn-15", { ParamAngleX: 15 }),
4434
+ square("nod-15", { ParamAngleY: 15 }),
4435
+ square("blink", { ParamEyeLOpen: 0 }),
4436
+ square("blink-half", { ParamEyeLOpen: 0.5 }),
4437
+ square("gaze", { ParamEyeBallX: 1 }),
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
+ })
4454
+ ];
4455
+ if (mouth) {
4456
+ const crop = {
4457
+ sx: x0 + (mouth.cx - 90) * s,
4458
+ sy: (mouth.cy - 60) * s,
4459
+ sw: 180 * s,
4460
+ sh: 120 * s,
4461
+ dw: 720,
4462
+ dh: 480
4463
+ };
4464
+ for (const open of [0, 0.3, 0.6, 1]) {
4465
+ for (const [name, form] of [
4466
+ ["m1", -1],
4467
+ ["0", 0],
4468
+ ["p1", 1]
4469
+ ]) {
4470
+ poses.push({
4471
+ name: `mouth-open-${open}-form-${name}`,
4472
+ values: { ParamMouthOpenY: open, ParamMouthForm: form },
4473
+ crop
4474
+ });
4475
+ }
4476
+ }
4477
+ poses.push(
4478
+ {
4479
+ name: "mouth-laugh",
4480
+ values: { ParamMouthOpenY: 0.8, ParamMouthForm: 1 },
4481
+ crop
4482
+ },
4483
+ { name: "mouth-surprised", values: { ParamMouthOpenY: 0.9 }, crop },
4484
+ {
4485
+ name: "mouth-turn-p30-half",
4486
+ values: { ParamAngleX: 30, ParamMouthOpenY: 0.5 },
4487
+ crop
4488
+ }
4489
+ );
4490
+ }
4491
+ if (fullBody) {
4492
+ poses.push(
4493
+ whole("full-rest"),
4494
+ whole("full-turn-p30", { ParamAngleX: 30 }),
4495
+ whole("full-body-x-m10", { ParamBodyAngleX: -10 }),
4496
+ whole("full-body-x-p10", { ParamBodyAngleX: 10 }),
4497
+ whole("full-body-y-m10", { ParamBodyAngleY: -10 }),
4498
+ whole("full-body-y-p10", { ParamBodyAngleY: 10 }),
4499
+ whole("full-body-z-m10", { ParamBodyAngleZ: -10 }),
4500
+ whole("full-body-z-p10", { ParamBodyAngleZ: 10 }),
4501
+ whole("full-arm-l-16", { ParamArmL: 16 }),
4502
+ whole("full-arm-l-32", { ParamArmL: 32 }),
4503
+ whole("full-arm-r-16", { ParamArmR: 16 }),
4504
+ whole("full-arm-r-32", { ParamArmR: 32 }),
4505
+ whole("full-elbow-l-m10", { ParamElbowL: -10 }),
4506
+ whole("full-elbow-l-45", { ParamElbowL: 45 }),
4507
+ whole("full-elbow-l-90", { ParamElbowL: 90 }),
4508
+ whole("full-elbow-r-m10", { ParamElbowR: -10 }),
4509
+ whole("full-elbow-r-45", { ParamElbowR: 45 }),
4510
+ whole("full-elbow-r-90", { ParamElbowR: 90 })
4511
+ );
4512
+ if (model.parameters.some((p) => p.id === StandardParameter4.ArmPoseRight)) {
4513
+ poses.push(
4514
+ whole("full-pose-l", { ParamArmPoseL: 1 }),
4515
+ whole("full-pose-r", { ParamArmPoseR: 1 }),
4516
+ whole("full-pose-r-angle-m15", {
4517
+ ParamArmPoseR: 1,
4518
+ ParamArmPoseAngleR: -15
4519
+ }),
4520
+ whole("full-pose-r-angle-p15", {
4521
+ ParamArmPoseR: 1,
4522
+ ParamArmPoseAngleR: 15
4523
+ }),
4524
+ whole("full-pose-r-half", { ParamArmPoseR: 0.5 })
4525
+ );
4526
+ }
4527
+ }
4528
+ return { canvas, view, fullBody, mouth, poses };
4529
+ }
4530
+ var PNG_PREFIX = "data:image/png;base64,";
4531
+ var PAGE_SCRIPT_MS = 1e4;
4532
+ var LOAD_MS = 6e4;
4533
+ var CAPTURE_MS = 15e3;
4534
+ function readPageScript() {
4535
+ const url = new URL("../dist/render-page.global.js", import.meta.url);
4536
+ try {
4537
+ return readFileSync(url, "utf8");
4538
+ } catch (cause) {
4539
+ throw new Error(
4540
+ "could not read the render page script; run `pnpm build` in packages/mcp",
4541
+ { cause }
4542
+ );
4543
+ }
4544
+ }
4545
+ async function renderPoses(input) {
4546
+ try {
4547
+ const modelFile = confineToWorkingDirectory(
4548
+ process.cwd(),
4549
+ resolveInputPath(input.modelPath, "model"),
4550
+ "model path",
4551
+ input.modelPath
4552
+ );
4553
+ const outDir = resolveOutputDir(input.outDir);
4554
+ const model = loadIkiModel2(readFileSync(modelFile, "utf8"));
4555
+ const plan = planRenders(model);
4556
+ const browser = findBrowser();
4557
+ if (!browser) return { ok: false, error: NO_BROWSER_MESSAGE };
4558
+ const pageScript = readPageScript();
4559
+ const folds = checkModelFolds(model);
4560
+ const { failedTextures, poses } = await withBrowser(
4561
+ browser,
4562
+ async (evaluate) => {
4563
+ await evaluate(pageScript, PAGE_SCRIPT_MS);
4564
+ const loaded = await evaluate(
4565
+ `window.__ikiRender.load(${JSON.stringify(model)}, ${JSON.stringify({ canvas: plan.canvas, view: plan.view })})`,
4566
+ LOAD_MS
4567
+ );
4568
+ const written = [];
4569
+ for (const pose of plan.poses) {
4570
+ const url = await evaluate(
4571
+ `window.__ikiRender.capture(${JSON.stringify(pose.values)}, ${JSON.stringify(pose.crop)})`,
4572
+ CAPTURE_MS
4573
+ );
4574
+ if (typeof url !== "string" || !url.startsWith(PNG_PREFIX)) {
4575
+ throw new Error(`pose ${pose.name}: the page returned no PNG`);
4576
+ }
4577
+ const file = path9.join(outDir, `${pose.name}.png`);
4578
+ writeFileAtomic(
4579
+ file,
4580
+ Buffer.from(url.slice(PNG_PREFIX.length), "base64")
4581
+ );
4582
+ written.push({ name: pose.name, path: file });
4583
+ }
4584
+ return { failedTextures: loaded.failedTextures, poses: written };
4585
+ }
4586
+ );
4587
+ return {
4588
+ ok: true,
4589
+ outDir,
4590
+ canvas: plan.canvas,
4591
+ fullBody: plan.fullBody,
4592
+ mouth: plan.mouth,
4593
+ failedTextures,
4594
+ poses,
4595
+ modelCanvas: model.canvas,
4596
+ folds
4597
+ };
4598
+ } catch (error) {
4599
+ if (error instanceof AutoRigInputError || error instanceof IkiFormatError2) {
4600
+ return { ok: false, error: error.message };
4601
+ }
4602
+ throw error;
4603
+ }
4604
+ }
4605
+
3303
4606
  // src/server.ts
3304
4607
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3305
4608
  import { z } from "zod";
3306
4609
  function createIkiMcpServer() {
3307
- const server = new McpServer({ name: "iki", version: "0.23.2" });
4610
+ const server = new McpServer({ name: "iki", version: "0.25.0" });
3308
4611
  server.registerTool(
3309
4612
  "validate_iki",
3310
4613
  {
@@ -3369,7 +4672,7 @@ function createIkiMcpServer() {
3369
4672
  server.registerTool(
3370
4673
  "auto_rig_from_layers",
3371
4674
  {
3372
- 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.",
3373
4676
  inputSchema: {
3374
4677
  layers: z.array(
3375
4678
  z.object({
@@ -3409,7 +4712,7 @@ function createIkiMcpServer() {
3409
4712
  async (args) => {
3410
4713
  try {
3411
4714
  const r = await autoRigFromLayers(args);
3412
- 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}`;
3413
4716
  return { content: [{ type: "text", text }], structuredContent: r };
3414
4717
  } catch (err) {
3415
4718
  const error = err instanceof Error ? err.message : String(err);
@@ -3534,10 +4837,43 @@ function createIkiMcpServer() {
3534
4837
  }
3535
4838
  }
3536
4839
  );
4840
+ server.registerTool(
4841
+ "render_poses",
4842
+ {
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.",
4844
+ inputSchema: {
4845
+ modelPath: z.string().describe(
4846
+ "Rigged .iki file path (resolved against cwd; must sit under the working directory)."
4847
+ ),
4848
+ outDir: z.string().describe(
4849
+ "Existing directory to write the pose PNGs into (resolved against cwd; must already exist; confined to the working directory)."
4850
+ )
4851
+ }
4852
+ },
4853
+ async (args) => {
4854
+ try {
4855
+ const r = await renderPoses(args);
4856
+ const text = r.ok ? [
4857
+ ...r.poses.map((p) => p.path),
4858
+ ...formatFoldReport(r.folds, r.modelCanvas)
4859
+ ].join("\n") : `INVALID: ${r.error}`;
4860
+ return { content: [{ type: "text", text }], structuredContent: r };
4861
+ } catch (err) {
4862
+ const error = err instanceof Error ? err.message : String(err);
4863
+ return {
4864
+ content: [{ type: "text", text: `Unexpected error: ${error}` }],
4865
+ structuredContent: { ok: false, error },
4866
+ isError: true
4867
+ };
4868
+ }
4869
+ }
4870
+ );
3537
4871
  return server;
3538
4872
  }
3539
4873
 
3540
4874
  export {
4875
+ checkModelFolds,
4876
+ formatFoldReport,
3541
4877
  validateIki,
3542
4878
  describeIki,
3543
4879
  listStandardParameters,
@@ -3547,6 +4883,7 @@ export {
3547
4883
  measureLayers,
3548
4884
  formatMeasureReport,
3549
4885
  composeLayersFromParts,
4886
+ renderPoses,
3550
4887
  createIkiMcpServer
3551
4888
  };
3552
- //# sourceMappingURL=chunk-SXLILLB6.mjs.map
4889
+ //# sourceMappingURL=chunk-JIVXQW4L.mjs.map