@ikijs/mcp 0.10.0 → 0.11.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
@@ -254,6 +254,24 @@ var BG_HUE_MAX = 260;
254
254
  var BG_SAT_MAX = 0.2;
255
255
  var BG_V_MIN = 0.55;
256
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
+ }
257
275
  function rgbToHsv(r, g, b) {
258
276
  r /= 255;
259
277
  g /= 255;
@@ -775,6 +793,19 @@ function facePlateHalfOf(layers) {
775
793
  return face.cropW / 2;
776
794
  }
777
795
  var STRAND_MIN_RUN_FRACTION = 0.5;
796
+ var LOSSLESS_PAGE_ROLE = "nose";
797
+ async function renderAtlasPage(crops, quantizeColors) {
798
+ const layout = (0, import_editor2.packAtlas)(
799
+ crops.map((c) => ({ id: c.id, width: c.width, height: c.height }))
800
+ );
801
+ if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {
802
+ throw new AutoRigInputError(
803
+ `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`
804
+ );
805
+ }
806
+ const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);
807
+ return { crops, layout, dataUri };
808
+ }
778
809
  async function autoRigFromLayers(input) {
779
810
  try {
780
811
  const layers = input.layers;
@@ -886,10 +917,14 @@ async function autoRigFromLayers(input) {
886
917
  );
887
918
  }
888
919
  layer.rowHalfWidths = rowHalfWidths;
920
+ } else if (role === "nose") {
921
+ const core = denseCoreOf(png.rgba, canvasW, canvasH);
922
+ if (core !== null) layer.denseCore = core;
889
923
  }
890
924
  layerInputs.push(layer);
891
925
  crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
892
926
  }
927
+ const noseCore = layerInputs.find((l) => l.role === "nose")?.denseCore;
893
928
  const eyeRow = eyeRowOf(layerInputs);
894
929
  const span = foregroundSpan(
895
930
  opaque,
@@ -999,46 +1034,58 @@ async function autoRigFromLayers(input) {
999
1034
  throw new AutoRigInputError(e.message);
1000
1035
  }
1001
1036
  const doc = new import_editor2.EditorDocument(model);
1002
- const layout = (0, import_editor2.packAtlas)(
1003
- crops.map((c) => ({ id: c.id, width: c.width, height: c.height }))
1004
- );
1005
- if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {
1006
- throw new AutoRigInputError(
1007
- `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`
1008
- );
1009
- }
1010
- const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);
1011
- if (dataUri.length > MAX_OUTPUT_BYTES) {
1037
+ const losslessCrop = quantizeColors === void 0 ? void 0 : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);
1038
+ const pages = losslessCrop === void 0 ? [await renderAtlasPage(crops, quantizeColors)] : [
1039
+ await renderAtlasPage(
1040
+ crops.filter((c) => c !== losslessCrop),
1041
+ quantizeColors
1042
+ ),
1043
+ await renderAtlasPage([losslessCrop], void 0)
1044
+ ];
1045
+ const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);
1046
+ if (atlasBytes > MAX_OUTPUT_BYTES) {
1012
1047
  throw new AutoRigInputError(
1013
- `atlas data URI ${dataUri.length} bytes exceeds ${MAX_OUTPUT_BYTES}`
1048
+ `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`
1014
1049
  );
1015
1050
  }
