@ikijs/mcp 0.21.0 → 0.23.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,781 @@ 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 hole = (q) => label[q] === main;
1353
+ const upperHalf = (x, y) => 2 * y < top[x] + bot[x];
1354
+ const faintUpper = (p, x, y) => y < bot[x] && hole(p) && upperHalf(x, y);
1355
+ const besideHole = (p, x, y) => x > 0 && hole(p - 1) || x < w - 1 && hole(p + 1) || y > 0 && hole(p - w) || y < h - 1 && hole(p + w);
1356
+ const upper = Buffer.alloc(n * 4);
1357
+ const lower = Buffer.alloc(n * 4);
1358
+ const inner = Buffer.alloc(n * 4);
1359
+ const tongue = Buffer.alloc(n * 4);
1360
+ const teeth = Buffer.alloc(n * 4);
1361
+ const copy = (to, p) => frame.copy(to, p * 4, p * 4, p * 4 + 4);
1362
+ for (let y = 0; y < h; y++) {
1363
+ for (let x = 0; x < w; x++) {
1364
+ const p = y * w + x;
1365
+ const inOpening = top[x] >= 0;
1366
+ if ((!inOpening || y < top[x] || faintUpper(p, x, y)) && !(wall[x] && grown[p]))
1367
+ copy(upper, p);
1368
+ if (inOpening && skinRow[x] >= 0 && y >= skinRow[x]) copy(lower, p);
1369
+ if (!grown[p]) {
1370
+ const a = alpha(p);
1371
+ if (a >= import_editor6.ALPHA_OPAQUE && a < 255 && besideHole(p, x, y)) {
1372
+ inner.set(interior.cavity, p * 4);
1373
+ inner[p * 4 + 3] = 255 - a;
1374
+ }
1375
+ continue;
1376
+ }
1377
+ const out = [...interior.cavity];
1378
+ const ix = x - gx;
1379
+ const iy = y - gy;
1380
+ if (ix >= 0 && ix < gw && iy >= 0 && iy < gh) {
1381
+ const i = (iy * gw + ix) * 4;
1382
+ const a = fitted[i + 3] / 255;
1383
+ for (let c = 0; c < 3; c++) out[c] += (fitted[i + c] - out[c]) * a;
1384
+ }
1385
+ if ((inM[p] || wall[x]) && !faintUpper(p, x, y)) {
1386
+ const a = alpha(p) / 255;
1387
+ for (let c = 0; c < 3; c++) out[c] += (frame[p * 4 + c] - out[c]) * a;
1388
+ }
1389
+ inner[p * 4] = Math.round(out[0]);
1390
+ inner[p * 4 + 1] = Math.round(out[1]);
1391
+ inner[p * 4 + 2] = Math.round(out[2]);
1392
+ inner[p * 4 + 3] = 255;
1393
+ if (hole(p) && luma(inner, p * 4) >= CAVITY_LUMA) {
1394
+ const to = upperHalf(x, y) ? teeth : tongue;
1395
+ inner.copy(to, p * 4, p * 4, p * 4 + 4);
1396
+ inner.set(interior.cavity, p * 4);
1397
+ }
1398
+ }
1399
+ }
1400
+ const opening = assertFoldContract(
1401
+ { mouth_inner: inner, lip_lower: lower, lip_upper: upper },
1402
+ w,
1403
+ h
1404
+ );
1405
+ const [innerPng, lowerPng, upperPng, tonguePng, teethPng] = await Promise.all(
1406
+ [inner, lower, upper, tongue, teeth].map((b) => encode(b, w, h))
1407
+ );
1408
+ return {
1409
+ inner: innerPng,
1410
+ lower: lowerPng,
1411
+ upper: upperPng,
1412
+ tongue: tonguePng,
1413
+ teeth: teethPng,
1414
+ opening
1415
+ };
1416
+ }
1417
+ async function restShiftOf(layers, width, height) {
1418
+ const [mouth_inner, lip_lower, lip_upper] = await Promise.all(
1419
+ [layers.mouth_inner, layers.lip_lower, layers.lip_upper].map(
1420
+ async (png) => (await rawOf(png)).data
1421
+ )
1422
+ );
1423
+ const byRole = /* @__PURE__ */ new Map();
1424
+ for (const [role, layer] of measureLips(
1425
+ { mouth_inner, lip_lower, lip_upper },
1426
+ width,
1427
+ height
1428
+ )) {
1429
+ if (layer === null) {
1430
+ throw new AutoRigInputError(
1431
+ `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`
1432
+ );
1433
+ }
1434
+ byRole.set(role, layer);
1435
+ }
1436
+ return (0, import_editor6.mouthRestShift)(byRole);
1437
+ }
1438
+ async function closedLips(upper, lower, shift, left, top) {
1439
+ const shut = async (png, role) => {
1440
+ const { data, info } = await rawOf(png);
1441
+ const { width: w, height: h } = info;
1442
+ const out = Buffer.alloc(w * h * 4);
1443
+ for (let x = 0; x < w; x++) {
1444
+ const px2 = (row, c) => row < 0 || row >= h ? 0 : data[(row * w + x) * 4 + c];
1445
+ const landed = [];
1446
+ for (let row = 0; row < h; row++) {
1447
+ const dy = shift(role, left + x, top + row);
1448
+ if (dy !== void 0) landed.push([row, row + 0.5 - dy]);
1449
+ }
1450
+ if (landed.length > 1) {
1451
+ const [a, b] = landed;
1452
+ const [y, z2] = landed.slice(-2);
1453
+ landed.unshift([a[0] - 1, 2 * a[1] - b[1]]);
1454
+ landed.push([z2[0] + 1, 2 * z2[1] - y[1]]);
1455
+ }
1456
+ let i = 0;
1457
+ for (let to = 0; to < h; to++) {
1458
+ const centre = to + 0.5;
1459
+ while (i + 1 < landed.length && landed[i + 1][1] < centre) i++;
1460
+ if (i + 1 >= landed.length || landed[i][1] > centre) continue;
1461
+ const [r0, y0] = landed[i];
1462
+ const [r1, y1] = landed[i + 1];
1463
+ const t = (centre - y0) / (y1 - y0);
1464
+ const a0 = px2(r0, 3);
1465
+ const a1 = px2(r1, 3);
1466
+ const a = (1 - t) * a0 + t * a1;
1467
+ if (a === 0) continue;
1468
+ const o = (to * w + x) * 4;
1469
+ for (let c = 0; c < 3; c++)
1470
+ out[o + c] = Math.round(
1471
+ ((1 - t) * a0 * px2(r0, c) + t * a1 * px2(r1, c)) / a
1472
+ );
1473
+ out[o + 3] = Math.round(a);
1474
+ }
1475
+ }
1476
+ return encode(out, w, h);
1477
+ };
1478
+ const [u, l] = await Promise.all([
1479
+ shut(upper, "lip_upper"),
1480
+ shut(lower, "lip_lower")
1481
+ ]);
1482
+ return { upper: u, lower: l };
1483
+ }
1484
+
1485
+ // src/measure-lips.ts
1486
+ var isLipLayerRole = (role) => import_editor7.LIP_ROLES.includes(role) || (0, import_editor7.isLipInsideRole)(role);
1487
+ var MIN_OPENING_ROWS = 8;
1488
+ var MIN_LINE_ROWS = 2;
1489
+ var GREEN_EXCESS = 40;
1490
+ var INTERIOR_GAP_FRACTION = 0.05;
1491
+ var columns = (cols) => `${cols.length} column${cols.length === 1 ? "" : "s"} (first at x=${cols[0]})`;
1492
+ async function lipWarnings(absDir, layers) {
1493
+ const warnings = [];
1494
+ const present = import_editor7.LIP_ROLES.filter((role) => layers[role] !== void 0);
1495
+ const inside = import_editor7.LIP_INSIDE_ROLES.filter((role) => layers[role] !== void 0);
1496
+ if (present.length === 0) {
1497
+ if (inside.length > 0) {
1498
+ warnings.push(
1499
+ `${inside.join("/")}: a lip set's inside layer with no lip set \u2014 auto_rig_from_layers refuses it (it is cut from the interior and clipped to it). Recompose from mouth_keyed.png + mouth_interior.png, or remove it.`
1500
+ );
1501
+ }
1502
+ return { warnings };
1503
+ }
1504
+ const legacy = ["mouth", "mouth_open"].filter(
1505
+ (role) => layers[role] !== void 0
1506
+ );
1507
+ if (legacy.length > 0) {
1508
+ warnings.push(
1509
+ `${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.`
1510
+ );
1511
+ }
1512
+ if (present.length < import_editor7.LIP_ROLES.length) {
1513
+ const missing = import_editor7.LIP_ROLES.filter((role) => layers[role] === void 0);
1514
+ warnings.push(
1515
+ `${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.`
1516
+ );
1517
+ return { warnings };
1518
+ }
1519
+ const { mouth_inner: inner, lip_upper: upper } = layers;
1520
+ for (const role of ["lip_lower", "lip_upper", ...inside]) {
1521
+ const stats = layers[role];
1522
+ if (stats.canvasW !== inner.canvasW || stats.canvasH !== inner.canvasH) {
1523
+ warnings.push(
1524
+ `${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.`
1525
+ );
1526
+ return { warnings };
1527
+ }
1528
+ }
1529
+ const box = (m) => ({
1530
+ x0: m.bboxCx - m.w / 2,
1531
+ x1: m.bboxCx + m.w / 2,
1532
+ y0: m.bboxCy - m.h / 2,
1533
+ y1: m.bboxCy + m.h / 2
1534
+ });
1535
+ const cavity = box(inner);
1536
+ for (const role of inside) {
1537
+ const b = box(layers[role]);
1538
+ if (b.x0 < cavity.x0 || b.x1 > cavity.x1 || b.y0 < cavity.y0 || b.y1 > cavity.y1) {
1539
+ warnings.push(
1540
+ `${role}: its box leaves mouth_inner's \u2014 the cavity clips it away there. Recompose from mouth_keyed.png + mouth_interior.png (free).`
1541
+ );
1542
+ }
1543
+ }
1544
+ const measurer = (0, import_editor7.createLayerSetMeasurer)({
1545
+ width: inner.canvasW,
1546
+ height: inner.canvasH
1547
+ });
1548
+ const set = /* @__PURE__ */ new Map();
1549
+ const green = [];
1550
+ for (const role of import_editor7.LIP_ROLES) {
1551
+ const fileName = `${role}.png`;
1552
+ const { rgba } = await decodePng(import_node_path4.default.join(absDir, fileName));
1553
+ set.set(role, measurer.add({ role, fileName, rgba }));
1554
+ for (let i = 0; i < rgba.length; i += 4) {
1555
+ if (rgba[i + 3] >= import_editor7.ALPHA_OPAQUE && rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS) {
1556
+ green.push(role);
1557
+ break;
1558
+ }
1559
+ }
1560
+ }
1561
+ let opening;
1562
+ try {
1563
+ opening = (0, import_editor7.mouthOpening)(set);
1564
+ } catch (err) {
1565
+ if (err instanceof import_editor7.LayerGeometryError) {
1566
+ warnings.push(err.message);
1567
+ return { warnings };
1568
+ }
1569
+ throw err;
1570
+ }
1571
+ const innerRuns = (0, import_editor7.columnRuns)(set.get("mouth_inner"));
1572
+ const noInterior = [];
1573
+ const gap = [];
1574
+ const noLine = [];
1575
+ const skinGap = [];
1576
+ let area = 0;
1577
+ let hollow = 0;
1578
+ for (let x = opening.x0; x <= opening.x1; x++) {
1579
+ const runs = innerRuns.get(x);
1580
+ if (runs === void 0) {
1581
+ noInterior.push(x);
1582
+ continue;
1583
+ }
1584
+ const span = runs[runs.length - 1][1] - runs[0][0];
1585
+ area += span;
1586
+ hollow += span - runs.reduce((n, r) => n + r[1] - r[0], 0);
1587
+ const c = opening.at(x);
1588
+ if (c.lineH <= 0) noLine.push(x);
1589
+ else if (c.Tu > c.T) gap.push(x);
1590
+ if (c.Bl < c.Bb) skinGap.push(x);
1591
+ }
1592
+ const recompose = (file, ask) => `Recompose from mouth_keyed.png + mouth_interior.png (free); if it persists, regenerate ${file} ${ask}. Billed.`;
1593
+ const regenKeyed = recompose(
1594
+ "mouth_keyed.png",
1595
+ "with a closed outline and solid lips under it"
1596
+ );
1597
+ if (noInterior.length > 0) {
1598
+ warnings.push(
1599
+ `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")}`
1600
+ );
1601
+ }
1602
+ if (gap.length > 0) {
1603
+ warnings.push(
1604
+ `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}`
1605
+ );
1606
+ }
1607
+ if (noLine.length > 0) {
1608
+ warnings.push(
1609
+ `lip_upper: no line above the interior in ${columns(noLine)} \u2014 nothing closes the mouth there. ${regenKeyed}`
1610
+ );
1611
+ }
1612
+ if (skinGap.length > 0) {
1613
+ warnings.push(
1614
+ `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}`
1615
+ );
1616
+ }
1617
+ const width = opening.x1 - opening.x0 + 1;
1618
+ const centre = opening.at(opening.centre);
1619
+ if (width < MIN_OPENING_WIDTH * upper.w) {
1620
+ warnings.push(
1621
+ `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.`
1622
+ );
1623
+ }
1624
+ if (centre.H < MIN_OPENING_ROWS) {
1625
+ const w = Math.ceil(upper.w * MIN_OPENING_ROWS / centre.H);
1626
+ const retune = w <= inner.canvasW ? w : null;
1627
+ warnings.push(
1628
+ `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.`
1629
+ );
1630
+ }
1631
+ if (opening.w < MIN_LINE_ROWS) {
1632
+ warnings.push(
1633
+ `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.`
1634
+ );
1635
+ }
1636
+ if (green.length > 0) {
1637
+ warnings.push(
1638
+ `${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.`
1639
+ );
1640
+ }
1641
+ if (area > 0 && hollow > INTERIOR_GAP_FRACTION * area) {
1642
+ warnings.push(
1643
+ `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.`
1644
+ );
1645
+ }
1646
+ return {
1647
+ warnings,
1648
+ lips: {
1649
+ opening: { width, height: centre.H, line: opening.w },
1650
+ deadZone: centre.overlap / (centre.H + centre.overlap)
1651
+ }
1652
+ };
1653
+ }
1654
+
1655
+ // src/measure-turn.ts
1656
+ var import_node_path5 = __toESM(require("path"));
1657
+ var import_editor8 = require("@ikijs/editor");
1658
+ var import_editor9 = require("@ikijs/editor");
822
1659
  var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
