@ikijs/mcp 0.19.0 → 0.20.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
@@ -400,11 +400,27 @@ var STANDARD_PARAMETER_INFO = [
400
400
  },
401
401
  {
402
402
  id: import_format.StandardParameter.ElbowLeft,
403
- description: "Left elbow, degrees; positive bends the forearm the way positive ArmLeft raises the arm."
403
+ description: "Left elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the right)."
404
404
  },
405
405
  {
406
406
  id: import_format.StandardParameter.ElbowRight,
407
- description: "Right elbow, degrees; positive bends the forearm the way positive ArmRight raises the arm."
407
+ description: "Right elbow, degrees; positive bends the forearm toward the body (the flexion of a hanging arm), negative a little outward (mirrored on the left)."
408
+ },
409
+ {
410
+ id: import_format.StandardParameter.ArmPoseLeft,
411
+ description: "Left pose-forearm switch, 0..1; 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm."
412
+ },
413
+ {
414
+ id: import_format.StandardParameter.ArmPoseRight,
415
+ description: "Right pose-forearm switch, 0..1; 0 the hanging forearm, 1 the drawn pose forearm, between them a crossfade of the two. Declared by auto-rigged models with a pose forearm."
416
+ },
417
+ {
418
+ id: import_format.StandardParameter.ArmPoseAngleLeft,
419
+ description: "Left pose forearm's own small rotation about the elbow, degrees; positive tips the raised hand outward, away from the body (mirrored on the right)."
420
+ },
421
+ {
422
+ id: import_format.StandardParameter.ArmPoseAngleRight,
423
+ description: "Right pose forearm's own small rotation about the elbow, degrees; positive tips the raised hand outward, away from the body (mirrored on the left)."
408
424
  }
409
425
  ];
