@ikijs/mcp 0.8.1 → 0.10.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
@@ -774,6 +774,7 @@ function facePlateHalfOf(layers) {
774
774
  }
775
775
  return face.cropW / 2;
776
776
  }
777
+ var STRAND_MIN_RUN_FRACTION = 0.5;
777
778
  async function autoRigFromLayers(input) {
778
779
  try {
779
780
  const layers = input.layers;
@@ -810,6 +811,7 @@ async function autoRigFromLayers(input) {
810
811
  const layerInputs = [];
811
812
  const crops = [];
812
813
  const rowSpansByRole = [];
814
+ let hairFrontMask;
813
815
  for (let i = 0; i < resolvedLayers.length; i++) {
814
816
  const { resolved, fileName } = resolvedLayers[i];
815
817
  const png = await decodePng(resolved);
@@ -854,16 +856,19 @@ async function autoRigFromLayers(input) {
854
856
  const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);
855
857
  const rowLeft = new Int32Array(canvasH).fill(canvasW);
856
858
  const rowRight = new Int32Array(canvasH).fill(-1);
859
+ const ownMask = role === "hair_front" ? new Uint8Array(canvasW * canvasH) : void 0;
857
860
  for (let y = 0; y < canvasH; y++) {
858
861
  for (let x = 0; x < canvasW; x++) {
859
862
  const p = y * canvasW + x;
860
863
  if (png.rgba[p * 4 + 3] < ALPHA_OPAQUE) continue;
861
864
  opaque[p] = 1;
865
+ if (ownMask !== void 0) ownMask[p] = 1;
862
866
  if (x < rowLeft[y]) rowLeft[y] = x;
863
867
  if (x > rowRight[y]) rowRight[y] = x;
864
868
  }
865
869
  }
866
870
  rowSpansByRole.push({ role, rowLeft, rowRight });
871
+ if (ownMask !== void 0) hairFrontMask = ownMask;
867
872
  const layer = {
868
873
  role,
869
874
  fileName,
@@ -909,6 +914,63 @@ async function autoRigFromLayers(input) {
909
914
  }
910
915
  headEdges = { left, right };
911
916
  }
917
+ let strandEdges;
918
+ 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));
919
+ if (hairFrontMask !== void 0 && irisLayers.length === 2) {
920
+ const mask = hairFrontMask;
921
+ const half = canvasW / 2;
922
+ const strandOn = (iris, other, side) => {
923
+ const r = Math.floor(iris.bbox.y + iris.bbox.h / 2);
924
+ const centre = iris.bbox.x + iris.bbox.w / 2;
925
+ const otherX = other.bbox.x + other.bbox.w / 2 - half;
926
+ const c = side < 0 ? Math.ceil(centre) - 1 : Math.floor(centre);
927
+ const span2 = rowSpansByRole.find((s) => s.role === iris.role);
928
+ if (span2.rowRight[r] < span2.rowLeft[r]) return void 0;
929
+ const minRun = STRAND_MIN_RUN_FRACTION * (span2.rowRight[r] + 1 - span2.rowLeft[r]);
930
+ const strand = new Uint8Array(canvasW);
931
+ for (let a = 0; a < canvasW; ) {
932
+ if (mask[r * canvasW + a] !== 1) {
933
+ a++;
934
+ continue;
935
+ }
936
+ let b = a;
937
+ while (b < canvasW && mask[r * canvasW + b] === 1) b++;
938
+ if (b - a >= minRun) strand.fill(1, a, b);
939
+ a = b;
940
+ }
941
+ const strandAt = (x2) => x2 >= 0 && x2 < canvasW && strand[x2] === 1;
942
+ const outerBoundary = (x2) => (side < 0 ? x2 : x2 + 1) - half;
943
+ let x = c;
944
+ let runFace;
945
+ if (!strandAt(c)) {
946
+ while (x >= 0 && x < canvasW && !strandAt(x)) x += side;
947
+ if (x < 0 || x >= canvasW) return void 0;
948
+ runFace = outerBoundary(x - side);
949
+ } else {
950
+ let f = c - side;
951
+ while (strandAt(f)) f -= side;
952
+ const face = outerBoundary(f);
953
+ runFace = side * (face - otherX) > 0 ? face : null;
954
+ }
955
+ while (strandAt(x)) x += side;
956
+ return {
957
+ y: canvasH / 2 - (r + 0.5),
958
+ irisOuter: (side < 0 ? span2.rowLeft[r] : span2.rowRight[r] + 1) - half,
959
+ irisInner: (side < 0 ? span2.rowRight[r] + 1 : span2.rowLeft[r]) - half,
960
+ runOuter: outerBoundary(x - side),
961
+ runFace
962
+ };
963
+ };
964
+ const [low, high] = irisLayers;
965
+ const left = strandOn(low, high, -1);
966
+ const right = strandOn(high, low, 1);
967
+ if (left !== void 0 || right !== void 0) {
968
+ strandEdges = {
969
+ ...left === void 0 ? {} : { left },
970
+ ...right === void 0 ? {} : { right }
971
+ };
972
+ }
973
+ }
912
974
  let turn;
913
975
  let model;
914
976
  try {
@@ -928,7 +990,8 @@ async function autoRigFromLayers(input) {
928
990
  onTurnSolved: (report) => {
929
991
  turn = report;
930
992
  },
931
- ...headEdges === void 0 ? {} : { headEdges }
993
+ ...headEdges === void 0 ? {} : { headEdges },
994
+ ...strandEdges === void 0 ? {} : { strandEdges }
932
995
  }
933
996
  );
934
997
  } catch (e) {
@@ -975,6 +1038,7 @@ async function autoRigFromLayers(input) {
975
1038
  ...headHalfWidth === void 0 ? {} : { headHalfWidth },
976
1039
  headHalfWidthApplied,
977
1040
  ...headEdges === void 0 ? {} : { headEdges },
1041
+ ...strandEdges === void 0 ? {} : { strandEdges },
978
1042
  ...turn === void 0 ? {} : { turn }
979
1043
  };
980
1044
  } catch (err) {
@@ -998,7 +1062,8 @@ var EYE_ASPECT_MIN = 0.5;
998
1062
  var IRIS_OFFSET_MAX_X = 3;
999
1063
  var IRIS_OFFSET_MAX_Y = 10;
1000
1064
  var EDGE_SOLID_MAX = 0.5;
1001
- var LASH_CENTRE_TOL_FRAC = 0.03;
1065
+ var LASH_STRAY_TOL_FRAC = 0.02;
1066
+ var EYE_FACING_TOL_FRAC = 0.02;
1002
1067
  var EDGE_RUN_MIN_PX = 40;
1003
1068
  var FLAT_CUT_MAX_FRAC = 0.1;
1004
1069
  var FLAT_CUT_MIN_PX = 40;
@@ -1079,6 +1144,21 @@ async function layerStats(filePath) {
1079
1144
  };
1080
1145
  }
1081
1146
  var pct = (v) => `${(v * 100).toFixed(0)}%`;
1147
+ async function lashOffSclera(eyePath, lashPath) {
1148
+ const eye = await decodePng(eyePath);
1149
+ const lash = await decodePng(lashPath);
1150
+ let opaque = 0;
1151
+ let off = 0;
1152
+ for (let y = 0; y < lash.height; y++) {
1153
+ for (let x = 0; x < lash.width; x++) {
1154
+ if (lash.rgba[(y * lash.width + x) * 4 + 3] < 128) continue;
1155
+ opaque++;
1156
+ const onEye = x < eye.width && y < eye.height;
1157
+ if (!onEye || eye.rgba[(y * eye.width + x) * 4 + 3] <= 8) off++;
1158
+ }
1159
+ }
1160
+ return { opaque, off };
1161
+ }
1082
1162
  async function measureDir(absDir) {
1083
1163
  const files = import_node_fs2.default.readdirSync(absDir).filter((f) => f.endsWith(".png") && f !== "preview.png").sort();
1084
1164
  if (files.length === 0) {
@@ -1160,12 +1240,28 @@ async function measureDir(absDir) {
1160
1240
  }
1161
1241
  }
1162
1242
  if (lash) {
1163
- const dx = lash.bboxCx - eye.bboxCx;
1243
+ const { opaque, off } = await lashOffSclera(
1244
+ import_node_path4.default.join(absDir, `eye_${side}.png`),
1245
+ import_node_path4.default.join(absDir, `lash_${side}.png`)
1246
+ );
1164
1247
  const dTop = lash.marginTop - eye.marginTop;
1165
- if (Math.abs(dx) > eye.w * LASH_CENTRE_TOL_FRAC || Math.abs(dTop) > 0.5) {
1248
+ const faults = [
1249
+ ...off > opaque * LASH_STRAY_TOL_FRAC ? [`${off} of its ${opaque} opaque px lie off eye_${side}'s sclera`] : [],
1250
+ ...Math.abs(dTop) > 0.5 ? [`its top edge is ${dTop.toFixed(1)} px off the sclera's`] : []
1251
+ ];
1252
+ if (faults.length > 0) {
1166
1253
  warnings.push(
1167
- `lash_${side}: centre is ${dx.toFixed(1)} px and top edge ${dTop.toFixed(1)} px off eye_${side}. They are split from one source and MUST share cx/cy/w in layout, or the blink fold tears. Retune to match.`
1254
+ `lash_${side}: ${faults.join(" and ")} \u2014 they are split from one source and MUST share cx/cy/w/h in layout, or the blink fold tears. Retune to match.`
1168
1255
  );
1256
+ } else {
1257
+ const bareLeft = lash.marginLeft - eye.marginLeft;
1258
+ const bareRight = lash.marginRight - eye.marginRight;
1259
+ const [bareOuter, bareInner] = side === "R" ? [bareLeft, bareRight] : [bareRight, bareLeft];
1260
+ if ((bareOuter - bareInner) / eye.w > EYE_FACING_TOL_FRAC) {
1261
+ warnings.push(
1262
+ `eye_${side}: its lash stops ${pct(bareOuter / eye.w)} of the eye width short of the outer corner and ${pct(bareInner / eye.w)} short of the nose side \u2014 the eyewhite is drawn facing the other way, lash wing at the inner corner. 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. Free fix: compose again with mirrorParts: ["eyewhite.png"] \u2014 no regeneration.`
1263
+ );
1264
+ }
1169
1265
  }
1170
1266
  }
1171
1267
  }
@@ -1297,6 +1393,12 @@ var ORDER = [
1297
1393
  "brow_R",
1298
1394
  "hair_front"
1299
1395
  ];
1396
+ var PART_FILES = [
1397
+ ...new Set(
1398
+ Object.values(DEFAULT_LAYOUT).map((cfg) => cfg.src).filter((src) => !src.startsWith("eyewhite_"))
1399
+ ),
1400
+ EYEWHITE_SRC
1401
+ ];
1300
1402
  function resolveLayout(overrides) {
1301
1403
  const resolved = { ...DEFAULT_LAYOUT };
1302
1404
  if (overrides === void 0) return resolved;
@@ -1332,6 +1434,18 @@ function resolveLayout(overrides) {
1332
1434
  }
1333
1435
  return resolved;
1334
1436
  }
1437
+ function resolveMirrorParts(names) {
1438
+ const mirrored = /* @__PURE__ */ new Set();
1439
+ for (const [i, name] of (names ?? []).entries()) {
1440
+ if (!PART_FILES.includes(name)) {
1441
+ throw new AutoRigInputError(
1442
+ `mirrorParts[${i}]: unknown part ${JSON.stringify(name)} \u2014 expected one of ${PART_FILES.join(", ")}`
1443
+ );
1444
+ }
1445
+ mirrored.add(name);
1446
+ }
1447
+ return mirrored;
1448
+ }
1335
1449
  function keyWhiteToAlpha(rgba) {
1336
1450
  const keyed = Buffer.from(rgba);
1337
1451
  for (let i = 0; i < keyed.length; i += 4) {
@@ -1341,7 +1455,7 @@ function keyWhiteToAlpha(rgba) {
1341
1455
  }
1342
1456
  return keyed;
1343
1457
  }
1344
- async function partBuffer(role, cfg, partsDir, inMemory) {
1458
+ async function partBuffer(role, cfg, partsDir, inMemory, flipSource) {
1345
1459
  let img;
1346
1460
  if (inMemory !== void 0) {
1347
1461
  img = (0, import_sharp2.default)(inMemory);
@@ -1359,7 +1473,7 @@ async function partBuffer(role, cfg, partsDir, inMemory) {
1359
1473
  });
1360
1474
  }
1361
1475
  if (!cfg.noTrim) img = img.trim({ threshold: 12 });
1362
- if (cfg.mirror) img = img.flop();
1476
+ if ((cfg.mirror ?? false) !== flipSource) img = img.flop();
1363
1477
  const trimmed = await img.png().toBuffer({ resolveWithObject: true });
1364
1478
  if (cfg.h === void 0) {
1365
1479
  const scaledH = Math.round(
@@ -1456,28 +1570,47 @@ async function composeLayersFromParts(input) {
1456
1570
  );
1457
1571
  }
1458
1572
  const layout = resolveLayout(input.layout);
1573
+ const mirrored = resolveMirrorParts(input.mirrorParts);
1459
1574
  const split = await prepEyeSplit(partsDir);
1460
1575
  const splitSources = /* @__PURE__ */ new Map([
1461
1576
  ["eyewhite_sclera.png", split.sclera],
1462
1577
  ["eyewhite_lash.png", split.lash]
1463
1578
  ]);
1464
- const layers = [];
1579
+ const placed = [];
1465
1580
  const skipped = [];
1466
- const preview = [];
1467
1581
  for (const role of ORDER) {
1468
1582
  const cfg = layout[role];
1583
+ const inMemory = splitSources.get(cfg.src);
1469
1584
  const part = await partBuffer(
1470
1585
  role,
1471
1586
  cfg,
1472
1587
  partsDir,
1473
- splitSources.get(cfg.src)
1588
+ inMemory,
1589
+ // The split halves are cut from eyewhite.png, the file a caller names.
1590
+ mirrored.has(inMemory === void 0 ? cfg.src : EYEWHITE_SRC)
1474
1591
  );
1475
1592
  if (part === null) {
1476
1593
  skipped.push(role);
1477
- import_node_fs3.default.rmSync(import_node_path5.default.join(outDir, `${role}.png`), { force: true });
1478
1594
  continue;
1479
1595
  }
1480
1596
  const { left, top } = placement(role, cfg, part.w, part.h);
1597
+ if (role === "lash_L" || role === "lash_R") {
1598
+ const eyeRole = role === "lash_L" ? "eye_L" : "eye_R";
1599
+ const eye = placed.find((p) => p.role === eyeRole);
1600
+ if (eye !== void 0 && (eye.left !== left || eye.top !== top || eye.part.w !== part.w || eye.part.h !== part.h)) {
1601
+ throw new AutoRigInputError(
1602
+ `layout.${role} places the lash at ${part.w}x${part.h} (${left},${top}), but layout.${eyeRole} places its sclera at ${eye.part.w}x${eye.part.h} (${eye.left},${eye.top}) \u2014 they are cut from one eyewhite into one frame, and the blink fold tears where they part. Set cx/cy/w/h the same on both.`
1603
+ );
1604
+ }
1605
+ }
1606
+ placed.push({ role, part, left, top });
1607
+ }
1608
+ for (const role of skipped) {
1609
+ import_node_fs3.default.rmSync(import_node_path5.default.join(outDir, `${role}.png`), { force: true });
1610
+ }
1611
+ const layers = [];
1612
+ const preview = [];
1613
+ for (const { role, part, left, top } of placed) {
1481
1614
  const layer = await blankCanvas().composite([{ input: part.buf, left, top }]).png().toBuffer();
1482
1615
  const outPath = import_node_path5.default.join(outDir, `${role}.png`);
1483
1616
  writeFileAtomic(outPath, layer);
@@ -1518,7 +1651,7 @@ async function composeLayersFromParts(input) {
1518
1651
 
1519
1652
  // src/server.ts
1520
1653
  function createIkiMcpServer() {
1521
- const server = new import_mcp.McpServer({ name: "iki", version: "0.8.1" });
1654
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.10.0" });
1522
1655
  server.registerTool(
1523
1656
  "validate_iki",
1524
1657
  {
@@ -1606,7 +1739,7 @@ function createIkiMcpServer() {
1606
1739
  noseShift: import_zod.z.number().optional(),
1607
1740
  mouthShift: import_zod.z.number().optional()
1608
1741
  }).optional().describe(
1609
- "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 (the result's `turn.clamped` lists the ones that were, `turn.achieved` what the rig reaches); a target you DO pass that 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."
1742
+ "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."
1610
1743
  )
1611
1744
  }
1612
1745
  },
@@ -1645,7 +1778,10 @@ function createIkiMcpServer() {
1645
1778
  h: import_zod.z.number()
1646
1779
  }).partial()
1647
1780
  ).optional().describe(
1648
- "Per-role override merged over the built-in defaults, keyed by role \u2014 hair_back, body, face, 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` and `h` are integers in 1..1100; omit `h` to keep the part's own aspect, set it to stretch (set it on a sclera and its lash together, or the blink fold tears)."
1781
+ "Per-role override merged over the built-in defaults, keyed by role \u2014 hair_back, body, face, 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` and `h` are integers in 1..1100; omit `h` to keep the part's own aspect, set it to stretch. 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."
1782
+ ),
1783
+ mirrorParts: import_zod.z.array(import_zod.z.string()).optional().describe(
1784
+ "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) and brow.png as the brow on the screen RIGHT (thick head at the image's left end, tail at its 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."
1649
1785
  )
1650
1786
  }
1651
1787
  },