@ikijs/mcp 0.11.1 → 0.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -28,7 +28,7 @@ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
28
28
  var import_zod = require("zod");
29
29
 
30
30
  // src/tools.ts
31
- var import_node_path3 = __toESM(require("path"));
31
+ var import_node_path2 = __toESM(require("path"));
32
32
  var import_format = require("@ikijs/format");
33
33
  var import_editor2 = require("@ikijs/editor");
34
34
 
@@ -231,135 +231,450 @@ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
231
231
  return `data:image/png;base64,${page.toString("base64")}`;
232
232
  }
233
233
 
234
- // src/measure-turn.ts
235
- var import_node_path2 = __toESM(require("path"));
236
- var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
237
- var IRIS_V_MIN = 0.18;
238
- var IRIS_V_MAX = 0.95;
239
- var IRIS_MEAN_V_MIN = 0.32;
240
- var CLOSE_RADIUS = 3;
241
- var CLOSE_RADIUS_REFERENCE_PX = 1254;
242
- var BLOB_MAX_FRAC = 0.12;
243
- var KEYED_SPAN_MAX_FRAC = 0.95;
244
- var MIN_AREA_REFERENCE_PIXELS = 1254 * 1254;
245
- var MIN_AREA = 300;
246
- var PAIR_DX_MIN_FRAC = 0.08;
247
- var PAIR_DX_MAX_FRAC = 0.35;
248
- var PAIR_DY_MAX_FRAC = 0.05;
249
- var MAX_CANDIDATES = 12;
250
- var HEAD_BAND = 10;
251
- var ALPHA_OPAQUE = 128;
252
- var BG_HUE_MIN = 220;
253
- var BG_HUE_MAX = 260;
254
- var BG_SAT_MAX = 0.2;
255
- var BG_V_MIN = 0.55;
256
- var BG_V_BLACK = 0.03;
257
- function denseCoreOf(rgba, width, height) {
258
- let minX = width;
259
- let minY = height;
260
- let maxX = -1;
261
- let maxY = -1;
262
- for (let y = 0; y < height; y++) {
263
- for (let x = 0; x < width; x++) {
264
- if (rgba[(y * width + x) * 4 + 3] >= ALPHA_OPAQUE) {
265
- if (x < minX) minX = x;
266
- if (x > maxX) maxX = x;
267
- if (y < minY) minY = y;
268
- if (y > maxY) maxY = y;
269
- }
270
- }
234
+ // src/tools.ts
235
+ function coerceModel(model) {
236
+ try {
237
+ const parsed = typeof model === "string" ? (0, import_format.loadIkiModel)(model) : (0, import_format.parseIkiModel)(model);
238
+ return { ok: true, model: parsed };
239
+ } catch (e) {
240
+ if (e instanceof import_format.IkiFormatError) return { ok: false, error: e.message };
241
+ throw e;
271
242
  }
272
- if (maxX < 0) return null;
273
- return { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 };
274
243
  }
275
- var SPECK_CORE_FRACTION = 0.25;
276
- function isSpeckCore(core, part) {
277
- return core.w < SPECK_CORE_FRACTION * part.w || core.h < SPECK_CORE_FRACTION * part.h;
278
- }
279
- function rgbToHsv(r, g, b) {
280
- r /= 255;
281
- g /= 255;
282
- b /= 255;
283
- const max = Math.max(r, g, b);
284
- const min = Math.min(r, g, b);
285
- const d = max - min;
286
- let h = 0;
287
- if (d > 0) {
288
- if (max === r) h = (g - b) / d % 6;
289
- else if (max === g) h = (b - r) / d + 2;
290
- else h = (r - g) / d + 4;
291
- h *= 60;
292
- if (h < 0) h += 360;
293
- }
294
- return [h, max === 0 ? 0 : d / max, max];
244
+ function validateIki(model) {
245
+ const result = coerceModel(model);
246
+ if (!result.ok) return { ok: false, error: result.error };
247
+ return { ok: true };
295
248
  }
296
- function dilate(mask, width, height, r) {
297
- const out = new Uint8Array(width * height);
298
- for (let y = 0; y < height; y++) {
299
- for (let x = 0; x < width; x++) {
300
- if (!mask[y * width + x]) continue;
301
- for (let dy = -r; dy <= r; dy++) {
302
- for (let dx = -r; dx <= r; dx++) {
303
- const yy = y + dy;
304
- const xx = x + dx;
305
- if (yy >= 0 && yy < height && xx >= 0 && xx < width)
306
- out[yy * width + xx] = 1;
249
+ function describeIki(model) {
250
+ const result = coerceModel(model);
251
+ if (!result.ok) return { ok: false, error: result.error };
252
+ const m = result.model;
253
+ const parameters = m.parameters.map((p) => ({
254
+ id: p.id,
255
+ min: p.min,
256
+ max: p.max,
257
+ default: p.default
258
+ }));
259
+ const parts = m.parts.map((p) => {
260
+ const entry = {
261
+ id: p.id,
262
+ order: p.order
263
+ };
264
+ if (p.deformer !== void 0) entry.deformer = p.deformer;
265
+ return entry;
266
+ });
267
+ const deformers = (m.deformers ?? []).map(
268
+ (d) => {
269
+ const kind = d.kind === "warp" ? "warp" : "matrix";
270
+ const entry = { id: d.id, kind };
271
+ if (d.parent !== void 0) entry.parent = d.parent;
272
+ if (d.kind === "warp") {
273
+ if (d.warp2d !== void 0) {
274
+ entry.warp = {
275
+ mode: "2d",
276
+ parameterX: d.warp2d.parameter,
277
+ parameterY: d.warp2d.parameterY,
278
+ gridX: d.grid.cols,
279
+ gridY: d.grid.rows
280
+ };
281
+ } else if (d.warps !== void 0 && d.warps.length > 0) {
282
+ entry.warp = {
283
+ mode: "1d",
284
+ parameters: d.warps.map((w) => w.parameter)
285
+ };
307
286
  }
308
287
  }
288
+ return entry;
309
289
  }
290
+ );
291
+ const summary = {
292
+ name: m.name,
293
+ canvas: { width: m.canvas.width, height: m.canvas.height },
294
+ parameters,
295
+ parts,
296
+ deformers
297
+ };
298
+ return { ok: true, summary };
299
+ }
300
+ var STANDARD_PARAMETER_INFO = [
301
+ {
302
+ id: import_format.StandardParameter.MouthOpen,
303
+ description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
304
+ },
305
+ {
306
+ id: import_format.StandardParameter.MouthForm,
307
+ description: "Mouth form / smile (-1 .. 1)."
308
+ },
309
+ {
310
+ id: import_format.StandardParameter.EyeOpenLeft,
311
+ description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
312
+ },
313
+ {
314
+ id: import_format.StandardParameter.EyeOpenRight,
315
+ description: "Right eye open (0 closed .. 1 open)."
316
+ },
317
+ {
318
+ id: import_format.StandardParameter.EyeballX,
319
+ description: "Eyeball gaze, horizontal (-1 .. 1)."
320
+ },
321
+ {
322
+ id: import_format.StandardParameter.EyeballY,
323
+ description: "Eyeball gaze, vertical (-1 .. 1)."
324
+ },
325
+ {
326
+ id: import_format.StandardParameter.AngleX,
327
+ description: "Head angle, horizontal degrees."
328
+ },
329
+ {
330
+ id: import_format.StandardParameter.AngleY,
331
+ description: "Head angle, vertical degrees."
332
+ },
333
+ {
334
+ id: import_format.StandardParameter.AngleZ,
335
+ description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
336
+ },
337
+ {
338
+ id: import_format.StandardParameter.Breath,
339
+ description: "Idle breath (0 .. 1), cycled by the host."
340
+ },
341
+ {
342
+ id: import_format.StandardParameter.BrowLeftY,
343
+ description: "Left brow raise/lower (-1 .. 1)."
344
+ },
345
+ {
346
+ id: import_format.StandardParameter.BrowRightY,
347
+ description: "Right brow raise/lower (-1 .. 1)."
348
+ },
349
+ {
350
+ id: import_format.StandardParameter.BrowLeftAngle,
351
+ description: "Left brow tilt/angle (-1 .. 1)."
352
+ },
353
+ {
354
+ id: import_format.StandardParameter.BrowRightAngle,
355
+ description: "Right brow tilt/angle (-1 .. 1)."
356
+ },
357
+ {
358
+ id: import_format.StandardParameter.HairSwayX,
359
+ description: "Horizontal hair-sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
360
+ },
361
+ {
362
+ id: import_format.StandardParameter.HairSwayZ,
363
+ description: "Hair-sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
310
364
  }
311
- return out;
365
+ ];
366
+ function listStandardParameters() {
367
+ return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));
312
368
  }
313
- function erode(mask, width, height, r) {
314
- const out = new Uint8Array(width * height);
315
- for (let y = 0; y < height; y++) {
316
- for (let x = 0; x < width; x++) {
317
- if (!mask[y * width + x]) continue;
318
- let keep = true;
319
- for (let dy = -r; dy <= r && keep; dy++) {
320
- for (let dx = -r; dx <= r; dx++) {
321
- const yy = y + dy;
322
- const xx = x + dx;
323
- if (yy < 0 || yy >= height || xx < 0 || xx >= width || !mask[yy * width + xx]) {
324
- keep = false;
325
- break;
326
- }
327
- }
328
- }
329
- if (keep) out[y * width + x] = 1;
330
- }
369
+ function expectInput(label, fn) {
370
+ try {
371
+ return fn();
372
+ } catch (e) {
373
+ throw new AutoRigInputError(
374
+ `${label}: ${e instanceof Error ? e.message : String(e)}`
375
+ );
331
376
  }
332
- return out;
333
377
  }
334
- function closeMask(mask, width, height, r) {
335
- return erode(dilate(mask, width, height, r), width, height, r);
378
+ var LOSSLESS_PAGE_ROLE = "nose";
379
+ async function renderAtlasPage(crops, quantizeColors) {
380
+ const layout = (0, import_editor2.packAtlas)(
381
+ crops.map((c) => ({ id: c.id, width: c.width, height: c.height }))
382
+ );
383
+ if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {
384
+ throw new AutoRigInputError(
385
+ `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`
386
+ );
387
+ }
388
+ const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);
389
+ return { crops, layout, dataUri };
336
390
  }
337
- function components(mask, width, height, minArea) {
338
- const seen = new Uint8Array(width * height);
339
- const out = [];
340
- for (let i = 0; i < width * height; i++) {
341
- if (!mask[i] || seen[i]) continue;
342
- const stack = [i];
343
- seen[i] = 1;
344
- let x0 = width;
345
- let x1 = 0;
346
- let y0 = height;
347
- let y1 = 0;
348
- let n = 0;
349
- let sx = 0;
350
- let sy = 0;
351
- while (stack.length) {
352
- const p = stack.pop();
353
- const x = p % width;
354
- const y = p / width | 0;
355
- n++;
356
- sx += x;
357
- sy += y;
358
- if (x < x0) x0 = x;
359
- if (x > x1) x1 = x;
360
- if (y < y0) y0 = y;
361
- if (y > y1) y1 = y;
362
- const neighbours = [];
391
+ async function autoRigFromLayers(input) {
392
+ try {
393
+ const layers = input.layers;
394
+ if (!Array.isArray(layers) || layers.length === 0) {
395
+ throw new AutoRigInputError("layers must be a non-empty array");
396
+ }
397
+ if (layers.length > MAX_LAYERS) {
398
+ throw new AutoRigInputError(
399
+ `too many layers: ${layers.length} > ${MAX_LAYERS}`
400
+ );
401
+ }
402
+ const outPath = resolveOutputPath(
403
+ input.outputPath ?? "auto-rigged-model.iki"
404
+ );
405
+ const quantizeColors = input.quantizeColors;
406
+ if (quantizeColors !== void 0 && (!Number.isInteger(quantizeColors) || quantizeColors < 2 || quantizeColors > 256)) {
407
+ throw new AutoRigInputError(
408
+ `quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`
409
+ );
410
+ }
411
+ const resolvedLayers = layers.map((layer) => {
412
+ const resolved = resolveInputPath(layer.path);
413
+ return { resolved, fileName: layer.fileName ?? import_node_path2.default.basename(resolved) };
414
+ });
415
+ const rolePairs = expectInput(
416
+ "role parsing",
417
+ () => (0, import_editor2.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
418
+ );
419
+ const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));
420
+ let canvasW = 0;
421
+ let canvasH = 0;
422
+ let totalPixels = 0;
423
+ let measurer;
424
+ const crops = [];
425
+ for (let i = 0; i < resolvedLayers.length; i++) {
426
+ const { resolved, fileName } = resolvedLayers[i];
427
+ const png = await decodePng(resolved);
428
+ if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {
429
+ throw new AutoRigInputError(
430
+ `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`
431
+ );
432
+ }
433
+ totalPixels += png.width * png.height;
434
+ if (totalPixels > MAX_TOTAL_PIXELS) {
435
+ throw new AutoRigInputError(
436
+ `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`
437
+ );
438
+ }
439
+ if (i === 0) {
440
+ canvasW = png.width;
441
+ canvasH = png.height;
442
+ if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {
443
+ throw new AutoRigInputError(
444
+ `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`
445
+ );
446
+ }
447
+ measurer = (0, import_editor2.createLayerSetMeasurer)({ width: canvasW, height: canvasH });
448
+ } else if (png.width !== canvasW || png.height !== canvasH) {
449
+ throw new AutoRigInputError(
450
+ `layer "${fileName}" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
451
+ );
452
+ }
453
+ const role = roleByFileName.get(fileName);
454
+ if (role === void 0) {
455
+ throw new AutoRigInputError(`no role resolved for "${fileName}"`);
456
+ }
457
+ const layer = measurer.add({ role, fileName, rgba: png.rgba });
458
+ if (layer === null) {
459
+ throw new AutoRigInputError(
460
+ `role "${role}" file "${fileName}": layer is empty after alpha threshold`
461
+ );
462
+ }
463
+ const { bbox } = layer;
464
+ const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);
465
+ crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
466
+ }
467
+ const measurement = measurer.finish();
468
+ const { headHalfWidth, headHalfWidthApplied, turnOptions } = measurement;
469
+ const { headEdges, strandEdges } = turnOptions;
470
+ const noseCore = measurement.layers.find(
471
+ (l) => l.role === "nose"
472
+ )?.denseCore;
473
+ let turn;
474
+ let model;
475
+ try {
476
+ const { eyeShift, farEyeRatio, silhouetteRatio, noseShift, mouthShift } = input.turnTargets ?? {};
477
+ model = (0, import_editor2.generateIkiFromLayerSet)(
478
+ measurement.layers,
479
+ { width: canvasW, height: canvasH },
480
+ {
481
+ turnTargets: {
482
+ eyeShift,
483
+ farEyeRatio,
484
+ silhouetteRatio,
485
+ noseShift,
486
+ mouthShift,
487
+ ...turnOptions.turnTargets
488
+ },
489
+ onTurnSolved: (report) => {
490
+ turn = report;
491
+ },
492
+ ...headEdges === void 0 ? {} : { headEdges },
493
+ ...strandEdges === void 0 ? {} : { strandEdges }
494
+ }
495
+ );
496
+ } catch (e) {
497
+ if (!(e instanceof import_editor2.TurnTargetError)) throw e;
498
+ throw new AutoRigInputError(e.message);
499
+ }
500
+ const doc = new import_editor2.EditorDocument(model);
501
+ const losslessCrop = quantizeColors === void 0 ? void 0 : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);
502
+ const pages = losslessCrop === void 0 ? [await renderAtlasPage(crops, quantizeColors)] : [
503
+ await renderAtlasPage(
504
+ crops.filter((c) => c !== losslessCrop),
505
+ quantizeColors
506
+ ),
507
+ await renderAtlasPage([losslessCrop], void 0)
508
+ ];
509
+ const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);
510
+ if (atlasBytes > MAX_OUTPUT_BYTES) {
511
+ throw new AutoRigInputError(
512
+ `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`
513
+ );
514
+ }
515
+ const partTextureAssignments = pages.flatMap(
516
+ ({ crops: pageCrops, layout }) => pageCrops.map((crop) => {
517
+ const placement2 = layout.placements.find((p) => p.id === crop.id);
518
+ if (placement2 === void 0) {
519
+ throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
520
+ }
521
+ return {
522
+ partId: crop.id,
523
+ uv: (0, import_editor2.uvRectFor)(placement2, {
524
+ width: layout.pageWidth,
525
+ height: layout.pageHeight
526
+ })
527
+ };
528
+ })
529
+ );
530
+ doc.applyAtlas({
531
+ textures: [{ source: pages[0].dataUri }],
532
+ partTextureAssignments
533
+ });
534
+ let patched = doc.getModel();
535
+ if (losslessCrop !== void 0) {
536
+ patched = structuredClone(patched);
537
+ patched.textures = pages.map((p) => ({ source: p.dataUri }));
538
+ patched.parts.find((p) => p.id === losslessCrop.id).texture.index = 1;
539
+ }
540
+ const finalModel = (0, import_format.parseIkiModel)(patched);
541
+ writeFileAtomic(outPath, JSON.stringify(finalModel));
542
+ return {
543
+ ok: true,
544
+ path: outPath,
545
+ canvas: { width: canvasW, height: canvasH },
546
+ partCount: finalModel.parts.length,
547
+ atlasBytes,
548
+ ...headHalfWidth === void 0 ? {} : { headHalfWidth },
549
+ headHalfWidthApplied,
550
+ ...headEdges === void 0 ? {} : { headEdges },
551
+ ...strandEdges === void 0 ? {} : { strandEdges },
552
+ ...noseCore === void 0 ? {} : { noseCore },
553
+ ...turn === void 0 ? {} : { turn }
554
+ };
555
+ } catch (err) {
556
+ if (err instanceof AutoRigInputError)
557
+ return { ok: false, error: err.message };
558
+ throw err;
559
+ }
560
+ }
561
+
562
+ // src/compose.ts
563
+ var import_node_fs3 = __toESM(require("fs"));
564
+ var import_node_path5 = __toESM(require("path"));
565
+ var import_sharp2 = __toESM(require("sharp"));
566
+
567
+ // src/measure.ts
568
+ var import_node_fs2 = __toESM(require("fs"));
569
+ var import_node_path4 = __toESM(require("path"));
570
+
571
+ // src/measure-turn.ts
572
+ var import_node_path3 = __toESM(require("path"));
573
+ var import_editor3 = require("@ikijs/editor");
574
+ var import_editor4 = require("@ikijs/editor");
575
+ var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
576
+ var IRIS_V_MIN = 0.18;
577
+ var IRIS_V_MAX = 0.95;
578
+ var IRIS_MEAN_V_MIN = 0.32;
579
+ var CLOSE_RADIUS = 3;
580
+ var CLOSE_RADIUS_REFERENCE_PX = 1254;
581
+ var BLOB_MAX_FRAC = 0.12;
582
+ var KEYED_SPAN_MAX_FRAC = 0.95;
583
+ var MIN_AREA_REFERENCE_PIXELS = 1254 * 1254;
584
+ var MIN_AREA = 300;
585
+ var PAIR_DX_MIN_FRAC = 0.08;
586
+ var PAIR_DX_MAX_FRAC = 0.35;
587
+ var PAIR_DY_MAX_FRAC = 0.05;
588
+ var MAX_CANDIDATES = 12;
589
+ var BG_HUE_MIN = 220;
590
+ var BG_HUE_MAX = 260;
591
+ var BG_SAT_MAX = 0.2;
592
+ var BG_V_MIN = 0.55;
593
+ var BG_V_BLACK = 0.03;
594
+ function rgbToHsv(r, g, b) {
595
+ r /= 255;
596
+ g /= 255;
597
+ b /= 255;
598
+ const max = Math.max(r, g, b);
599
+ const min = Math.min(r, g, b);
600
+ const d = max - min;
601
+ let h = 0;
602
+ if (d > 0) {
603
+ if (max === r) h = (g - b) / d % 6;
604
+ else if (max === g) h = (b - r) / d + 2;
605
+ else h = (r - g) / d + 4;
606
+ h *= 60;
607
+ if (h < 0) h += 360;
608
+ }
609
+ return [h, max === 0 ? 0 : d / max, max];
610
+ }
611
+ function dilate(mask, width, height, r) {
612
+ const out = new Uint8Array(width * height);
613
+ for (let y = 0; y < height; y++) {
614
+ for (let x = 0; x < width; x++) {
615
+ if (!mask[y * width + x]) continue;
616
+ for (let dy = -r; dy <= r; dy++) {
617
+ for (let dx = -r; dx <= r; dx++) {
618
+ const yy = y + dy;
619
+ const xx = x + dx;
620
+ if (yy >= 0 && yy < height && xx >= 0 && xx < width)
621
+ out[yy * width + xx] = 1;
622
+ }
623
+ }
624
+ }
625
+ }
626
+ return out;
627
+ }
628
+ function erode(mask, width, height, r) {
629
+ const out = new Uint8Array(width * height);
630
+ for (let y = 0; y < height; y++) {
631
+ for (let x = 0; x < width; x++) {
632
+ if (!mask[y * width + x]) continue;
633
+ let keep = true;
634
+ for (let dy = -r; dy <= r && keep; dy++) {
635
+ for (let dx = -r; dx <= r; dx++) {
636
+ const yy = y + dy;
637
+ const xx = x + dx;
638
+ if (yy < 0 || yy >= height || xx < 0 || xx >= width || !mask[yy * width + xx]) {
639
+ keep = false;
640
+ break;
641
+ }
642
+ }
643
+ }
644
+ if (keep) out[y * width + x] = 1;
645
+ }
646
+ }
647
+ return out;
648
+ }
649
+ function closeMask(mask, width, height, r) {
650
+ return erode(dilate(mask, width, height, r), width, height, r);
651
+ }
652
+ function components(mask, width, height, minArea) {
653
+ const seen = new Uint8Array(width * height);
654
+ const out = [];
655
+ for (let i = 0; i < width * height; i++) {
656
+ if (!mask[i] || seen[i]) continue;
657
+ const stack = [i];
658
+ seen[i] = 1;
659
+ let x0 = width;
660
+ let x1 = 0;
661
+ let y0 = height;
662
+ let y1 = 0;
663
+ let n = 0;
664
+ let sx = 0;
665
+ let sy = 0;
666
+ while (stack.length) {
667
+ const p = stack.pop();
668
+ const x = p % width;
669
+ const y = p / width | 0;
670
+ n++;
671
+ sx += x;
672
+ sy += y;
673
+ if (x < x0) x0 = x;
674
+ if (x > x1) x1 = x;
675
+ if (y < y0) y0 = y;
676
+ if (y > y1) y1 = y;
677
+ const neighbours = [];
363
678
  if (x > 0) neighbours.push(p - 1);
364
679
  if (x < width - 1) neighbours.push(p + 1);
365
680
  if (y > 0) neighbours.push(p - width);
@@ -386,21 +701,6 @@ function components(mask, width, height, minArea) {
386
701
  }
387
702
  return out.sort((a, b) => b.area - a.area);
388
703
  }
389
- function foregroundSpan(mask, width, height, rowLo, rowHi) {
390
- let left = width;
391
- let right = -1;
392
- for (let y = Math.max(0, rowLo); y <= Math.min(height - 1, rowHi); y++) {
393
- for (let x = 0; x < width; x++) {
394
- if (!mask[y * width + x]) continue;
395
- if (x < left) left = x;
396
- if (x > right) right = x;
397
- }
398
- }
399
- return { left, right };
400
- }
401
- function headHalfOf(span) {
402
- return (span.right - span.left + 1) / 2;
403
- }
404
704
  function resolveIris(override) {
405
705
  const iris = { ...DEFAULT_IRIS, ...override };
406
706
  if (iris.hueMin < 0 || iris.hueMax > 360 || iris.hueMin >= iris.hueMax) {
@@ -421,7 +721,7 @@ async function measureTurnImage(filePath, iris) {
421
721
  let transparent = false;
422
722
  if (hasAlpha) {
423
723
  for (let i = 0; i < n; i++) {
424
- if (rgba[i * 4 + 3] < ALPHA_OPAQUE) {
724
+ if (rgba[i * 4 + 3] < import_editor3.ALPHA_OPAQUE) {
425
725
  transparent = true;
426
726
  break;
427
727
  }
@@ -432,7 +732,7 @@ async function measureTurnImage(filePath, iris) {
432
732
  const fg = new Uint8Array(n);
433
733
  const value = new Float32Array(n);
434
734
  for (let i = 0; i < n; i++) {
435
- if (rgba[i * 4 + 3] < ALPHA_OPAQUE) continue;
735
+ if (rgba[i * 4 + 3] < import_editor3.ALPHA_OPAQUE) continue;
436
736
  const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);
437
737
  if (maskMode === "alpha") {
438
738
  fg[i] = 1;
@@ -498,12 +798,12 @@ async function measureTurnImage(filePath, iris) {
498
798
  }
499
799
  const [irisL, irisR] = best.pair;
500
800
  const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);
501
- const { left, right } = foregroundSpan(
801
+ const { left, right } = (0, import_editor3.foregroundSpan)(
502
802
  fg,
503
803
  width,
504
804
  height,
505
- eyeRow - HEAD_BAND,
506
- eyeRow + HEAD_BAND
805
+ eyeRow - import_editor3.HEAD_BAND,
806
+ eyeRow + import_editor3.HEAD_BAND
507
807
  );
508
808
  if (right <= left) {
509
809
  throw new AutoRigInputError(
@@ -521,576 +821,69 @@ async function measureTurnImage(filePath, iris) {
521
821
  height,
522
822
  maskMode,
523
823
  irisL,
524
- irisR,
525
- eyeRow,
526
- head: {
527
- left,
528
- right,
529
- cx: (left + right) / 2,
530
- half: headHalfOf({ left, right })
531
- },
532
- pairCx: (irisL.cx + irisR.cx) / 2,
533
- eyeGap: irisR.cx - irisL.cx
534
- };
535
- }
536
- function farNearWidths(m, turnSign) {
537
- return turnSign < 0 ? { far: m.irisL.w, near: m.irisR.w } : { far: m.irisR.w, near: m.irisL.w };
538
- }
539
- function overlaySvg(m) {
540
- const box = (b, stroke) => `<rect x="${b.x0}" y="${b.y0}" width="${b.w}" height="${b.h}" fill="none" stroke="${stroke}" stroke-width="3"/>`;
541
- const tick = (x, half, stroke) => `<line x1="${x}" y1="${m.eyeRow - half}" x2="${x}" y2="${m.eyeRow + half}" stroke="${stroke}" stroke-width="3"/>`;
542
- return `<svg width="${m.width}" height="${m.height}">` + box(m.irisL, "#ff0000") + box(m.irisR, "#00c000") + tick(m.head.left, 40, "#0000ff") + tick(m.head.right, 40, "#0000ff") + tick(m.head.cx, 60, "#ff8800") + tick(m.pairCx, 60, "#ff00ff") + "</svg>";
543
- }
544
- async function writeOverlay(debugDir, label, m) {
545
- const outPath = import_node_path2.default.join(
546
- debugDir,
547
- `${label}-${import_node_path2.default.basename(m.file, ".png")}.debug.png`
548
- );
549
- writeFileAtomic(outPath, await encodeOverlayPng(m.file, overlaySvg(m)));
550
- return outPath;
551
- }
552
- var IRIS_HEIGHT_SCALE_TOLERANCE = 0.1;
553
- async function measureTurnReference(input) {
554
- try {
555
- const iris = resolveIris(input.iris);
556
- const frontPath = resolveInputPath(input.front);
557
- const turnedPath = resolveInputPath(input.turned);
558
- const debugDir = input.debugDir === void 0 ? null : resolveOutputDir(input.debugDir);
559
- const front = await measureTurnImage(frontPath, iris);
560
- const turned = await measureTurnImage(turnedPath, iris);
561
- const frontIrisH = (front.irisL.h + front.irisR.h) / 2;
562
- const turnedIrisH = (turned.irisL.h + turned.irisR.h) / 2;
563
- if (Math.abs(turnedIrisH - frontIrisH) / frontIrisH > IRIS_HEIGHT_SCALE_TOLERANCE) {
564
- throw new AutoRigInputError(
565
- `front and turned images are not at the same scale: mean iris height ${frontIrisH.toFixed(1)}px front vs ${turnedIrisH.toFixed(1)}px turned, more than ${(IRIS_HEIGHT_SCALE_TOLERANCE * 100).toFixed(0)}% apart \u2014 a yaw does not change iris height, so the pair must share the same framing and head size`
566
- );
567
- }
568
- const frontShift = front.pairCx - front.head.cx;
569
- const turnedShift = turned.pairCx - turned.head.cx;
570
- const shift = turnedShift - frontShift;
571
- const turnSign = shift < 0 ? -1 : 1;
572
- const f = farNearWidths(front, turnSign);
573
- const t = farNearWidths(turned, turnSign);
574
- const debug = debugDir === null ? void 0 : [
575
- await writeOverlay(debugDir, "front", front),
576
- await writeOverlay(debugDir, "turned", turned)
577
- ];
578
- return {
579
- ok: true,
580
- front,
581
- turned,
582
- farEyeRatio: t.far / t.near / (f.far / f.near),
583
- eyeShift: shift / front.head.half,
584
- silhouetteRatio: turned.head.half / front.head.half,
585
- turnSign,
586
- ...debug === void 0 ? {} : { debug }
587
- };
588
- } catch (err) {
589
- if (err instanceof AutoRigInputError)
590
- return { ok: false, error: err.message };
591
- throw err;
592
- }
593
- }
594
- var n1 = (v) => v.toFixed(1);
595
- var n3 = (v) => v.toFixed(3);
596
- function imageBlock(label, m) {
597
- return [
598
- `# ${label} ${m.file} ${m.width}x${m.height} mask: ${m.maskMode}`,
599
- `iris widths ${m.irisL.w} / ${m.irisR.w} px centres ${n1(m.irisL.cx)} / ${n1(m.irisR.cx)} eye row ${m.eyeRow} gap ${n1(m.eyeGap)}`,
600
- `head ${m.head.left}..${m.head.right} centre ${n1(m.head.cx)} half ${n1(m.head.half)} pair centre ${n1(m.pairCx)}`
601
- ];
602
- }
603
- function formatTurnReport(result) {
604
- const { front, turned } = result;
605
- const f = farNearWidths(front, result.turnSign);
606
- const t = farNearWidths(turned, result.turnSign);
607
- const lines = [
608
- `farEyeRatio ${n3(result.farEyeRatio)} far/near iris width ${t.far}/${t.near} turned over ${f.far}/${f.near} front`,
609
- `eyeShift ${n3(result.eyeShift)} pair-vs-head centre ${n1(turned.pairCx - turned.head.cx)} px turned, ${n1(front.pairCx - front.head.cx)} px front, over front head half ${n1(front.head.half)} px (hh)`,
610
- `silhouetteRatio ${n3(result.silhouetteRatio)} head half ${n1(turned.head.half)} px turned over ${n1(front.head.half)} px front`,
611
- `turnSign ${result.turnSign} (the head turned toward the image's ${result.turnSign < 0 ? "left" : "right"})`,
612
- "",
613
- ...imageBlock("front", front),
614
- "",
615
- ...imageBlock("turned", turned)
616
- ];
617
- if (result.debug !== void 0) {
618
- lines.push("", ...result.debug.map((p) => `debug overlay ${p}`));
619
- }
620
- return lines.join("\n");
621
- }
622
-
623
- // src/tools.ts
624
- function coerceModel(model) {
625
- try {
626
- const parsed = typeof model === "string" ? (0, import_format.loadIkiModel)(model) : (0, import_format.parseIkiModel)(model);
627
- return { ok: true, model: parsed };
628
- } catch (e) {
629
- if (e instanceof import_format.IkiFormatError) return { ok: false, error: e.message };
630
- throw e;
631
- }
632
- }
633
- function validateIki(model) {
634
- const result = coerceModel(model);
635
- if (!result.ok) return { ok: false, error: result.error };
636
- return { ok: true };
637
- }
638
- function describeIki(model) {
639
- const result = coerceModel(model);
640
- if (!result.ok) return { ok: false, error: result.error };
641
- const m = result.model;
642
- const parameters = m.parameters.map((p) => ({
643
- id: p.id,
644
- min: p.min,
645
- max: p.max,
646
- default: p.default
647
- }));
648
- const parts = m.parts.map((p) => {
649
- const entry = {
650
- id: p.id,
651
- order: p.order
652
- };
653
- if (p.deformer !== void 0) entry.deformer = p.deformer;
654
- return entry;
655
- });
656
- const deformers = (m.deformers ?? []).map(
657
- (d) => {
658
- const kind = d.kind === "warp" ? "warp" : "matrix";
659
- const entry = { id: d.id, kind };
660
- if (d.parent !== void 0) entry.parent = d.parent;
661
- if (d.kind === "warp") {
662
- if (d.warp2d !== void 0) {
663
- entry.warp = {
664
- mode: "2d",
665
- parameterX: d.warp2d.parameter,
666
- parameterY: d.warp2d.parameterY,
667
- gridX: d.grid.cols,
668
- gridY: d.grid.rows
669
- };
670
- } else if (d.warps !== void 0 && d.warps.length > 0) {
671
- entry.warp = {
672
- mode: "1d",
673
- parameters: d.warps.map((w) => w.parameter)
674
- };
675
- }
676
- }
677
- return entry;
678
- }
679
- );
680
- const summary = {
681
- name: m.name,
682
- canvas: { width: m.canvas.width, height: m.canvas.height },
683
- parameters,
684
- parts,
685
- deformers
686
- };
687
- return { ok: true, summary };
688
- }
689
- var STANDARD_PARAMETER_INFO = [
690
- {
691
- id: import_format.StandardParameter.MouthOpen,
692
- description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
693
- },
694
- {
695
- id: import_format.StandardParameter.MouthForm,
696
- description: "Mouth form / smile (-1 .. 1)."
697
- },
698
- {
699
- id: import_format.StandardParameter.EyeOpenLeft,
700
- description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
701
- },
702
- {
703
- id: import_format.StandardParameter.EyeOpenRight,
704
- description: "Right eye open (0 closed .. 1 open)."
705
- },
706
- {
707
- id: import_format.StandardParameter.EyeballX,
708
- description: "Eyeball gaze, horizontal (-1 .. 1)."
709
- },
710
- {
711
- id: import_format.StandardParameter.EyeballY,
712
- description: "Eyeball gaze, vertical (-1 .. 1)."
713
- },
714
- {
715
- id: import_format.StandardParameter.AngleX,
716
- description: "Head angle, horizontal degrees."
717
- },
718
- {
719
- id: import_format.StandardParameter.AngleY,
720
- description: "Head angle, vertical degrees."
721
- },
722
- {
723
- id: import_format.StandardParameter.AngleZ,
724
- description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
725
- },
726
- {
727
- id: import_format.StandardParameter.Breath,
728
- description: "Idle breath (0 .. 1), cycled by the host."
729
- },
730
- {
731
- id: import_format.StandardParameter.BrowLeftY,
732
- description: "Left brow raise/lower (-1 .. 1)."
733
- },
734
- {
735
- id: import_format.StandardParameter.BrowRightY,
736
- description: "Right brow raise/lower (-1 .. 1)."
737
- },
738
- {
739
- id: import_format.StandardParameter.BrowLeftAngle,
740
- description: "Left brow tilt/angle (-1 .. 1)."
741
- },
742
- {
743
- id: import_format.StandardParameter.BrowRightAngle,
744
- description: "Right brow tilt/angle (-1 .. 1)."
745
- },
746
- {
747
- id: import_format.StandardParameter.HairSwayX,
748
- description: "Horizontal hair-sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
749
- },
750
- {
751
- id: import_format.StandardParameter.HairSwayZ,
752
- description: "Hair-sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
753
- }
754
- ];
755
- function listStandardParameters() {
756
- return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));
757
- }
758
- function expectInput(label, fn) {
759
- try {
760
- return fn();
761
- } catch (e) {
762
- throw new AutoRigInputError(
763
- `${label}: ${e instanceof Error ? e.message : String(e)}`
764
- );
765
- }
766
- }
767
- function eyeRowOf(layers) {
768
- const centreY = (role) => {
769
- const layer = layers.find((l) => l.role === role);
770
- return layer && layer.bbox.y + layer.bbox.h / 2;
771
- };
772
- const pairRow = (left, right) => {
773
- const a = centreY(left);
774
- const b = centreY(right);
775
- return a === void 0 || b === void 0 ? void 0 : (a + b) / 2;
824
+ irisR,
825
+ eyeRow,
826
+ head: {
827
+ left,
828
+ right,
829
+ cx: (left + right) / 2,
830
+ half: (0, import_editor3.headHalfOf)({ left, right })
831
+ },
832
+ pairCx: (irisL.cx + irisR.cx) / 2,
833
+ eyeGap: irisR.cx - irisL.cx
776
834
  };
777
- const row = pairRow("iris_L", "iris_R") ?? pairRow("eye_L", "eye_R");
778
- if (row === void 0) {
779
- throw new Error("auto-rig: no eye pair to measure the head width at");
780
- }
781
- return Math.round(row);
782
835
  }
783
- function foregroundSpanOfRows(rowLeft, rowRight, rowLo, rowHi) {
784
- let left = Infinity;
785
- let right = -Infinity;
786
- for (let y = Math.max(0, rowLo); y <= Math.min(rowLeft.length - 1, rowHi); y++) {
787
- if (rowLeft[y] < left) left = rowLeft[y];
788
- if (rowRight[y] > right) right = rowRight[y];
789
- }
790
- return { left, right };
836
+ function farNearWidths(m, turnSign) {
837
+ return turnSign < 0 ? { far: m.irisL.w, near: m.irisR.w } : { far: m.irisR.w, near: m.irisL.w };
791
838
  }
792
- function facePlateHalfOf(layers) {
793
- const face = layers.find((l) => l.role === "face");
794
- if (face === void 0) {
795
- throw new Error("auto-rig: no face layer to measure the plate against");
796
- }
797
- return face.cropW / 2;
839
+ function overlaySvg(m) {
840
+ const box = (b, stroke) => `<rect x="${b.x0}" y="${b.y0}" width="${b.w}" height="${b.h}" fill="none" stroke="${stroke}" stroke-width="3"/>`;
841
+ const tick = (x, half, stroke) => `<line x1="${x}" y1="${m.eyeRow - half}" x2="${x}" y2="${m.eyeRow + half}" stroke="${stroke}" stroke-width="3"/>`;
842
+ return `<svg width="${m.width}" height="${m.height}">` + box(m.irisL, "#ff0000") + box(m.irisR, "#00c000") + tick(m.head.left, 40, "#0000ff") + tick(m.head.right, 40, "#0000ff") + tick(m.head.cx, 60, "#ff8800") + tick(m.pairCx, 60, "#ff00ff") + "</svg>";
798
843
  }
799
- var STRAND_MIN_RUN_FRACTION = 0.5;
800
- var LOSSLESS_PAGE_ROLE = "nose";
801
- async function renderAtlasPage(crops, quantizeColors) {
802
- const layout = (0, import_editor2.packAtlas)(
803
- crops.map((c) => ({ id: c.id, width: c.width, height: c.height }))
844
+ async function writeOverlay(debugDir, label, m) {
845
+ const outPath = import_node_path3.default.join(
846
+ debugDir,
847
+ `${label}-${import_node_path3.default.basename(m.file, ".png")}.debug.png`
804
848
  );
805
- if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {
806
- throw new AutoRigInputError(
807
- `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`
808
- );
809
- }
810
- const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);
811
- return { crops, layout, dataUri };
849
+ writeFileAtomic(outPath, await encodeOverlayPng(m.file, overlaySvg(m)));
850
+ return outPath;
812
851
  }
813
- async function autoRigFromLayers(input) {
852
+ var IRIS_HEIGHT_SCALE_TOLERANCE = 0.1;
853
+ async function measureTurnReference(input) {
814
854
  try {
815
- const layers = input.layers;
816
- if (!Array.isArray(layers) || layers.length === 0) {
817
- throw new AutoRigInputError("layers must be a non-empty array");
818
- }
819
- if (layers.length > MAX_LAYERS) {
820
- throw new AutoRigInputError(
821
- `too many layers: ${layers.length} > ${MAX_LAYERS}`
822
- );
823
- }
824
- const outPath = resolveOutputPath(
825
- input.outputPath ?? "auto-rigged-model.iki"
826
- );
827
- const quantizeColors = input.quantizeColors;
828
- if (quantizeColors !== void 0 && (!Number.isInteger(quantizeColors) || quantizeColors < 2 || quantizeColors > 256)) {
855
+ const iris = resolveIris(input.iris);
856
+ const frontPath = resolveInputPath(input.front);
857
+ const turnedPath = resolveInputPath(input.turned);
858
+ const debugDir = input.debugDir === void 0 ? null : resolveOutputDir(input.debugDir);
859
+ const front = await measureTurnImage(frontPath, iris);
860
+ const turned = await measureTurnImage(turnedPath, iris);
861
+ const frontIrisH = (front.irisL.h + front.irisR.h) / 2;
862
+ const turnedIrisH = (turned.irisL.h + turned.irisR.h) / 2;
863
+ if (Math.abs(turnedIrisH - frontIrisH) / frontIrisH > IRIS_HEIGHT_SCALE_TOLERANCE) {
829
864
  throw new AutoRigInputError(
830
- `quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`
831
- );
832
- }
833
- const resolvedLayers = layers.map((layer) => {
834
- const resolved = resolveInputPath(layer.path);
835
- return { resolved, fileName: layer.fileName ?? import_node_path3.default.basename(resolved) };
836
- });
837
- const rolePairs = expectInput(
838
- "role parsing",
839
- () => (0, import_editor2.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
840
- );
841
- const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));
842
- let canvasW = 0;
843
- let canvasH = 0;
844
- let totalPixels = 0;
845
- let opaque = new Uint8Array(0);
846
- const layerInputs = [];
847
- const crops = [];
848
- const rowSpansByRole = [];
849
- let hairFrontMask;
850
- for (let i = 0; i < resolvedLayers.length; i++) {
851
- const { resolved, fileName } = resolvedLayers[i];
852
- const png = await decodePng(resolved);
853
- if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {
854
- throw new AutoRigInputError(
855
- `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`
856
- );
857
- }
858
- totalPixels += png.width * png.height;
859
- if (totalPixels > MAX_TOTAL_PIXELS) {
860
- throw new AutoRigInputError(
861
- `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`
862
- );
863
- }
864
- if (i === 0) {
865
- canvasW = png.width;
866
- canvasH = png.height;
867
- if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {
868
- throw new AutoRigInputError(
869
- `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`
870
- );
871
- }
872
- opaque = new Uint8Array(canvasW * canvasH);
873
- } else if (png.width !== canvasW || png.height !== canvasH) {
874
- throw new AutoRigInputError(
875
- `layer "${fileName}" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
876
- );
877
- }
878
- const role = roleByFileName.get(fileName);
879
- if (role === void 0) {
880
- throw new AutoRigInputError(`no role resolved for "${fileName}"`);
881
- }
882
- let bbox;
883
- try {
884
- bbox = detectAlphaBbox(png.rgba, png.width, png.height);
885
- } catch (e) {
886
- const msg = e instanceof Error ? e.message : String(e);
887
- throw new AutoRigInputError(
888
- `role "${role}" file "${fileName}": ${msg}`
889
- );
890
- }
891
- const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);
892
- const rowLeft = new Int32Array(canvasH).fill(canvasW);
893
- const rowRight = new Int32Array(canvasH).fill(-1);
894
- const ownMask = role === "hair_front" ? new Uint8Array(canvasW * canvasH) : void 0;
895
- for (let y = 0; y < canvasH; y++) {
896
- for (let x = 0; x < canvasW; x++) {
897
- const p = y * canvasW + x;
898
- if (png.rgba[p * 4 + 3] < ALPHA_OPAQUE) continue;
899
- opaque[p] = 1;
900
- if (ownMask !== void 0) ownMask[p] = 1;
901
- if (x < rowLeft[y]) rowLeft[y] = x;
902
- if (x > rowRight[y]) rowRight[y] = x;
903
- }
904
- }
905
- rowSpansByRole.push({ role, rowLeft, rowRight });
906
- if (ownMask !== void 0) hairFrontMask = ownMask;
907
- const layer = {
908
- role,
909
- fileName,
910
- canvasW,
911
- canvasH,
912
- bbox,
913
- cropW: bbox.w,
914
- cropH: bbox.h
915
- };
916
- if (role === "face") {
917
- const rowHalfWidths = [];
918
- for (let y = bbox.y; y < bbox.y + bbox.h; y++) {
919
- rowHalfWidths.push(
920
- rowRight[y] >= rowLeft[y] ? headHalfOf({ left: rowLeft[y], right: rowRight[y] }) : 0
921
- );
922
- }
923
- layer.rowHalfWidths = rowHalfWidths;
924
- } else if (role === "nose") {
925
- const core = denseCoreOf(png.rgba, canvasW, canvasH);
926
- if (core !== null && !isSpeckCore(core, bbox)) layer.denseCore = core;
927
- }
928
- layerInputs.push(layer);
929
- crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
930
- }
931
- const noseCore = layerInputs.find((l) => l.role === "nose")?.denseCore;
932
- const eyeRow = eyeRowOf(layerInputs);
933
- const span = foregroundSpan(
934
- opaque,
935
- canvasW,
936
- canvasH,
937
- eyeRow - HEAD_BAND,
938
- eyeRow + HEAD_BAND
939
- );
940
- const headHalfWidth = span.right > span.left ? headHalfOf(span) : void 0;
941
- const headHalfWidthApplied = headHalfWidth !== void 0 && headHalfWidth > facePlateHalfOf(layerInputs);
942
- let headEdges;
943
- if (headHalfWidthApplied) {
944
- const bandLo = eyeRow - HEAD_BAND;
945
- const bandHi = eyeRow + HEAD_BAND;
946
- const left = [];
947
- const right = [];
948
- for (const { role, rowLeft, rowRight } of rowSpansByRole) {
949
- const own = foregroundSpanOfRows(rowLeft, rowRight, bandLo, bandHi);
950
- if (own.right <= own.left) continue;
951
- left.push({ role, x: own.left - canvasW / 2 });
952
- right.push({ role, x: own.right - canvasW / 2 });
953
- }
954
- headEdges = { left, right };
955
- }
956
- let strandEdges;
957
- const irisLayers = layerInputs.filter((l) => l.role === "iris_L" || l.role === "iris_R").sort((a, b) => a.bbox.x + a.bbox.w / 2 - (b.bbox.x + b.bbox.w / 2));
958
- if (hairFrontMask !== void 0 && irisLayers.length === 2) {
959
- const mask = hairFrontMask;
960
- const half = canvasW / 2;
961
- const strandOn = (iris, other, side) => {
962
- const r = Math.floor(iris.bbox.y + iris.bbox.h / 2);
963
- const centre = iris.bbox.x + iris.bbox.w / 2;
964
- const otherX = other.bbox.x + other.bbox.w / 2 - half;
965
- const c = side < 0 ? Math.ceil(centre) - 1 : Math.floor(centre);
966
- const span2 = rowSpansByRole.find((s) => s.role === iris.role);
967
- if (span2.rowRight[r] < span2.rowLeft[r]) return void 0;
968
- const minRun = STRAND_MIN_RUN_FRACTION * (span2.rowRight[r] + 1 - span2.rowLeft[r]);
969
- const strand = new Uint8Array(canvasW);
970
- for (let a = 0; a < canvasW; ) {
971
- if (mask[r * canvasW + a] !== 1) {
972
- a++;
973
- continue;
974
- }
975
- let b = a;
976
- while (b < canvasW && mask[r * canvasW + b] === 1) b++;
977
- if (b - a >= minRun) strand.fill(1, a, b);
978
- a = b;
979
- }
980
- const strandAt = (x2) => x2 >= 0 && x2 < canvasW && strand[x2] === 1;
981
- const outerBoundary = (x2) => (side < 0 ? x2 : x2 + 1) - half;
982
- let x = c;
983
- let runFace;
984
- if (!strandAt(c)) {
985
- while (x >= 0 && x < canvasW && !strandAt(x)) x += side;
986
- if (x < 0 || x >= canvasW) return void 0;
987
- runFace = outerBoundary(x - side);
988
- } else {
989
- let f = c - side;
990
- while (strandAt(f)) f -= side;
991
- const face = outerBoundary(f);
992
- runFace = side * (face - otherX) > 0 ? face : null;
993
- }
994
- while (strandAt(x)) x += side;
995
- return {
996
- y: canvasH / 2 - (r + 0.5),
997
- irisOuter: (side < 0 ? span2.rowLeft[r] : span2.rowRight[r] + 1) - half,
998
- irisInner: (side < 0 ? span2.rowRight[r] + 1 : span2.rowLeft[r]) - half,
999
- runOuter: outerBoundary(x - side),
1000
- runFace
1001
- };
1002
- };
1003
- const [low, high] = irisLayers;
1004
- const left = strandOn(low, high, -1);
1005
- const right = strandOn(high, low, 1);
1006
- if (left !== void 0 || right !== void 0) {
1007
- strandEdges = {
1008
- ...left === void 0 ? {} : { left },
1009
- ...right === void 0 ? {} : { right }
1010
- };
1011
- }
1012
- }
1013
- let turn;
1014
- let model;
1015
- try {
1016
- const { eyeShift, farEyeRatio, silhouetteRatio, noseShift, mouthShift } = input.turnTargets ?? {};
1017
- model = (0, import_editor2.generateIkiFromLayerSet)(
1018
- layerInputs,
1019
- { width: canvasW, height: canvasH },
1020
- {
1021
- turnTargets: {
1022
- eyeShift,
1023
- farEyeRatio,
1024
- silhouetteRatio,
1025
- noseShift,
1026
- mouthShift,
1027
- ...headHalfWidthApplied ? { headHalfWidth } : {}
1028
- },
1029
- onTurnSolved: (report) => {
1030
- turn = report;
1031
- },
1032
- ...headEdges === void 0 ? {} : { headEdges },
1033
- ...strandEdges === void 0 ? {} : { strandEdges }
1034
- }
865
+ `front and turned images are not at the same scale: mean iris height ${frontIrisH.toFixed(1)}px front vs ${turnedIrisH.toFixed(1)}px turned, more than ${(IRIS_HEIGHT_SCALE_TOLERANCE * 100).toFixed(0)}% apart \u2014 a yaw does not change iris height, so the pair must share the same framing and head size`
1035
866
  );
1036
- } catch (e) {
1037
- if (!(e instanceof import_editor2.TurnTargetError)) throw e;
1038
- throw new AutoRigInputError(e.message);
1039
867
  }
1040
- const doc = new import_editor2.EditorDocument(model);
1041
- const losslessCrop = quantizeColors === void 0 ? void 0 : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);
1042
- const pages = losslessCrop === void 0 ? [await renderAtlasPage(crops, quantizeColors)] : [
1043
- await renderAtlasPage(
1044
- crops.filter((c) => c !== losslessCrop),
1045
- quantizeColors
1046
- ),
1047
- await renderAtlasPage([losslessCrop], void 0)
868
+ const frontShift = front.pairCx - front.head.cx;
869
+ const turnedShift = turned.pairCx - turned.head.cx;
870
+ const shift = turnedShift - frontShift;
871
+ const turnSign = shift < 0 ? -1 : 1;
872
+ const f = farNearWidths(front, turnSign);
873
+ const t = farNearWidths(turned, turnSign);
874
+ const debug = debugDir === null ? void 0 : [
875
+ await writeOverlay(debugDir, "front", front),
876
+ await writeOverlay(debugDir, "turned", turned)
1048
877
  ];
1049
- const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);
1050
- if (atlasBytes > MAX_OUTPUT_BYTES) {
1051
- throw new AutoRigInputError(
1052
- `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`
1053
- );
1054
- }
1055
- const partTextureAssignments = pages.flatMap(
1056
- ({ crops: pageCrops, layout }) => pageCrops.map((crop) => {
1057
- const placement2 = layout.placements.find((p) => p.id === crop.id);
1058
- if (placement2 === void 0) {
1059
- throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
1060
- }
1061
- return {
1062
- partId: crop.id,
1063
- uv: (0, import_editor2.uvRectFor)(placement2, {
1064
- width: layout.pageWidth,
1065
- height: layout.pageHeight
1066
- })
1067
- };
1068
- })
1069
- );
1070
- doc.applyAtlas({
1071
- textures: [{ source: pages[0].dataUri }],
1072
- partTextureAssignments
1073
- });
1074
- let patched = doc.getModel();
1075
- if (losslessCrop !== void 0) {
1076
- patched = structuredClone(patched);
1077
- patched.textures = pages.map((p) => ({ source: p.dataUri }));
1078
- patched.parts.find((p) => p.id === losslessCrop.id).texture.index = 1;
1079
- }
1080
- const finalModel = (0, import_format.parseIkiModel)(patched);
1081
- writeFileAtomic(outPath, JSON.stringify(finalModel));
1082
878
  return {
1083
879
  ok: true,
1084
- path: outPath,
1085
- canvas: { width: canvasW, height: canvasH },
1086
- partCount: finalModel.parts.length,
1087
- atlasBytes,
1088
- ...headHalfWidth === void 0 ? {} : { headHalfWidth },
1089
- headHalfWidthApplied,
1090
- ...headEdges === void 0 ? {} : { headEdges },
1091
- ...strandEdges === void 0 ? {} : { strandEdges },
1092
- ...noseCore === void 0 ? {} : { noseCore },
1093
- ...turn === void 0 ? {} : { turn }
880
+ front,
881
+ turned,
882
+ farEyeRatio: t.far / t.near / (f.far / f.near),
883
+ eyeShift: shift / front.head.half,
884
+ silhouetteRatio: turned.head.half / front.head.half,
885
+ turnSign,
886
+ ...debug === void 0 ? {} : { debug }
1094
887
  };
1095
888
  } catch (err) {
1096
889
  if (err instanceof AutoRigInputError)
@@ -1098,15 +891,36 @@ async function autoRigFromLayers(input) {
1098
891
  throw err;
1099
892
  }
1100
893
  }
1101
-
1102
- // src/compose.ts
1103
- var import_node_fs3 = __toESM(require("fs"));
1104
- var import_node_path5 = __toESM(require("path"));
1105
- var import_sharp2 = __toESM(require("sharp"));
894
+ var n1 = (v) => v.toFixed(1);
895
+ var n3 = (v) => v.toFixed(3);
896
+ function imageBlock(label, m) {
897
+ return [
898
+ `# ${label} ${m.file} ${m.width}x${m.height} mask: ${m.maskMode}`,
899
+ `iris widths ${m.irisL.w} / ${m.irisR.w} px centres ${n1(m.irisL.cx)} / ${n1(m.irisR.cx)} eye row ${m.eyeRow} gap ${n1(m.eyeGap)}`,
900
+ `head ${m.head.left}..${m.head.right} centre ${n1(m.head.cx)} half ${n1(m.head.half)} pair centre ${n1(m.pairCx)}`
901
+ ];
902
+ }
903
+ function formatTurnReport(result) {
904
+ const { front, turned } = result;
905
+ const f = farNearWidths(front, result.turnSign);
906
+ const t = farNearWidths(turned, result.turnSign);
907
+ const lines = [
908
+ `farEyeRatio ${n3(result.farEyeRatio)} far/near iris width ${t.far}/${t.near} turned over ${f.far}/${f.near} front`,
909
+ `eyeShift ${n3(result.eyeShift)} pair-vs-head centre ${n1(turned.pairCx - turned.head.cx)} px turned, ${n1(front.pairCx - front.head.cx)} px front, over front head half ${n1(front.head.half)} px (hh)`,
910
+ `silhouetteRatio ${n3(result.silhouetteRatio)} head half ${n1(turned.head.half)} px turned over ${n1(front.head.half)} px front`,
911
+ `turnSign ${result.turnSign} (the head turned toward the image's ${result.turnSign < 0 ? "left" : "right"})`,
912
+ "",
913
+ ...imageBlock("front", front),
914
+ "",
915
+ ...imageBlock("turned", turned)
916
+ ];
917
+ if (result.debug !== void 0) {
918
+ lines.push("", ...result.debug.map((p) => `debug overlay ${p}`));
919
+ }
920
+ return lines.join("\n");
921
+ }
1106
922
 
1107
923
  // src/measure.ts
1108
- var import_node_fs2 = __toESM(require("fs"));
1109
- var import_node_path4 = __toESM(require("path"));
1110
924
  var IRIS_RATIO_MIN = 0.45;
1111
925
  var IRIS_RATIO_MAX = 0.72;
1112
926
  var EYE_ASPECT_MIN = 0.5;
@@ -1203,7 +1017,7 @@ function noseSpeckWarning({ core, part }, source) {
1203
1017
  `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,
1204
1018
  `auto_rig_from_layers turns and tilts the nose about its whole crop instead`
1205
1019
  ];
1206
- return `nose: ${found} \u2014 under ${SPECK_CORE_FRACTION} of its width or height, a speck: a lone nostril mark or highlight at alpha >= 128, not the drawing, so ${consequence}. Regenerate the nose with its shading painted denser, so the drawing itself reaches alpha 128. Billed.`;
1020
+ return `nose: ${found} \u2014 under ${import_editor4.SPECK_CORE_FRACTION} of its width or height, a speck: a lone nostril mark or highlight at alpha >= 128, not the drawing, so ${consequence}. Regenerate the nose with its shading painted denser, so the drawing itself reaches alpha 128. Billed.`;
1207
1021
  }
1208
1022
  async function lashOffSclera(eyePath, lashPath) {
1209
1023
  const eye = await decodePng(eyePath);
@@ -1330,10 +1144,10 @@ async function measureDir(absDir, noseSpeck) {
1330
1144
  warnings.push(noseSpeckWarning(noseSpeck, "compose"));
1331
1145
  } else if (layers.nose !== void 0) {
1332
1146
  const nose = await decodePng(import_node_path4.default.join(absDir, "nose.png"));
1333
- const core = denseCoreOf(nose.rgba, nose.width, nose.height);
1147
+ const core = (0, import_editor4.denseCoreOf)(nose.rgba, nose.width, nose.height);
1334
1148
  if (core !== null) {
1335
1149
  const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);
1336
- if (isSpeckCore(core, crop))
1150
+ if ((0, import_editor4.isSpeckCore)(core, crop))
1337
1151
  warnings.push(noseSpeckWarning({ core, part: crop }, "layer"));
1338
1152
  }
1339
1153
  }
@@ -1535,14 +1349,14 @@ function keyWhiteToAlpha(rgba) {
1535
1349
  async function coreAndBoundsOf(png) {
1536
1350
  const { data, info } = await (0, import_sharp2.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1537
1351
  return {
1538
- core: denseCoreOf(data, info.width, info.height),
1352
+ core: (0, import_editor4.denseCoreOf)(data, info.width, info.height),
1539
1353
  bounds: { x: 0, y: 0, w: info.width, h: info.height }
1540
1354
  };
1541
1355
  }
1542
1356
  async function noseSizingOf(png) {
1543
1357
  const { core, bounds } = await coreAndBoundsOf(png);
1544
1358
  if (core === null) return { box: bounds, whole: true };
1545
- if (isSpeckCore(core, bounds)) {
1359
+ if ((0, import_editor4.isSpeckCore)(core, bounds)) {
1546
1360
  return {
1547
1361
  box: bounds,
1548
1362
  whole: true,
@@ -1785,7 +1599,7 @@ async function composeLayersFromParts(input) {
1785
1599
 
1786
1600
  // src/server.ts
1787
1601
  function createIkiMcpServer() {
1788
- const server = new import_mcp.McpServer({ name: "iki", version: "0.11.1" });
1602
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.11.3" });
1789
1603
  server.registerTool(
1790
1604
  "validate_iki",
1791
1605
  {