410
426
  function listStandardParameters() {
@@ -620,7 +636,7 @@ async function autoRigFromLayers(input) {
620
636
  var import_node_fs3 = __toESM(require("fs"));
621
637
  var import_node_path6 = __toESM(require("path"));
622
638
  var import_sharp3 = __toESM(require("sharp"));
623
- var import_editor7 = require("@ikijs/editor");
639
+ var import_editor8 = require("@ikijs/editor");
624
640
 
625
641
  // src/measure.ts
626
642
  var import_node_fs2 = __toESM(require("fs"));
@@ -697,10 +713,96 @@ function capWarning(arm, g, body) {
697
713
  return `${arm}: its shoulder cap reaches ${px(overlap)} px under the torso's edge on its pivot row (y=${row}), under half its radius (${px(need)} px) \u2014 a gap opens beside the shoulder once the arm raises. Move layout.${arm}.cx ${Math.ceil(need - overlap)} px toward the body (free).`;
698
714
  }
699
715
 
716
+ // src/measure-forearm-pose.ts
717
+ var import_editor4 = require("@ikijs/editor");
718
+ var POSE_ROLES = ["forearm_pose_L", "forearm_pose_R"];
719
+ var ARM_OF = {
720
+ forearm_pose_L: "arm_L",
721
+ forearm_pose_R: "arm_R"
722
+ };
723
+ var POSE_PIVOT_TOLERANCE = 2;
724
+ var POSE_WIDTH_TOLERANCE = 0.1;
725
+ var POSE_LENGTH_TOLERANCE = 0.15;
726
+ function bottomRowY(layer) {
727
+ const painted = layer.rowRuns?.flatMap((runs, k2) => runs.length > 0 ? [k2] : []) ?? [];
728
+ const k = painted.at(-1) ?? layer.bbox.h - 1;
729
+ return layer.canvasH / 2 - (layer.bbox.y + k + 0.5);
730
+ }
731
+ async function forearmPoseWarnings(absDir, layers) {
732
+ const warnings = [];
733
+ for (const pose of POSE_ROLES) {
734
+ const stats = layers[pose];
735
+ if (stats === void 0) continue;
736
+ const arm = ARM_OF[pose];
737
+ const armStats = layers[arm];
738
+ if (armStats === void 0) {
739
+ warnings.push(
740
+ `${pose}: no ${arm} layer \u2014 a pose forearm hangs from its arm's elbow, and auto_rig_from_layers refuses it.`
741
+ );
742
+ continue;
743
+ }
744
+ if (stats.canvasW !== armStats.canvasW || stats.canvasH !== armStats.canvasH) {
745
+ warnings.push(
746
+ `${pose}: its canvas ${stats.canvasW}x${stats.canvasH} differs from ${arm}'s ${armStats.canvasW}x${armStats.canvasH} \u2014 auto_rig_from_layers refuses layers of different sizes; recompose them together.`
747
+ );
748
+ continue;
749
+ }
750
+ if (layers.body === void 0) continue;
751
+ const measurer = (0, import_editor4.createLayerSetMeasurer)({
752
+ width: stats.canvasW,
753
+ height: stats.canvasH
754
+ });
755
+ let a;
756
+ let armLayer;
757
+ try {
758
+ armLayer = await measured(measurer, absDir, arm);
759
+ a = (0, import_editor4.armGeometry)(armLayer, arm === "arm_R" ? Infinity : -Infinity);
760
+ } catch (err) {
761
+ if (err instanceof import_editor4.LayerGeometryError) continue;
762
+ throw err;
763
+ }
764
+ const b = (0, import_editor4.forearmPoseGeometry)(await measured(measurer, absDir, pose));
765
+ warnings.push(...jointWarnings(pose, arm, stats, a, armLayer, b));
766
+ }
767
+ return warnings;
768
+ }
769
+ function jointWarnings(pose, arm, stats, a, armLayer, b) {
770
+ const warnings = [];
771
+ const key = `layout.${pose}`;
772
+ const dx = a.elbow.x - b.pivot.x;
773
+ const dy = a.elbow.y - b.pivot.y;
774
+ const off = Math.hypot(dx, dy);
775
+ if (off > POSE_PIVOT_TOLERANCE) {
776
+ warnings.push(
777
+ `${pose}: its elbow end is ${px(off)} px off ${arm}'s elbow \u2014 the raised forearm detaches from the arm at the joint once it swaps in. Remove ${key}.cx/cy from the layout so it stays pinned on the elbow through later arm retunes (free), or set ${key}.cx to ${Math.round(stats.bboxCx + 0.5 + dx)} and ${key}.cy to ${Math.round(stats.bboxCy + 0.5 - dy)} (free).`
778
+ );
779
+ }
780
+ const armRun = a.seamRun[1] - a.seamRun[0];
781
+ const poseRun = 2 * b.radius;
782
+ const widthRatio = poseRun / armRun;
783
+ const widthBad = Math.abs(widthRatio - 1) > POSE_WIDTH_TOLERANCE;
784
+ if (widthBad) {
785
+ warnings.push(
786
+ `${pose}: its elbow end is ${px(poseRun)} px wide, ${Math.round(Math.abs(widthRatio - 1) * 100)}% off ${arm}'s elbow run (${px(armRun)} px) \u2014 the sleeve steps at the joint once it swaps in. Set ${key}.w to ${Math.round(stats.w / widthRatio)} (free).`
787
+ );
788
+ }
789
+ const armLen = a.elbow.y - bottomRowY(armLayer);
790
+ const poseLen = b.top - b.pivot.y;
791
+ const lengthRatio = poseLen / armLen;
792
+ if (Math.abs(lengthRatio - 1) > POSE_LENGTH_TOLERANCE) {
793
+ const fix = 1 / lengthRatio;
794
+ const freeFix = Math.abs(widthRatio * fix - 1) <= POSE_WIDTH_TOLERANCE;
795
+ warnings.push(
796
+ `${pose}: its length from the elbow end to the hand is ${px(poseLen)} px against ${arm}'s ${px(armLen)} px from its elbow to its hand \u2014 ` + (freeFix ? `the raised hand reaches the wrong height. Set ${key}.w to ${Math.round(stats.w * fix)} (free)` + (widthBad ? `, which fixes the width too.` : `.`) : `the raised hand reaches the wrong height, and no single w fits both its length and its width. Regenerate forearm_pose.png with the forearm and hand as long as the hanging arm's below its elbow. Billed.`)
797
+ );
798
+ }
799
+ return warnings;
800
+ }
801
+
700
802
  // src/measure-turn.ts
701
803
  var import_node_path4 = __toESM(require("path"));
702
- var import_editor4 = require("@ikijs/editor");
703
804
  var import_editor5 = require("@ikijs/editor");
805
+ var import_editor6 = require("@ikijs/editor");
704
806
  var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
705
807
  var IRIS_V_MIN = 0.18;
706
808
  var IRIS_V_MAX = 0.95;
@@ -850,7 +952,7 @@ async function measureTurnImage(filePath, iris) {
850
952
  let transparent = false;
851
953
  if (hasAlpha) {
852
954
  for (let i = 0; i < n; i++) {
853
- if (rgba[i * 4 + 3] < import_editor4.ALPHA_OPAQUE) {
955
+ if (rgba[i * 4 + 3] < import_editor5.ALPHA_OPAQUE) {
854
956
  transparent = true;
855
957
  break;
856
958
  }
@@ -861,7 +963,7 @@ async function measureTurnImage(filePath, iris) {
861
963
  const fg = new Uint8Array(n);
862
964
  const value = new Float32Array(n);
863
965
  for (let i = 0; i < n; i++) {
864
- if (rgba[i * 4 + 3] < import_editor4.ALPHA_OPAQUE) continue;
966
+ if (rgba[i * 4 + 3] < import_editor5.ALPHA_OPAQUE) continue;
865
967
  const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);
866
968
  if (maskMode === "alpha") {
867
969
  fg[i] = 1;
@@ -927,12 +1029,12 @@ async function measureTurnImage(filePath, iris) {
927
1029
  }
928
1030
  const [irisL, irisR] = best.pair;
929
1031
  const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);
930
- const { left, right } = (0, import_editor4.foregroundSpan)(
1032
+ const { left, right } = (0, import_editor5.foregroundSpan)(
931
1033
  fg,
932
1034
  width,
933
1035
  height,
934
- eyeRow - import_editor4.HEAD_BAND,
935
- eyeRow + import_editor4.HEAD_BAND
1036
+ eyeRow - import_editor5.HEAD_BAND,
1037
+ eyeRow + import_editor5.HEAD_BAND
936
1038
  );
937
1039
  if (right <= left) {
938
1040
  throw new AutoRigInputError(
@@ -956,7 +1058,7 @@ async function measureTurnImage(filePath, iris) {
956
1058
  left,
957
1059
  right,
958
1060
  cx: (left + right) / 2,
959
- half: (0, import_editor4.headHalfOf)({ left, right })
1061
+ half: (0, import_editor5.headHalfOf)({ left, right })
960
1062
  },
961
1063
  pairCx: (irisL.cx + irisR.cx) / 2,
962
1064
  eyeGap: irisR.cx - irisL.cx
@@ -1138,7 +1240,7 @@ async function layerStats(filePath) {
1138
1240
  };
1139
1241
  }
1140
1242
  var pct = (v) => `${(v * 100).toFixed(0)}%`;
1141
- var isArm = (role) => ARM_ROLES.includes(role);
1243
+ var isArm = (role) => ARM_ROLES.includes(role) || POSE_ROLES.includes(role);
1142
1244
  function noseSpeckWarning({ core, part }, source) {
1143
1245
  const [found, consequence] = source === "compose" ? [
1144
1246
  `the source part's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} trimmed part`,
@@ -1147,7 +1249,7 @@ function noseSpeckWarning({ core, part }, source) {
1147
1249
  `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,
1148
1250
  `auto_rig_from_layers turns and tilts the nose about its whole crop instead`
1149
1251
  ];
1150
- return `nose: ${found} \u2014 under ${import_editor5.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.`;
1252
+ return `nose: ${found} \u2014 under ${import_editor6.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.`;
1151
1253
  }
1152
1254
  async function lashOffSclera(eyePath, lashPath) {
1153
1255
  const eye = await decodePng(eyePath);
@@ -1224,6 +1326,7 @@ async function measureDir(absDir, noseSpeck) {
1224
1326
  }
1225
1327
  }
1226
1328
  warnings.push(...await armWarnings(absDir, layers));
1329
+ warnings.push(...await forearmPoseWarnings(absDir, layers));
1227
1330
  for (const side of ["L", "R"]) {
1228
1331
  const eye = layers[`eye_${side}`];
1229
1332
  const iris = layers[`iris_${side}`];
@@ -1280,10 +1383,10 @@ async function measureDir(absDir, noseSpeck) {
1280
1383
  warnings.push(noseSpeckWarning(noseSpeck, "compose"));
1281
1384
  } else if (layers.nose !== void 0) {
1282
1385
  const nose = await decodePng(import_node_path5.default.join(absDir, "nose.png"));
1283
- const core = (0, import_editor5.denseCoreOf)(nose.rgba, nose.width, nose.height);
1386
+ const core = (0, import_editor6.denseCoreOf)(nose.rgba, nose.width, nose.height);
1284
1387
  if (core !== null) {
1285
1388
  const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);
1286
- if ((0, import_editor5.isSpeckCore)(core, crop))
1389
+ if ((0, import_editor6.isSpeckCore)(core, crop))
1287
1390
  warnings.push(noseSpeckWarning({ core, part: crop }, "layer"));
1288
1391
  }
1289
1392
  }
@@ -1342,12 +1445,12 @@ function formatMeasureReport(result) {
1342
1445
 
1343
1446
  // src/compose-arms.ts
1344
1447
  var import_sharp2 = __toESM(require("sharp"));
1345
- var import_editor6 = require("@ikijs/editor");
1448
+ var import_editor7 = require("@ikijs/editor");
1346
1449
  var ARM_WIDTH = 0.4;
1347
1450
  var SHOULDER_DROP = 0.12;
1348
1451
  async function armPlacement(role, cfg, part, body) {
1349
1452
  const { data } = await (0, import_sharp2.default)(part.buf).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1350
- const layer = (0, import_editor6.createLayerSetMeasurer)({ width: part.w, height: part.h }).add({
1453
+ const layer = (0, import_editor7.createLayerSetMeasurer)({ width: part.w, height: part.h }).add({
1351
1454
  role,
1352
1455
  fileName: "arm.png",
1353
1456
  rgba: data
@@ -1357,28 +1460,62 @@ async function armPlacement(role, cfg, part, body) {
1357
1460
  `layout.${role}: arm.png is empty after alpha threshold once resized`
1358
1461
  );
1359
1462
  }
1360
- let shoulder;
1463
+ let g;
1361
1464
  try {
1362
- ({ shoulder } = (0, import_editor6.armGeometry)(
1363
- layer,
1364
- role === "arm_R" ? Infinity : -Infinity
1365
- ));
1465
+ g = (0, import_editor7.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
1366
1466
  } catch (err) {
1367
- if (err instanceof import_editor6.LayerGeometryError) {
1467
+ if (err instanceof import_editor7.LayerGeometryError) {
1368
1468
  throw new AutoRigInputError(`layout.${role}: ${err.message}`);
1369
1469
  }
1370
1470
  throw err;
1371
1471
  }
1372
- const pivotX = shoulder.x + part.w / 2;
1373
- const pivotY = part.h / 2 - shoulder.y;
1472
+ const pivotX = g.shoulder.x + part.w / 2;
1473
+ const pivotY = part.h / 2 - g.shoulder.y;
1374
1474
  const cornerX = role === "arm_R" ? body.left : body.left + body.w;
1375
1475
  const cornerY = body.top + SHOULDER_DROP * body.h;
1476
+ const left = Math.round(
1477
+ cfg.cx === void 0 ? cornerX - pivotX : cfg.cx - part.w / 2
1478
+ );
1479
+ const top = Math.round(
1480
+ cfg.cy === void 0 ? cornerY - pivotY : cfg.cy - part.h / 2
1481
+ );
1482
+ return {
1483
+ left,
1484
+ top,
1485
+ elbow: {
1486
+ x: left + g.elbow.x + part.w / 2,
1487
+ y: top + part.h / 2 - g.elbow.y
1488
+ },
1489
+ elbowRun: g.seamRun[1] - g.seamRun[0]
1490
+ };
1491
+ }
1492
+ async function poseGeometryOf(role, png, size, when) {
1493
+ const { data } = await (0, import_sharp2.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1494
+ const layer = (0, import_editor7.createLayerSetMeasurer)({
1495
+ width: size.w,
1496
+ height: size.h
1497
+ }).add({ role, fileName: "forearm_pose.png", rgba: data });
1498
+ if (layer === null) {
1499
+ throw new AutoRigInputError(
1500
+ `layout.${role}: forearm_pose.png is empty after alpha threshold${when}`
1501
+ );
1502
+ }
1503
+ return (0, import_editor7.forearmPoseGeometry)(layer);
1504
+ }
1505
+ async function forearmPoseWidth(role, trimmed, elbowRun) {
1506
+ const g = await poseGeometryOf(role, trimmed.data, trimmed, "");
1507
+ return Math.max(1, Math.round(trimmed.w * elbowRun / (2 * g.radius)));
1508
+ }
1509
+ async function forearmPosePlacement(role, cfg, part, elbow) {
1510
+ const { pivot } = await poseGeometryOf(role, part.buf, part, " once resized");
1511
+ const pivotX = pivot.x + part.w / 2;
1512
+ const pivotY = part.h / 2 - pivot.y;
1376
1513
  return {
1377
1514
  left: Math.round(
1378
- cfg.cx === void 0 ? cornerX - pivotX : cfg.cx - part.w / 2
1515
+ cfg.cx === void 0 ? elbow.x - pivotX : cfg.cx - part.w / 2
1379
1516
  ),
1380
1517
  top: Math.round(
1381
- cfg.cy === void 0 ? cornerY - pivotY : cfg.cy - part.h / 2
1518
+ cfg.cy === void 0 ? elbow.y - pivotY : cfg.cy - part.h / 2
1382
1519
  )
1383
1520
  };
1384
1521
  }
@@ -1468,7 +1605,15 @@ var DEFAULT_LAYOUT = {
1468
1605
  // prettier-ignore
1469
1606
  brow_L: { src: "brow.png", cx: 645, cy: 405, w: 105, mirror: false },
1470
1607
  brow_R: { src: "brow.png", cx: 455, cy: 405, w: 105, mirror: true },
1471
- hair_front: { src: "hair_front.png", cx: 550, cy: 425, w: 660 }
1608
+ hair_front: { src: "hair_front.png", cx: 550, cy: 425, w: 660 },
1609
+ // The pose forearms, one drawing for both: forearm_pose_R (screen left)
1610
+ // takes forearm_pose.png as drawn and forearm_pose_L mirrors it, like the
1611
+ // arms. The rig draws them above the face and the hair, so they come last.
1612
+ // No cx/cy/w defaults: an unset `w` scales the forearm's elbow end to the
1613
+ // placed arm's elbow run, an unset `cx` or `cy` pins its elbow-end pivot
1614
+ // on the arm's elbow (ArmLayout). OPTIONAL and opt-in, like the arms.
1615
+ forearm_pose_L: { src: "forearm_pose.png", optional: true, mirror: true },
1616
+ forearm_pose_R: { src: "forearm_pose.png", optional: true, mirror: false }
1472
1617
  };
1473
1618
  var LOWER_LASH = { lash_lower_L: "eye_L", lash_lower_R: "eye_R" };
1474
1619
  var LOWER_LASH_SRC = "eyewhite_lash_lower.png";
@@ -1493,7 +1638,9 @@ var ORDER = [
1493
1638
  "lash_R",
1494
1639
  "brow_L",
1495
1640
  "brow_R",
1496
- "hair_front"
1641
+ "hair_front",
1642
+ "forearm_pose_L",
1643
+ "forearm_pose_R"
1497
1644
  ];
1498
1645
  var PART_FILES = [
1499
1646
  ...new Set(
@@ -1611,18 +1758,18 @@ function keyWhiteToAlpha(rgba) {
1611
1758
  async function coreAndBoundsOf(png) {
1612
1759
  const { data, info } = await (0, import_sharp3.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1613
1760
  return {
1614
- core: (0, import_editor5.denseCoreOf)(data, info.width, info.height),
1761
+ core: (0, import_editor6.denseCoreOf)(data, info.width, info.height),
1615
1762
  bounds: { x: 0, y: 0, w: info.width, h: info.height }
1616
1763
  };
1617
1764
  }
1618
1765
  async function hasCoverage(png) {
1619
1766
  const { data, info } = await (0, import_sharp3.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1620
- return (0, import_editor7.detectAlphaBbox)(data, info.width, info.height) !== null;
1767
+ return (0, import_editor8.detectAlphaBbox)(data, info.width, info.height) !== null;
1621
1768
  }
1622
1769
  async function noseSizingOf(png) {
1623
1770
  const { core, bounds } = await coreAndBoundsOf(png);
1624
1771
  if (core === null) return { box: bounds, whole: true };
1625
- if ((0, import_editor5.isSpeckCore)(core, bounds)) {
1772
+ if ((0, import_editor6.isSpeckCore)(core, bounds)) {
1626
1773
  return {
1627
1774
  box: bounds,
1628
1775
  whole: true,
@@ -1634,7 +1781,7 @@ async function noseSizingOf(png) {
1634
1781
  }
1635
1782
  return { box: core, whole: false };
1636
1783
  }
1637
- async function partBuffer(role, cfg, partsDir, inMemory, flipSource, canvas) {
1784
+ async function trimmedPart(role, cfg, partsDir, inMemory, flipSource) {
1638
1785
  let img;
1639
1786
  if (inMemory !== void 0) {
1640
1787
  img = (0, import_sharp3.default)(inMemory);
@@ -1662,7 +1809,14 @@ async function partBuffer(role, cfg, partsDir, inMemory, flipSource, canvas) {
1662
1809
  }
1663
1810
  if ((cfg.mirror ?? false) !== flipSource) img = img.flop();
1664
1811
  const trimmed = await img.png().toBuffer({ resolveWithObject: true });
1665
- const { width: trimmedW, height: trimmedH } = trimmed.info;
1812
+ return {
1813
+ data: trimmed.data,
1814
+ w: trimmed.info.width,
1815
+ h: trimmed.info.height
1816
+ };
1817
+ }
1818
+ async function sizedPart(role, cfg, trimmed, canvas) {
1819
+ const { w: trimmedW, h: trimmedH } = trimmed;
1666
1820
  const nose = role === "nose" ? await noseSizingOf(trimmed.data) : void 0;
1667
1821
  const sized = nose?.box ?? { x: 0, y: 0, w: trimmedW, h: trimmedH };
1668
1822
  const width = Math.round(trimmedW * cfg.w / sized.w);
@@ -1681,6 +1835,10 @@ async function partBuffer(role, cfg, partsDir, inMemory, flipSource, canvas) {
1681
1835
  nose
1682
1836
  };
1683
1837
  }
1838
+ async function partBuffer(role, cfg, partsDir, inMemory, flipSource, canvas) {
1839
+ const trimmed = await trimmedPart(role, cfg, partsDir, inMemory, flipSource);
1840
+ return trimmed === null ? null : sizedPart(role, cfg, trimmed, canvas);
1841
+ }
1684
1842
  function assertOnCanvas(source, w, h, left, top, canvas) {
1685
1843
  if (left + w <= 0 || top + h <= 0 || left >= canvas.width || top >= canvas.height) {
1686
1844
  throw new AutoRigInputError(
@@ -1753,7 +1911,7 @@ function boxWithoutStraySpecks(rgba, W, H) {
1753
1911
  while (depth > 0) {
1754
1912
  const p = stack[--depth];
1755
1913
  size++;
1756
- if (rgba[p * 4 + 3] >= import_editor7.ALPHA_OPAQUE) opaque = true;
1914
+ if (rgba[p * 4 + 3] >= import_editor8.ALPHA_OPAQUE) opaque = true;
1757
1915
  const px2 = p % W;
1758
1916
  const py = (p - px2) / W;
1759
1917
  setLeft = Math.min(setLeft, px2);
@@ -1794,7 +1952,7 @@ function detachedAboveWhite(rgba, W, H) {
1794
1952
  for (let p = 0; p < n; p++) {
1795
1953
  const alpha = rgba[p * 4 + 3];
1796
1954
  if (alpha > 0 && luma(rgba, p * 4) >= EYE_LASH_LUMA)
1797
- ink[p] = alpha >= import_editor7.ALPHA_OPAQUE ? 2 : 1;
1955
+ ink[p] = alpha >= import_editor8.ALPHA_OPAQUE ? 2 : 1;
1798
1956
  }
1799
1957
  const label = new Int32Array(n).fill(-1);
1800
1958
  const stack = new Int32Array(n);
@@ -1977,12 +2135,17 @@ async function composeLayersFromParts(input) {
1977
2135
  mirrored.has(arm.src),
1978
2136
  canvas
1979
2137
  );
1980
- const { left: left2, top: top2 } = await armPlacement(key, arm, part2, {
1981
- left: body.left,
1982
- top: body.top,
1983
- w: body.part.w,
1984
- h: body.part.h
1985
- });
2138
+ const { left: left2, top: top2, elbow, elbowRun } = await armPlacement(
2139
+ key,
2140
+ arm,
2141
+ part2,
2142
+ {
2143
+ left: body.left,
2144
+ top: body.top,
2145
+ w: body.part.w,
2146
+ h: body.part.h
2147
+ }
2148
+ );
1986
2149
  const unset = ["cx", "cy"].filter(
1987
2150
  (field) => arm[field] === void 0
1988
2151
  );
@@ -1994,6 +2157,58 @@ async function composeLayersFromParts(input) {
1994
2157
  top2,
1995
2158
  canvas
1996
2159
  );
2160
+ placed.push({ role, part: part2, left: left2, top: top2, elbow, elbowRun });
2161
+ continue;
2162
+ }
2163
+ if (key === "forearm_pose_L" || key === "forearm_pose_R") {
2164
+ const pose = layout[key];
2165
+ if (!import_node_fs3.default.existsSync(import_node_path6.default.join(partsDir, pose.src))) continue;
2166
+ const armRole = key === "forearm_pose_L" ? "arm_L" : "arm_R";
2167
+ const arm = placed.find((p) => p.role === armRole);
2168
+ if (arm?.elbow === void 0 || arm.elbowRun === void 0) {
2169
+ throw new AutoRigInputError(
2170
+ "forearm_pose.png: a pose forearm needs arm.png \u2014 the composer pins it on the arm's elbow, and auto_rig_from_layers hangs it from the arm"
2171
+ );
2172
+ }
2173
+ const trimmed = await trimmedPart(
2174
+ role,
2175
+ pose,
2176
+ partsDir,
2177
+ void 0,
2178
+ mirrored.has(pose.src)
2179
+ );
2180
+ const w = pose.w ?? await forearmPoseWidth(key, trimmed, arm.elbowRun);
2181
+ let part2;
2182
+ try {
2183
+ part2 = await sizedPart(role, { ...pose, w }, trimmed, canvas);
2184
+ } catch (err) {
2185
+ if (pose.w === void 0 && err instanceof AutoRigInputError) {
2186
+ throw new AutoRigInputError(
2187
+ err.message.replace(
2188
+ `layout.${role}.w:`,
2189
+ `layout.${role}.w (unset: scaled to ${armRole}'s elbow run):`
2190
+ )
2191
+ );
2192
+ }
2193
+ throw err;
2194
+ }
2195
+ const { left: left2, top: top2 } = await forearmPosePlacement(
2196
+ key,
2197
+ pose,
2198
+ part2,
2199
+ arm.elbow
2200
+ );
2201
+ const unset = ["cx", "cy"].filter(
2202
+ (field) => pose[field] === void 0
2203
+ );
2204
+ assertOnCanvas(
2205
+ unset.length === 0 ? `layout.${key}.cx/cy` : `layout.${key}.cx/cy (${unset.join("/")} unset: its elbow-end pivot hangs on the elbow of layout.${armRole}'s placed arm)`,
2206
+ part2.w,
2207
+ part2.h,
2208
+ left2,
2209
+ top2,
2210
+ canvas
2211
+ );
1997
2212
  placed.push({ role, part: part2, left: left2, top: top2 });
1998
2213
  continue;
1999
2214
  }
@@ -2037,6 +2252,10 @@ async function composeLayersFromParts(input) {
2037
2252
  if (placed.some((p) => p.role === role)) continue;
2038
2253
  import_node_fs3.default.rmSync(import_node_path6.default.join(outDir, `${role}.png`), { force: true });
2039
2254
  }
2255
+ const posed = (role) => role === "forearm_pose_L" || role === "forearm_pose_R";
2256
+ if (!placed.some((p) => posed(p.role))) {
2257
+ import_node_fs3.default.rmSync(import_node_path6.default.join(outDir, "preview-pose.png"), { force: true });
2258
+ }
2040
2259
  const layers = [];
2041
2260
  const preview = [];
2042
2261
  for (const { role, part, left, top } of placed) {
@@ -2051,7 +2270,7 @@ async function composeLayersFromParts(input) {
2051
2270
  left,
2052
2271
  top
2053
2272
  });
2054
- preview.push({ input: part.buf, left, top });
2273
+ if (!posed(role)) preview.push({ input: part.buf, left, top });
2055
2274
  }
2056
2275
  const previewPng = await (0, import_sharp3.default)({
2057
2276
  create: {
@@ -2063,12 +2282,42 @@ async function composeLayersFromParts(input) {
2063
2282
  }).composite(preview).png().toBuffer();
2064
2283
  const previewPath = import_node_path6.default.join(outDir, "preview.png");
2065
2284
  writeFileAtomic(previewPath, previewPng);
2285
+ let previewPosePath;
2286
+ if (placed.some((p) => posed(p.role))) {
2287
+ const pose = [];
2288
+ for (const { role, part, left, top, elbow } of placed) {
2289
+ const armPosed = elbow !== void 0 && placed.some(
2290
+ (p) => p.role === (role === "arm_L" ? "forearm_pose_L" : "forearm_pose_R")
2291
+ );
2292
+ if (!armPosed) {
2293
+ pose.push({ input: part.buf, left, top });
2294
+ continue;
2295
+ }
2296
+ const rows = Math.min(part.h, Math.max(1, Math.round(elbow.y - top)));
2297
+ pose.push({
2298
+ input: await (0, import_sharp3.default)(part.buf).extract({ left: 0, top: 0, width: part.w, height: rows }).png().toBuffer(),
2299
+ left,
2300
+ top
2301
+ });
2302
+ }
2303
+ const posePng = await (0, import_sharp3.default)({
2304
+ create: {
2305
+ width: canvas.width,
2306
+ height: canvas.height,
2307
+ channels: 4,
2308
+ background: { r: 245, g: 245, b: 248, alpha: 1 }
2309
+ }
2310
+ }).composite(pose).png().toBuffer();
2311
+ previewPosePath = import_node_path6.default.join(outDir, "preview-pose.png");
2312
+ writeFileAtomic(previewPosePath, posePng);
2313
+ }
2066
2314
  return {
2067
2315
  ok: true,
2068
2316
  outDir,
2069
2317
  layers,
2070
2318
  skipped,
2071
2319
  preview: previewPath,
2320
+ ...previewPosePath === void 0 ? {} : { previewPose: previewPosePath },
2072
2321
  measure: await measureDir(outDir, noseSpeck)
2073
2322
  };
2074
2323
  } catch (err) {
@@ -2080,7 +2329,7 @@ async function composeLayersFromParts(input) {
2080
2329
 
2081
2330
  // src/server.ts
2082
2331
  function createIkiMcpServer() {
2083
- const server = new import_mcp.McpServer({ name: "iki", version: "0.19.0" });
2332
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.20.0" });
2084
2333
  server.registerTool(
2085
2334
  "validate_iki",
2086
2335
  {
@@ -2145,7 +2394,7 @@ function createIkiMcpServer() {
2145
2394
  server.registerTool(
2146
2395
  "auto_rig_from_layers",
2147
2396
  {
2148
- description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R, mouth required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, etc. optional; an arm needs the body) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given.",
2397
+ description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R, mouth required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, etc. optional; an arm needs the body, and a pose forearm needs its arm) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given.",
2149
2398
  inputSchema: {
2150
2399
  layers: import_zod.z.array(
2151
2400
  import_zod.z.object({
@@ -2200,13 +2449,13 @@ function createIkiMcpServer() {
2200
2449
  server.registerTool(
2201
2450
  "compose_layers_from_parts",
2202
2451
  {
2203
- description: "Composes AI-generated part PNGs into canvas-aligned, role-named PNG layers on disk, ready for auto_rig_from_layers (the eyewhite split, alpha-trim/white-key, and placement pipeline the character-generation skill needs), with the same geometry report measure_layers returns standalone included inline. face, mouth, eyewhite, iris, brow, hair_front are required; hair_back, body, mouth_open, blush (one blush.png makes the blush_L/blush_R pair) and nose are optional \u2014 without a nose layer the head still turns on the rig's default profile, but it has no nose to lead the turn, and `auto_rig_from_layers` fits no turn to the art (`turnTargets` is inert, no `turn` report). One arm.png \u2014 the arm on the screen LEFT, drawn hanging with its shoulder at the top \u2014 makes both arms of a full body: arm_R takes it as drawn and arm_L mirrored. The arms are opt-in: without arm.png the compose is a bust's and `skipped` never lists them. arm.png needs body.png, and each arm is hung on the body's shoulder by default (see `layout`). The inline report carries the full-body checks too: a body whose feet a tall canvas's bottom cuts off, an arm without a body, and an arm whose shoulder cap does not reach under the torso's edge. A nose whose dense core is a speck \u2014 under a quarter of its trimmed part's width or height, such as a lone nostril mark or highlight \u2014 is sized and placed whole, and the inline report warns of it. A light mark drawn detached above the eye white, such as a double-eyelid crease, is dropped from the sclera (the iris's clip); dark strokes there stay lash ink. The eyewhite's dark lower lid \u2014 its line and lashes \u2014 becomes lash_lower_L/lash_lower_R, drawn over the iris; a white with none writes none and lists them in `skipped`.",
2452
+ description: "Composes AI-generated part PNGs into canvas-aligned, role-named PNG layers on disk, ready for auto_rig_from_layers (the eyewhite split, alpha-trim/white-key, and placement pipeline the character-generation skill needs), with the same geometry report measure_layers returns standalone included inline. face, mouth, eyewhite, iris, brow, hair_front are required; hair_back, body, mouth_open, blush (one blush.png makes the blush_L/blush_R pair) and nose are optional \u2014 without a nose layer the head still turns on the rig's default profile, but it has no nose to lead the turn, and `auto_rig_from_layers` fits no turn to the art (`turnTargets` is inert, no `turn` report). One arm.png \u2014 the arm on the screen LEFT, drawn hanging with its shoulder at the top \u2014 makes both arms of a full body: arm_R takes it as drawn and arm_L mirrored. The arms are opt-in: without arm.png the compose is a bust's and `skipped` never lists them. arm.png needs body.png, and each arm is hung on the body's shoulder by default (see `layout`). One forearm_pose.png \u2014 the arm's forearm raised, on the screen LEFT, standing up from its elbow with the hand at the top \u2014 makes both pose forearms (forearm_pose_R as drawn, forearm_pose_L mirrored): each is scaled so its elbow end is as wide as its arm's elbow run and pinned on that arm's elbow (see `layout`), and it needs arm.png. With one, preview-pose.png shows the switch at 1 as the rig draws it (the hanging forearms hidden below the elbow, the pose forearms over everything) while preview.png stays the rest pose; without one it is removed. The inline report carries the full-body checks too: a body whose feet a tall canvas's bottom cuts off, an arm without a body, an arm whose shoulder cap does not reach under the torso's edge, and a pose forearm without its arm or off its arm's elbow in pivot, width or length. A nose whose dense core is a speck \u2014 under a quarter of its trimmed part's width or height, such as a lone nostril mark or highlight \u2014 is sized and placed whole, and the inline report warns of it. A light mark drawn detached above the eye white, such as a double-eyelid crease, is dropped from the sclera (the iris's clip); dark strokes there stay lash ink. The eyewhite's dark lower lid \u2014 its line and lashes \u2014 becomes lash_lower_L/lash_lower_R, drawn over the iris; a white with none writes none and lists them in `skipped`.",
2204
2453
  inputSchema: {
2205
2454
  partsDir: import_zod.z.string().describe(
2206
2455
  "Directory of the source part PNGs (resolved against cwd)."
2207
2456
  ),
2208
2457
  outDir: import_zod.z.string().describe(
2209
- "Existing directory to write the role layer PNGs + preview.png into (resolved against cwd; must already exist; confined to the working directory). Reused across runs: a role this run does not write \u2014 one it skips, or an arm once arm.png is gone \u2014 has its stale PNG from an earlier run deleted."
2458
+ "Existing directory to write the role layer PNGs + preview.png (and preview-pose.png when there is a forearm_pose.png) into (resolved against cwd; must already exist; confined to the working directory). Reused across runs: a role this run does not write \u2014 one it skips, or an arm or pose forearm once arm.png or forearm_pose.png is gone, preview-pose.png included \u2014 has its stale PNG from an earlier run deleted."
2210
2459
  ),
2211
2460
  layout: import_zod.z.record(
2212
2461
  import_zod.z.string(),
@@ -2217,10 +2466,10 @@ function createIkiMcpServer() {
2217
2466
  h: import_zod.z.number()
2218
2467
  }).partial()
2219
2468
  ).optional().describe(
2220
- "Per-role override merged over the built-in defaults, keyed by role \u2014 hair_back, body, arm_L, arm_R, face, blush_L, blush_R, nose, mouth, mouth_open, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front \u2014 e.g. `{ eye_L: { cx: 660 } }`. `w` is an integer in 1..1100 (the canvas width) and `h` in 1..canvasHeight; omit `h` to keep the part's own aspect, set it to stretch. The defaults of the face's features \u2014 blush, nose, mouth, mouth_open, eyes, irises, lashes, brows \u2014 are proportions of the face: an override of face.cx, face.cy or face.w carries them with it (scaled by the width; face.h stretches the face alone), while a feature's own override names canvas px. The nose is sized and placed by its dense core (its pixels at alpha >= 128, the drawing inside a soft nose's feather), not its whole part: `w`/`h` size the core, `cx` centres it, and a set `cy` centres its rows. A nose whose core is a speck \u2014 under a quarter of the trimmed part's width or height, such as a lone nostril mark or highlight \u2014 is sized and placed whole instead, and the report warns of it. Its `cy` defaults to unset, which lands the core's bottom row (the tip) 0.66 of the way from the eye row down to the mouth's, so the nose follows a retuned eye or mouth row. eye_L/lash_L and eye_R/lash_R are cut from one eyewhite into one frame, so each pair must land on the same frame \u2014 a pair set to land apart is rejected. lash_lower_L/lash_lower_R are cut from it too and have no key: they land on their eye's frame. arm_L/arm_R have no cx/cy/w defaults: an unset `w` is 0.4 of the placed body's width, and an unset `cx` or `cy` hangs the arm's shoulder pivot \u2014 the one auto_rig_from_layers turns it about \u2014 on the body box's shoulder corner on that axis: its left edge for arm_R, its right edge for arm_L, 0.12 of its height under its top. A set one centres the arm as for every other role."
2469
+ "Per-role override merged over the built-in defaults, keyed by role \u2014 hair_back, body, arm_L, arm_R, face, blush_L, blush_R, nose, mouth, mouth_open, eye_L, eye_R, iris_L, iris_R, lash_L, lash_R, brow_L, brow_R, hair_front, forearm_pose_L, forearm_pose_R \u2014 e.g. `{ eye_L: { cx: 660 } }`. `w` is an integer in 1..1100 (the canvas width) and `h` in 1..canvasHeight; omit `h` to keep the part's own aspect, set it to stretch. The defaults of the face's features \u2014 blush, nose, mouth, mouth_open, eyes, irises, lashes, brows \u2014 are proportions of the face: an override of face.cx, face.cy or face.w carries them with it (scaled by the width; face.h stretches the face alone), while a feature's own override names canvas px. The nose is sized and placed by its dense core (its pixels at alpha >= 128, the drawing inside a soft nose's feather), not its whole part: `w`/`h` size the core, `cx` centres it, and a set `cy` centres its rows. A nose whose core is a speck \u2014 under a quarter of the trimmed part's width or height, such as a lone nostril mark or highlight \u2014 is sized and placed whole instead, and the report warns of it. Its `cy` defaults to unset, which lands the core's bottom row (the tip) 0.66 of the way from the eye row down to the mouth's, so the nose follows a retuned eye or mouth row. eye_L/lash_L and eye_R/lash_R are cut from one eyewhite into one frame, so each pair must land on the same frame \u2014 a pair set to land apart is rejected. lash_lower_L/lash_lower_R are cut from it too and have no key: they land on their eye's frame. arm_L/arm_R have no cx/cy/w defaults: an unset `w` is 0.4 of the placed body's width, and an unset `cx` or `cy` hangs the arm's shoulder pivot \u2014 the one auto_rig_from_layers turns it about \u2014 on the body box's shoulder corner on that axis: its left edge for arm_R, its right edge for arm_L, 0.12 of its height under its top. A set one centres the arm as for every other role. forearm_pose_L/forearm_pose_R have no cx/cy/w defaults either: an unset `w` scales the forearm so its elbow end (the shoulder rule run from its bottom) is as wide as the placed arm's elbow run, and an unset `cx` or `cy` pins that elbow end's pivot on the arm's elbow \u2014 the one auto_rig_from_layers hangs it from."
2221
2470
  ),
2222
2471
  mirrorParts: import_zod.z.array(import_zod.z.string()).optional().describe(
2223
- "Part files to flip left-right as they are read, e.g. `[\"eyewhite.png\"]`. The composer reads eyewhite.png as the eye on the screen LEFT (lash wing at the image's left end, lash-free tear duct at its right), brow.png as the brow on the screen RIGHT (thick head at the image's left end, tail at its right), blush.png as the blush on the screen LEFT (outer end, toward the face's edge, at the image's left end, inner end at its right), and arm.png as the arm on the screen LEFT (the character's right, hanging, its shoulder at the image's top); a part drawn the other way round is fixed here for free. It flips the source, so every role cut from it flips together and an eye's sclera and lash stay in one frame."
2472
+ "Part files to flip left-right as they are read, e.g. `[\"eyewhite.png\"]`. The composer reads eyewhite.png as the eye on the screen LEFT (lash wing at the image's left end, lash-free tear duct at its right), brow.png as the brow on the screen RIGHT (thick head at the image's left end, tail at its right), blush.png as the blush on the screen LEFT (outer end, toward the face's edge, at the image's left end, inner end at its right), arm.png as the arm on the screen LEFT (the character's right, hanging, its shoulder at the image's top), and forearm_pose.png as the raised forearm on the screen LEFT (standing up from its elbow, the hand at the image's top, the thumb toward the body at the image's right); a part drawn the other way round is fixed here for free. It flips the source, so every role cut from it flips together and an eye's sclera and lash stay in one frame."
2224
2473
  ),
2225
2474
  canvasHeight: import_zod.z.number().optional().describe(
2226
2475
  "The canvas's height in px: an even integer in 1100..4096, default 1100 (a square bust canvas; at 1100 every output is byte-identical to leaving it out). The width stays 1100. The canvas grows downward: every default and every override keeps its canvas px from the top-left, so the head lands where it does on a bust and a full body gets room below. An odd height is refused \u2014 model space is centred on the canvas, so it would put the head on a half pixel \u2014 and it is checked before any part decodes."
@@ -2248,7 +2497,7 @@ function createIkiMcpServer() {
2248
2497
  server.registerTool(
2249
2498
  "measure_layers",
2250
2499
  {
2251
- description: "Reports read-only geometry checks over an already-composed layers directory \u2014 the same checks compose_layers_from_parts returns inline (iris ratio/offset, eye aspect, cropped/cut edges, a nose whose dense core is a speck of its crop, missing optional roles, a body whose feet a tall canvas's bottom cuts off, an arm without a body, an arm whose shoulder cap does not reach under the torso's edge on its shoulder pivot's row). Every preview*.png is skipped. Use to re-check a layers dir without recomposing. Its nose check reads the composed file against its crop, which is what auto_rig_from_layers acts on. Compose's inline report does the same unless the composer found the source part's core a speck, which it reports instead \u2014 so a speck that resampling erased from the layer shows there and not here.",
2500
+ description: "Reports read-only geometry checks over an already-composed layers directory \u2014 the same checks compose_layers_from_parts returns inline (iris ratio/offset, eye aspect, cropped/cut edges, a nose whose dense core is a speck of its crop, missing optional roles, a body whose feet a tall canvas's bottom cuts off, an arm without a body, an arm whose shoulder cap does not reach under the torso's edge on its shoulder pivot's row, a pose forearm without its arm or whose elbow end is off its arm's elbow in pivot, width or length). Every preview*.png is skipped. Use to re-check a layers dir without recomposing. Its nose check reads the composed file against its crop, which is what auto_rig_from_layers acts on. Compose's inline report does the same unless the composer found the source part's core a speck, which it reports instead \u2014 so a speck that resampling erased from the layer shows there and not here.",
2252
2501
  inputSchema: {
2253
2502
  layersDir: import_zod.z.string().describe(
2254
2503
  "Directory of role-named layer PNGs (resolved against cwd)."