@ikijs/mcp 0.11.2 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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,8 +231,354 @@ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
231
231
  return `data:image/png;base64,${page.toString("base64")}`;
232
232
  }
233
233
 
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;
242
+ }
243
+ }
244
+ function validateIki(model) {
245
+ const result = coerceModel(model);
246
+ if (!result.ok) return { ok: false, error: result.error };
247
+ return { ok: true };
248
+ }
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
+ };
286
+ }
287
+ }
288
+ return entry;
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."
364
+ }
365
+ ];
366
+ function listStandardParameters() {
367
+ return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));
368
+ }
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
+ );
376
+ }
377
+ }
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 };
390
+ }
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 turnTargets = input.turnTargets;
412
+ if (turnTargets !== void 0) {
413
+ if (typeof turnTargets !== "object" || turnTargets === null || Array.isArray(turnTargets)) {
414
+ throw new AutoRigInputError("turnTargets must be a plain object");
415
+ }
416
+ if (turnTargets.headHalfWidth !== void 0) {
417
+ throw new AutoRigInputError(
418
+ "turnTargets.headHalfWidth is measured off the layers, not accepted as input"
419
+ );
420
+ }
421
+ }
422
+ const resolvedLayers = layers.map((layer) => {
423
+ const resolved = resolveInputPath(layer.path);
424
+ return { resolved, fileName: layer.fileName ?? import_node_path2.default.basename(resolved) };
425
+ });
426
+ const rolePairs = expectInput(
427
+ "role parsing",
428
+ () => (0, import_editor2.parseLayerRoles)(resolvedLayers.map((r) => r.fileName))
429
+ );
430
+ const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));
431
+ let canvasW = 0;
432
+ let canvasH = 0;
433
+ let totalPixels = 0;
434
+ let measurer;
435
+ const crops = [];
436
+ for (let i = 0; i < resolvedLayers.length; i++) {
437
+ const { resolved, fileName } = resolvedLayers[i];
438
+ const png = await decodePng(resolved);
439
+ if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {
440
+ throw new AutoRigInputError(
441
+ `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`
442
+ );
443
+ }
444
+ totalPixels += png.width * png.height;
445
+ if (totalPixels > MAX_TOTAL_PIXELS) {
446
+ throw new AutoRigInputError(
447
+ `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`
448
+ );
449
+ }
450
+ if (i === 0) {
451
+ canvasW = png.width;
452
+ canvasH = png.height;
453
+ if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {
454
+ throw new AutoRigInputError(
455
+ `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`
456
+ );
457
+ }
458
+ measurer = (0, import_editor2.createLayerSetMeasurer)({ width: canvasW, height: canvasH });
459
+ } else if (png.width !== canvasW || png.height !== canvasH) {
460
+ throw new AutoRigInputError(
461
+ `layer "${fileName}" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
462
+ );
463
+ }
464
+ const role = roleByFileName.get(fileName);
465
+ if (role === void 0) {
466
+ throw new AutoRigInputError(`no role resolved for "${fileName}"`);
467
+ }
468
+ const layer = measurer.add({ role, fileName, rgba: png.rgba });
469
+ if (layer === null) {
470
+ throw new AutoRigInputError(
471
+ `role "${role}" file "${fileName}": layer is empty after alpha threshold`
472
+ );
473
+ }
474
+ const { bbox } = layer;
475
+ const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);
476
+ crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
477
+ }
478
+ const measurement = measurer.finish();
479
+ const { headHalfWidth, headHalfWidthApplied, turnOptions } = measurement;
480
+ const { headEdges, strandEdges } = turnOptions;
481
+ const noseCore = measurement.layers.find(
482
+ (l) => l.role === "nose"
483
+ )?.denseCore;
484
+ let turn;
485
+ let model;
486
+ try {
487
+ model = (0, import_editor2.generateIkiFromLayerSet)(
488
+ measurement.layers,
489
+ { width: canvasW, height: canvasH },
490
+ {
491
+ turnTargets: {
492
+ ...input.turnTargets,
493
+ ...turnOptions.turnTargets
494
+ },
495
+ onTurnSolved: (report) => {
496
+ turn = report;
497
+ },
498
+ ...input.style === void 0 ? {} : { style: input.style },
499
+ ...headEdges === void 0 ? {} : { headEdges },
500
+ ...strandEdges === void 0 ? {} : { strandEdges }
501
+ }
502
+ );
503
+ } catch (e) {
504
+ if (!(e instanceof import_editor2.TurnTargetError)) throw e;
505
+ throw new AutoRigInputError(e.message);
506
+ }
507
+ const doc = new import_editor2.EditorDocument(model);
508
+ const losslessCrop = quantizeColors === void 0 ? void 0 : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);
509
+ const pages = losslessCrop === void 0 ? [await renderAtlasPage(crops, quantizeColors)] : [
510
+ await renderAtlasPage(
511
+ crops.filter((c) => c !== losslessCrop),
512
+ quantizeColors
513
+ ),
514
+ await renderAtlasPage([losslessCrop], void 0)
515
+ ];
516
+ const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);
517
+ if (atlasBytes > MAX_OUTPUT_BYTES) {
518
+ throw new AutoRigInputError(
519
+ `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`
520
+ );
521
+ }
522
+ const partTextureAssignments = pages.flatMap(
523
+ ({ crops: pageCrops, layout }) => pageCrops.map((crop) => {
524
+ const placement2 = layout.placements.find((p) => p.id === crop.id);
525
+ if (placement2 === void 0) {
526
+ throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
527
+ }
528
+ return {
529
+ partId: crop.id,
530
+ uv: (0, import_editor2.uvRectFor)(placement2, {
531
+ width: layout.pageWidth,
532
+ height: layout.pageHeight
533
+ })
534
+ };
535
+ })
536
+ );
537
+ doc.applyAtlas({
538
+ textures: [{ source: pages[0].dataUri }],
539
+ partTextureAssignments
540
+ });
541
+ let patched = doc.getModel();
542
+ if (losslessCrop !== void 0) {
543
+ patched = structuredClone(patched);
544
+ patched.textures = pages.map((p) => ({ source: p.dataUri }));
545
+ patched.parts.find((p) => p.id === losslessCrop.id).texture.index = 1;
546
+ }
547
+ const finalModel = (0, import_format.parseIkiModel)(patched);
548
+ writeFileAtomic(outPath, JSON.stringify(finalModel));
549
+ return {
550
+ ok: true,
551
+ path: outPath,
552
+ canvas: { width: canvasW, height: canvasH },
553
+ partCount: finalModel.parts.length,
554
+ atlasBytes,
555
+ ...headHalfWidth === void 0 ? {} : { headHalfWidth },
556
+ headHalfWidthApplied,
557
+ ...headEdges === void 0 ? {} : { headEdges },
558
+ ...strandEdges === void 0 ? {} : { strandEdges },
559
+ ...noseCore === void 0 ? {} : { noseCore },
560
+ ...turn === void 0 ? {} : { turn }
561
+ };
562
+ } catch (err) {
563
+ if (err instanceof AutoRigInputError)
564
+ return { ok: false, error: err.message };
565
+ throw err;
566
+ }
567
+ }
568
+
569
+ // src/compose.ts
570
+ var import_node_fs3 = __toESM(require("fs"));
571
+ var import_node_path5 = __toESM(require("path"));
572
+ var import_sharp2 = __toESM(require("sharp"));
573
+
574
+ // src/measure.ts
575
+ var import_node_fs2 = __toESM(require("fs"));
576
+ var import_node_path4 = __toESM(require("path"));
577
+
234
578
  // src/measure-turn.ts
235
- var import_node_path2 = __toESM(require("path"));
579
+ var import_node_path3 = __toESM(require("path"));
580
+ var import_editor3 = require("@ikijs/editor");
581
+ var import_editor4 = require("@ikijs/editor");
236
582
  var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
237
583
  var IRIS_V_MIN = 0.18;
238
584
  var IRIS_V_MAX = 0.95;
@@ -247,35 +593,11 @@ var PAIR_DX_MIN_FRAC = 0.08;
247
593
  var PAIR_DX_MAX_FRAC = 0.35;
248
594
  var PAIR_DY_MAX_FRAC = 0.05;
249
595
  var MAX_CANDIDATES = 12;
250
- var HEAD_BAND = 10;
251
- var ALPHA_OPAQUE = 128;
252
596
  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
- }
271
- }
272
- if (maxX < 0) return null;
273
- return { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 };
274
- }
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
- }
597
+ var BG_HUE_MAX = 260;
598
+ var BG_SAT_MAX = 0.2;
599
+ var BG_V_MIN = 0.55;
600
+ var BG_V_BLACK = 0.03;
279
601
  function rgbToHsv(r, g, b) {
280
602
  r /= 255;
281
603
  g /= 255;
@@ -386,21 +708,6 @@ function components(mask, width, height, minArea) {
386
708
  }
387
709
  return out.sort((a, b) => b.area - a.area);
388
710
  }
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
711
  function resolveIris(override) {
405
712
  const iris = { ...DEFAULT_IRIS, ...override };
406
713
  if (iris.hueMin < 0 || iris.hueMax > 360 || iris.hueMin >= iris.hueMax) {
@@ -421,7 +728,7 @@ async function measureTurnImage(filePath, iris) {
421
728
  let transparent = false;
422
729
  if (hasAlpha) {
423
730
  for (let i = 0; i < n; i++) {
424
- if (rgba[i * 4 + 3] < ALPHA_OPAQUE) {
731
+ if (rgba[i * 4 + 3] < import_editor3.ALPHA_OPAQUE) {
425
732
  transparent = true;
426
733
  break;
427
734
  }
@@ -432,7 +739,7 @@ async function measureTurnImage(filePath, iris) {
432
739
  const fg = new Uint8Array(n);
433
740
  const value = new Float32Array(n);
434
741
  for (let i = 0; i < n; i++) {
435
- if (rgba[i * 4 + 3] < ALPHA_OPAQUE) continue;
742
+ if (rgba[i * 4 + 3] < import_editor3.ALPHA_OPAQUE) continue;
436
743
  const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);
437
744
  if (maskMode === "alpha") {
438
745
  fg[i] = 1;
@@ -498,12 +805,12 @@ async function measureTurnImage(filePath, iris) {
498
805
  }
499
806
  const [irisL, irisR] = best.pair;
500
807
  const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);
501
- const { left, right } = foregroundSpan(
808
+ const { left, right } = (0, import_editor3.foregroundSpan)(
502
809
  fg,
503
810
  width,
504
811
  height,
505
- eyeRow - HEAD_BAND,
506
- eyeRow + HEAD_BAND
812
+ eyeRow - import_editor3.HEAD_BAND,
813
+ eyeRow + import_editor3.HEAD_BAND
507
814
  );
508
815
  if (right <= left) {
509
816
  throw new AutoRigInputError(
@@ -516,581 +823,74 @@ async function measureTurnImage(filePath, iris) {
516
823
  );
517
824
  }
518
825
  return {
519
- file: filePath,
520
- width,
521
- height,
522
- maskMode,
523
- 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;
826
+ file: filePath,
827
+ width,
828
+ height,
829
+ maskMode,
830
+ irisL,
831
+ irisR,
832
+ eyeRow,
833
+ head: {
834
+ left,
835
+ right,
836
+ cx: (left + right) / 2,
837
+ half: (0, import_editor3.headHalfOf)({ left, right })
838
+ },
839
+ pairCx: (irisL.cx + irisR.cx) / 2,
840
+ eyeGap: irisR.cx - irisL.cx
776
841
  };
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
842
  }
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 };
843
+ function farNearWidths(m, turnSign) {
844
+ return turnSign < 0 ? { far: m.irisL.w, near: m.irisR.w } : { far: m.irisR.w, near: m.irisL.w };
791
845
  }
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;
846
+ function overlaySvg(m) {
847
+ const box = (b, stroke) => `<rect x="${b.x0}" y="${b.y0}" width="${b.w}" height="${b.h}" fill="none" stroke="${stroke}" stroke-width="3"/>`;
848
+ const tick = (x, half, stroke) => `<line x1="${x}" y1="${m.eyeRow - half}" x2="${x}" y2="${m.eyeRow + half}" stroke="${stroke}" stroke-width="3"/>`;
849
+ 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
850
  }
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 }))
851
+ async function writeOverlay(debugDir, label, m) {
852
+ const outPath = import_node_path3.default.join(
853
+ debugDir,
854
+ `${label}-${import_node_path3.default.basename(m.file, ".png")}.debug.png`
804
855
  );
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 };
856
+ writeFileAtomic(outPath, await encodeOverlayPng(m.file, overlaySvg(m)));
857
+ return outPath;
812
858
  }
813
- async function autoRigFromLayers(input) {
859
+ var IRIS_HEIGHT_SCALE_TOLERANCE = 0.1;
860
+ async function measureTurnReference(input) {
814
861
  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)) {
862
+ const iris = resolveIris(input.iris);
863
+ const frontPath = resolveInputPath(input.front);
864
+ const turnedPath = resolveInputPath(input.turned);
865
+ const debugDir = input.debugDir === void 0 ? null : resolveOutputDir(input.debugDir);
866
+ const front = await measureTurnImage(frontPath, iris);
867
+ const turned = await measureTurnImage(turnedPath, iris);
868
+ const frontIrisH = (front.irisL.h + front.irisR.h) / 2;
869
+ const turnedIrisH = (turned.irisL.h + turned.irisR.h) / 2;
870
+ if (Math.abs(turnedIrisH - frontIrisH) / frontIrisH > IRIS_HEIGHT_SCALE_TOLERANCE) {
829
871
  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
- }
872
+ `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
873
  );
1036
- } catch (e) {
1037
- if (!(e instanceof import_editor2.TurnTargetError)) throw e;
1038
- throw new AutoRigInputError(e.message);
1039
874
  }
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)
875
+ const frontShift = front.pairCx - front.head.cx;
876
+ const turnedShift = turned.pairCx - turned.head.cx;
877
+ const shift = turnedShift - frontShift;
878
+ const turnSign = shift < 0 ? -1 : 1;
879
+ const f = farNearWidths(front, turnSign);
880
+ const t = farNearWidths(turned, turnSign);
881
+ const debug = debugDir === null ? void 0 : [
882
+ await writeOverlay(debugDir, "front", front),
883
+ await writeOverlay(debugDir, "turned", turned)
1048
884
  ];
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
885
  return {
1083
886
  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 }