1016
- const partTextureAssignments = crops.map((crop) => {
1017
- const placement2 = layout.placements.find((p) => p.id === crop.id);
1018
- if (placement2 === void 0) {
1019
- throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
1020
- }
1021
- return {
1022
- partId: crop.id,
1023
- uv: (0, import_editor2.uvRectFor)(placement2, {
1024
- width: layout.pageWidth,
1025
- height: layout.pageHeight
1026
- })
1027
- };
1051
+ const partTextureAssignments = pages.flatMap(
1052
+ ({ crops: pageCrops, layout }) => pageCrops.map((crop) => {
1053
+ const placement2 = layout.placements.find((p) => p.id === crop.id);
1054
+ if (placement2 === void 0) {
1055
+ throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
1056
+ }
1057
+ return {
1058
+ partId: crop.id,
1059
+ uv: (0, import_editor2.uvRectFor)(placement2, {
1060
+ width: layout.pageWidth,
1061
+ height: layout.pageHeight
1062
+ })
1063
+ };
1064
+ })
1065
+ );
1066
+ doc.applyAtlas({
1067
+ textures: [{ source: pages[0].dataUri }],
1068
+ partTextureAssignments
1028
1069
  });
1029
- doc.applyAtlas({ textures: [{ source: dataUri }], partTextureAssignments });
1030
- const finalModel = (0, import_format.parseIkiModel)(doc.getModel());
1070
+ let patched = doc.getModel();
1071
+ if (losslessCrop !== void 0) {
1072
+ patched = structuredClone(patched);
1073
+ patched.textures = pages.map((p) => ({ source: p.dataUri }));
1074
+ patched.parts.find((p) => p.id === losslessCrop.id).texture.index = 1;
1075
+ }
1076
+ const finalModel = (0, import_format.parseIkiModel)(patched);
1031
1077
  writeFileAtomic(outPath, JSON.stringify(finalModel));
1032
1078
  return {
1033
1079
  ok: true,
1034
1080
  path: outPath,
1035
1081
  canvas: { width: canvasW, height: canvasH },
1036
1082
  partCount: finalModel.parts.length,
1037
- atlasBytes: dataUri.length,
1083
+ atlasBytes,
1038
1084
  ...headHalfWidth === void 0 ? {} : { headHalfWidth },
1039
1085
  headHalfWidthApplied,
1040
1086
  ...headEdges === void 0 ? {} : { headEdges },
1041
1087
  ...strandEdges === void 0 ? {} : { strandEdges },
1088
+ ...noseCore === void 0 ? {} : { noseCore },
1042
1089
  ...turn === void 0 ? {} : { turn }
1043
1090
  };
1044
1091
  } catch (err) {
@@ -1325,6 +1372,7 @@ var IRIS_W = Math.round(EYE_W * 0.5625);
1325
1372
  var EYEWHITE_SRC = "eyewhite.png";
1326
1373
  var EYE_LASH_LUMA = 120;
1327
1374
  var LASH_KEEP_FRACTION = 0.5;
1375
+ var NOSE_TIP_AT = 0.86;
1328
1376
  var DEFAULT_LAYOUT = {
1329
1377
  // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir
1330
1378
  // without them still composes (head-only character).
@@ -1336,9 +1384,11 @@ var DEFAULT_LAYOUT = {
1336
1384
  face: { src: "face.png", cx: 550, cy: 475, w: 400 },
1337
1385
  // The nose, drawn on its own (the face is drawn without one): the auto-rig
1338
1386
  // leads the head turn with it and keys the other features' slide on its
1339
- // presence, so without it the features stay on the face plate. Sits between
1340
- // the eyes and above the mouth. OPTIONAL: a parts dir without it composes.
1341
- nose: { src: "nose.png", cx: 550, cy: 586, w: 40, optional: true },
1387
+ // presence, so without it the features stay on the face plate. `w` is the
1388
+ // width of its dense core, and it has no `cy`: its row comes from the tip
1389
+ // rule (NOSE_TIP_AT), between the eyes and the mouth, so it follows them
1390
+ // when they are retuned. OPTIONAL: a parts dir without it composes.
1391
+ nose: { src: "nose.png", cx: 550, w: 40, optional: true },
1342
1392
  mouth: { src: "mouth.png", cx: 550, cy: 619, w: 68 },
1343
1393
  // Cross-fades with `mouth` on ParamMouthOpenY (opacity, not scaleY) once the
1344
1394
  // auto-rig sees both roles. Same cx/w as `mouth` so the lip width matches;
@@ -1409,7 +1459,7 @@ function resolveLayout(overrides) {
1409
1459
  );
1410
1460
  }
1411
1461
  if (override === void 0) continue;
1412
- const next = { ...resolved[role] };
1462
+ const set = {};
1413
1463
  for (const field of ["cx", "cy"]) {
1414
1464
  const value = override[field];
1415
1465
  if (value === void 0) continue;
@@ -1418,7 +1468,7 @@ function resolveLayout(overrides) {
1418
1468
  `layout.${role}.${field} must be a finite number, got ${String(value)}`
1419
1469
  );
1420
1470
  }
1421
- next[field] = value;
1471
+ set[field] = value;
1422
1472
  }
1423
1473
  for (const field of ["w", "h"]) {
1424
1474
  const value = override[field];
@@ -1428,9 +1478,11 @@ function resolveLayout(overrides) {
1428
1478
  `layout.${role}.${field} must be an integer in 1..${CANVAS}, got ${String(value)}`
1429
1479
  );
1430
1480
  }
1431
- next[field] = value;
1481
+ set[field] = value;
1432
1482
  }
1433
- resolved[role] = next;
1483
+ const key = role;
1484
+ if (key === "nose") resolved.nose = { ...resolved.nose, ...set };
1485
+ else resolved[key] = { ...resolved[key], ...set };
1434
1486
  }
