@ikijs/mcp 0.21.0 → 0.22.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/index.js CHANGED
@@ -650,17 +650,83 @@ async function autoRigFromLayers(input) {
650
650
 
651
651
  // src/compose.ts
652
652
  var import_node_fs3 = __toESM(require("fs"));
653
- var import_node_path6 = __toESM(require("path"));
654
- var import_sharp3 = __toESM(require("sharp"));
655
- var import_editor8 = require("@ikijs/editor");
653
+ var import_node_path7 = __toESM(require("path"));
654
+ var import_sharp4 = __toESM(require("sharp"));
655
+ var import_editor11 = require("@ikijs/editor");
656
+
657
+ // src/trim.ts
658
+ var import_editor3 = require("@ikijs/editor");
659
+ var TRIM_THRESHOLD = 12;
660
+ var STRAY_SPECK_FRACTION = 0.01;
661
+ function luma(rgba, i) {
662
+ return 0.299 * rgba[i] + 0.587 * rgba[i + 1] + 0.114 * rgba[i + 2];
663
+ }
664
+ function boxWithoutStraySpecks(rgba, W, H) {
665
+ const n = W * H;
666
+ let kept = 0;
667
+ for (let p = 0; p < n; p++) if (rgba[p * 4 + 3] > TRIM_THRESHOLD) kept++;
668
+ const visited = new Uint8Array(n);
669
+ let stack = new Int32Array(1024);
670
+ const drawing = [W, H, -1, -1];
671
+ const strays = [W, H, -1, -1];
672
+ let anyOpaque = false;
673
+ for (let start = 0; start < n; start++) {
674
+ if (visited[start] || rgba[start * 4 + 3] <= TRIM_THRESHOLD) continue;
675
+ let setLeft = W;
676
+ let setTop = H;
677
+ let setRight = -1;
678
+ let setBottom = -1;
679
+ let size = 0;
680
+ let opaque = false;
681
+ let depth = 0;
682
+ visited[start] = 1;
683
+ stack[depth++] = start;
684
+ while (depth > 0) {
685
+ const p = stack[--depth];
686
+ size++;
687
+ if (rgba[p * 4 + 3] >= import_editor3.ALPHA_OPAQUE) opaque = true;
688
+ const px2 = p % W;
689
+ const py = (p - px2) / W;
690
+ setLeft = Math.min(setLeft, px2);
691
+ setTop = Math.min(setTop, py);
692
+ setRight = Math.max(setRight, px2);
693
+ setBottom = Math.max(setBottom, py);
694
+ for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {
695
+ for (let x = Math.max(0, px2 - 1); x <= Math.min(W - 1, px2 + 1); x++) {
696
+ const q = y * W + x;
697
+ if (!visited[q] && rgba[q * 4 + 3] > TRIM_THRESHOLD) {
698
+ visited[q] = 1;
699
+ if (depth === stack.length) {
700
+ const grown = new Int32Array(Math.min(n, stack.length * 2));
701
+ grown.set(stack);
702
+ stack = grown;
703
+ }
704
+ stack[depth++] = q;
705
+ }
706
+ }
707
+ }
708
+ }
709
+ anyOpaque ||= opaque;
710
+ const into = !opaque && size < kept * STRAY_SPECK_FRACTION ? strays : drawing;
711
+ into[0] = Math.min(into[0], setLeft);
712
+ into[1] = Math.min(into[1], setTop);
713
+ into[2] = Math.max(into[2], setRight);
714
+ into[3] = Math.max(into[3], setBottom);
715
+ }
716
+ if (!anyOpaque || strays[2] < 0) return null;
717
+ const [left, top, right, bottom] = drawing;
718
+ if (strays[0] >= left && strays[1] >= top && strays[2] <= right && strays[3] <= bottom)
719
+ return null;
720
+ return { left, top, width: right - left + 1, height: bottom - top + 1 };
721
+ }
656
722
 
657
723
  // src/measure.ts
658
724
  var import_node_fs2 = __toESM(require("fs"));
659
- var import_node_path5 = __toESM(require("path"));
725
+ var import_node_path6 = __toESM(require("path"));
660
726
 
661
727
  // src/measure-arms.ts
662
728
  var import_node_path3 = __toESM(require("path"));
663
- var import_editor3 = require("@ikijs/editor");
729
+ var import_editor4 = require("@ikijs/editor");
664
730
  var ARM_ROLES = ["arm_L", "arm_R"];
665
731
  var CAP_OVERLAP = 0.5;
666
732
  var px = (v) => `${Number(v.toFixed(1))}`;
@@ -689,7 +755,7 @@ async function armWarnings(absDir, layers) {
689
755
  continue;
690
756
  }
691
757
  if (set === void 0) {
692
- const measurer = (0, import_editor3.createLayerSetMeasurer)({
758
+ const measurer = (0, import_editor4.createLayerSetMeasurer)({
693
759
  width: body.canvasW,
694
760
  height: body.canvasH
695
761
  });
@@ -697,12 +763,12 @@ async function armWarnings(absDir, layers) {
697
763
  }
698
764
  let g;
699
765
  try {
700
- g = (0, import_editor3.armGeometry)(
766
+ g = (0, import_editor4.armGeometry)(
701
767
  await measured(set.measurer, absDir, arm),
702
768
  set.body.bbox.x + set.body.bbox.w / 2 - body.canvasW / 2
703
769
  );
704
770
  } catch (err) {
705
- if (err instanceof import_editor3.LayerGeometryError) {
771
+ if (err instanceof import_editor4.LayerGeometryError) {
706
772
  warnings.push(
707
773
  `${arm}: ${err.message} \u2014 auto_rig_from_layers refuses it. Regenerate arm.png drawn hanging, shoulder at the top. Billed.`
708
774
  );
@@ -730,7 +796,7 @@ function capWarning(arm, g, body) {
730
796
  }
731
797
 
732
798
  // src/measure-forearm-pose.ts
733
- var import_editor4 = require("@ikijs/editor");
799
+ var import_editor5 = require("@ikijs/editor");
734
800
  var POSE_ROLES = ["forearm_pose_L", "forearm_pose_R"];
735
801
  var ARM_OF = {
736
802
  forearm_pose_L: "arm_L",
@@ -764,7 +830,7 @@ async function forearmPoseWarnings(absDir, layers) {
764
830
  continue;
765
831
  }
766
832
  if (layers.body === void 0) continue;
767
- const measurer = (0, import_editor4.createLayerSetMeasurer)({
833
+ const measurer = (0, import_editor5.createLayerSetMeasurer)({
768
834
  width: stats.canvasW,
769
835
  height: stats.canvasH
770
836
  });
@@ -772,12 +838,12 @@ async function forearmPoseWarnings(absDir, layers) {
772
838
  let armLayer;
773
839
  try {
774
840
  armLayer = await measured(measurer, absDir, arm);
775
- a = (0, import_editor4.armGeometry)(armLayer, arm === "arm_R" ? Infinity : -Infinity);
841
+ a = (0, import_editor5.armGeometry)(armLayer, arm === "arm_R" ? Infinity : -Infinity);
776
842
  } catch (err) {
777
- if (err instanceof import_editor4.LayerGeometryError) continue;
843
+ if (err instanceof import_editor5.LayerGeometryError) continue;
778
844
  throw err;
779
845
  }
780
- const b = (0, import_editor4.forearmPoseGeometry)(await measured(measurer, absDir, pose));
846
+ const b = (0, import_editor5.forearmPoseGeometry)(await measured(measurer, absDir, pose));
781
847
  warnings.push(...jointWarnings(pose, arm, stats, a, armLayer, b));
782
848
  }
783
849
  return warnings;
@@ -815,10 +881,721 @@ function jointWarnings(pose, arm, stats, a, armLayer, b) {
815
881
  return warnings;
816
882
  }
817
883
 
818
- // src/measure-turn.ts
884
+ // src/measure-lips.ts
819
885
  var import_node_path4 = __toESM(require("path"));
820
- var import_editor5 = require("@ikijs/editor");
886
+ var import_editor7 = require("@ikijs/editor");
887
+
888
+ // src/compose-lips.ts
889
+ var import_sharp2 = __toESM(require("sharp"));
821
890
  var import_editor6 = require("@ikijs/editor");
891
+ var KEYED_SRC = "mouth_keyed.png";
892
+ var INTERIOR_SRC = "mouth_interior.png";
893
+ var KEY_CANDIDATE = 0.5;
894
+ var KEY_FILL_DIST = 20;
895
+ var KEY_REACH = 8;
896
+ var KEY_COLLINEAR = 12;
897
+ var KEY_MIN_SHARE = 0.05;
898
+ var STRAY_KEY_FRACTION = 0.02;
899
+ var MIN_OPENING_WIDTH = 0.3;
900
+ var SECOND_HOLE_FRACTION = 0.05;
901
+ var BAND_LUMA = 150;
902
+ var BAND_CAP = 3;
903
+ var CAVITY_LUMA = 100;
904
+ var SKIN_MIN_R = 225;
905
+ var SKIN_MIN_G = 160;
906
+ var SKIN_MIN_B = 135;
907
+ var TEETH_MIN_G = 215;
908
+ var TEETH_MIN_B = 205;
909
+ var isSkin = (r, g, b) => r > SKIN_MIN_R && g > SKIN_MIN_G && b > SKIN_MIN_B && !(g > TEETH_MIN_G && b > TEETH_MIN_B);
910
+ function components(mask, W, H) {
911
+ const n = W * H;
912
+ const label = new Int32Array(n).fill(-1);
913
+ const stack = new Int32Array(n);
914
+ const sizes = [];
915
+ const boxes = [];
916
+ for (let start = 0; start < n; start++) {
917
+ if (!mask[start] || label[start] >= 0) continue;
918
+ const id = sizes.length;
919
+ const box = { x0: W, y0: H, x1: -1, y1: -1 };
920
+ let size = 0;
921
+ let depth = 0;
922
+ label[start] = id;
923
+ stack[depth++] = start;
924
+ while (depth > 0) {
925
+ const p = stack[--depth];
926
+ size++;
927
+ const px2 = p % W;
928
+ const py = (p - px2) / W;
929
+ box.x0 = Math.min(box.x0, px2);
930
+ box.x1 = Math.max(box.x1, px2);
931
+ box.y0 = Math.min(box.y0, py);
932
+ box.y1 = Math.max(box.y1, py);
933
+ for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {
934
+ for (let x = Math.max(0, px2 - 1); x <= Math.min(W - 1, px2 + 1); x++) {
935
+ if (x !== px2 && y !== py) continue;
936
+ const q = y * W + x;
937
+ if (mask[q] && label[q] < 0) {
938
+ label[q] = id;
939
+ stack[depth++] = q;
940
+ }
941
+ }
942
+ }
943
+ }
944
+ sizes.push(size);
945
+ boxes.push(box);
946
+ }
947
+ return { label, sizes, boxes };
948
+ }
949
+ var largest = (sizes) => sizes.reduce((best, s, i) => best < 0 || s > sizes[best] ? i : best, -1);
950
+ function dilate(mask, W, H, reach) {
951
+ const rows = new Uint8Array(W * H);
952
+ const prefix = new Int32Array(Math.max(W, H) + 1);
953
+ for (let y = 0; y < H; y++) {
954
+ for (let x = 0; x < W; x++) prefix[x + 1] = prefix[x] + mask[y * W + x];
955
+ for (let x = 0; x < W; x++) {
956
+ rows[y * W + x] = prefix[Math.min(W, x + reach + 1)] - prefix[Math.max(0, x - reach)] > 0 ? 1 : 0;
957
+ }
958
+ }
959
+ const out = new Uint8Array(W * H);
960
+ for (let x = 0; x < W; x++) {
961
+ for (let y = 0; y < H; y++) prefix[y + 1] = prefix[y] + rows[y * W + x];
962
+ for (let y = 0; y < H; y++) {
963
+ out[y * W + x] = prefix[Math.min(H, y + reach + 1)] - prefix[Math.max(0, y - reach)] > 0 ? 1 : 0;
964
+ }
965
+ }
966
+ return out;
967
+ }
968
+ function shareOf(rgba, i, j, g) {
969
+ const dr = g[0] - rgba[j];
970
+ const dg = g[1] - rgba[j + 1];
971
+ const db = g[2] - rgba[j + 2];
972
+ const t = ((rgba[i] - rgba[j]) * dr + (rgba[i + 1] - rgba[j + 1]) * dg + (rgba[i + 2] - rgba[j + 2]) * db) / (dr * dr + dg * dg + db * db);
973
+ return Math.min(1, Math.max(0, t));
974
+ }
975
+ function keyGreen(rgba, W, H) {
976
+ const n = W * H;
977
+ const noGreen = new AutoRigInputError(
978
+ `${KEYED_SRC}: no green opening (#00FF00) to key \u2014 regenerate it with the inside of the open mouth painted ONE flat pure green`
979
+ );
980
+ const hist = [
981
+ new Uint32Array(256),
982
+ new Uint32Array(256),
983
+ new Uint32Array(256)
984
+ ];
985
+ let candidates = 0;
986
+ for (let p = 0; p < n; p++) {
987
+ const i = p * 4;
988
+ if (rgba[i + 3] < import_editor6.ALPHA_OPAQUE) continue;
989
+ const excess = (rgba[i + 1] - Math.max(rgba[i], rgba[i + 2])) / 255;
990
+ if (excess < KEY_CANDIDATE) continue;
991
+ candidates++;
992
+ for (let c = 0; c < 3; c++) hist[c][rgba[i + c]]++;
993
+ }
994
+ if (candidates === 0) throw noGreen;
995
+ const median = (h) => {
996
+ let seen = 0;
997
+ for (let v = 0; v < 256; v++) {
998
+ seen += h[v];
999
+ if (seen * 2 >= candidates) return v;
1000
+ }
1001
+ return 255;
1002
+ };
1003
+ const G = [median(hist[0]), median(hist[1]), median(hist[2])];
1004
+ const out = Buffer.from(rgba);
1005
+ const fill = new Uint8Array(n);
1006
+ const ref = new Uint8Array(n);
1007
+ let fillCount = 0;
1008
+ for (let p = 0; p < n; p++) {
1009
+ const i = p * 4;
1010
+ if (rgba[i + 3] === 0) continue;
1011
+ const dr = rgba[i] - G[0];
1012
+ const dg = rgba[i + 1] - G[1];
1013
+ const db = rgba[i + 2] - G[2];
1014
+ const green = dr * dr + dg * dg + db * db <= KEY_FILL_DIST * KEY_FILL_DIST;
1015
+ if (rgba[i + 3] < import_editor6.ALPHA_OPAQUE) {
1016
+ if (green) out[i + 3] = 0;
1017
+ } else if (green) {
1018
+ fill[p] = 1;
1019
+ fillCount++;
1020
+ } else {
1021
+ ref[p] = 1;
1022
+ }
1023
+ }
1024
+ if (fillCount === 0) throw noGreen;
1025
+ const reach = dilate(fill, W, H, KEY_REACH);
1026
+ const collinear = KEY_COLLINEAR * KEY_COLLINEAR;
1027
+ for (let y = 0; y < H; y++) {
1028
+ for (let x = 0; x < W; x++) {
1029
+ const p = y * W + x;
1030
+ if (!reach[p] || fill[p] || out[p * 4 + 3] === 0) continue;
1031
+ const i = p * 4;
1032
+ let best = i;
1033
+ let bestD2 = (rgba[i] - G[0]) ** 2 + (rgba[i + 1] - G[1]) ** 2 + (rgba[i + 2] - G[2]) ** 2;
1034
+ const y1 = Math.min(H - 1, y + KEY_REACH);
1035
+ const x1 = Math.min(W - 1, x + KEY_REACH);
1036
+ for (let qy = Math.max(0, y - KEY_REACH); qy <= y1; qy++) {
1037
+ for (let qx = Math.max(0, x - KEY_REACH); qx <= x1; qx++) {
1038
+ const q = qy * W + qx;
1039
+ if (q === p || !ref[q]) continue;
1040
+ const j = q * 4;
1041
+ const d2 = (rgba[j] - G[0]) ** 2 + (rgba[j + 1] - G[1]) ** 2 + (rgba[j + 2] - G[2]) ** 2;
1042
+ if (d2 <= bestD2) continue;
1043
+ const t = shareOf(rgba, i, j, G);
1044
+ const er = rgba[i] - rgba[j] - t * (G[0] - rgba[j]);
1045
+ const eg = rgba[i + 1] - rgba[j + 1] - t * (G[1] - rgba[j + 1]);
1046
+ const eb = rgba[i + 2] - rgba[j + 2] - t * (G[2] - rgba[j + 2]);
1047
+ if (er * er + eg * eg + eb * eb > collinear) continue;
1048
+ bestD2 = d2;
1049
+ best = j;
1050
+ }
1051
+ }
1052
+ const k = shareOf(rgba, i, best, G);
1053
+ if (k < KEY_MIN_SHARE) continue;
1054
+ rgba.copy(out, i, best, best + 3);
1055
+ out[i + 3] = Math.round(rgba[i + 3] * (1 - k));
1056
+ }
1057
+ }
1058
+ for (let p = 0; p < n; p++) if (fill[p]) out[p * 4 + 3] = 0;
1059
+ const { sizes } = components(fill, W, H);
1060
+ const main = largest(sizes);
1061
+ const strays = sizes.filter((_, i) => i !== main);
1062
+ const strayPx = strays.reduce((a, b) => a + b, 0);
1063
+ if (strayPx > STRAY_KEY_FRACTION * sizes[main]) {
1064
+ throw new AutoRigInputError(
1065
+ `${KEYED_SRC}: green outside the opening (${strayPx} px in ${strays.length} regions beside the opening's) \u2014 the key must be one flat region inside the outline; regenerate with no green elsewhere`
1066
+ );
1067
+ }
1068
+ return out;
1069
+ }
1070
+ var GROUND_TOLERANCE = 4;
1071
+ var GROUND_LIGHT = 200;
1072
+ var GROUND_MIN = 238;
1073
+ var GROUND_BORDER_SHARE = 0.65;
1074
+ function keyBorderWhite(rgba, W, H) {
1075
+ const border = [[], [], []];
1076
+ const edge = (p) => {
1077
+ for (let c = 0; c < 3; c++) border[c].push(rgba[p * 4 + c]);
1078
+ };
1079
+ for (let x = 0; x < W; x++) {
1080
+ edge(x);
1081
+ edge((H - 1) * W + x);
1082
+ }
1083
+ for (let y = 1; y < H - 1; y++) {
1084
+ edge(y * W);
1085
+ edge(y * W + W - 1);
1086
+ }
1087
+ const ground = border.map((v) => v.sort((a, b) => a - b)[v.length >> 1]);
1088
+ const light = ground.every((v) => v >= GROUND_LIGHT);
1089
+ if (light && ground.some((v) => v < GROUND_MIN)) {
1090
+ throw new AutoRigInputError(
1091
+ `${INTERIOR_SRC} came back opaque on a non-white ground \u2014 regenerate it with a transparent background. Billed.`
1092
+ );
1093
+ }
1094
+ if (!light) ground.fill(255);
1095
+ const out = Buffer.from(rgba);
1096
+ const seen = new Uint8Array(W * H);
1097
+ const stack = new Int32Array(W * H);
1098
+ let depth = 0;
1099
+ const seed = (p) => {
1100
+ if (seen[p]) return;
1101
+ for (let c = 0; c < 3; c++) {
1102
+ if (Math.abs(rgba[p * 4 + c] - ground[c]) > GROUND_TOLERANCE) return;
1103
+ }
1104
+ seen[p] = 1;
1105
+ stack[depth++] = p;
1106
+ };
1107
+ for (let x = 0; x < W; x++) {
1108
+ seed(x);
1109
+ seed((H - 1) * W + x);
1110
+ }
1111
+ for (let y = 0; y < H; y++) {
1112
+ seed(y * W);
1113
+ seed(y * W + W - 1);
1114
+ }
1115
+ if (light && depth < GROUND_BORDER_SHARE * border[0].length) {
1116
+ throw new AutoRigInputError(
1117
+ `${INTERIOR_SRC} came back opaque on a white ground too noisy or shaded to key cleanly \u2014 regenerate it with a transparent background. Billed.`
1118
+ );
1119
+ }
1120
+ while (depth > 0) {
1121
+ const p = stack[--depth];
1122
+ out[p * 4 + 3] = 0;
1123
+ const x = p % W;
1124
+ if (x > 0) seed(p - 1);
1125
+ if (x < W - 1) seed(p + 1);
1126
+ if (p >= W) seed(p - W);
1127
+ if (p < W * H - W) seed(p + W);
1128
+ }
1129
+ return out;
1130
+ }
1131
+ function drawingBox(rgba, W, H) {
1132
+ const speckless = boxWithoutStraySpecks(rgba, W, H);
1133
+ if (speckless !== null) {
1134
+ return {
1135
+ x: speckless.left,
1136
+ y: speckless.top,
1137
+ w: speckless.width,
1138
+ h: speckless.height
1139
+ };
1140
+ }
1141
+ let x0 = W;
1142
+ let y0 = H;
1143
+ let x1 = -1;
1144
+ let y1 = -1;
1145
+ for (let y = 0; y < H; y++) {
1146
+ for (let x = 0; x < W; x++) {
1147
+ if (rgba[(y * W + x) * 4 + 3] <= TRIM_THRESHOLD) continue;
1148
+ x0 = Math.min(x0, x);
1149
+ x1 = Math.max(x1, x);
1150
+ y0 = Math.min(y0, y);
1151
+ y1 = Math.max(y1, y);
1152
+ }
1153
+ }
1154
+ return x1 < 0 ? null : { x: x0, y: y0, w: x1 - x0 + 1, h: y1 - y0 + 1 };
1155
+ }
1156
+ async function prepInterior(rgba, W, H) {
1157
+ const empty = new AutoRigInputError(
1158
+ `${INTERIOR_SRC}: nothing but lips/skin after trimming \u2014 regenerate it with the cavity, the teeth and the tongue only, NO lips`
1159
+ );
1160
+ const first = drawingBox(rgba, W, H);
1161
+ if (first === null) throw empty;
1162
+ const cw = first.w;
1163
+ const ch = first.h;
1164
+ const crop = Buffer.alloc(cw * ch * 4);
1165
+ for (let y = 0; y < ch; y++) {
1166
+ const from2 = ((first.y + y) * W + first.x) * 4;
1167
+ rgba.copy(crop, y * cw * 4, from2, from2 + cw * 4);
1168
+ }
1169
+ const skin = new Uint8Array(cw * ch);
1170
+ for (let p = 0; p < cw * ch; p++) {
1171
+ const i = p * 4;
1172
+ if (crop[i + 3] > TRIM_THRESHOLD && isSkin(crop[i], crop[i + 1], crop[i + 2]))
1173
+ skin[p] = 1;
1174
+ }
1175
+ const { label, boxes } = components(skin, cw, ch);
1176
+ const rim = boxes.map(
1177
+ (b) => b.x0 === 0 || b.y0 === 0 || b.x1 === cw - 1 || b.y1 === ch - 1
1178
+ );
1179
+ for (let p = 0; p < cw * ch; p++) {
1180
+ if (label[p] >= 0 && rim[label[p]]) crop[p * 4 + 3] = 0;
1181
+ }
1182
+ const box = drawingBox(crop, cw, ch);
1183
+ if (box === null) throw empty;
1184
+ const sum = [0, 0, 0];
1185
+ const all = [0, 0, 0];
1186
+ let dark = 0;
1187
+ let count = 0;
1188
+ for (let y = box.y; y < box.y + box.h; y++) {
1189
+ for (let x = box.x; x < box.x + box.w; x++) {
1190
+ const i = (y * cw + x) * 4;
1191
+ if (crop[i + 3] < import_editor6.ALPHA_OPAQUE) continue;
1192
+ count++;
1193
+ for (let c = 0; c < 3; c++) all[c] += crop[i + c];
1194
+ if (luma(crop, i) < CAVITY_LUMA) {
1195
+ dark++;
1196
+ for (let c = 0; c < 3; c++) sum[c] += crop[i + c];
1197
+ }
1198
+ }
1199
+ }
1200
+ if (count === 0) throw empty;
1201
+ const [from, over] = dark > 0 ? [sum, dark] : [all, count];
1202
+ const cavity = from.map((v) => Math.round(v / over));
1203
+ return { png: await cropToBuffer(crop, cw, ch, box), cavity };
1204
+ }
1205
+ var rawOf = async (png) => (0, import_sharp2.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1206
+ var encode = (rgba, w, h) => (0, import_sharp2.default)(rgba, { raw: { width: w, height: h, channels: 4 } }).png().toBuffer();
1207
+ function enclosedHole(frame, w, h) {
1208
+ const n = w * h;
1209
+ const alpha = (p) => frame[p * 4 + 3];
1210
+ const outside = new Uint8Array(n);
1211
+ const stack = new Int32Array(n);
1212
+ let depth = 0;
1213
+ const seed = (p) => {
1214
+ if (!outside[p] && alpha(p) < import_editor6.ALPHA_OPAQUE) {
1215
+ outside[p] = 1;
1216
+ stack[depth++] = p;
1217
+ }
1218
+ };
1219
+ for (let x = 0; x < w; x++) {
1220
+ seed(x);
1221
+ seed((h - 1) * w + x);
1222
+ }
1223
+ for (let y = 0; y < h; y++) {
1224
+ seed(y * w);
1225
+ seed(y * w + w - 1);
1226
+ }
1227
+ while (depth > 0) {
1228
+ const p = stack[--depth];
1229
+ const x = p % w;
1230
+ if (x > 0) seed(p - 1);
1231
+ if (x < w - 1) seed(p + 1);
1232
+ if (p >= w) seed(p - w);
1233
+ if (p < n - w) seed(p + w);
1234
+ }
1235
+ const mask = new Uint8Array(n);
1236
+ for (let p = 0; p < n; p++) {
1237
+ if (alpha(p) < import_editor6.ALPHA_OPAQUE && !outside[p]) mask[p] = 1;
1238
+ }
1239
+ const { label, sizes, boxes } = components(mask, w, h);
1240
+ const main = largest(sizes);
1241
+ if (main < 0) {
1242
+ throw new AutoRigInputError(
1243
+ `${KEYED_SRC}: the outline is not closed round the opening (the key reached the outside, or the line is broken or too thin at this size) \u2014 regenerate with ONE closed, bolder outline`
1244
+ );
1245
+ }
1246
+ const box = boxes[main];
1247
+ const holeW = box.x1 - box.x0 + 1;
1248
+ if (holeW < MIN_OPENING_WIDTH * w) {
1249
+ throw new AutoRigInputError(
1250
+ `${KEYED_SRC}: the opening is only ${holeW} px wide of the mouth's ${w} \u2014 too small to fold; regenerate with the mouth open wider, or, if its outline is broken (only a small pocket of the opening was enclosed), with ONE closed, bolder outline`
1251
+ );
1252
+ }
1253
+ const others = sizes.filter(
1254
+ (s, i) => i !== main && s >= SECOND_HOLE_FRACTION * sizes[main]
1255
+ );
1256
+ if (others.length > 0) {
1257
+ throw new AutoRigInputError(
1258
+ `${KEYED_SRC}: the opening is not one connected region (${others.length + 1} holes: teeth or tongue drawn into the green?) \u2014 regenerate with nothing drawn inside the green`
1259
+ );
1260
+ }
1261
+ return { label, main, box };
1262
+ }
1263
+ function measureLips(layers, w, h) {
1264
+ const measurer = (0, import_editor6.createLayerSetMeasurer)({ width: w, height: h });
1265
+ return new Map(
1266
+ Object.entries(layers).map(([role, rgba]) => [
1267
+ role,
1268
+ measurer.add({ role, fileName: `${role}.png`, rgba })
1269
+ ])
1270
+ );
1271
+ }
1272
+ function assertFoldContract(layers, w, h) {
1273
+ const byRole = /* @__PURE__ */ new Map();
1274
+ for (const [role, layer] of measureLips(layers, w, h)) {
1275
+ if (layer === null && role === "lip_lower") {
1276
+ throw new AutoRigInputError(
1277
+ `${KEYED_SRC}: no lip_lower after the split \u2014 there is no skin under the opening; draw the lower lip under the outline`
1278
+ );
1279
+ }
1280
+ byRole.set(role, layer);
1281
+ }
1282
+ const opening = (0, import_editor6.mouthOpening)(byRole);
1283
+ const runs = (0, import_editor6.columnRuns)(byRole.get("mouth_inner"));
1284
+ for (let col = opening.x0; col <= opening.x1; col++) {
1285
+ const c = opening.at(col);
1286
+ const why = !runs.has(col) ? "has no interior run" : c.Tu > c.T ? `has a gap between the line and the interior (Tu ${c.Tu} > T ${c.T})` : c.T > c.lineTop || c.lineH <= 0 ? `has no line above the interior (T ${c.T}, line top ${c.lineTop})` : c.Bl < c.Bb ? `has a gap between the interior and the skin (Bl ${c.Bl} < Bb ${c.Bb})` : null;
1287
+ if (why !== null) throw new Error(`splitLipSet: column ${col} ${why}`);
1288
+ }
1289
+ return opening;
1290
+ }
1291
+ async function splitLipSet(keyedPng, w, h, interior) {
1292
+ const { data: frame, info } = await rawOf(keyedPng);
1293
+ if (info.width !== w || info.height !== h) {
1294
+ throw new Error(
1295
+ `splitLipSet: the frame is ${info.width}x${info.height}, not ${w}x${h}`
1296
+ );
1297
+ }
1298
+ const n = w * h;
1299
+ const alpha = (p) => frame[p * 4 + 3];
1300
+ const { label, main, box: hb } = enclosedHole(frame, w, h);
1301
+ const holeW = hb.x1 - hb.x0 + 1;
1302
+ const top = new Int32Array(w).fill(-1);
1303
+ const bot = new Int32Array(w).fill(-1);
1304
+ for (let y = 0; y < h; y++) {
1305
+ for (let x = hb.x0; x <= hb.x1; x++) {
1306
+ if (label[y * w + x] !== main) continue;
1307
+ if (top[x] < 0) top[x] = y;
1308
+ bot[x] = y + 1;
1309
+ }
1310
+ }
1311
+ const centre = Math.round((hb.x0 + hb.x1) / 2);
1312
+ let stroke = 0;
1313
+ while (top[centre] - 1 - stroke >= 0 && alpha((top[centre] - 1 - stroke) * w + centre) >= import_editor6.ALPHA_OPAQUE)
1314
+ stroke++;
1315
+ const bandCap = BAND_CAP * Math.max(1, stroke);
1316
+ const skinRow = new Int32Array(w).fill(-1);
1317
+ const inM = new Uint8Array(n);
1318
+ for (let x = hb.x0; x <= hb.x1; x++) {
1319
+ let y = bot[x];
1320
+ while (y < h && y - bot[x] < bandCap && alpha(y * w + x) >= import_editor6.ALPHA_OPAQUE && luma(frame, (y * w + x) * 4) < BAND_LUMA)
1321
+ y++;
1322
+ for (let k = top[x]; k < y; k++) inM[k * w + x] = 1;
1323
+ let r = y;
1324
+ while (r < h && alpha(r * w + x) < import_editor6.ALPHA_OPAQUE) r++;
1325
+ if (r < h) {
1326
+ skinRow[x] = r;
1327
+ inM[r * w + x] = 1;
1328
+ }
1329
+ }
1330
+ const grown = Uint8Array.from(inM);
1331
+ for (let y = 0; y < h; y++) {
1332
+ for (let x = 0; x < w; x++) {
1333
+ const p = y * w + x;
1334
+ if (inM[p] || alpha(p) < import_editor6.ALPHA_OPAQUE) continue;
1335
+ if (top[x] >= 0 && y < top[x]) continue;
1336
+ if (x > 0 && inM[p - 1] || x < w - 1 && inM[p + 1]) grown[p] = 1;
1337
+ }
1338
+ }
1339
+ const wall = new Uint8Array(w);
1340
+ for (const x of [hb.x0 - 1, hb.x1 + 1]) {
1341
+ if (x < 0 || x >= w) continue;
1342
+ let first = 0;
1343
+ while (first < h && !(grown[first * w + x] && !inM[first * w + x])) first++;
1344
+ if (first > 0 && first < h && alpha((first - 1) * w + x) >= import_editor6.ALPHA_OPAQUE)
1345
+ wall[x] = 1;
1346
+ }
1347
+ const gx = hb.x0 - 1;
1348
+ const gy = hb.y0 - 1;
1349
+ const gw = holeW + 2;
1350
+ const gh = hb.y1 - hb.y0 + 3;
1351
+ const { data: fitted } = await (0, import_sharp2.default)(interior.png).resize(gw, gh, { fit: "fill" }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1352
+ const faintUpper = (p, x, y) => y < bot[x] && label[p] === main && 2 * y < top[x] + bot[x];
1353
+ const upper = Buffer.alloc(n * 4);
1354
+ const lower = Buffer.alloc(n * 4);
1355
+ const inner = Buffer.alloc(n * 4);
1356
+ const copy = (to, p) => frame.copy(to, p * 4, p * 4, p * 4 + 4);
1357
+ for (let y = 0; y < h; y++) {
1358
+ for (let x = 0; x < w; x++) {
1359
+ const p = y * w + x;
1360
+ const inOpening = top[x] >= 0;
1361
+ if ((!inOpening || y < top[x] || faintUpper(p, x, y)) && !(wall[x] && grown[p]))
1362
+ copy(upper, p);
1363
+ if (inOpening && skinRow[x] >= 0 && y >= skinRow[x]) copy(lower, p);
1364
+ if (!grown[p]) continue;
1365
+ const out = [...interior.cavity];
1366
+ const ix = x - gx;
1367
+ const iy = y - gy;
1368
+ if (ix >= 0 && ix < gw && iy >= 0 && iy < gh) {
1369
+ const i = (iy * gw + ix) * 4;
1370
+ const a = fitted[i + 3] / 255;
1371
+ for (let c = 0; c < 3; c++) out[c] += (fitted[i + c] - out[c]) * a;
1372
+ }
1373
+ if ((inM[p] || wall[x]) && !faintUpper(p, x, y)) {
1374
+ const a = alpha(p) / 255;
1375
+ for (let c = 0; c < 3; c++) out[c] += (frame[p * 4 + c] - out[c]) * a;
1376
+ }
1377
+ inner[p * 4] = Math.round(out[0]);
1378
+ inner[p * 4 + 1] = Math.round(out[1]);
1379
+ inner[p * 4 + 2] = Math.round(out[2]);
1380
+ inner[p * 4 + 3] = 255;
1381
+ }
1382
+ }
1383
+ const opening = assertFoldContract(
1384
+ { mouth_inner: inner, lip_lower: lower, lip_upper: upper },
1385
+ w,
1386
+ h
1387
+ );
1388
+ const [innerPng, lowerPng, upperPng] = await Promise.all([
1389
+ encode(inner, w, h),
1390
+ encode(lower, w, h),
1391
+ encode(upper, w, h)
1392
+ ]);
1393
+ return { inner: innerPng, lower: lowerPng, upper: upperPng, opening };
1394
+ }
1395
+ async function restShiftOf(layers, width, height) {
1396
+ const [mouth_inner, lip_lower, lip_upper] = await Promise.all(
1397
+ [layers.mouth_inner, layers.lip_lower, layers.lip_upper].map(
1398
+ async (png) => (await rawOf(png)).data
1399
+ )
1400
+ );
1401
+ const byRole = /* @__PURE__ */ new Map();
1402
+ for (const [role, layer] of measureLips(
1403
+ { mouth_inner, lip_lower, lip_upper },
1404
+ width,
1405
+ height
1406
+ )) {
1407
+ if (layer === null) {
1408
+ throw new AutoRigInputError(
1409
+ `layout.mouth_inner places the lip set so that ${role} falls off the canvas (nothing of it is left) \u2014 move it back on the canvas`
1410
+ );
1411
+ }
1412
+ byRole.set(role, layer);
1413
+ }
1414
+ return (0, import_editor6.mouthRestShift)(byRole);
1415
+ }
1416
+ async function closedLips(upper, lower, shift, left) {
1417
+ const shut = async (png, role) => {
1418
+ const { data, info } = await rawOf(png);
1419
+ const { width: w, height: h } = info;
1420
+ const out = Buffer.alloc(w * h * 4);
1421
+ for (let x = 0; x < w; x++) {
1422
+ const dy = shift(role, left + x);
1423
+ const f = Math.floor(dy);
1424
+ const t = dy - f;
1425
+ const px2 = (row, c) => row < 0 || row >= h ? 0 : data[(row * w + x) * 4 + c];
1426
+ for (let to = 0; to < h; to++) {
1427
+ const a0 = px2(to + f, 3);
1428
+ const a1 = px2(to + f + 1, 3);
1429
+ const a = (1 - t) * a0 + t * a1;
1430
+ if (a === 0) continue;
1431
+ const o = (to * w + x) * 4;
1432
+ for (let c = 0; c < 3; c++)
1433
+ out[o + c] = Math.round(
1434
+ ((1 - t) * a0 * px2(to + f, c) + t * a1 * px2(to + f + 1, c)) / a
1435
+ );
1436
+ out[o + 3] = Math.round(a);
1437
+ }
1438
+ }
1439
+ return encode(out, w, h);
1440
+ };
1441
+ const [u, l] = await Promise.all([
1442
+ shut(upper, "lip_upper"),
1443
+ shut(lower, "lip_lower")
1444
+ ]);
1445
+ return { upper: u, lower: l };
1446
+ }
1447
+
1448
+ // src/measure-lips.ts
1449
+ var isLipRole = (role) => import_editor7.LIP_ROLES.includes(role);
1450
+ var MIN_OPENING_ROWS = 8;
1451
+ var MIN_LINE_ROWS = 2;
1452
+ var GREEN_EXCESS = 40;
1453
+ var INTERIOR_GAP_FRACTION = 0.05;
1454
+ var columns = (cols) => `${cols.length} column${cols.length === 1 ? "" : "s"} (first at x=${cols[0]})`;
1455
+ async function lipWarnings(absDir, layers) {
1456
+ const warnings = [];
1457
+ const present = import_editor7.LIP_ROLES.filter((role) => layers[role] !== void 0);
1458
+ if (present.length === 0) return { warnings };
1459
+ const legacy = ["mouth", "mouth_open"].filter(
1460
+ (role) => layers[role] !== void 0
1461
+ );
1462
+ if (legacy.length > 0) {
1463
+ warnings.push(
1464
+ `${present.join("/")}: the lip set cannot be mixed with ${legacy.join("/")} \u2014 auto_rig_from_layers refuses it. Remove one route: compose again with only mouth_keyed.png + mouth_interior.png, or without them.`
1465
+ );
1466
+ }
1467
+ if (present.length < import_editor7.LIP_ROLES.length) {
1468
+ const missing = import_editor7.LIP_ROLES.filter((role) => layers[role] === void 0);
1469
+ warnings.push(
1470
+ `${present.join("/")}: partial lip set, missing ${missing.join("/")} \u2014 auto_rig_from_layers refuses it. Compose mouth_keyed.png + mouth_interior.png together, which cuts all three.`
1471
+ );
1472
+ return { warnings };
1473
+ }
1474
+ const { mouth_inner: inner, lip_upper: upper } = layers;
1475
+ for (const role of ["lip_lower", "lip_upper"]) {
1476
+ const stats = layers[role];
1477
+ if (stats.canvasW !== inner.canvasW || stats.canvasH !== inner.canvasH) {
1478
+ warnings.push(
1479
+ `${role}: its canvas ${stats.canvasW}x${stats.canvasH} differs from mouth_inner's ${inner.canvasW}x${inner.canvasH} \u2014 auto_rig_from_layers refuses layers of different sizes; recompose them together.`
1480
+ );
1481
+ return { warnings };
1482
+ }
1483
+ }
1484
+ const measurer = (0, import_editor7.createLayerSetMeasurer)({
1485
+ width: inner.canvasW,
1486
+ height: inner.canvasH
1487
+ });
1488
+ const set = /* @__PURE__ */ new Map();
1489
+ const green = [];
1490
+ for (const role of import_editor7.LIP_ROLES) {
1491
+ const fileName = `${role}.png`;
1492
+ const { rgba } = await decodePng(import_node_path4.default.join(absDir, fileName));
1493
+ set.set(role, measurer.add({ role, fileName, rgba }));
1494
+ for (let i = 0; i < rgba.length; i += 4) {
1495
+ if (rgba[i + 3] >= import_editor7.ALPHA_OPAQUE && rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS) {
1496
+ green.push(role);
1497
+ break;
1498
+ }
1499
+ }
1500
+ }
1501
+ let opening;
1502
+ try {
1503
+ opening = (0, import_editor7.mouthOpening)(set);
1504
+ } catch (err) {
1505
+ if (err instanceof import_editor7.LayerGeometryError) {
1506
+ warnings.push(err.message);
1507
+ return { warnings };
1508
+ }
1509
+ throw err;
1510
+ }
1511
+ const innerRuns = (0, import_editor7.columnRuns)(set.get("mouth_inner"));
1512
+ const noInterior = [];
1513
+ const gap = [];
1514
+ const noLine = [];
1515
+ const skinGap = [];
1516
+ let area = 0;
1517
+ let hollow = 0;
1518
+ for (let x = opening.x0; x <= opening.x1; x++) {
1519
+ const runs = innerRuns.get(x);
1520
+ if (runs === void 0) {
1521
+ noInterior.push(x);
1522
+ continue;
1523
+ }
1524
+ const span = runs[runs.length - 1][1] - runs[0][0];
1525
+ area += span;
1526
+ hollow += span - runs.reduce((n, r) => n + r[1] - r[0], 0);
1527
+ const c = opening.at(x);
1528
+ if (c.lineH <= 0) noLine.push(x);
1529
+ else if (c.Tu > c.T) gap.push(x);
1530
+ if (c.Bl < c.Bb) skinGap.push(x);
1531
+ }
1532
+ const recompose = (file, ask) => `Recompose from mouth_keyed.png + mouth_interior.png (free); if it persists, regenerate ${file} ${ask}. Billed.`;
1533
+ const regenKeyed = recompose(
1534
+ "mouth_keyed.png",
1535
+ "with a closed outline and solid lips under it"
1536
+ );
1537
+ if (noInterior.length > 0) {
1538
+ warnings.push(
1539
+ `mouth_inner: no interior in ${columns(noInterior)} of the opening \u2014 the fold has nothing to scale there. ${recompose("mouth_interior.png", "as one solid cavity")}`
1540
+ );
1541
+ }
1542
+ if (gap.length > 0) {
1543
+ warnings.push(
1544
+ `lip_upper: a gap between the line and the interior in ${columns(gap)} \u2014 the face shows through it at rest (the interior's top must reach the line's ink). ${regenKeyed}`
1545
+ );
1546
+ }
1547
+ if (noLine.length > 0) {
1548
+ warnings.push(
1549
+ `lip_upper: no line above the interior in ${columns(noLine)} \u2014 nothing closes the mouth there. ${regenKeyed}`
1550
+ );
1551
+ }
1552
+ if (skinGap.length > 0) {
1553
+ warnings.push(
1554
+ `lip_lower: a gap between the interior and the skin in ${columns(skinGap)} \u2014 the face shows through it once the mouth opens (the skin must reach the interior's bottom). ${regenKeyed}`
1555
+ );
1556
+ }
1557
+ const width = opening.x1 - opening.x0 + 1;
1558
+ const centre = opening.at(opening.centre);
1559
+ if (width < MIN_OPENING_WIDTH * upper.w) {
1560
+ warnings.push(
1561
+ `mouth_inner: the opening is ${width} px wide, ${Math.round(100 * width / upper.w)}% of lip_upper's ${upper.w} px (under ${Math.round(100 * MIN_OPENING_WIDTH)}%) \u2014 too narrow to fold; the slit stays a hairline. Regenerate mouth_keyed.png with the mouth open wider. Billed.`
1562
+ );
1563
+ }
1564
+ if (centre.H < MIN_OPENING_ROWS) {
1565
+ const w = Math.ceil(upper.w * MIN_OPENING_ROWS / centre.H);
1566
+ const retune = w <= inner.canvasW ? w : null;
1567
+ warnings.push(
1568
+ `mouth_inner: the opening is ${centre.H} px tall at its centre (under ${MIN_OPENING_ROWS}) \u2014 too small to fold; the slit stays shut until MouthOpen is nearly 1. ` + (retune === null ? "" : `If the mouth is smaller than the reference's, set layout.mouth_inner.w to ${retune} (free; the whole set scales with it, so scale layout.mouth_inner.h too if it is set). Otherwise `) + `${retune === null ? "R" : "r"}egenerate mouth_keyed.png with the mouth open taller. Billed.`
1569
+ );
1570
+ }
1571
+ if (opening.w < MIN_LINE_ROWS) {
1572
+ warnings.push(
1573
+ `lip_upper: the upper line is ${opening.w} px at the opening's centre (under ${MIN_LINE_ROWS}) \u2014 a hairline closes to nothing. Regenerate mouth_keyed.png with a bolder upper line, never thinner than the reference's mouth line. Billed.`
1574
+ );
1575
+ }
1576
+ if (green.length > 0) {
1577
+ warnings.push(
1578
+ `${green.join("/")}: opaque green left (key green, g exceeds r and b by over ${GREEN_EXCESS}) \u2014 it shows as a green fringe on the lips. Regenerate mouth_keyed.png with the green only inside the opening, or mouth_interior.png without green in it. Billed.`
1579
+ );
1580
+ }
1581
+ if (area > 0 && hollow > INTERIOR_GAP_FRACTION * area) {
1582
+ warnings.push(
1583
+ `mouth_inner: ${Math.round(100 * hollow / area)}% of the opening is transparent inside the interior's own span (over ${Math.round(100 * INTERIOR_GAP_FRACTION)}%) \u2014 the face shows through it. Regenerate mouth_interior.png as one solid cavity. Billed.`
1584
+ );
1585
+ }
1586
+ return {
1587
+ warnings,
1588
+ lips: {
1589
+ opening: { width, height: centre.H, line: opening.w },
1590
+ deadZone: centre.overlap / (centre.H + centre.overlap)
1591
+ }
1592
+ };
1593
+ }
1594
+
1595
+ // src/measure-turn.ts
1596
+ var import_node_path5 = __toESM(require("path"));
1597
+ var import_editor8 = require("@ikijs/editor");
1598
+ var import_editor9 = require("@ikijs/editor");
822
1599
  var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
823
1600
  var IRIS_V_MIN = 0.18;
824
1601
  var IRIS_V_MAX = 0.95;
@@ -855,7 +1632,7 @@ function rgbToHsv(r, g, b) {
855
1632
  }
856
1633
  return [h, max === 0 ? 0 : d / max, max];
857
1634
  }
858
- function dilate(mask, width, height, r) {
1635
+ function dilate2(mask, width, height, r) {
859
1636
  const out = new Uint8Array(width * height);
860
1637
  for (let y = 0; y < height; y++) {
861
1638
  for (let x = 0; x < width; x++) {
@@ -894,9 +1671,9 @@ function erode(mask, width, height, r) {
894
1671
  return out;
895
1672
  }
896
1673
  function closeMask(mask, width, height, r) {
897
- return erode(dilate(mask, width, height, r), width, height, r);
1674
+ return erode(dilate2(mask, width, height, r), width, height, r);
898
1675
  }
899
- function components(mask, width, height, minArea) {
1676
+ function components2(mask, width, height, minArea) {
900
1677
  const seen = new Uint8Array(width * height);
901
1678
  const out = [];
902
1679
  for (let i = 0; i < width * height; i++) {
@@ -968,7 +1745,7 @@ async function measureTurnImage(filePath, iris) {
968
1745
  let transparent = false;
969
1746
  if (hasAlpha) {
970
1747
  for (let i = 0; i < n; i++) {
971
- if (rgba[i * 4 + 3] < import_editor5.ALPHA_OPAQUE) {
1748
+ if (rgba[i * 4 + 3] < import_editor8.ALPHA_OPAQUE) {
972
1749
  transparent = true;
973
1750
  break;
974
1751
  }
@@ -979,7 +1756,7 @@ async function measureTurnImage(filePath, iris) {
979
1756
  const fg = new Uint8Array(n);
980
1757
  const value = new Float32Array(n);
981
1758
  for (let i = 0; i < n; i++) {
982
- if (rgba[i * 4 + 3] < import_editor5.ALPHA_OPAQUE) continue;
1759
+ if (rgba[i * 4 + 3] < import_editor8.ALPHA_OPAQUE) continue;
983
1760
  const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);
984
1761
  if (maskMode === "alpha") {
985
1762
  fg[i] = 1;
@@ -1015,7 +1792,7 @@ async function measureTurnImage(filePath, iris) {
1015
1792
  }
1016
1793
  return count ? total / count : 0;
1017
1794
  };
1018
- const candidates = components(
1795
+ const candidates = components2(
1019
1796
  closeMask(irisMask, width, height, closeRadius),
1020
1797
  width,
1021
1798
  height,
@@ -1045,12 +1822,12 @@ async function measureTurnImage(filePath, iris) {
1045
1822
  }
1046
1823
  const [irisL, irisR] = best.pair;
1047
1824
  const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);
1048
- const { left, right } = (0, import_editor5.foregroundSpan)(
1825
+ const { left, right } = (0, import_editor8.foregroundSpan)(
1049
1826
  fg,
1050
1827
  width,
1051
1828
  height,
1052
- eyeRow - import_editor5.HEAD_BAND,
1053
- eyeRow + import_editor5.HEAD_BAND
1829
+ eyeRow - import_editor8.HEAD_BAND,
1830
+ eyeRow + import_editor8.HEAD_BAND
1054
1831
  );
1055
1832
  if (right <= left) {
1056
1833
  throw new AutoRigInputError(
@@ -1074,7 +1851,7 @@ async function measureTurnImage(filePath, iris) {
1074
1851
  left,
1075
1852
  right,
1076
1853
  cx: (left + right) / 2,
1077
- half: (0, import_editor5.headHalfOf)({ left, right })
1854
+ half: (0, import_editor8.headHalfOf)({ left, right })
1078
1855
  },
1079
1856
  pairCx: (irisL.cx + irisR.cx) / 2,
1080
1857
  eyeGap: irisR.cx - irisL.cx
@@ -1089,9 +1866,9 @@ function overlaySvg(m) {
1089
1866
  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>";
1090
1867
  }
1091
1868
  async function writeOverlay(debugDir, label, m) {
1092
- const outPath = import_node_path4.default.join(
1869
+ const outPath = import_node_path5.default.join(
1093
1870
  debugDir,
1094
- `${label}-${import_node_path4.default.basename(m.file, ".png")}.debug.png`
1871
+ `${label}-${import_node_path5.default.basename(m.file, ".png")}.debug.png`
1095
1872
  );
1096
1873
  writeFileAtomic(outPath, await encodeOverlayPng(m.file, overlaySvg(m)));
1097
1874
  return outPath;
@@ -1265,7 +2042,7 @@ function noseSpeckWarning({ core, part }, source) {
1265
2042
  `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,
1266
2043
  `auto_rig_from_layers turns and tilts the nose about its whole crop instead`
1267
2044
  ];
1268
- 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.`;
2045
+ return `nose: ${found} \u2014 under ${import_editor9.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.`;
1269
2046
  }
1270
2047
  async function lashOffSclera(eyePath, lashPath) {
1271
2048
  const eye = await decodePng(eyePath);
@@ -1295,8 +2072,8 @@ async function measureDir(absDir, noseSpeck) {
1295
2072
  const layers = {};
1296
2073
  const empty = [];
1297
2074
  for (const f of files) {
1298
- const role = import_node_path5.default.basename(f, ".png");
1299
- const m = await layerStats(import_node_path5.default.join(absDir, f));
2075
+ const role = import_node_path6.default.basename(f, ".png");
2076
+ const m = await layerStats(import_node_path6.default.join(absDir, f));
1300
2077
  if (!m) {
1301
2078
  empty.push(role);
1302
2079
  continue;
@@ -1305,6 +2082,7 @@ async function measureDir(absDir, noseSpeck) {
1305
2082
  }
1306
2083
  const warnings = [];
1307
2084
  for (const [role, m] of Object.entries(layers)) {
2085
+ if (isLipRole(role)) continue;
1308
2086
  const edges = [
1309
2087
  ["top", m.edgeTop, m.w, m.marginTop],
1310
2088
  ["left", m.edgeLeft, m.h, m.marginLeft],
@@ -1334,7 +2112,7 @@ async function measureDir(absDir, noseSpeck) {
1334
2112
  }
1335
2113
  }
1336
2114
  for (const [role, m] of Object.entries(layers)) {
1337
- if (role === "body") continue;
2115
+ if (role === "body" || isLipRole(role)) continue;
1338
2116
  if (m.flatCutRun > FLAT_CUT_MAX_FRAC * m.w && m.flatCutRun >= FLAT_CUT_MIN_PX) {
1339
2117
  warnings.push(
1340
2118
  `${role}: ${m.flatCutRun}px of straight flat edge at y=${m.flatCutY} (${pct(m.flatCutRun / m.w)} of its width) \u2014 the source art is cut through there. ` + (isArm(role) ? `It hides at rest and opens into a seam once the arm raises. ` : `It hides while the head faces front and opens into a seam on turn. `) + `Regenerate this part with the whole subject inside the frame.`
@@ -1343,6 +2121,8 @@ async function measureDir(absDir, noseSpeck) {
1343
2121
  }
1344
2122
  warnings.push(...await armWarnings(absDir, layers));
1345
2123
  warnings.push(...await forearmPoseWarnings(absDir, layers));
2124
+ const lip = await lipWarnings(absDir, layers);
2125
+ warnings.push(...lip.warnings);
1346
2126
  for (const side of ["L", "R"]) {
1347
2127
  const eye = layers[`eye_${side}`];
1348
2128
  const iris = layers[`iris_${side}`];
@@ -1371,8 +2151,8 @@ async function measureDir(absDir, noseSpeck) {
1371
2151
  }
1372
2152
  if (lash) {
1373
2153
  const { opaque, off } = await lashOffSclera(
1374
- import_node_path5.default.join(absDir, `eye_${side}.png`),
1375
- import_node_path5.default.join(absDir, `lash_${side}.png`)
2154
+ import_node_path6.default.join(absDir, `eye_${side}.png`),
2155
+ import_node_path6.default.join(absDir, `lash_${side}.png`)
1376
2156
  );
1377
2157
  const dTop = lash.marginTop - eye.marginTop;
1378
2158
  const faults = [
@@ -1398,11 +2178,11 @@ async function measureDir(absDir, noseSpeck) {
1398
2178
  if (noseSpeck !== void 0) {
1399
2179
  warnings.push(noseSpeckWarning(noseSpeck, "compose"));
1400
2180
  } else if (layers.nose !== void 0) {
1401
- const nose = await decodePng(import_node_path5.default.join(absDir, "nose.png"));
1402
- const core = (0, import_editor6.denseCoreOf)(nose.rgba, nose.width, nose.height);
2181
+ const nose = await decodePng(import_node_path6.default.join(absDir, "nose.png"));
2182
+ const core = (0, import_editor9.denseCoreOf)(nose.rgba, nose.width, nose.height);
1403
2183
  if (core !== null) {
1404
2184
  const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);
1405
- if ((0, import_editor6.isSpeckCore)(core, crop))
2185
+ if ((0, import_editor9.isSpeckCore)(core, crop))
1406
2186
  warnings.push(noseSpeckWarning({ core, part: crop }, "layer"));
1407
2187
  }
1408
2188
  }
@@ -1416,7 +2196,12 @@ async function measureDir(absDir, noseSpeck) {
1416
2196
  ]) {
1417
2197
  if (layers[role] === void 0) warnings.push(`${role}: missing \u2014 ${why}.`);
1418
2198
  }
1419
- return { layers, empty, warnings };
2199
+ return {
2200
+ layers,
2201
+ empty,
2202
+ warnings,
2203
+ ...lip.lips === void 0 ? {} : { lips: lip.lips }
2204
+ };
1420
2205
  }
1421
2206
  async function measureLayers(input) {
1422
2207
  try {
@@ -1450,6 +2235,13 @@ function formatMeasureReport(result) {
1450
2235
  `${role.padEnd(13)} ${`${m.w}x${m.h}`.padEnd(11)} ${`${m.bboxCx.toFixed(0)},${m.bboxCy.toFixed(0)}`.padEnd(14)} ${`${m.massCx.toFixed(0)},${m.massCy.toFixed(0)}`.padEnd(13)} ${m.marginTop}/${m.marginBottom}/${m.marginLeft}/${m.marginRight}`
1451
2236
  );
1452
2237
  }
2238
+ if (result.lips !== void 0) {
2239
+ const { opening, deadZone } = result.lips;
2240
+ lines.push(
2241
+ "",
2242
+ `lips: opening ${opening.width} px wide, ${opening.height} px tall at its centre under a ${opening.line} px line \u2014 no slit below MouthOpen ${deadZone.toFixed(2)}`
2243
+ );
2244
+ }
1453
2245
  lines.push("", "# checks", "");
1454
2246
  if (result.warnings.length === 0) {
1455
2247
  lines.push("all geometry checks passed");
@@ -1460,13 +2252,13 @@ function formatMeasureReport(result) {
1460
2252
  }
1461
2253
 
1462
2254
  // src/compose-arms.ts
1463
- var import_sharp2 = __toESM(require("sharp"));
1464
- var import_editor7 = require("@ikijs/editor");
2255
+ var import_sharp3 = __toESM(require("sharp"));
2256
+ var import_editor10 = require("@ikijs/editor");
1465
2257
  var ARM_WIDTH = 0.4;
1466
2258
  var SHOULDER_DROP = 0.12;
1467
2259
  async function armPlacement(role, cfg, part, body) {
1468
- const { data } = await (0, import_sharp2.default)(part.buf).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1469
- const layer = (0, import_editor7.createLayerSetMeasurer)({ width: part.w, height: part.h }).add({
2260
+ const { data } = await (0, import_sharp3.default)(part.buf).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2261
+ const layer = (0, import_editor10.createLayerSetMeasurer)({ width: part.w, height: part.h }).add({
1470
2262
  role,
1471
2263
  fileName: "arm.png",
1472
2264
  rgba: data
@@ -1478,9 +2270,9 @@ async function armPlacement(role, cfg, part, body) {
1478
2270
  }
1479
2271
  let g;
1480
2272
  try {
1481
- g = (0, import_editor7.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
2273
+ g = (0, import_editor10.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
1482
2274
  } catch (err) {
1483
- if (err instanceof import_editor7.LayerGeometryError) {
2275
+ if (err instanceof import_editor10.LayerGeometryError) {
1484
2276
  throw new AutoRigInputError(`layout.${role}: ${err.message}`);
1485
2277
  }
1486
2278
  throw err;
@@ -1506,8 +2298,8 @@ async function armPlacement(role, cfg, part, body) {
1506
2298
  };
1507
2299
  }
1508
2300
  async function poseGeometryOf(role, png, size, when) {
1509
- const { data } = await (0, import_sharp2.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1510
- const layer = (0, import_editor7.createLayerSetMeasurer)({
2301
+ const { data } = await (0, import_sharp3.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2302
+ const layer = (0, import_editor10.createLayerSetMeasurer)({
1511
2303
  width: size.w,
1512
2304
  height: size.h
1513
2305
  }).add({ role, fileName: "forearm_pose.png", rgba: data });
@@ -1516,7 +2308,7 @@ async function poseGeometryOf(role, png, size, when) {
1516
2308
  `layout.${role}: forearm_pose.png is empty after alpha threshold${when}`
1517
2309
  );
1518
2310
  }
1519
- return (0, import_editor7.forearmPoseGeometry)(layer);
2311
+ return (0, import_editor10.forearmPoseGeometry)(layer);
1520
2312
  }
1521
2313
  async function forearmPoseWidth(role, trimmed, elbowRun) {
1522
2314
  const g = await poseGeometryOf(role, trimmed.data, trimmed, "");
@@ -1546,8 +2338,6 @@ var IRIS_W = 50;
1546
2338
  var EYEWHITE_SRC = "eyewhite.png";
1547
2339
  var EYE_LASH_LUMA = 120;
1548
2340
  var LASH_KEEP_FRACTION = 0.5;
1549
- var TRIM_THRESHOLD = 12;
1550
- var STRAY_SPECK_FRACTION = 0.01;
1551
2341
  var NOSE_TIP_AT = 0.66;
1552
2342
  var DEFAULT_LAYOUT = {
1553
2343
  // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir
@@ -1598,6 +2388,18 @@ var DEFAULT_LAYOUT = {
1598
2388
  w: 76,
1599
2389
  optional: true
1600
2390
  },
2391
+ // The lip set's ONE frame, mouth_open's place: the keyed mouth is split into
2392
+ // mouth_inner / lip_lower / lip_upper and all three land here, so a retune
2393
+ // moves them together. lip_lower and lip_upper have no key of their own
2394
+ // (LIP_FRAME). OPTIONAL and opt-in: with mouth_keyed.png + mouth_interior.png
2395
+ // it stands in for mouth and mouth_open.
2396
+ mouth_inner: {
2397
+ src: KEYED_SRC,
2398
+ cx: 550,
2399
+ cy: 596,
2400
+ w: 76,
2401
+ optional: true
2402
+ },
1601
2403
  // eye_* (sclera) and lash_* share the eyewhite's cropped frame via noTrim (so
1602
2404
  // they are NOT re-bboxed independently): the upper lash stays anchored ABOVE
1603
2405
  // the sclera center, so on blink it folds DOWN over the eye like the sample
@@ -1644,6 +2446,9 @@ var ORDER = [
1644
2446
  "nose",
1645
2447
  "mouth",
1646
2448
  "mouth_open",
2449
+ "mouth_inner",
2450
+ "lip_lower",
2451
+ "lip_upper",
1647
2452
  "eye_L",
1648
2453
  "eye_R",
1649
2454
  "iris_L",
@@ -1662,13 +2467,15 @@ var PART_FILES = [
1662
2467
  ...new Set(
1663
2468
  Object.values(DEFAULT_LAYOUT).map((cfg) => cfg.src).filter((src) => !src.startsWith("eyewhite_"))
1664
2469
  ),
1665
- EYEWHITE_SRC
2470
+ EYEWHITE_SRC,
2471
+ INTERIOR_SRC
1666
2472
  ];
1667
2473
  var FACE_FEATURES = [
1668
2474
  "blush_L",
1669
2475
  "blush_R",
1670
2476
  "mouth",
1671
2477
  "mouth_open",
2478
+ "mouth_inner",
1672
2479
  "eye_L",
1673
2480
  "eye_R",
1674
2481
  "iris_L",
@@ -1772,20 +2579,20 @@ function keyWhiteToAlpha(rgba) {
1772
2579
  return keyed;
1773
2580
  }
1774
2581
  async function coreAndBoundsOf(png) {
1775
- const { data, info } = await (0, import_sharp3.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2582
+ const { data, info } = await (0, import_sharp4.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1776
2583
  return {
1777
- core: (0, import_editor6.denseCoreOf)(data, info.width, info.height),
2584
+ core: (0, import_editor9.denseCoreOf)(data, info.width, info.height),
1778
2585
  bounds: { x: 0, y: 0, w: info.width, h: info.height }
1779
2586
  };
1780
2587
  }
1781
2588
  async function hasCoverage(png) {
1782
- const { data, info } = await (0, import_sharp3.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1783
- return (0, import_editor8.detectAlphaBbox)(data, info.width, info.height) !== null;
2589
+ const { data, info } = await (0, import_sharp4.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2590
+ return (0, import_editor11.detectAlphaBbox)(data, info.width, info.height) !== null;
1784
2591
  }
1785
2592
  async function noseSizingOf(png) {
1786
2593
  const { core, bounds } = await coreAndBoundsOf(png);
1787
2594
  if (core === null) return { box: bounds, whole: true };
1788
- if ((0, import_editor6.isSpeckCore)(core, bounds)) {
2595
+ if ((0, import_editor9.isSpeckCore)(core, bounds)) {
1789
2596
  return {
1790
2597
  box: bounds,
1791
2598
  whole: true,
@@ -1800,24 +2607,24 @@ async function noseSizingOf(png) {
1800
2607
  async function trimmedPart(role, cfg, partsDir, inMemory, flipSource) {
1801
2608
  let img;
1802
2609
  if (inMemory !== void 0) {
1803
- img = (0, import_sharp3.default)(inMemory);
2610
+ img = (0, import_sharp4.default)(inMemory);
1804
2611
  } else {
1805
- const srcPath = import_node_path6.default.join(partsDir, cfg.src);
2612
+ const srcPath = import_node_path7.default.join(partsDir, cfg.src);
1806
2613
  if (!import_node_fs3.default.existsSync(srcPath)) {
1807
2614
  if (cfg.optional) return null;
1808
2615
  throw new AutoRigInputError(
1809
- `missing part source for role "${role}": ${srcPath}`
2616
+ `missing part source for role "${role}": ${srcPath}` + (role === "mouth" ? " \u2014 draw mouth.png (with mouth_open.png), or the lip set's mouth_keyed.png + mouth_interior.png" : "")
1810
2617
  );
1811
2618
  }
1812
2619
  const png = await decodePng(srcPath);
1813
- img = (0, import_sharp3.default)(png.hasAlpha ? png.rgba : keyWhiteToAlpha(png.rgba), {
2620
+ img = (0, import_sharp4.default)(png.hasAlpha ? png.rgba : keyWhiteToAlpha(png.rgba), {
1814
2621
  raw: { width: png.width, height: png.height, channels: 4 }
1815
2622
  });
1816
2623
  }
1817
2624
  if (!cfg.noTrim) {
1818
2625
  const kept = await img.trim({ threshold: TRIM_THRESHOLD }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1819
2626
  const { width: keptW, height: keptH } = kept.info;
1820
- img = (0, import_sharp3.default)(kept.data, {
2627
+ img = (0, import_sharp4.default)(kept.data, {
1821
2628
  raw: { width: keptW, height: keptH, channels: 4 }
1822
2629
  });
1823
2630
  const box = boxWithoutStraySpecks(kept.data, keptW, keptH);
@@ -1843,7 +2650,7 @@ async function sizedPart(role, cfg, trimmed, canvas) {
1843
2650
  `layout.${role}.${field}: resized part ${width}x${height} exceeds the ${canvasName(canvas)} canvas`
1844
2651
  );
1845
2652
  }
1846
- const resized = await (0, import_sharp3.default)(trimmed.data).resize(cfg.h === void 0 ? { width } : { width, height, fit: "fill" }).png().toBuffer({ resolveWithObject: true });
2653
+ const resized = await (0, import_sharp4.default)(trimmed.data).resize(cfg.h === void 0 ? { width } : { width, height, fit: "fill" }).png().toBuffer({ resolveWithObject: true });
1847
2654
  return {
1848
2655
  buf: resized.data,
1849
2656
  w: resized.info.width,
@@ -1868,7 +2675,7 @@ function placement(role, cfg, w, h, canvas) {
1868
2675
  assertOnCanvas(`layout.${role}.cx/cy`, w, h, left, top, canvas);
1869
2676
  return { left, top };
1870
2677
  }
1871
- function nosePlacement(layout, box, w, h, canvas) {
2678
+ function nosePlacement(layout, mouthKey, box, w, h, canvas) {
1872
2679
  const { cx, cy } = layout.nose;
1873
2680
  const left = Math.round(cx - (box.x + box.w / 2));
1874
2681
  let top;
@@ -1877,12 +2684,12 @@ function nosePlacement(layout, box, w, h, canvas) {
1877
2684
  } else {
1878
2685
  const eyeRow = (layout.eye_L.cy + layout.eye_R.cy) / 2;
1879
2686
  const tipRow = Math.round(
1880
- eyeRow + NOSE_TIP_AT * (layout.mouth.cy - eyeRow)
2687
+ eyeRow + NOSE_TIP_AT * (layout[mouthKey].cy - eyeRow)
1881
2688
  );
1882
2689
  top = tipRow - (box.y + box.h - 1);
1883
2690
  }
1884
2691
  assertOnCanvas(
1885
- 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)",
2692
+ cy !== void 0 ? "layout.nose.cx/cy" : `layout.nose.cx/cy (cy unset: its tip row comes from layout.eye_L/eye_R/${mouthKey}.cy)`,
1886
2693
  w,
1887
2694
  h,
1888
2695
  left,
@@ -1892,7 +2699,7 @@ function nosePlacement(layout, box, w, h, canvas) {
1892
2699
  return { left, top };
1893
2700
  }
1894
2701
  function blankCanvas(canvas) {
1895
- return (0, import_sharp3.default)({
2702
+ return (0, import_sharp4.default)({
1896
2703
  create: {
1897
2704
  width: canvas.width,
1898
2705
  height: canvas.height,
@@ -1901,74 +2708,13 @@ function blankCanvas(canvas) {
1901
2708
  }
1902
2709
  });
1903
2710
  }
1904
- function luma(rgba, i) {
1905
- return 0.299 * rgba[i] + 0.587 * rgba[i + 1] + 0.114 * rgba[i + 2];
1906
- }
1907
- function boxWithoutStraySpecks(rgba, W, H) {
1908
- const n = W * H;
1909
- let kept = 0;
1910
- for (let p = 0; p < n; p++) if (rgba[p * 4 + 3] > TRIM_THRESHOLD) kept++;
1911
- const visited = new Uint8Array(n);
1912
- let stack = new Int32Array(1024);
1913
- const drawing = [W, H, -1, -1];
1914
- const strays = [W, H, -1, -1];
1915
- let anyOpaque = false;
1916
- for (let start = 0; start < n; start++) {
1917
- if (visited[start] || rgba[start * 4 + 3] <= TRIM_THRESHOLD) continue;
1918
- let setLeft = W;
1919
- let setTop = H;
1920
- let setRight = -1;
1921
- let setBottom = -1;
1922
- let size = 0;
1923
- let opaque = false;
1924
- let depth = 0;
1925
- visited[start] = 1;
1926
- stack[depth++] = start;
1927
- while (depth > 0) {
1928
- const p = stack[--depth];
1929
- size++;
1930
- if (rgba[p * 4 + 3] >= import_editor8.ALPHA_OPAQUE) opaque = true;
1931
- const px2 = p % W;
1932
- const py = (p - px2) / W;
1933
- setLeft = Math.min(setLeft, px2);
1934
- setTop = Math.min(setTop, py);
1935
- setRight = Math.max(setRight, px2);
1936
- setBottom = Math.max(setBottom, py);
1937
- for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {
1938
- for (let x = Math.max(0, px2 - 1); x <= Math.min(W - 1, px2 + 1); x++) {
1939
- const q = y * W + x;
1940
- if (!visited[q] && rgba[q * 4 + 3] > TRIM_THRESHOLD) {
1941
- visited[q] = 1;
1942
- if (depth === stack.length) {
1943
- const grown = new Int32Array(Math.min(n, stack.length * 2));
1944
- grown.set(stack);
1945
- stack = grown;
1946
- }
1947
- stack[depth++] = q;
1948
- }
1949
- }
1950
- }
1951
- }
1952
- anyOpaque ||= opaque;
1953
- const into = !opaque && size < kept * STRAY_SPECK_FRACTION ? strays : drawing;
1954
- into[0] = Math.min(into[0], setLeft);
1955
- into[1] = Math.min(into[1], setTop);
1956
- into[2] = Math.max(into[2], setRight);
1957
- into[3] = Math.max(into[3], setBottom);
1958
- }
1959
- if (!anyOpaque || strays[2] < 0) return null;
1960
- const [left, top, right, bottom] = drawing;
1961
- if (strays[0] >= left && strays[1] >= top && strays[2] <= right && strays[3] <= bottom)
1962
- return null;
1963
- return { left, top, width: right - left + 1, height: bottom - top + 1 };
1964
- }
1965
2711
  function detachedAboveWhite(rgba, W, H) {
1966
2712
  const n = W * H;
1967
2713
  const ink = new Uint8Array(n);
1968
2714
  for (let p = 0; p < n; p++) {
1969
2715
  const alpha = rgba[p * 4 + 3];
1970
2716
  if (alpha > 0 && luma(rgba, p * 4) >= EYE_LASH_LUMA)
1971
- ink[p] = alpha >= import_editor8.ALPHA_OPAQUE ? 2 : 1;
2717
+ ink[p] = alpha >= import_editor11.ALPHA_OPAQUE ? 2 : 1;
1972
2718
  }
1973
2719
  const label = new Int32Array(n).fill(-1);
1974
2720
  const stack = new Int32Array(n);
@@ -2048,7 +2794,7 @@ function detachedAboveWhite(rgba, W, H) {
2048
2794
  return detached;
2049
2795
  }
2050
2796
  async function prepEyeSplit(partsDir) {
2051
- const srcPath = import_node_path6.default.join(partsDir, EYEWHITE_SRC);
2797
+ const srcPath = import_node_path7.default.join(partsDir, EYEWHITE_SRC);
2052
2798
  if (!import_node_fs3.default.existsSync(srcPath)) {
2053
2799
  throw new AutoRigInputError(`missing eyewhite source: ${srcPath}`);
2054
2800
  }
@@ -2100,6 +2846,50 @@ async function prepEyeSplit(partsDir) {
2100
2846
  lashLower: lowerInk ? await cropToBuffer(lashLower, W, H, region) : null
2101
2847
  };
2102
2848
  }
2849
+ function hasTransparency(rgba) {
2850
+ for (let p = 3; p < rgba.length; p += 4) if (rgba[p] < 255) return true;
2851
+ return false;
2852
+ }
2853
+ async function prepLipSources(partsDir, mirrored) {
2854
+ const has = (name) => import_node_fs3.default.existsSync(import_node_path7.default.join(partsDir, name));
2855
+ const keyed = has(KEYED_SRC);
2856
+ const interior = has(INTERIOR_SRC);
2857
+ if (keyed && !interior) {
2858
+ throw new AutoRigInputError(
2859
+ `${KEYED_SRC} needs ${INTERIOR_SRC}: the composer fits the drawn interior into the keyed opening \u2014 draw it (billed)`
2860
+ );
2861
+ }
2862
+ if (interior && !keyed) {
2863
+ throw new AutoRigInputError(
2864
+ `${INTERIOR_SRC} needs ${KEYED_SRC}: the composer cuts the lip set from the keyed open mouth and fits the interior into its opening \u2014 draw it (billed)`
2865
+ );
2866
+ }
2867
+ if (!keyed) return void 0;
2868
+ const legacy = ["mouth.png", "mouth_open.png"].filter(has);
2869
+ if (legacy.length > 0) {
2870
+ throw new AutoRigInputError(
2871
+ `${KEYED_SRC}/${INTERIOR_SRC} cannot be composed beside mouth.png/mouth_open.png (the lip set replaces the mouth drawings, and auto_rig_from_layers refuses the mix) \u2014 remove ${legacy.join(" and ")}`
2872
+ );
2873
+ }
2874
+ const k = await decodePng(import_node_path7.default.join(partsDir, KEYED_SRC));
2875
+ const keyedRgba = keyGreen(
2876
+ hasTransparency(k.rgba) ? k.rgba : keyWhiteToAlpha(k.rgba),
2877
+ k.width,
2878
+ k.height
2879
+ );
2880
+ const i = await decodePng(import_node_path7.default.join(partsDir, INTERIOR_SRC));
2881
+ const prepared = await prepInterior(
2882
+ hasTransparency(i.rgba) ? i.rgba : keyBorderWhite(i.rgba, i.width, i.height),
2883
+ i.width,
2884
+ i.height
2885
+ );
2886
+ return {
2887
+ keyedPng: await (0, import_sharp4.default)(keyedRgba, {
2888
+ raw: { width: k.width, height: k.height, channels: 4 }
2889
+ }).png().toBuffer(),
2890
+ interior: mirrored.has(INTERIOR_SRC) ? { ...prepared, png: await (0, import_sharp4.default)(prepared.png).flop().png().toBuffer() } : prepared
2891
+ };
2892
+ }
2103
2893
  async function composeLayersFromParts(input) {
2104
2894
  try {
2105
2895
  const outDir = resolveOutputDir(input.outDir);
@@ -2123,10 +2913,49 @@ async function composeLayersFromParts(input) {
2123
2913
  if (split.lashLower !== null) {
2124
2914
  splitSources.set(LOWER_LASH_SRC, split.lashLower);
2125
2915
  }
2916
+ const lips = await prepLipSources(partsDir, mirrored);
2917
+ let lipSplit;
2126
2918
  const placed = [];
2127
2919
  const skipped = [];
2128
2920
  let noseSpeck;
2129
2921
  for (const role of ORDER) {
2922
+ if (lips !== void 0 && (role === "mouth" || role === "mouth_open")) {
2923
+ continue;
2924
+ }
2925
+ if (role === "mouth_inner") {
2926
+ if (lips === void 0) continue;
2927
+ const cfg2 = layout.mouth_inner;
2928
+ const part2 = await partBuffer(
2929
+ role,
2930
+ cfg2,
2931
+ partsDir,
2932
+ lips.keyedPng,
2933
+ mirrored.has(KEYED_SRC),
2934
+ canvas
2935
+ );
2936
+ const split2 = await splitLipSet(
2937
+ part2.buf,
2938
+ part2.w,
2939
+ part2.h,
2940
+ lips.interior
2941
+ );
2942
+ const { left: left2, top: top2 } = placement(role, cfg2, part2.w, part2.h, canvas);
2943
+ lipSplit = { split: split2, w: part2.w, h: part2.h, left: left2, top: top2 };
2944
+ placed.push({
2945
+ role,
2946
+ part: { buf: split2.inner, w: part2.w, h: part2.h },
2947
+ left: left2,
2948
+ top: top2
2949
+ });
2950
+ continue;
2951
+ }
2952
+ if (role === "lip_lower" || role === "lip_upper") {
2953
+ if (lipSplit === void 0) continue;
2954
+ const { split: split2, w, h, left: left2, top: top2 } = lipSplit;
2955
+ const buf = role === "lip_lower" ? split2.lower : split2.upper;
2956
+ placed.push({ role, part: { buf, w, h }, left: left2, top: top2 });
2957
+ continue;
2958
+ }
2130
2959
  const lower = role === "lash_lower_L" || role === "lash_lower_R";
2131
2960
  const key = lower ? LOWER_LASH[role] : role;
2132
2961
  if (lower && split.lashLower === null) {
@@ -2135,7 +2964,7 @@ async function composeLayersFromParts(input) {
2135
2964
  }
2136
2965
  if (key === "arm_L" || key === "arm_R") {
2137
2966
  const arm = layout[key];
2138
- if (!import_node_fs3.default.existsSync(import_node_path6.default.join(partsDir, arm.src))) continue;
2967
+ if (!import_node_fs3.default.existsSync(import_node_path7.default.join(partsDir, arm.src))) continue;
2139
2968
  const body = placed.find((p) => p.role === "body");
2140
2969
  if (body === void 0) {
2141
2970
  throw new AutoRigInputError(
@@ -2178,7 +3007,7 @@ async function composeLayersFromParts(input) {
2178
3007
  }
2179
3008
  if (key === "forearm_pose_L" || key === "forearm_pose_R") {
2180
3009
  const pose = layout[key];
2181
- if (!import_node_fs3.default.existsSync(import_node_path6.default.join(partsDir, pose.src))) continue;
3010
+ if (!import_node_fs3.default.existsSync(import_node_path7.default.join(partsDir, pose.src))) continue;
2182
3011
  const armRole = key === "forearm_pose_L" ? "arm_L" : "arm_R";
2183
3012
  const arm = placed.find((p) => p.role === armRole);
2184
3013
  if (arm?.elbow === void 0 || arm.elbowRun === void 0) {
@@ -2249,7 +3078,14 @@ async function composeLayersFromParts(input) {
2249
3078
  noseSpeck = part.nose?.speck;
2250
3079
  const { core, bounds } = await coreAndBoundsOf(part.buf);
2251
3080
  const box = part.nose?.whole ? bounds : core ?? bounds;
2252
- ({ left, top } = nosePlacement(layout, box, part.w, part.h, canvas));
3081
+ ({ left, top } = nosePlacement(
3082
+ layout,
3083
+ lips === void 0 ? "mouth" : "mouth_inner",
3084
+ box,
3085
+ part.w,
3086
+ part.h,
3087
+ canvas
3088
+ ));
2253
3089
  } else {
2254
3090
  ({ left, top } = placement(key, layout[key], part.w, part.h, canvas));
2255
3091
  }
@@ -2264,20 +3100,39 @@ async function composeLayersFromParts(input) {
2264
3100
  }
2265
3101
  placed.push({ role, part, left, top });
2266
3102
  }
3103
+ const built = /* @__PURE__ */ new Map();
3104
+ for (const { role, part, left, top } of placed) {
3105
+ built.set(
3106
+ role,
3107
+ await blankCanvas(canvas).composite([{ input: part.buf, left, top }]).png().toBuffer()
3108
+ );
3109
+ }
3110
+ const closed = lipSplit === void 0 ? void 0 : await closedLips(
3111
+ lipSplit.split.upper,
3112
+ lipSplit.split.lower,
3113
+ await restShiftOf(
3114
+ {
3115
+ mouth_inner: built.get("mouth_inner"),
3116
+ lip_lower: built.get("lip_lower"),
3117
+ lip_upper: built.get("lip_upper")
3118
+ },
3119
+ canvas.width,
3120
+ canvas.height
3121
+ ),
3122
+ lipSplit.left
3123
+ );
2267
3124
  for (const role of ORDER) {
2268
3125
  if (placed.some((p) => p.role === role)) continue;
2269
- import_node_fs3.default.rmSync(import_node_path6.default.join(outDir, `${role}.png`), { force: true });
3126
+ import_node_fs3.default.rmSync(import_node_path7.default.join(outDir, `${role}.png`), { force: true });
2270
3127
  }
2271
3128
  const posed = (role) => role === "forearm_pose_L" || role === "forearm_pose_R";
2272
3129
  if (!placed.some((p) => posed(p.role))) {
2273
- import_node_fs3.default.rmSync(import_node_path6.default.join(outDir, "preview-pose.png"), { force: true });
3130
+ import_node_fs3.default.rmSync(import_node_path7.default.join(outDir, "preview-pose.png"), { force: true });
2274
3131
  }
2275
3132
  const layers = [];
2276
- const preview = [];
2277
3133
  for (const { role, part, left, top } of placed) {
2278
- const layer = await blankCanvas(canvas).composite([{ input: part.buf, left, top }]).png().toBuffer();
2279
- const outPath = import_node_path6.default.join(outDir, `${role}.png`);
2280
- writeFileAtomic(outPath, layer);
3134
+ const outPath = import_node_path7.default.join(outDir, `${role}.png`);
3135
+ writeFileAtomic(outPath, built.get(role));
2281
3136
  layers.push({
2282
3137
  role,
2283
3138
  path: outPath,
@@ -2286,9 +3141,20 @@ async function composeLayersFromParts(input) {
2286
3141
  left,
2287
3142
  top
2288
3143
  });
2289
- if (!posed(role)) preview.push({ input: part.buf, left, top });
2290
3144
  }
2291
- const previewPng = await (0, import_sharp3.default)({
3145
+ const restInput = (role, buf) => {
3146
+ if (role === "mouth_inner") return null;
3147
+ if (closed === void 0) return buf;
3148
+ if (role === "lip_upper") return closed.upper;
3149
+ if (role === "lip_lower") return closed.lower;
3150
+ return buf;
3151
+ };
3152
+ const preview = [];
3153
+ for (const { role, part, left, top } of placed) {
3154
+ const input2 = restInput(role, part.buf);
3155
+ if (!posed(role) && input2 !== null) preview.push({ input: input2, left, top });
3156
+ }
3157
+ const previewPng = await (0, import_sharp4.default)({
2292
3158
  create: {
2293
3159
  width: canvas.width,
2294
3160
  height: canvas.height,
@@ -2296,7 +3162,7 @@ async function composeLayersFromParts(input) {
2296
3162
  background: { r: 245, g: 245, b: 248, alpha: 1 }
2297
3163
  }
2298
3164
  }).composite(preview).png().toBuffer();
2299
- const previewPath = import_node_path6.default.join(outDir, "preview.png");
3165
+ const previewPath = import_node_path7.default.join(outDir, "preview.png");
2300
3166
  writeFileAtomic(previewPath, previewPng);
2301
3167
  let previewPosePath;
2302
3168
  if (placed.some((p) => posed(p.role))) {
@@ -2306,17 +3172,18 @@ async function composeLayersFromParts(input) {
2306
3172
  (p) => p.role === (role === "arm_L" ? "forearm_pose_L" : "forearm_pose_R")
2307
3173
  );
2308
3174
  if (!armPosed) {
2309
- pose.push({ input: part.buf, left, top });
3175
+ const input2 = restInput(role, part.buf);
3176
+ if (input2 !== null) pose.push({ input: input2, left, top });
2310
3177
  continue;
2311
3178
  }
2312
3179
  const rows = Math.min(part.h, Math.max(1, Math.round(elbow.y - top)));
2313
3180
  pose.push({
2314
- input: await (0, import_sharp3.default)(part.buf).extract({ left: 0, top: 0, width: part.w, height: rows }).png().toBuffer(),
3181
+ input: await (0, import_sharp4.default)(part.buf).extract({ left: 0, top: 0, width: part.w, height: rows }).png().toBuffer(),
2315
3182
  left,
2316
3183
  top
2317
3184
  });
2318
3185
  }
2319
- const posePng = await (0, import_sharp3.default)({
3186
+ const posePng = await (0, import_sharp4.default)({
2320
3187
  create: {
2321
3188
  width: canvas.width,
2322
3189
  height: canvas.height,
@@ -2324,7 +3191,7 @@ async function composeLayersFromParts(input) {
2324
3191
  background: { r: 245, g: 245, b: 248, alpha: 1 }
2325
3192
  }
2326
3193
  }).composite(pose).png().toBuffer();
2327
- previewPosePath = import_node_path6.default.join(outDir, "preview-pose.png");
3194
+ previewPosePath = import_node_path7.default.join(outDir, "preview-pose.png");
2328
3195
  writeFileAtomic(previewPosePath, posePng);
2329
3196
  }
2330
3197
  return {
@@ -2347,7 +3214,7 @@ async function composeLayersFromParts(input) {
2347
3214
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
2348
3215
  var import_zod = require("zod");
2349
3216
  function createIkiMcpServer() {
2350
- const server = new import_mcp.McpServer({ name: "iki", version: "0.21.0" });
3217
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.22.0" });
2351
3218
  server.registerTool(
2352
3219
  "validate_iki",
2353
3220
  {
@@ -2467,7 +3334,7 @@ function createIkiMcpServer() {
2467
3334
  server.registerTool(
2468
3335
  "compose_layers_from_parts",
2469
3336
  {
2470
- 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`.",
3337
+ 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, eyewhite, iris, brow, hair_front are required, with mouth.png \u2014 or the lip set's mouth_keyed.png (the open mouth, its inside painted flat #00FF00) + mouth_interior.png (the cavity, teeth and tongue alone), which the composer keys and splits into mouth_inner / lip_lower / lip_upper on one frame so auto_rig_from_layers folds the mouth open like the eyelid; the two routes cannot be mixed, one keyed file without the other is refused, and a key that fails (no green, green outside the opening, an outline not closed round it, more than one opening, no skin under the opening, an interior that is only lips, or one drawn opaque on a non-white or noisy ground) is refused naming the regeneration; with the lip set neither mouth nor mouth_open is written and preview.png shows the mouth closed, as the rig draws the rest pose. hair_back, body, mouth_open (legacy route only), 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`.",
2471
3338
  inputSchema: {
2472
3339
  partsDir: import_zod.z.string().describe(
2473
3340
  "Directory of the source part PNGs (resolved against cwd)."
@@ -2484,7 +3351,7 @@ function createIkiMcpServer() {
2484
3351
  h: import_zod.z.number()
2485
3352
  }).partial()
2486
3353
  ).optional().describe(
2487
- "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."
3354
+ "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, mouth_inner, 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, mouth_inner, 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. mouth_inner is the lip set's one frame (mouth_open's place by default; lip_lower and lip_upper have no key and land on it, so a retune moves the three together), and with the lip set the nose's tip rule reads layout.mouth_inner.cy. 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."
2488
3355
  ),
2489
3356
  mirrorParts: import_zod.z.array(import_zod.z.string()).optional().describe(
2490
3357
  "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."
@@ -2515,7 +3382,7 @@ function createIkiMcpServer() {
2515
3382
  server.registerTool(
2516
3383
  "measure_layers",
2517
3384
  {
2518
- 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.",
3385
+ 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, and the lip set: a partial one or one beside mouth/mouth_open, the fold's contract per column of the opening, an opening too narrow or short, a line too thin, green left, an interior with holes \u2014 with the opening's size and the MouthOpen below which no slit shows). 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.",
2519
3386
  inputSchema: {
2520
3387
  layersDir: import_zod.z.string().describe(
2521
3388
  "Directory of role-named layer PNGs (resolved against cwd)."