887
+ front,
888
+ turned,
889
+ farEyeRatio: t.far / t.near / (f.far / f.near),
890
+ eyeShift: shift / front.head.half,
891
+ silhouetteRatio: turned.head.half / front.head.half,
892
+ turnSign,
893
+ ...debug === void 0 ? {} : { debug }
1094
894
  };
1095
895
  } catch (err) {
1096
896
  if (err instanceof AutoRigInputError)
@@ -1098,15 +898,36 @@ async function autoRigFromLayers(input) {
1098
898
  throw err;
1099
899
  }
1100
900
  }
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"));
901
+ var n1 = (v) => v.toFixed(1);
902
+ var n3 = (v) => v.toFixed(3);
903
+ function imageBlock(label, m) {
904
+ return [
905
+ `# ${label} ${m.file} ${m.width}x${m.height} mask: ${m.maskMode}`,
906
+ `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)}`,
907
+ `head ${m.head.left}..${m.head.right} centre ${n1(m.head.cx)} half ${n1(m.head.half)} pair centre ${n1(m.pairCx)}`
908
+ ];
909
+ }
910
+ function formatTurnReport(result) {
911
+ const { front, turned } = result;
912
+ const f = farNearWidths(front, result.turnSign);
913
+ const t = farNearWidths(turned, result.turnSign);
914
+ const lines = [
915
+ `farEyeRatio ${n3(result.farEyeRatio)} far/near iris width ${t.far}/${t.near} turned over ${f.far}/${f.near} front`,
916
+ `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)`,
917
+ `silhouetteRatio ${n3(result.silhouetteRatio)} head half ${n1(turned.head.half)} px turned over ${n1(front.head.half)} px front`,
918
+ `turnSign ${result.turnSign} (the head turned toward the image's ${result.turnSign < 0 ? "left" : "right"})`,
919
+ "",
920
+ ...imageBlock("front", front),
921
+ "",
922
+ ...imageBlock("turned", turned)
923
+ ];
924
+ if (result.debug !== void 0) {
925
+ lines.push("", ...result.debug.map((p) => `debug overlay ${p}`));
926
+ }
927
+ return lines.join("\n");
928
+ }
1106
929
 