823
1660
  var IRIS_V_MIN = 0.18;
824
1661
  var IRIS_V_MAX = 0.95;
@@ -855,7 +1692,7 @@ function rgbToHsv(r, g, b) {
855
1692
  }
856
1693
  return [h, max === 0 ? 0 : d / max, max];
857
1694
  }
858
- function dilate(mask, width, height, r) {
1695
+ function dilate2(mask, width, height, r) {
859
1696
  const out = new Uint8Array(width * height);
860
1697
  for (let y = 0; y < height; y++) {
861
1698
  for (let x = 0; x < width; x++) {
@@ -894,9 +1731,9 @@ function erode(mask, width, height, r) {
894
1731
  return out;
895
1732
  }
896
1733
  function closeMask(mask, width, height, r) {
897
- return erode(dilate(mask, width, height, r), width, height, r);
1734
+ return erode(dilate2(mask, width, height, r), width, height, r);
898
1735
  }
899
- function components(mask, width, height, minArea) {
1736
+ function components2(mask, width, height, minArea) {
900
1737
  const seen = new Uint8Array(width * height);
901
1738
  const out = [];
902
1739
  for (let i = 0; i < width * height; i++) {
@@ -968,7 +1805,7 @@ async function measureTurnImage(filePath, iris) {
968
1805
  let transparent = false;
969
1806
  if (hasAlpha) {
970
1807
  for (let i = 0; i < n; i++) {
971
- if (rgba[i * 4 + 3] < import_editor5.ALPHA_OPAQUE) {
1808
+ if (rgba[i * 4 + 3] < import_editor8.ALPHA_OPAQUE) {
972
1809
  transparent = true;
973
1810
  break;
974
1811
  }
@@ -979,7 +1816,7 @@ async function measureTurnImage(filePath, iris) {
979
1816
  const fg = new Uint8Array(n);
980
1817
  const value = new Float32Array(n);
981
1818
  for (let i = 0; i < n; i++) {
982
- if (rgba[i * 4 + 3] < import_editor5.ALPHA_OPAQUE) continue;
1819
+ if (rgba[i * 4 + 3] < import_editor8.ALPHA_OPAQUE) continue;
983
1820
  const [hue, s, v] = rgbToHsv(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]);
984
1821
  if (maskMode === "alpha") {
985
1822
  fg[i] = 1;
@@ -1015,7 +1852,7 @@ async function measureTurnImage(filePath, iris) {
1015
1852
  }
1016
1853
  return count ? total / count : 0;
1017
1854
  };
1018
- const candidates = components(
1855
+ const candidates = components2(
1019
1856
  closeMask(irisMask, width, height, closeRadius),
1020
1857
  width,
1021
1858
  height,
@@ -1045,12 +1882,12 @@ async function measureTurnImage(filePath, iris) {
1045
1882
  }
1046
1883
  const [irisL, irisR] = best.pair;
1047
1884
  const eyeRow = Math.round((irisL.cy + irisR.cy) / 2);
1048
- const { left, right } = (0, import_editor5.foregroundSpan)(
1885
+ const { left, right } = (0, import_editor8.foregroundSpan)(
1049
1886
  fg,
1050
1887
  width,
1051
1888
  height,
1052
- eyeRow - import_editor5.HEAD_BAND,
1053
- eyeRow + import_editor5.HEAD_BAND
1889
+ eyeRow - import_editor8.HEAD_BAND,
1890
+ eyeRow + import_editor8.HEAD_BAND
1054
1891
  );
1055
1892
  if (right <= left) {
1056
1893
  throw new AutoRigInputError(
@@ -1074,7 +1911,7 @@ async function measureTurnImage(filePath, iris) {
1074
1911
  left,
1075
1912
  right,
1076
1913
  cx: (left + right) / 2,
1077
- half: (0, import_editor5.headHalfOf)({ left, right })
1914
+ half: (0, import_editor8.headHalfOf)({ left, right })
1078
1915
  },
1079
1916
  pairCx: (irisL.cx + irisR.cx) / 2,
1080
1917
  eyeGap: irisR.cx - irisL.cx
@@ -1089,9 +1926,9 @@ function overlaySvg(m) {
1089
1926
  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
1927
  }
1091
1928
  async function writeOverlay(debugDir, label, m) {
1092
- const outPath = import_node_path4.default.join(
1929
+ const outPath = import_node_path5.default.join(
1093
1930
  debugDir,
1094
- `${label}-${import_node_path4.default.basename(m.file, ".png")}.debug.png`
1931
+ `${label}-${import_node_path5.default.basename(m.file, ".png")}.debug.png`
1095
1932
  );
1096
1933
  writeFileAtomic(outPath, await encodeOverlayPng(m.file, overlaySvg(m)));
1097
1934
  return outPath;
@@ -1265,7 +2102,7 @@ function noseSpeckWarning({ core, part }, source) {
1265
2102
  `the layer's dense core is ${core.w}x${core.h} in its ${part.w}x${part.h} crop`,
1266
2103
  `auto_rig_from_layers turns and tilts the nose about its whole crop instead`
1267
2104
  ];
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.`;
2105
+ 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
2106
  }
1270
2107
  async function lashOffSclera(eyePath, lashPath) {
1271
2108
  const eye = await decodePng(eyePath);
@@ -1295,8 +2132,8 @@ async function measureDir(absDir, noseSpeck) {
1295
2132
  const layers = {};
1296
2133
  const empty = [];
1297
2134
  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));
2135
+ const role = import_node_path6.default.basename(f, ".png");
2136
+ const m = await layerStats(import_node_path6.default.join(absDir, f));
1300
2137
  if (!m) {
1301
2138
  empty.push(role);
1302
2139
  continue;
@@ -1305,6 +2142,7 @@ async function measureDir(absDir, noseSpeck) {
1305
2142
  }
1306
2143
  const warnings = [];
1307
2144
  for (const [role, m] of Object.entries(layers)) {
2145
+ if (isLipLayerRole(role)) continue;
1308
2146
  const edges = [
1309
2147
  ["top", m.edgeTop, m.w, m.marginTop],
1310
2148
  ["left", m.edgeLeft, m.h, m.marginLeft],
@@ -1334,7 +2172,7 @@ async function measureDir(absDir, noseSpeck) {
1334
2172
  }
1335
2173
  }
1336
2174
  for (const [role, m] of Object.entries(layers)) {
1337
- if (role === "body") continue;
2175
+ if (role === "body" || isLipLayerRole(role)) continue;
1338
2176
  if (m.flatCutRun > FLAT_CUT_MAX_FRAC * m.w && m.flatCutRun >= FLAT_CUT_MIN_PX) {
1339
2177
  warnings.push(
1340
2178
  `${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 +2181,8 @@ async function measureDir(absDir, noseSpeck) {
1343
2181
  }
1344
2182
  warnings.push(...await armWarnings(absDir, layers));
1345
2183
  warnings.push(...await forearmPoseWarnings(absDir, layers));
2184
+ const lip = await lipWarnings(absDir, layers);
2185
+ warnings.push(...lip.warnings);
1346
2186
  for (const side of ["L", "R"]) {
1347
2187
  const eye = layers[`eye_${side}`];
1348
2188
  const iris = layers[`iris_${side}`];
@@ -1371,8 +2211,8 @@ async function measureDir(absDir, noseSpeck) {
1371
2211
  }
1372
2212
  if (lash) {
1373
2213
  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`)
2214
+ import_node_path6.default.join(absDir, `eye_${side}.png`),
2215
+ import_node_path6.default.join(absDir, `lash_${side}.png`)
1376
2216
  );
1377
2217
  const dTop = lash.marginTop - eye.marginTop;
1378
2218
  const faults = [
@@ -1398,11 +2238,11 @@ async function measureDir(absDir, noseSpeck) {
1398
2238
  if (noseSpeck !== void 0) {
1399
2239
  warnings.push(noseSpeckWarning(noseSpeck, "compose"));
1400
2240
  } 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);
2241
+ const nose = await decodePng(import_node_path6.default.join(absDir, "nose.png"));
2242
+ const core = (0, import_editor9.denseCoreOf)(nose.rgba, nose.width, nose.height);
1403
2243
  if (core !== null) {
1404
2244
  const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);
1405
- if ((0, import_editor6.isSpeckCore)(core, crop))
2245
+ if ((0, import_editor9.isSpeckCore)(core, crop))
1406
2246
  warnings.push(noseSpeckWarning({ core, part: crop }, "layer"));
1407
2247
  }
1408
2248
  }
@@ -1416,7 +2256,12 @@ async function measureDir(absDir, noseSpeck) {
1416
2256
  ]) {
1417
2257
  if (layers[role] === void 0) warnings.push(`${role}: missing \u2014 ${why}.`);
1418
2258
  }
1419
- return { layers, empty, warnings };
2259
+ return {
2260
+ layers,
2261
+ empty,
2262
+ warnings,
2263
+ ...lip.lips === void 0 ? {} : { lips: lip.lips }
2264
+ };
1420
2265
  }
1421
2266
  async function measureLayers(input) {
1422
2267
  try {
@@ -1450,6 +2295,13 @@ function formatMeasureReport(result) {
1450
2295
  `${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
2296
  );
1452
2297
  }
2298
+ if (result.lips !== void 0) {
2299
+ const { opening, deadZone } = result.lips;
2300
+ lines.push(
2301
+ "",
2302
+ `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)}`
2303
+ );
2304
+ }
1453
2305
  lines.push("", "# checks", "");
1454
2306
  if (result.warnings.length === 0) {
1455
2307
  lines.push("all geometry checks passed");
@@ -1460,13 +2312,13 @@ function formatMeasureReport(result) {
1460
2312
  }
1461
2313
 
1462
2314
  // src/compose-arms.ts
1463
- var import_sharp2 = __toESM(require("sharp"));
1464
- var import_editor7 = require("@ikijs/editor");
2315
+ var import_sharp3 = __toESM(require("sharp"));
2316
+ var import_editor10 = require("@ikijs/editor");
1465
2317
  var ARM_WIDTH = 0.4;
1466
2318
  var SHOULDER_DROP = 0.12;
1467
2319
  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({
2320
+ const { data } = await (0, import_sharp3.default)(part.buf).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2321
+ const layer = (0, import_editor10.createLayerSetMeasurer)({ width: part.w, height: part.h }).add({
1470
2322
  role,
1471
2323
  fileName: "arm.png",
1472
2324
  rgba: data
@@ -1478,9 +2330,9 @@ async function armPlacement(role, cfg, part, body) {
1478
2330
  }
1479
2331
  let g;
1480
2332
  try {
1481
- g = (0, import_editor7.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
2333
+ g = (0, import_editor10.armGeometry)(layer, role === "arm_R" ? Infinity : -Infinity);
1482
2334
  } catch (err) {
1483
- if (err instanceof import_editor7.LayerGeometryError) {
2335
+ if (err instanceof import_editor10.LayerGeometryError) {
1484
2336
  throw new AutoRigInputError(`layout.${role}: ${err.message}`);
1485
2337
  }
1486
2338
  throw err;
@@ -1506,8 +2358,8 @@ async function armPlacement(role, cfg, part, body) {
1506
2358
  };
1507
2359
  }
1508
2360
  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)({
2361
+ const { data } = await (0, import_sharp3.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2362
+ const layer = (0, import_editor10.createLayerSetMeasurer)({
1511
2363
  width: size.w,
1512
2364
  height: size.h
1513
2365
  }).add({ role, fileName: "forearm_pose.png", rgba: data });
@@ -1516,7 +2368,7 @@ async function poseGeometryOf(role, png, size, when) {
1516
2368
  `layout.${role}: forearm_pose.png is empty after alpha threshold${when}`
1517
2369
  );
1518
2370
  }
1519
- return (0, import_editor7.forearmPoseGeometry)(layer);
2371
+ return (0, import_editor10.forearmPoseGeometry)(layer);
1520
2372
  }
1521
2373
  async function forearmPoseWidth(role, trimmed, elbowRun) {
1522
2374
  const g = await poseGeometryOf(role, trimmed.data, trimmed, "");
@@ -1546,8 +2398,6 @@ var IRIS_W = 50;
1546
2398
  var EYEWHITE_SRC = "eyewhite.png";
1547
2399
  var EYE_LASH_LUMA = 120;
1548
2400
  var LASH_KEEP_FRACTION = 0.5;
1549
- var TRIM_THRESHOLD = 12;
1550
- var STRAY_SPECK_FRACTION = 0.01;
1551
2401
  var NOSE_TIP_AT = 0.66;
1552
2402
  var DEFAULT_LAYOUT = {
1553
2403
  // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir
@@ -1598,6 +2448,19 @@ var DEFAULT_LAYOUT = {
1598
2448
  w: 76,
1599
2449
  optional: true
1600
2450
  },
2451
+ // The lip set's ONE frame, mouth_open's place: the keyed mouth is split into
2452
+ // mouth_inner / lip_lower / lip_upper, the interior's light paint into
2453
+ // mouth_tongue / mouth_teeth, and all of them land here, so a retune moves
2454
+ // them together. The other four have no key of their own (LIP_FRAME).
2455
+ // OPTIONAL and opt-in: with mouth_keyed.png + mouth_interior.png it stands
2456
+ // in for mouth and mouth_open.
2457
+ mouth_inner: {
2458
+ src: KEYED_SRC,
2459
+ cx: 550,
2460
+ cy: 596,
2461
+ w: 76,
2462
+ optional: true
2463
+ },
1601
2464
  // eye_* (sclera) and lash_* share the eyewhite's cropped frame via noTrim (so
1602
2465
  // they are NOT re-bboxed independently): the upper lash stays anchored ABOVE
1603
2466
  // the sclera center, so on blink it folds DOWN over the eye like the sample
@@ -1644,6 +2507,11 @@ var ORDER = [
1644
2507
  "nose",
1645
2508
  "mouth",
1646
2509
  "mouth_open",
2510
+ "mouth_inner",
2511
+ "mouth_tongue",
2512
+ "mouth_teeth",
2513
+ "lip_lower",
2514
+ "lip_upper",
1647
2515
  "eye_L",
1648
2516
  "eye_R",
1649
2517
  "iris_L",
@@ -1662,13 +2530,15 @@ var PART_FILES = [
1662
2530
  ...new Set(
1663
2531
  Object.values(DEFAULT_LAYOUT).map((cfg) => cfg.src).filter((src) => !src.startsWith("eyewhite_"))
1664
2532
  ),
1665
- EYEWHITE_SRC
2533
+ EYEWHITE_SRC,
2534
+ INTERIOR_SRC
1666
2535
  ];
1667
2536
  var FACE_FEATURES = [
1668
2537
  "blush_L",
1669
2538
  "blush_R",
1670
2539
  "mouth",
1671
2540
  "mouth_open",
2541
+ "mouth_inner",
1672
2542
  "eye_L",
1673
2543
  "eye_R",
1674
2544
  "iris_L",
@@ -1772,20 +2642,20 @@ function keyWhiteToAlpha(rgba) {
1772
2642
  return keyed;
1773
2643
  }
1774
2644
  async function coreAndBoundsOf(png) {
1775
- const { data, info } = await (0, import_sharp3.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2645
+ const { data, info } = await (0, import_sharp4.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1776
2646
  return {
1777
- core: (0, import_editor6.denseCoreOf)(data, info.width, info.height),
2647
+ core: (0, import_editor9.denseCoreOf)(data, info.width, info.height),
1778
2648
  bounds: { x: 0, y: 0, w: info.width, h: info.height }
1779
2649
  };
1780
2650
  }
1781
2651
  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;
2652
+ const { data, info } = await (0, import_sharp4.default)(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2653
+ return (0, import_editor11.detectAlphaBbox)(data, info.width, info.height) !== null;
1784
2654
  }
1785
2655
  async function noseSizingOf(png) {
1786
2656
  const { core, bounds } = await coreAndBoundsOf(png);
1787
2657
  if (core === null) return { box: bounds, whole: true };
1788
- if ((0, import_editor6.isSpeckCore)(core, bounds)) {
2658
+ if ((0, import_editor9.isSpeckCore)(core, bounds)) {
1789
2659
  return {
1790
2660
  box: bounds,
1791
2661
  whole: true,
@@ -1800,24 +2670,24 @@ async function noseSizingOf(png) {
1800
2670
  async function trimmedPart(role, cfg, partsDir, inMemory, flipSource) {
1801
2671
  let img;
1802
2672
  if (inMemory !== void 0) {
1803
- img = (0, import_sharp3.default)(inMemory);
2673
+ img = (0, import_sharp4.default)(inMemory);
1804
2674
  } else {
1805
- const srcPath = import_node_path6.default.join(partsDir, cfg.src);
2675
+ const srcPath = import_node_path7.default.join(partsDir, cfg.src);
1806
2676
  if (!import_node_fs3.default.existsSync(srcPath)) {
1807
2677
  if (cfg.optional) return null;
1808
2678
  throw new AutoRigInputError(
1809
- `missing part source for role "${role}": ${srcPath}`
2679
+ `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
2680
  );
1811
2681
  }
1812
2682
  const png = await decodePng(srcPath);
1813
- img = (0, import_sharp3.default)(png.hasAlpha ? png.rgba : keyWhiteToAlpha(png.rgba), {
2683
+ img = (0, import_sharp4.default)(png.hasAlpha ? png.rgba : keyWhiteToAlpha(png.rgba), {
1814
2684
  raw: { width: png.width, height: png.height, channels: 4 }
1815
2685
  });
1816
2686
  }
1817
2687
  if (!cfg.noTrim) {
1818
2688
  const kept = await img.trim({ threshold: TRIM_THRESHOLD }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1819
2689
  const { width: keptW, height: keptH } = kept.info;
1820
- img = (0, import_sharp3.default)(kept.data, {
2690
+ img = (0, import_sharp4.default)(kept.data, {
1821
2691
  raw: { width: keptW, height: keptH, channels: 4 }
1822
2692
  });
1823
2693
  const box = boxWithoutStraySpecks(kept.data, keptW, keptH);
@@ -1843,7 +2713,7 @@ async function sizedPart(role, cfg, trimmed, canvas) {
1843
2713
  `layout.${role}.${field}: resized part ${width}x${height} exceeds the ${canvasName(canvas)} canvas`
1844
2714
  );
1845
2715
  }
1846
- const resized = await (0, import_sharp3.default)(trimmed.data).resize(cfg.h === void 0 ? { width } : { width, height, fit: "fill" }).png().toBuffer({ resolveWithObject: true });
2716
+ const resized = await (0, import_sharp4.default)(trimmed.data).resize(cfg.h === void 0 ? { width } : { width, height, fit: "fill" }).png().toBuffer({ resolveWithObject: true });
1847
2717
  return {
1848
2718
  buf: resized.data,
1849
2719
  w: resized.info.width,
@@ -1868,7 +2738,7 @@ function placement(role, cfg, w, h, canvas) {
1868
2738
  assertOnCanvas(`layout.${role}.cx/cy`, w, h, left, top, canvas);
1869
2739
  return { left, top };
1870
2740
  }
1871
- function nosePlacement(layout, box, w, h, canvas) {
2741
+ function nosePlacement(layout, mouthKey, box, w, h, canvas) {
1872
2742
  const { cx, cy } = layout.nose;
1873
2743
  const left = Math.round(cx - (box.x + box.w / 2));
1874
2744
  let top;
@@ -1877,12 +2747,12 @@ function nosePlacement(layout, box, w, h, canvas) {
1877
2747
  } else {
1878
2748
  const eyeRow = (layout.eye_L.cy + layout.eye_R.cy) / 2;
1879
2749
  const tipRow = Math.round(
1880
- eyeRow + NOSE_TIP_AT * (layout.mouth.cy - eyeRow)
2750
+ eyeRow + NOSE_TIP_AT * (layout[mouthKey].cy - eyeRow)
1881
2751
  );
1882
2752
  top = tipRow - (box.y + box.h - 1);
1883
2753
  }
1884
2754
  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)",
2755
+ 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
2756
  w,
1887
2757
  h,
1888
2758
  left,
@@ -1892,7 +2762,7 @@ function nosePlacement(layout, box, w, h, canvas) {
1892
2762
  return { left, top };
1893
2763
  }
1894
2764
  function blankCanvas(canvas) {
1895
- return (0, import_sharp3.default)({
2765
+ return (0, import_sharp4.default)({
1896
2766
  create: {
1897
2767
  width: canvas.width,
1898
2768
  height: canvas.height,
@@ -1901,74 +2771,13 @@ function blankCanvas(canvas) {
1901
2771
  }
1902
2772
  });
1903
2773
  }
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
2774
  function detachedAboveWhite(rgba, W, H) {
1966
2775
  const n = W * H;
1967
2776
  const ink = new Uint8Array(n);
1968
2777
  for (let p = 0; p < n; p++) {
1969
2778
  const alpha = rgba[p * 4 + 3];
1970
2779
  if (alpha > 0 && luma(rgba, p * 4) >= EYE_LASH_LUMA)
1971
- ink[p] = alpha >= import_editor8.ALPHA_OPAQUE ? 2 : 1;
2780
+ ink[p] = alpha >= import_editor11.ALPHA_OPAQUE ? 2 : 1;
1972
2781
  }
1973
2782
  const label = new Int32Array(n).fill(-1);
1974
2783
  const stack = new Int32Array(n);
@@ -2048,7 +2857,7 @@ function detachedAboveWhite(rgba, W, H) {
2048
2857
  return detached;
2049
2858
  }
2050
2859
  async function prepEyeSplit(partsDir) {
2051
- const srcPath = import_node_path6.default.join(partsDir, EYEWHITE_SRC);
2860
+ const srcPath = import_node_path7.default.join(partsDir, EYEWHITE_SRC);
2052
2861
  if (!import_node_fs3.default.existsSync(srcPath)) {
2053
2862
  throw new AutoRigInputError(`missing eyewhite source: ${srcPath}`);
2054
2863
  }
@@ -2100,6 +2909,50 @@ async function prepEyeSplit(partsDir) {
2100
2909
  lashLower: lowerInk ? await cropToBuffer(lashLower, W, H, region) : null
2101
2910
  };
2102
2911
  }
2912
+ function hasTransparency(rgba) {
2913
+ for (let p = 3; p < rgba.length; p += 4) if (rgba[p] < 255) return true;
2914
+ return false;
2915
+ }
2916
+ async function prepLipSources(partsDir, mirrored) {
2917
+ const has = (name) => import_node_fs3.default.existsSync(import_node_path7.default.join(partsDir, name));
2918
+ const keyed = has(KEYED_SRC);
2919
+ const interior = has(INTERIOR_SRC);
2920
+ if (keyed && !interior) {
2921
+ throw new AutoRigInputError(
2922
+ `${KEYED_SRC} needs ${INTERIOR_SRC}: the composer fits the drawn interior into the keyed opening \u2014 draw it (billed)`
2923
+ );
2924
+ }
2925
+ if (interior && !keyed) {
2926
+ throw new AutoRigInputError(
2927
+ `${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)`
2928
+ );
2929
+ }
2930
+ if (!keyed) return void 0;
2931
+ const legacy = ["mouth.png", "mouth_open.png"].filter(has);
2932
+ if (legacy.length > 0) {
2933
+ throw new AutoRigInputError(
2934
+ `${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 ")}`
2935
+ );
2936
+ }
2937
+ const k = await decodePng(import_node_path7.default.join(partsDir, KEYED_SRC));
2938
+ const keyedRgba = keyGreen(
2939
+ hasTransparency(k.rgba) ? k.rgba : keyWhiteToAlpha(k.rgba),
2940
+ k.width,
2941
+ k.height
2942
+ );
2943
+ const i = await decodePng(import_node_path7.default.join(partsDir, INTERIOR_SRC));
2944
+ const prepared = await prepInterior(
2945
+ hasTransparency(i.rgba) ? i.rgba : keyBorderWhite(i.rgba, i.width, i.height),
2946
+ i.width,
2947
+ i.height
2948
+ );
2949
+ return {
2950
+ keyedPng: await (0, import_sharp4.default)(keyedRgba, {
2951
+ raw: { width: k.width, height: k.height, channels: 4 }
2952
+ }).png().toBuffer(),
2953
+ interior: mirrored.has(INTERIOR_SRC) ? { ...prepared, png: await (0, import_sharp4.default)(prepared.png).flop().png().toBuffer() } : prepared
2954
+ };
2955
+ }
2103
2956
  async function composeLayersFromParts(input) {
2104
2957
  try {
2105
2958
  const outDir = resolveOutputDir(input.outDir);
@@ -2123,10 +2976,58 @@ async function composeLayersFromParts(input) {
2123
2976
  if (split.lashLower !== null) {
2124
2977
  splitSources.set(LOWER_LASH_SRC, split.lashLower);
2125
2978
  }
2979
+ const lips = await prepLipSources(partsDir, mirrored);
2980
+ let lipSplit;
2126
2981
  const placed = [];
2127
2982
  const skipped = [];
2128
2983
  let noseSpeck;
2129
2984
  for (const role of ORDER) {
2985
+ if (lips !== void 0 && (role === "mouth" || role === "mouth_open")) {
2986
+ continue;
2987
+ }
2988
+ if (role === "mouth_inner") {
2989
+ if (lips === void 0) continue;
2990
+ const cfg2 = layout.mouth_inner;
2991
+ const part2 = await partBuffer(
2992
+ role,
2993
+ cfg2,
2994
+ partsDir,
2995
+ lips.keyedPng,
2996
+ mirrored.has(KEYED_SRC),
2997
+ canvas
2998
+ );
2999
+ const split2 = await splitLipSet(
3000
+ part2.buf,
3001
+ part2.w,
3002
+ part2.h,
3003
+ lips.interior
3004
+ );
3005
+ const { left: left2, top: top2 } = placement(role, cfg2, part2.w, part2.h, canvas);
3006
+ lipSplit = { split: split2, w: part2.w, h: part2.h, left: left2, top: top2 };
3007
+ placed.push({
3008
+ role,
3009
+ part: { buf: split2.inner, w: part2.w, h: part2.h },
3010
+ left: left2,
3011
+ top: top2
3012
+ });
3013
+ continue;
3014
+ }
3015
+ if (role === "mouth_tongue" || role === "mouth_teeth" || role === "lip_lower" || role === "lip_upper") {
3016
+ if (lipSplit === void 0) continue;
3017
+ const { split: split2, w, h, left: left2, top: top2 } = lipSplit;
3018
+ const buf = {
3019
+ mouth_tongue: split2.tongue,
3020
+ mouth_teeth: split2.teeth,
3021
+ lip_lower: split2.lower,
3022
+ lip_upper: split2.upper
3023
+ }[role];
3024
+ if ((0, import_editor11.isLipInsideRole)(role) && !await hasCoverage(buf)) {
3025
+ skipped.push(role);
3026
+ continue;
3027
+ }
3028
+ placed.push({ role, part: { buf, w, h }, left: left2, top: top2 });
3029
+ continue;
3030
+ }
2130
3031
  const lower = role === "lash_lower_L" || role === "lash_lower_R";
2131
3032
  const key = lower ? LOWER_LASH[role] : role;
2132
3033
  if (lower && split.lashLower === null) {
@@ -2135,7 +3036,7 @@ async function composeLayersFromParts(input) {
2135
3036
  }
2136
3037
  if (key === "arm_L" || key === "arm_R") {
2137
3038
  const arm = layout[key];
2138
- if (!import_node_fs3.default.existsSync(import_node_path6.default.join(partsDir, arm.src))) continue;
3039
+ if (!import_node_fs3.default.existsSync(import_node_path7.default.join(partsDir, arm.src))) continue;
2139
3040
  const body = placed.find((p) => p.role === "body");
2140
3041
  if (body === void 0) {
2141
3042
  throw new AutoRigInputError(
@@ -2178,7 +3079,7 @@ async function composeLayersFromParts(input) {
2178
3079
  }
2179
3080
  if (key === "forearm_pose_L" || key === "forearm_pose_R") {
2180
3081
  const pose = layout[key];
2181
- if (!import_node_fs3.default.existsSync(import_node_path6.default.join(partsDir, pose.src))) continue;
3082
+ if (!import_node_fs3.default.existsSync(import_node_path7.default.join(partsDir, pose.src))) continue;
2182
3083
  const armRole = key === "forearm_pose_L" ? "arm_L" : "arm_R";
2183
3084
  const arm = placed.find((p) => p.role === armRole);
2184
3085
  if (arm?.elbow === void 0 || arm.elbowRun === void 0) {
@@ -2249,7 +3150,14 @@ async function composeLayersFromParts(input) {
2249
3150
  noseSpeck = part.nose?.speck;
2250
3151
  const { core, bounds } = await coreAndBoundsOf(part.buf);
2251
3152
  const box = part.nose?.whole ? bounds : core ?? bounds;
2252
- ({ left, top } = nosePlacement(layout, box, part.w, part.h, canvas));
3153
+ ({ left, top } = nosePlacement(
3154
+ layout,
3155
+ lips === void 0 ? "mouth" : "mouth_inner",
3156
+ box,
3157
+ part.w,
3158
+ part.h,
3159
+ canvas
3160
+ ));
2253
3161
  } else {
2254
3162
  ({ left, top } = placement(key, layout[key], part.w, part.h, canvas));
2255
3163
  }
@@ -2264,20 +3172,40 @@ async function composeLayersFromParts(input) {
2264
3172
  }
2265
3173
  placed.push({ role, part, left, top });
2266
3174
  }
3175
+ const built = /* @__PURE__ */ new Map();
3176
+ for (const { role, part, left, top } of placed) {
3177
+ built.set(
3178
+ role,
3179
+ await blankCanvas(canvas).composite([{ input: part.buf, left, top }]).png().toBuffer()
3180
+ );
3181
+ }
3182
+ const closed = lipSplit === void 0 ? void 0 : await closedLips(
3183
+ lipSplit.split.upper,
3184
+ lipSplit.split.lower,
3185
+ await restShiftOf(
3186
+ {
3187
+ mouth_inner: built.get("mouth_inner"),
3188
+ lip_lower: built.get("lip_lower"),
3189
+ lip_upper: built.get("lip_upper")
3190
+ },
3191
+ canvas.width,
3192
+ canvas.height
3193
+ ),
3194
+ lipSplit.left,
3195
+ lipSplit.top
3196
+ );
2267
3197
  for (const role of ORDER) {
2268
3198
  if (placed.some((p) => p.role === role)) continue;
2269
- import_node_fs3.default.rmSync(import_node_path6.default.join(outDir, `${role}.png`), { force: true });
3199
+ import_node_fs3.default.rmSync(import_node_path7.default.join(outDir, `${role}.png`), { force: true });
2270
3200
  }
2271
3201
  const posed = (role) => role === "forearm_pose_L" || role === "forearm_pose_R";
2272
3202
  if (!placed.some((p) => posed(p.role))) {
2273
- import_node_fs3.default.rmSync(import_node_path6.default.join(outDir, "preview-pose.png"), { force: true });
3203
+ import_node_fs3.default.rmSync(import_node_path7.default.join(outDir, "preview-pose.png"), { force: true });
2274
3204
  }
2275
3205
  const layers = [];
2276
- const preview = [];
2277
3206
  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);
3207
+ const outPath = import_node_path7.default.join(outDir, `${role}.png`);
3208
+ writeFileAtomic(outPath, built.get(role));
2281
3209
  layers.push({
2282
3210
  role,
2283
3211
  path: outPath,
@@ -2286,9 +3214,20 @@ async function composeLayersFromParts(input) {
2286
3214
  left,
2287
3215
  top
2288
3216
  });
2289
- if (!posed(role)) preview.push({ input: part.buf, left, top });
2290
3217
  }
2291
- const previewPng = await (0, import_sharp3.default)({
3218
+ const restInput = (role, buf) => {
3219
+ if (role === "mouth_inner" || (0, import_editor11.isLipInsideRole)(role)) return null;
3220
+ if (closed === void 0) return buf;
3221
+ if (role === "lip_upper") return closed.upper;
3222
+ if (role === "lip_lower") return closed.lower;
3223
+ return buf;
3224
+ };
3225
+ const preview = [];
3226
+ for (const { role, part, left, top } of placed) {
3227
+ const input2 = restInput(role, part.buf);
3228
+ if (!posed(role) && input2 !== null) preview.push({ input: input2, left, top });
3229
+ }
3230
+ const previewPng = await (0, import_sharp4.default)({
2292
3231
  create: {
2293
3232
  width: canvas.width,
2294
3233
  height: canvas.height,
@@ -2296,7 +3235,7 @@ async function composeLayersFromParts(input) {
2296
3235
  background: { r: 245, g: 245, b: 248, alpha: 1 }
2297
3236
  }
2298
3237
  }).composite(preview).png().toBuffer();
2299
- const previewPath = import_node_path6.default.join(outDir, "preview.png");
3238
+ const previewPath = import_node_path7.default.join(outDir, "preview.png");
2300
3239
  writeFileAtomic(previewPath, previewPng);
2301
3240
  let previewPosePath;
2302
3241
  if (placed.some((p) => posed(p.role))) {
@@ -2306,17 +3245,18 @@ async function composeLayersFromParts(input) {
2306
3245
  (p) => p.role === (role === "arm_L" ? "forearm_pose_L" : "forearm_pose_R")
2307
3246
  );
2308
3247
  if (!armPosed) {
2309
- pose.push({ input: part.buf, left, top });
3248
+ const input2 = restInput(role, part.buf);
3249
+ if (input2 !== null) pose.push({ input: input2, left, top });
2310
3250
  continue;
2311
3251
  }
2312
3252
  const rows = Math.min(part.h, Math.max(1, Math.round(elbow.y - top)));
2313
3253
  pose.push({
2314
- input: await (0, import_sharp3.default)(part.buf).extract({ left: 0, top: 0, width: part.w, height: rows }).png().toBuffer(),
3254
+ input: await (0, import_sharp4.default)(part.buf).extract({ left: 0, top: 0, width: part.w, height: rows }).png().toBuffer(),
2315
3255
  left,
2316
3256
  top
2317
3257
  });
2318
3258
  }
2319
- const posePng = await (0, import_sharp3.default)({
3259
+ const posePng = await (0, import_sharp4.default)({
2320
3260
  create: {
2321
3261
  width: canvas.width,
2322
3262
  height: canvas.height,
@@ -2324,7 +3264,7 @@ async function composeLayersFromParts(input) {
2324
3264
  background: { r: 245, g: 245, b: 248, alpha: 1 }
2325
3265
  }
2326
3266
  }).composite(pose).png().toBuffer();
2327
- previewPosePath = import_node_path6.default.join(outDir, "preview-pose.png");
3267
+ previewPosePath = import_node_path7.default.join(outDir, "preview-pose.png");
2328
3268
  writeFileAtomic(previewPosePath, posePng);
2329
3269
  }
2330
3270
  return {
@@ -2347,7 +3287,7 @@ async function composeLayersFromParts(input) {
2347
3287
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
2348
3288
  var import_zod = require("zod");
2349
3289
  function createIkiMcpServer() {
2350
- const server = new import_mcp.McpServer({ name: "iki", version: "0.21.0" });
3290
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.23.0" });
2351
3291
  server.registerTool(
2352
3292
  "validate_iki",
2353
3293
  {
@@ -2412,7 +3352,7 @@ function createIkiMcpServer() {
2412
3352
  server.registerTool(
2413
3353
  "auto_rig_from_layers",
2414
3354
  {
2415
- description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R and either mouth or the lip set (mouth_inner + lip_lower + lip_upper, a mouth that folds open instead of crossfading) required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, etc. optional; an arm needs the body, a pose forearm needs its arm, and a partial lip set or one mixed with mouth/mouth_open is refused) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given.",
3355
+ description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R and either mouth or the lip set (mouth_inner + lip_lower + lip_upper, a mouth that folds open instead of crossfading) required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, mouth_tongue/mouth_teeth (only with the lip set: drawn under its lips and clipped to mouth_inner), etc. optional; an arm needs the body, a pose forearm needs its arm, and a partial lip set, one mixed with mouth/mouth_open, or mouth_tongue/mouth_teeth without it is refused) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given.",
2416
3356
  inputSchema: {
2417
3357
  layers: import_zod.z.array(
2418
3358
  import_zod.z.object({
@@ -2467,7 +3407,7 @@ function createIkiMcpServer() {
2467
3407
  server.registerTool(
2468
3408
  "compose_layers_from_parts",
2469
3409
  {
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`.",
3410
+ 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 interior's light paint (luma 100 and over) written as mouth_tongue and mouth_teeth on the same frame, riding the opening's bottom and the upper line and clipped to the cavity (listed in `skipped` when the interior has none); 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
3411
  inputSchema: {
2472
3412
  partsDir: import_zod.z.string().describe(
2473
3413
  "Directory of the source part PNGs (resolved against cwd)."
@@ -2484,7 +3424,7 @@ function createIkiMcpServer() {
2484
3424
  h: import_zod.z.number()
2485
3425
  }).partial()
2486
3426
  ).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."
3427
+ "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, lip_upper, mouth_tongue and mouth_teeth have no key and land on it, so a retune moves them 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
3428
  ),
2489
3429
  mirrorParts: import_zod.z.array(import_zod.z.string()).optional().describe(
2490
3430
  "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 +3455,7 @@ function createIkiMcpServer() {
2515
3455
  server.registerTool(
2516
3456
  "measure_layers",
2517
3457
  {
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.",
3458
+ 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, and of mouth_tongue/mouth_teeth: one with no lip set, one on another canvas, one whose box leaves mouth_inner's \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
3459
  inputSchema: {
2520
3460
  layersDir: import_zod.z.string().describe(
2521
3461
  "Directory of role-named layer PNGs (resolved against cwd)."