1435
1487
  return resolved;
1436
1488
  }
@@ -1455,6 +1507,15 @@ function keyWhiteToAlpha(rgba) {
1455
1507
  }
1456
1508
  return keyed;
1457
1509
  }
1510
+ async function coreOf(png) {
1511
+ const { data, info } = await (0, import_sharp2.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1512
+ return denseCoreOf(data, info.width, info.height) ?? {
1513
+ x: 0,
1514
+ y: 0,
1515
+ w: info.width,
1516
+ h: info.height
1517
+ };
1518
+ }
1458
1519
  async function partBuffer(role, cfg, partsDir, inMemory, flipSource) {
1459
1520
  let img;
1460
1521
  if (inMemory !== void 0) {
@@ -1475,33 +1536,56 @@ async function partBuffer(role, cfg, partsDir, inMemory, flipSource) {
1475
1536
  if (!cfg.noTrim) img = img.trim({ threshold: 12 });
1476
1537
  if ((cfg.mirror ?? false) !== flipSource) img = img.flop();
1477
1538
  const trimmed = await img.png().toBuffer({ resolveWithObject: true });
1478
- if (cfg.h === void 0) {
1479
- const scaledH = Math.round(
1480
- trimmed.info.height * cfg.w / trimmed.info.width
1539
+ const { width: trimmedW, height: trimmedH } = trimmed.info;
1540
+ const sized = role === "nose" ? await coreOf(trimmed.data) : { x: 0, y: 0, w: trimmedW, h: trimmedH };
1541
+ const width = Math.round(trimmedW * cfg.w / sized.w);
1542
+ const height = cfg.h === void 0 ? Math.round(trimmedH * width / trimmedW) : Math.round(trimmedH * cfg.h / sized.h);
1543
+ if (width > CANVAS || height > CANVAS) {
1544
+ const field = width > CANVAS || cfg.h === void 0 ? "w" : "h";
1545
+ throw new AutoRigInputError(
1546
+ `layout.${role}.${field}: resized part ${width}x${height} exceeds the ${CANVAS} canvas`
1481
1547
  );
1482
- if (scaledH > CANVAS) {
1483
- throw new AutoRigInputError(
1484
- `layout.${role}.w: resized part ${cfg.w}x${scaledH} exceeds the ${CANVAS} canvas`
1485
- );
1486
- }
1487
1548
  }
1488
- const resized = await (0, import_sharp2.default)(trimmed.data).resize(
1489
- cfg.h === void 0 ? { width: cfg.w } : { width: cfg.w, height: cfg.h, fit: "fill" }
1490
- ).png().toBuffer({ resolveWithObject: true });
1549
+ const resized = await (0, import_sharp2.default)(trimmed.data).resize(cfg.h === void 0 ? { width } : { width, height, fit: "fill" }).png().toBuffer({ resolveWithObject: true });
1491
1550
  return {
1492
1551
  buf: resized.data,
1493
1552
  w: resized.info.width,
1494
1553
  h: resized.info.height
1495
1554
  };
1496
1555
  }
1497
- function placement(role, cfg, w, h) {
1498
- const left = Math.round(cfg.cx - w / 2);
1499
- const top = Math.round(cfg.cy - h / 2);
1556
+ function assertOnCanvas(source, w, h, left, top) {
1500
1557
  if (left + w <= 0 || top + h <= 0 || left >= CANVAS || top >= CANVAS) {
1501
1558
  throw new AutoRigInputError(
1502
- `layout.${role}.cx/cy: the placed part (${w}x${h} at ${left},${top}) falls entirely outside the ${CANVAS} canvas`
1559
+ `${source}: the placed part (${w}x${h} at ${left},${top}) falls entirely outside the ${CANVAS} canvas`
1503
1560
  );
1504
1561
  }
1562
+ }
1563
+ function placement(role, cfg, w, h) {
1564
+ const left = Math.round(cfg.cx - w / 2);
1565
+ const top = Math.round(cfg.cy - h / 2);
1566
+ assertOnCanvas(`layout.${role}.cx/cy`, w, h, left, top);
1567
+ return { left, top };
1568
+ }
1569
+ function nosePlacement(layout, core, w, h) {
1570
+ const { cx, cy } = layout.nose;
1571
+ const left = Math.round(cx - (core.x + core.w / 2));
1572
+ let top;
1573
+ if (cy !== void 0) {
1574
+ top = Math.round(cy - (core.y + core.h / 2));
1575
+ } else {
1576
+ const eyeRow = (layout.eye_L.cy + layout.eye_R.cy) / 2;
1577
+ const tipRow = Math.round(
1578
+ eyeRow + NOSE_TIP_AT * (layout.mouth.cy - eyeRow)
1579
+ );
1580
+ top = tipRow - (core.y + core.h - 1);
1581
+ }
1582
+ assertOnCanvas(
1583
+ cy !== void 0 ? "layout.nose.cx/cy" : "layout.nose.cx/cy (cy unset: its tip row comes from layout.eye_L/eye_R/mouth.cy)",
1584
+ w,
1585
+ h,
1586
+ left,
1587
+ top
1588
+ );
1505
1589
  return { left, top };
1506
1590
  }
1507
1591
  function blankCanvas() {
@@ -1593,7 +1677,7 @@ async function composeLayersFromParts(input) {
1593
1677
  skipped.push(role);
1594
1678
  continue;
1595
1679
  }
1596
- const { left, top } = placement(role, cfg, part.w, part.h);
1680
+ const { left, top } = role === "nose" ? nosePlacement(layout, await coreOf(part.buf), part.w, part.h) : placement(role, layout[role], part.w, part.h);
1597
1681
  if (role === "lash_L" || role === "lash_R") {
1598
1682
  const eyeRole = role === "lash_L" ? "eye_L" : "eye_R";
1599
1683
  const eye = placed.find((p) => p.role === eyeRole);
@@ -1651,7 +1735,7 @@ async function composeLayersFromParts(input) {
1651
1735
 
1652
1736
  // src/server.ts
1653
1737
  function createIkiMcpServer() {
1654
- const server = new import_mcp.McpServer({ name: "iki", version: "0.10.0" });
1738
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.11.0" });
1655
1739
  server.registerTool(
1656
1740
  "validate_iki",
1657
1741
  {
@@ -1730,7 +1814,7 @@ function createIkiMcpServer() {
1730
1814
  "Output .iki path (resolved against cwd; parent dir must exist)."
1731
1815
  ),
1732
1816
  quantizeColors: import_zod.z.number().int().min(2).max(256).optional().describe(
1733
- "Palette-quantize the atlas PNG to this many colours (2..256). Flat-shaded art keeps its look at 256 and the model shrinks to about a quarter; omit for lossless."
1817
+ "Palette-quantize the atlas PNG to this many colours (2..256). Flat-shaded art keeps its look at 256 and the model shrinks to about a quarter; omit for lossless. A `nose` layer stays lossless on a second atlas page of its own, since the palette rims a soft-shaded nose's feather; the nose's own lossless page adds a content-dependent amount, since splitting it off also changes how page 0 re-quantizes without it; the result's `atlasBytes` sums both pages."
1734
1818
  ),
1735
1819
  turnTargets: import_zod.z.object({
1736
1820
  eyeShift: import_zod.z.number().optional(),
@@ -1778,7 +1862,7 @@ function createIkiMcpServer() {
1778
1862
  h: import_zod.z.number()
1779
1863
  }).partial()
1780
1864
  ).optional().describe(
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."
1865
+ "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. 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. Its `cy` defaults to unset, which lands the core's bottom row (the tip) 0.86 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."
1782
1866
  ),
1783
1867
  mirrorParts: import_zod.z.array(import_zod.z.string()).optional().describe(
1784
1868
  "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."