1107
930
  // src/measure.ts
1108
- var import_node_fs2 = __toESM(require("fs"));
1109
- var import_node_path4 = __toESM(require("path"));
1110
931
  var IRIS_RATIO_MIN = 0.45;
1111
932
  var IRIS_RATIO_MAX = 0.72;
1112
933
  var EYE_ASPECT_MIN = 0.5;
@@ -1203,7 +1024,7 @@ function noseSpeckWarning({ core, part }, source) {
1203
1024
  `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,
1204
1025
  `auto_rig_from_layers turns and tilts the nose about its whole crop instead`
1205
1026
  ];
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.`;
1027
+ 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
1028
  }
1208
1029
  async function lashOffSclera(eyePath, lashPath) {
1209
1030
  const eye = await decodePng(eyePath);
@@ -1330,10 +1151,10 @@ async function measureDir(absDir, noseSpeck) {
1330
1151
  warnings.push(noseSpeckWarning(noseSpeck, "compose"));
1331
1152
  } else if (layers.nose !== void 0) {
1332
1153
  const nose = await decodePng(import_node_path4.default.join(absDir, "nose.png"));
1333
- const core = denseCoreOf(nose.rgba, nose.width, nose.height);
1154
+ const core = (0, import_editor4.denseCoreOf)(nose.rgba, nose.width, nose.height);
1334
1155
  if (core !== null) {
1335
1156
  const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);
1336
- if (isSpeckCore(core, crop))
1157
+ if ((0, import_editor4.isSpeckCore)(core, crop))
1337
1158
  warnings.push(noseSpeckWarning({ core, part: crop }, "layer"));
1338
1159
  }
1339
1160
  }
@@ -1402,9 +1223,8 @@ var DEFAULT_LAYOUT = {
1402
1223
  // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir
1403
1224
  // without them still composes (head-only character).
1404
1225
  hair_back: { src: "hair_back.png", cx: 550, cy: 523, w: 800, optional: true },
1405
- // The torso, cut off by the canvas bottom. It rides its own `bodyDeformer`: a
1406
- // light share of the head turn and half its breath bob, so the character is
1407
- // not a floating head.
1226
+ // The torso, cut off by the canvas bottom, so the character is not a
1227
+ // floating head. It rides its own `bodyDeformer`, which only breathes.
1408
1228
  body: { src: "body.png", cx: 550, cy: 1017, w: 840, optional: true },
1409
1229
  face: { src: "face.png", cx: 550, cy: 475, w: 400 },
1410
1230
  // The nose, drawn on its own (the face is drawn without one): the auto-rig
@@ -1535,14 +1355,14 @@ function keyWhiteToAlpha(rgba) {
1535
1355
  async function coreAndBoundsOf(png) {
1536
1356
  const { data, info } = await (0, import_sharp2.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1537
1357
  return {
1538
- core: denseCoreOf(data, info.width, info.height),
1358
+ core: (0, import_editor4.denseCoreOf)(data, info.width, info.height),
1539
1359
  bounds: { x: 0, y: 0, w: info.width, h: info.height }
1540
1360
  };
1541
1361
  }
1542
1362
  async function noseSizingOf(png) {
1543
1363
  const { core, bounds } = await coreAndBoundsOf(png);
1544
1364
  if (core === null) return { box: bounds, whole: true };
1545
- if (isSpeckCore(core, bounds)) {
1365
+ if ((0, import_editor4.isSpeckCore)(core, bounds)) {
1546
1366
  return {
1547
1367
  box: bounds,
1548
1368
  whole: true,
@@ -1785,7 +1605,7 @@ async function composeLayersFromParts(input) {
1785
1605
 
1786
1606
  // src/server.ts
1787
1607
  function createIkiMcpServer() {
1788
- const server = new import_mcp.McpServer({ name: "iki", version: "0.11.2" });
1608
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.12.0" });
1789
1609
  server.registerTool(
1790
1610
  "validate_iki",
1791
1611
  {
@@ -1872,8 +1692,18 @@ function createIkiMcpServer() {
1872
1692
  silhouetteRatio: import_zod.z.number().optional(),
1873
1693
  noseShift: import_zod.z.number().optional(),
1874
1694
  mouthShift: import_zod.z.number().optional()
1875
- }).optional().describe(
1876
- "What the head turn is fitted to, as `measure_turn_reference` reports it off a front/turned reference pair. `eyeShift` (and the optional `noseShift`/`mouthShift`, derived from it when absent) is how far that feature slides across the head at full turn, as a fraction of the head's half-width \u2014 a MAGNITUDE: the rig turns both ways, so the sign is ignored. `farEyeRatio` is the far/near eye width at full turn over that same ratio at rest, `silhouetteRatio` the head's half-width turned over at rest. The half-width the shifts are fractions of is measured off the layers themselves, so it is not an input. An omitted field falls back to a default, which is clamped to what this layer set can do, and so is a passed `eyeShift` past the room the art leaves the far eye \u2014 the face plate's edge, or the bangs' side strand over the far iris (the result's `turn.clamped` lists every clamped field, `turn.achieved` what the rig reaches, and `turn.strandOverlap` how much of a far iris the bangs still cover). Any other passed target this layer set cannot reach, including an `eyeShift` smaller than the slide the face's own turn already gives the eyes, comes back as `INVALID: \u2026` naming the field and the attainable range, since it is a measurement rather than a preference \u2014 except a passed `silhouetteRatio` when no ratio in its whole accepted range renders on this layer set: that refusal reads `\u2026 is unreachable for this layer set, and so is every silhouetteRatio in [0.5, 1.5]` and names no range, so leave the field out, since a defaulted one clamps."
1695
+ }).passthrough().optional().describe(
1696
+ "What the head turn is fitted to, as `measure_turn_reference` reports it off a front/turned reference pair. `eyeShift` (and the optional `noseShift`/`mouthShift`) is how far that feature slides across the head at full turn, as a fraction of the head's half-width \u2014 a MAGNITUDE: the rig turns both ways, so the sign is ignored. `farEyeRatio` is the far/near eye width at full turn over that same ratio at rest, `silhouetteRatio` the head's half-width turned over at rest. The half-width the shifts are fractions of is measured off the layers themselves, so it is not an input. An omitted field leaves that part of the turn at the Live2D profile the rig defaults to. A passed `eyeShift` is fitted by the turn's amount and clamped to the room the art leaves the far eye \u2014 the face plate's edge, or the bangs' side strand over the far iris (the result's `turn.clamped` lists every clamped field, `turn.achieved` what the rig reaches, and `turn.strandOverlap` how much of a far iris the bangs still cover). Any other passed target this layer set cannot reach comes back as `INVALID: \u2026` naming the field and the attainable range, since it is a measurement rather than a preference. A field not named here is refused the same way."
1697
+ ),
1698
+ style: import_zod.z.object({
1699
+ turn: import_zod.z.number().optional(),
1700
+ featureLead: import_zod.z.number().optional(),
1701
+ hairFollow: import_zod.z.number().optional(),
1702
+ outlineFollow: import_zod.z.number().optional(),
1703
+ blink: import_zod.z.number().optional(),
1704
+ sway: import_zod.z.number().optional()
1705
+ }).passthrough().optional().describe(
1706
+ "Per-character tuning from the Live2D profile the rig defaults to \u2014 only what the Live2D samples themselves disagree on: `turn` scales the whole head turn (plate, features, hair and the eyes' foreshortening; 0..3, 1 = the profile; ignored when `turnTargets.eyeShift` is given), `featureLead` how far the features lead the face plate (0..3, 1 = the profile), `hairFollow` the front hair's share of the face's turn (0..2, profile 1.1), `outlineFollow` its outer edge's share where the front hair draws the head's outline (0..2, profile 0: the outline holds), `blink` how far the upper lid comes down over the eye's height (0.1..1, profile 0.58), `sway` the hair sway amplitude (0..5, 1 = the profile). A value out of range, or a knob not named here, comes back as `INVALID: \u2026`."
1877
1707
  )
1878
1708
  }
1879
1709
  },