@ikijs/mcp 0.20.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.
@@ -982,7 +982,7 @@ function formatTurnReport(result) {
982
982
 
983
983
  // src/measure.ts
984
984
  import fs2 from "fs";
985
- import path5 from "path";
985
+ import path6 from "path";
986
986
 
987
987
  // src/measure-arms.ts
988
988
  import path4 from "path";
@@ -1150,6 +1150,798 @@ function jointWarnings(pose, arm, stats, a, armLayer, b) {
1150
1150
  return warnings;
1151
1151
  }
1152
1152
 
1153
+ // src/measure-lips.ts
1154
+ import path5 from "path";
1155
+ import {
1156
+ ALPHA_OPAQUE as ALPHA_OPAQUE4,
1157
+ LIP_ROLES,
1158
+ LayerGeometryError as LayerGeometryError4,
1159
+ columnRuns as columnRuns2,
1160
+ createLayerSetMeasurer as createLayerSetMeasurer5,
1161
+ mouthOpening as mouthOpening2
1162
+ } from "@ikijs/editor";
1163
+
1164
+ // src/compose-lips.ts
1165
+ import sharp2 from "sharp";
1166
+ import {
1167
+ ALPHA_OPAQUE as ALPHA_OPAQUE3,
1168
+ columnRuns,
1169
+ createLayerSetMeasurer as createLayerSetMeasurer4,
1170
+ mouthOpening,
1171
+ mouthRestShift
1172
+ } from "@ikijs/editor";
1173
+
1174
+ // src/trim.ts
1175
+ import { ALPHA_OPAQUE as ALPHA_OPAQUE2 } from "@ikijs/editor";
1176
+ var TRIM_THRESHOLD = 12;
1177
+ var STRAY_SPECK_FRACTION = 0.01;
1178
+ function luma(rgba, i) {
1179
+ return 0.299 * rgba[i] + 0.587 * rgba[i + 1] + 0.114 * rgba[i + 2];
1180
+ }
1181
+ function boxWithoutStraySpecks(rgba, W, H) {
1182
+ const n = W * H;
1183
+ let kept = 0;
1184
+ for (let p = 0; p < n; p++) if (rgba[p * 4 + 3] > TRIM_THRESHOLD) kept++;
1185
+ const visited = new Uint8Array(n);
1186
+ let stack = new Int32Array(1024);
1187
+ const drawing = [W, H, -1, -1];
1188
+ const strays = [W, H, -1, -1];
1189
+ let anyOpaque = false;
1190
+ for (let start = 0; start < n; start++) {
1191
+ if (visited[start] || rgba[start * 4 + 3] <= TRIM_THRESHOLD) continue;
1192
+ let setLeft = W;
1193
+ let setTop = H;
1194
+ let setRight = -1;
1195
+ let setBottom = -1;
1196
+ let size = 0;
1197
+ let opaque = false;
1198
+ let depth = 0;
1199
+ visited[start] = 1;
1200
+ stack[depth++] = start;
1201
+ while (depth > 0) {
1202
+ const p = stack[--depth];
1203
+ size++;
1204
+ if (rgba[p * 4 + 3] >= ALPHA_OPAQUE2) opaque = true;
1205
+ const px2 = p % W;
1206
+ const py = (p - px2) / W;
1207
+ setLeft = Math.min(setLeft, px2);
1208
+ setTop = Math.min(setTop, py);
1209
+ setRight = Math.max(setRight, px2);
1210
+ setBottom = Math.max(setBottom, py);
1211
+ for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {
1212
+ for (let x = Math.max(0, px2 - 1); x <= Math.min(W - 1, px2 + 1); x++) {
1213
+ const q = y * W + x;
1214
+ if (!visited[q] && rgba[q * 4 + 3] > TRIM_THRESHOLD) {
1215
+ visited[q] = 1;
1216
+ if (depth === stack.length) {
1217
+ const grown = new Int32Array(Math.min(n, stack.length * 2));
1218
+ grown.set(stack);
1219
+ stack = grown;
1220
+ }
1221
+ stack[depth++] = q;
1222
+ }
1223
+ }
1224
+ }
1225
+ }
1226
+ anyOpaque ||= opaque;
1227
+ const into = !opaque && size < kept * STRAY_SPECK_FRACTION ? strays : drawing;
1228
+ into[0] = Math.min(into[0], setLeft);
1229
+ into[1] = Math.min(into[1], setTop);
1230
+ into[2] = Math.max(into[2], setRight);
1231
+ into[3] = Math.max(into[3], setBottom);
1232
+ }
1233
+ if (!anyOpaque || strays[2] < 0) return null;
1234
+ const [left, top, right, bottom] = drawing;
1235
+ if (strays[0] >= left && strays[1] >= top && strays[2] <= right && strays[3] <= bottom)
1236
+ return null;
1237
+ return { left, top, width: right - left + 1, height: bottom - top + 1 };
1238
+ }
1239
+
1240
+ // src/compose-lips.ts
1241
+ var KEYED_SRC = "mouth_keyed.png";
1242
+ var INTERIOR_SRC = "mouth_interior.png";
1243
+ var KEY_CANDIDATE = 0.5;
1244
+ var KEY_FILL_DIST = 20;
1245
+ var KEY_REACH = 8;
1246
+ var KEY_COLLINEAR = 12;
1247
+ var KEY_MIN_SHARE = 0.05;
1248
+ var STRAY_KEY_FRACTION = 0.02;
1249
+ var MIN_OPENING_WIDTH = 0.3;
1250
+ var SECOND_HOLE_FRACTION = 0.05;
1251
+ var BAND_LUMA = 150;
1252
+ var BAND_CAP = 3;
1253
+ var CAVITY_LUMA = 100;
1254
+ var SKIN_MIN_R = 225;
1255
+ var SKIN_MIN_G = 160;
1256
+ var SKIN_MIN_B = 135;
1257
+ var TEETH_MIN_G = 215;
1258
+ var TEETH_MIN_B = 205;
1259
+ 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);
1260
+ function components2(mask, W, H) {
1261
+ const n = W * H;
1262
+ const label = new Int32Array(n).fill(-1);
1263
+ const stack = new Int32Array(n);
1264
+ const sizes = [];
1265
+ const boxes = [];
1266
+ for (let start = 0; start < n; start++) {
1267
+ if (!mask[start] || label[start] >= 0) continue;
1268
+ const id = sizes.length;
1269
+ const box = { x0: W, y0: H, x1: -1, y1: -1 };
1270
+ let size = 0;
1271
+ let depth = 0;
1272
+ label[start] = id;
1273
+ stack[depth++] = start;
1274
+ while (depth > 0) {
1275
+ const p = stack[--depth];
1276
+ size++;
1277
+ const px2 = p % W;
1278
+ const py = (p - px2) / W;
1279
+ box.x0 = Math.min(box.x0, px2);
1280
+ box.x1 = Math.max(box.x1, px2);
1281
+ box.y0 = Math.min(box.y0, py);
1282
+ box.y1 = Math.max(box.y1, py);
1283
+ for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {
1284
+ for (let x = Math.max(0, px2 - 1); x <= Math.min(W - 1, px2 + 1); x++) {
1285
+ if (x !== px2 && y !== py) continue;
1286
+ const q = y * W + x;
1287
+ if (mask[q] && label[q] < 0) {
1288
+ label[q] = id;
1289
+ stack[depth++] = q;
1290
+ }
1291
+ }
1292
+ }
1293
+ }
1294
+ sizes.push(size);
1295
+ boxes.push(box);
1296
+ }
1297
+ return { label, sizes, boxes };
1298
+ }
1299
+ var largest = (sizes) => sizes.reduce((best, s, i) => best < 0 || s > sizes[best] ? i : best, -1);
1300
+ function dilate2(mask, W, H, reach) {
1301
+ const rows = new Uint8Array(W * H);
1302
+ const prefix = new Int32Array(Math.max(W, H) + 1);
1303
+ for (let y = 0; y < H; y++) {
1304
+ for (let x = 0; x < W; x++) prefix[x + 1] = prefix[x] + mask[y * W + x];
1305
+ for (let x = 0; x < W; x++) {
1306
+ rows[y * W + x] = prefix[Math.min(W, x + reach + 1)] - prefix[Math.max(0, x - reach)] > 0 ? 1 : 0;
1307
+ }
1308
+ }
1309
+ const out = new Uint8Array(W * H);
1310
+ for (let x = 0; x < W; x++) {
1311
+ for (let y = 0; y < H; y++) prefix[y + 1] = prefix[y] + rows[y * W + x];
1312
+ for (let y = 0; y < H; y++) {
1313
+ out[y * W + x] = prefix[Math.min(H, y + reach + 1)] - prefix[Math.max(0, y - reach)] > 0 ? 1 : 0;
1314
+ }
1315
+ }
1316
+ return out;
1317
+ }
1318
+ function shareOf(rgba, i, j, g) {
1319
+ const dr = g[0] - rgba[j];
1320
+ const dg = g[1] - rgba[j + 1];
1321
+ const db = g[2] - rgba[j + 2];
1322
+ 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);
1323
+ return Math.min(1, Math.max(0, t));
1324
+ }
1325
+ function keyGreen(rgba, W, H) {
1326
+ const n = W * H;
1327
+ const noGreen = new AutoRigInputError(
1328
+ `${KEYED_SRC}: no green opening (#00FF00) to key \u2014 regenerate it with the inside of the open mouth painted ONE flat pure green`
1329
+ );
1330
+ const hist = [
1331
+ new Uint32Array(256),
1332
+ new Uint32Array(256),
1333
+ new Uint32Array(256)
1334
+ ];
1335
+ let candidates = 0;
1336
+ for (let p = 0; p < n; p++) {
1337
+ const i = p * 4;
1338
+ if (rgba[i + 3] < ALPHA_OPAQUE3) continue;
1339
+ const excess = (rgba[i + 1] - Math.max(rgba[i], rgba[i + 2])) / 255;
1340
+ if (excess < KEY_CANDIDATE) continue;
1341
+ candidates++;
1342
+ for (let c = 0; c < 3; c++) hist[c][rgba[i + c]]++;
1343
+ }
1344
+ if (candidates === 0) throw noGreen;
1345
+ const median = (h) => {
1346
+ let seen = 0;
1347
+ for (let v = 0; v < 256; v++) {
1348
+ seen += h[v];
1349
+ if (seen * 2 >= candidates) return v;
1350
+ }
1351
+ return 255;
1352
+ };
1353
+ const G = [median(hist[0]), median(hist[1]), median(hist[2])];
1354
+ const out = Buffer.from(rgba);
1355
+ const fill = new Uint8Array(n);
1356
+ const ref = new Uint8Array(n);
1357
+ let fillCount = 0;
1358
+ for (let p = 0; p < n; p++) {
1359
+ const i = p * 4;
1360
+ if (rgba[i + 3] === 0) continue;
1361
+ const dr = rgba[i] - G[0];
1362
+ const dg = rgba[i + 1] - G[1];
1363
+ const db = rgba[i + 2] - G[2];
1364
+ const green = dr * dr + dg * dg + db * db <= KEY_FILL_DIST * KEY_FILL_DIST;
1365
+ if (rgba[i + 3] < ALPHA_OPAQUE3) {
1366
+ if (green) out[i + 3] = 0;
1367
+ } else if (green) {
1368
+ fill[p] = 1;
1369
+ fillCount++;
1370
+ } else {
1371
+ ref[p] = 1;
1372
+ }
1373
+ }
1374
+ if (fillCount === 0) throw noGreen;
1375
+ const reach = dilate2(fill, W, H, KEY_REACH);
1376
+ const collinear = KEY_COLLINEAR * KEY_COLLINEAR;
1377
+ for (let y = 0; y < H; y++) {
1378
+ for (let x = 0; x < W; x++) {
1379
+ const p = y * W + x;
1380
+ if (!reach[p] || fill[p] || out[p * 4 + 3] === 0) continue;
1381
+ const i = p * 4;
1382
+ let best = i;
1383
+ let bestD2 = (rgba[i] - G[0]) ** 2 + (rgba[i + 1] - G[1]) ** 2 + (rgba[i + 2] - G[2]) ** 2;
1384
+ const y1 = Math.min(H - 1, y + KEY_REACH);
1385
+ const x1 = Math.min(W - 1, x + KEY_REACH);
1386
+ for (let qy = Math.max(0, y - KEY_REACH); qy <= y1; qy++) {
1387
+ for (let qx = Math.max(0, x - KEY_REACH); qx <= x1; qx++) {
1388
+ const q = qy * W + qx;
1389
+ if (q === p || !ref[q]) continue;
1390
+ const j = q * 4;
1391
+ const d2 = (rgba[j] - G[0]) ** 2 + (rgba[j + 1] - G[1]) ** 2 + (rgba[j + 2] - G[2]) ** 2;
1392
+ if (d2 <= bestD2) continue;
1393
+ const t = shareOf(rgba, i, j, G);
1394
+ const er = rgba[i] - rgba[j] - t * (G[0] - rgba[j]);
1395
+ const eg = rgba[i + 1] - rgba[j + 1] - t * (G[1] - rgba[j + 1]);
1396
+ const eb = rgba[i + 2] - rgba[j + 2] - t * (G[2] - rgba[j + 2]);
1397
+ if (er * er + eg * eg + eb * eb > collinear) continue;
1398
+ bestD2 = d2;
1399
+ best = j;
1400
+ }
1401
+ }
1402
+ const k = shareOf(rgba, i, best, G);
1403
+ if (k < KEY_MIN_SHARE) continue;
1404
+ rgba.copy(out, i, best, best + 3);
1405
+ out[i + 3] = Math.round(rgba[i + 3] * (1 - k));
1406
+ }
1407
+ }
1408
+ for (let p = 0; p < n; p++) if (fill[p]) out[p * 4 + 3] = 0;
1409
+ const { sizes } = components2(fill, W, H);
1410
+ const main = largest(sizes);
1411
+ const strays = sizes.filter((_, i) => i !== main);
1412
+ const strayPx = strays.reduce((a, b) => a + b, 0);
1413
+ if (strayPx > STRAY_KEY_FRACTION * sizes[main]) {
1414
+ throw new AutoRigInputError(
1415
+ `${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`
1416
+ );
1417
+ }
1418
+ return out;
1419
+ }
1420
+ var GROUND_TOLERANCE = 4;
1421
+ var GROUND_LIGHT = 200;
1422
+ var GROUND_MIN = 238;
1423
+ var GROUND_BORDER_SHARE = 0.65;
1424
+ function keyBorderWhite(rgba, W, H) {
1425
+ const border = [[], [], []];
1426
+ const edge = (p) => {
1427
+ for (let c = 0; c < 3; c++) border[c].push(rgba[p * 4 + c]);
1428
+ };
1429
+ for (let x = 0; x < W; x++) {
1430
+ edge(x);
1431
+ edge((H - 1) * W + x);
1432
+ }
1433
+ for (let y = 1; y < H - 1; y++) {
1434
+ edge(y * W);
1435
+ edge(y * W + W - 1);
1436
+ }
1437
+ const ground = border.map((v) => v.sort((a, b) => a - b)[v.length >> 1]);
1438
+ const light = ground.every((v) => v >= GROUND_LIGHT);
1439
+ if (light && ground.some((v) => v < GROUND_MIN)) {
1440
+ throw new AutoRigInputError(
1441
+ `${INTERIOR_SRC} came back opaque on a non-white ground \u2014 regenerate it with a transparent background. Billed.`
1442
+ );
1443
+ }
1444
+ if (!light) ground.fill(255);
1445
+ const out = Buffer.from(rgba);
1446
+ const seen = new Uint8Array(W * H);
1447
+ const stack = new Int32Array(W * H);
1448
+ let depth = 0;
1449
+ const seed = (p) => {
1450
+ if (seen[p]) return;
1451
+ for (let c = 0; c < 3; c++) {
1452
+ if (Math.abs(rgba[p * 4 + c] - ground[c]) > GROUND_TOLERANCE) return;
1453
+ }
1454
+ seen[p] = 1;
1455
+ stack[depth++] = p;
1456
+ };
1457
+ for (let x = 0; x < W; x++) {
1458
+ seed(x);
1459
+ seed((H - 1) * W + x);
1460
+ }
1461
+ for (let y = 0; y < H; y++) {
1462
+ seed(y * W);
1463
+ seed(y * W + W - 1);
1464
+ }
1465
+ if (light && depth < GROUND_BORDER_SHARE * border[0].length) {
1466
+ throw new AutoRigInputError(
1467
+ `${INTERIOR_SRC} came back opaque on a white ground too noisy or shaded to key cleanly \u2014 regenerate it with a transparent background. Billed.`
1468
+ );
1469
+ }
1470
+ while (depth > 0) {
1471
+ const p = stack[--depth];
1472
+ out[p * 4 + 3] = 0;
1473
+ const x = p % W;
1474
+ if (x > 0) seed(p - 1);
1475
+ if (x < W - 1) seed(p + 1);
1476
+ if (p >= W) seed(p - W);
1477
+ if (p < W * H - W) seed(p + W);
1478
+ }
1479
+ return out;
1480
+ }
1481
+ function drawingBox(rgba, W, H) {
1482
+ const speckless = boxWithoutStraySpecks(rgba, W, H);
1483
+ if (speckless !== null) {
1484
+ return {
1485
+ x: speckless.left,
1486
+ y: speckless.top,
1487
+ w: speckless.width,
1488
+ h: speckless.height
1489
+ };
1490
+ }
1491
+ let x0 = W;
1492
+ let y0 = H;
1493
+ let x1 = -1;
1494
+ let y1 = -1;
1495
+ for (let y = 0; y < H; y++) {
1496
+ for (let x = 0; x < W; x++) {
1497
+ if (rgba[(y * W + x) * 4 + 3] <= TRIM_THRESHOLD) continue;
1498
+ x0 = Math.min(x0, x);
1499
+ x1 = Math.max(x1, x);
1500
+ y0 = Math.min(y0, y);
1501
+ y1 = Math.max(y1, y);
1502
+ }
1503
+ }
1504
+ return x1 < 0 ? null : { x: x0, y: y0, w: x1 - x0 + 1, h: y1 - y0 + 1 };
1505
+ }
1506
+ async function prepInterior(rgba, W, H) {
1507
+ const empty = new AutoRigInputError(
1508
+ `${INTERIOR_SRC}: nothing but lips/skin after trimming \u2014 regenerate it with the cavity, the teeth and the tongue only, NO lips`
1509
+ );
1510
+ const first = drawingBox(rgba, W, H);
1511
+ if (first === null) throw empty;
1512
+ const cw = first.w;
1513
+ const ch = first.h;
1514
+ const crop = Buffer.alloc(cw * ch * 4);
1515
+ for (let y = 0; y < ch; y++) {
1516
+ const from2 = ((first.y + y) * W + first.x) * 4;
1517
+ rgba.copy(crop, y * cw * 4, from2, from2 + cw * 4);
1518
+ }
1519
+ const skin = new Uint8Array(cw * ch);
1520
+ for (let p = 0; p < cw * ch; p++) {
1521
+ const i = p * 4;
1522
+ if (crop[i + 3] > TRIM_THRESHOLD && isSkin(crop[i], crop[i + 1], crop[i + 2]))
1523
+ skin[p] = 1;
1524
+ }
1525
+ const { label, boxes } = components2(skin, cw, ch);
1526
+ const rim = boxes.map(
1527
+ (b) => b.x0 === 0 || b.y0 === 0 || b.x1 === cw - 1 || b.y1 === ch - 1
1528
+ );
1529
+ for (let p = 0; p < cw * ch; p++) {
1530
+ if (label[p] >= 0 && rim[label[p]]) crop[p * 4 + 3] = 0;
1531
+ }
1532
+ const box = drawingBox(crop, cw, ch);
1533
+ if (box === null) throw empty;
1534
+ const sum = [0, 0, 0];
1535
+ const all = [0, 0, 0];
1536
+ let dark = 0;
1537
+ let count = 0;
1538
+ for (let y = box.y; y < box.y + box.h; y++) {
1539
+ for (let x = box.x; x < box.x + box.w; x++) {
1540
+ const i = (y * cw + x) * 4;
1541
+ if (crop[i + 3] < ALPHA_OPAQUE3) continue;
1542
+ count++;
1543
+ for (let c = 0; c < 3; c++) all[c] += crop[i + c];
1544
+ if (luma(crop, i) < CAVITY_LUMA) {
1545
+ dark++;
1546
+ for (let c = 0; c < 3; c++) sum[c] += crop[i + c];
1547
+ }
1548
+ }
1549
+ }
1550
+ if (count === 0) throw empty;
1551
+ const [from, over] = dark > 0 ? [sum, dark] : [all, count];
1552
+ const cavity = from.map((v) => Math.round(v / over));
1553
+ return { png: await cropToBuffer(crop, cw, ch, box), cavity };
1554
+ }
1555
+ var rawOf = async (png) => sharp2(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1556
+ var encode = (rgba, w, h) => sharp2(rgba, { raw: { width: w, height: h, channels: 4 } }).png().toBuffer();
1557
+ function enclosedHole(frame, w, h) {
1558
+ const n = w * h;
1559
+ const alpha = (p) => frame[p * 4 + 3];
1560
+ const outside = new Uint8Array(n);
1561
+ const stack = new Int32Array(n);
1562
+ let depth = 0;
1563
+ const seed = (p) => {
1564
+ if (!outside[p] && alpha(p) < ALPHA_OPAQUE3) {
1565
+ outside[p] = 1;
1566
+ stack[depth++] = p;
1567
+ }
1568
+ };
1569
+ for (let x = 0; x < w; x++) {
1570
+ seed(x);
1571
+ seed((h - 1) * w + x);
1572
+ }
1573
+ for (let y = 0; y < h; y++) {
1574
+ seed(y * w);
1575
+ seed(y * w + w - 1);
1576
+ }
1577
+ while (depth > 0) {
1578
+ const p = stack[--depth];
1579
+ const x = p % w;
1580
+ if (x > 0) seed(p - 1);
1581
+ if (x < w - 1) seed(p + 1);
1582
+ if (p >= w) seed(p - w);
1583
+ if (p < n - w) seed(p + w);
1584
+ }
1585
+ const mask = new Uint8Array(n);
1586
+ for (let p = 0; p < n; p++) {
1587
+ if (alpha(p) < ALPHA_OPAQUE3 && !outside[p]) mask[p] = 1;
1588
+ }
1589
+ const { label, sizes, boxes } = components2(mask, w, h);
1590
+ const main = largest(sizes);
1591
+ if (main < 0) {
1592
+ throw new AutoRigInputError(
1593
+ `${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`
1594
+ );
1595
+ }
1596
+ const box = boxes[main];
1597
+ const holeW = box.x1 - box.x0 + 1;
1598
+ if (holeW < MIN_OPENING_WIDTH * w) {
1599
+ throw new AutoRigInputError(
1600
+ `${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`
1601
+ );
1602
+ }
1603
+ const others = sizes.filter(
1604
+ (s, i) => i !== main && s >= SECOND_HOLE_FRACTION * sizes[main]
1605
+ );
1606
+ if (others.length > 0) {
1607
+ throw new AutoRigInputError(
1608
+ `${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`
1609
+ );
1610
+ }
1611
+ return { label, main, box };
1612
+ }
1613
+ function measureLips(layers, w, h) {
1614
+ const measurer = createLayerSetMeasurer4({ width: w, height: h });
1615
+ return new Map(
1616
+ Object.entries(layers).map(([role, rgba]) => [
1617
+ role,
1618
+ measurer.add({ role, fileName: `${role}.png`, rgba })
1619
+ ])
1620
+ );
1621
+ }
1622
+ function assertFoldContract(layers, w, h) {
1623
+ const byRole = /* @__PURE__ */ new Map();
1624
+ for (const [role, layer] of measureLips(layers, w, h)) {
1625
+ if (layer === null && role === "lip_lower") {
1626
+ throw new AutoRigInputError(
1627
+ `${KEYED_SRC}: no lip_lower after the split \u2014 there is no skin under the opening; draw the lower lip under the outline`
1628
+ );
1629
+ }
1630
+ byRole.set(role, layer);
1631
+ }
1632
+ const opening = mouthOpening(byRole);
1633
+ const runs = columnRuns(byRole.get("mouth_inner"));
1634
+ for (let col = opening.x0; col <= opening.x1; col++) {
1635
+ const c = opening.at(col);
1636
+ 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;
1637
+ if (why !== null) throw new Error(`splitLipSet: column ${col} ${why}`);
1638
+ }
1639
+ return opening;
1640
+ }
1641
+ async function splitLipSet(keyedPng, w, h, interior) {
1642
+ const { data: frame, info } = await rawOf(keyedPng);
1643
+ if (info.width !== w || info.height !== h) {
1644
+ throw new Error(
1645
+ `splitLipSet: the frame is ${info.width}x${info.height}, not ${w}x${h}`
1646
+ );
1647
+ }
1648
+ const n = w * h;
1649
+ const alpha = (p) => frame[p * 4 + 3];
1650
+ const { label, main, box: hb } = enclosedHole(frame, w, h);
1651
+ const holeW = hb.x1 - hb.x0 + 1;
1652
+ const top = new Int32Array(w).fill(-1);
1653
+ const bot = new Int32Array(w).fill(-1);
1654
+ for (let y = 0; y < h; y++) {
1655
+ for (let x = hb.x0; x <= hb.x1; x++) {
1656
+ if (label[y * w + x] !== main) continue;
1657
+ if (top[x] < 0) top[x] = y;
1658
+ bot[x] = y + 1;
1659
+ }
1660
+ }
1661
+ const centre = Math.round((hb.x0 + hb.x1) / 2);
1662
+ let stroke = 0;
1663
+ while (top[centre] - 1 - stroke >= 0 && alpha((top[centre] - 1 - stroke) * w + centre) >= ALPHA_OPAQUE3)
1664
+ stroke++;
1665
+ const bandCap = BAND_CAP * Math.max(1, stroke);
1666
+ const skinRow = new Int32Array(w).fill(-1);
1667
+ const inM = new Uint8Array(n);
1668
+ for (let x = hb.x0; x <= hb.x1; x++) {
1669
+ let y = bot[x];
1670
+ while (y < h && y - bot[x] < bandCap && alpha(y * w + x) >= ALPHA_OPAQUE3 && luma(frame, (y * w + x) * 4) < BAND_LUMA)
1671
+ y++;
1672
+ for (let k = top[x]; k < y; k++) inM[k * w + x] = 1;
1673
+ let r = y;
1674
+ while (r < h && alpha(r * w + x) < ALPHA_OPAQUE3) r++;
1675
+ if (r < h) {
1676
+ skinRow[x] = r;
1677
+ inM[r * w + x] = 1;
1678
+ }
1679
+ }
1680
+ const grown = Uint8Array.from(inM);
1681
+ for (let y = 0; y < h; y++) {
1682
+ for (let x = 0; x < w; x++) {
1683
+ const p = y * w + x;
1684
+ if (inM[p] || alpha(p) < ALPHA_OPAQUE3) continue;
1685
+ if (top[x] >= 0 && y < top[x]) continue;
1686
+ if (x > 0 && inM[p - 1] || x < w - 1 && inM[p + 1]) grown[p] = 1;
1687
+ }
1688
+ }
1689
+ const wall = new Uint8Array(w);
1690
+ for (const x of [hb.x0 - 1, hb.x1 + 1]) {
1691
+ if (x < 0 || x >= w) continue;
1692
+ let first = 0;
1693
+ while (first < h && !(grown[first * w + x] && !inM[first * w + x])) first++;
1694
+ if (first > 0 && first < h && alpha((first - 1) * w + x) >= ALPHA_OPAQUE3)
1695
+ wall[x] = 1;
1696
+ }
1697
+ const gx = hb.x0 - 1;
1698
+ const gy = hb.y0 - 1;
1699
+ const gw = holeW + 2;
1700
+ const gh = hb.y1 - hb.y0 + 3;
1701
+ const { data: fitted } = await sharp2(interior.png).resize(gw, gh, { fit: "fill" }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1702
+ const faintUpper = (p, x, y) => y < bot[x] && label[p] === main && 2 * y < top[x] + bot[x];
1703
+ const upper = Buffer.alloc(n * 4);
1704
+ const lower = Buffer.alloc(n * 4);
1705
+ const inner = Buffer.alloc(n * 4);
1706
+ const copy = (to, p) => frame.copy(to, p * 4, p * 4, p * 4 + 4);
1707
+ for (let y = 0; y < h; y++) {
1708
+ for (let x = 0; x < w; x++) {
1709
+ const p = y * w + x;
1710
+ const inOpening = top[x] >= 0;
1711
+ if ((!inOpening || y < top[x] || faintUpper(p, x, y)) && !(wall[x] && grown[p]))
1712
+ copy(upper, p);
1713
+ if (inOpening && skinRow[x] >= 0 && y >= skinRow[x]) copy(lower, p);
1714
+ if (!grown[p]) continue;
1715
+ const out = [...interior.cavity];
1716
+ const ix = x - gx;
1717
+ const iy = y - gy;
1718
+ if (ix >= 0 && ix < gw && iy >= 0 && iy < gh) {
1719
+ const i = (iy * gw + ix) * 4;
1720
+ const a = fitted[i + 3] / 255;
1721
+ for (let c = 0; c < 3; c++) out[c] += (fitted[i + c] - out[c]) * a;
1722
+ }
1723
+ if ((inM[p] || wall[x]) && !faintUpper(p, x, y)) {
1724
+ const a = alpha(p) / 255;
1725
+ for (let c = 0; c < 3; c++) out[c] += (frame[p * 4 + c] - out[c]) * a;
1726
+ }
1727
+ inner[p * 4] = Math.round(out[0]);
1728
+ inner[p * 4 + 1] = Math.round(out[1]);
1729
+ inner[p * 4 + 2] = Math.round(out[2]);
1730
+ inner[p * 4 + 3] = 255;
1731
+ }
1732
+ }
1733
+ const opening = assertFoldContract(
1734
+ { mouth_inner: inner, lip_lower: lower, lip_upper: upper },
1735
+ w,
1736
+ h
1737
+ );
1738
+ const [innerPng, lowerPng, upperPng] = await Promise.all([
1739
+ encode(inner, w, h),
1740
+ encode(lower, w, h),
1741
+ encode(upper, w, h)
1742
+ ]);
1743
+ return { inner: innerPng, lower: lowerPng, upper: upperPng, opening };
1744
+ }
1745
+ async function restShiftOf(layers, width, height) {
1746
+ const [mouth_inner, lip_lower, lip_upper] = await Promise.all(
1747
+ [layers.mouth_inner, layers.lip_lower, layers.lip_upper].map(
1748
+ async (png) => (await rawOf(png)).data
1749
+ )
1750
+ );
1751
+ const byRole = /* @__PURE__ */ new Map();
1752
+ for (const [role, layer] of measureLips(
1753
+ { mouth_inner, lip_lower, lip_upper },
1754
+ width,
1755
+ height
1756
+ )) {
1757
+ if (layer === null) {
1758
+ throw new AutoRigInputError(
1759
+ `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`
1760
+ );
1761
+ }
1762
+ byRole.set(role, layer);
1763
+ }
1764
+ return mouthRestShift(byRole);
1765
+ }
1766
+ async function closedLips(upper, lower, shift, left) {
1767
+ const shut = async (png, role) => {
1768
+ const { data, info } = await rawOf(png);
1769
+ const { width: w, height: h } = info;
1770
+ const out = Buffer.alloc(w * h * 4);
1771
+ for (let x = 0; x < w; x++) {
1772
+ const dy = shift(role, left + x);
1773
+ const f = Math.floor(dy);
1774
+ const t = dy - f;
1775
+ const px2 = (row, c) => row < 0 || row >= h ? 0 : data[(row * w + x) * 4 + c];
1776
+ for (let to = 0; to < h; to++) {
1777
+ const a0 = px2(to + f, 3);
1778
+ const a1 = px2(to + f + 1, 3);
1779
+ const a = (1 - t) * a0 + t * a1;
1780
+ if (a === 0) continue;
1781
+ const o = (to * w + x) * 4;
1782
+ for (let c = 0; c < 3; c++)
1783
+ out[o + c] = Math.round(
1784
+ ((1 - t) * a0 * px2(to + f, c) + t * a1 * px2(to + f + 1, c)) / a
1785
+ );
1786
+ out[o + 3] = Math.round(a);
1787
+ }
1788
+ }
1789
+ return encode(out, w, h);
1790
+ };
1791
+ const [u, l] = await Promise.all([
1792
+ shut(upper, "lip_upper"),
1793
+ shut(lower, "lip_lower")
1794
+ ]);
1795
+ return { upper: u, lower: l };
1796
+ }
1797
+
1798
+ // src/measure-lips.ts
1799
+ var isLipRole = (role) => LIP_ROLES.includes(role);
1800
+ var MIN_OPENING_ROWS = 8;
1801
+ var MIN_LINE_ROWS = 2;
1802
+ var GREEN_EXCESS = 40;
1803
+ var INTERIOR_GAP_FRACTION = 0.05;
1804
+ var columns = (cols) => `${cols.length} column${cols.length === 1 ? "" : "s"} (first at x=${cols[0]})`;
1805
+ async function lipWarnings(absDir, layers) {
1806
+ const warnings = [];
1807
+ const present = LIP_ROLES.filter((role) => layers[role] !== void 0);
1808
+ if (present.length === 0) return { warnings };
1809
+ const legacy = ["mouth", "mouth_open"].filter(
1810
+ (role) => layers[role] !== void 0
1811
+ );
1812
+ if (legacy.length > 0) {
1813
+ warnings.push(
1814
+ `${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.`
1815
+ );
1816
+ }
1817
+ if (present.length < LIP_ROLES.length) {
1818
+ const missing = LIP_ROLES.filter((role) => layers[role] === void 0);
1819
+ warnings.push(
1820
+ `${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.`
1821
+ );
1822
+ return { warnings };
1823
+ }
1824
+ const { mouth_inner: inner, lip_upper: upper } = layers;
1825
+ for (const role of ["lip_lower", "lip_upper"]) {
1826
+ const stats = layers[role];
1827
+ if (stats.canvasW !== inner.canvasW || stats.canvasH !== inner.canvasH) {
1828
+ warnings.push(
1829
+ `${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.`
1830
+ );
1831
+ return { warnings };
1832
+ }
1833
+ }
1834
+ const measurer = createLayerSetMeasurer5({
1835
+ width: inner.canvasW,
1836
+ height: inner.canvasH
1837
+ });
1838
+ const set = /* @__PURE__ */ new Map();
1839
+ const green = [];
1840
+ for (const role of LIP_ROLES) {
1841
+ const fileName = `${role}.png`;
1842
+ const { rgba } = await decodePng(path5.join(absDir, fileName));
1843
+ set.set(role, measurer.add({ role, fileName, rgba }));
1844
+ for (let i = 0; i < rgba.length; i += 4) {
1845
+ if (rgba[i + 3] >= ALPHA_OPAQUE4 && rgba[i + 1] - Math.max(rgba[i], rgba[i + 2]) > GREEN_EXCESS) {
1846
+ green.push(role);
1847
+ break;
1848
+ }
1849
+ }
1850
+ }
1851
+ let opening;
1852
+ try {
1853
+ opening = mouthOpening2(set);
1854
+ } catch (err) {
1855
+ if (err instanceof LayerGeometryError4) {
1856
+ warnings.push(err.message);
1857
+ return { warnings };
1858
+ }
1859
+ throw err;
1860
+ }
1861
+ const innerRuns = columnRuns2(set.get("mouth_inner"));
1862
+ const noInterior = [];
1863
+ const gap = [];
1864
+ const noLine = [];
1865
+ const skinGap = [];
1866
+ let area = 0;
1867
+ let hollow = 0;
1868
+ for (let x = opening.x0; x <= opening.x1; x++) {
1869
+ const runs = innerRuns.get(x);
1870
+ if (runs === void 0) {
1871
+ noInterior.push(x);
1872
+ continue;
1873
+ }
1874
+ const span = runs[runs.length - 1][1] - runs[0][0];
1875
+ area += span;
1876
+ hollow += span - runs.reduce((n, r) => n + r[1] - r[0], 0);
1877
+ const c = opening.at(x);
1878
+ if (c.lineH <= 0) noLine.push(x);
1879
+ else if (c.Tu > c.T) gap.push(x);
1880
+ if (c.Bl < c.Bb) skinGap.push(x);
1881
+ }
1882
+ const recompose = (file, ask) => `Recompose from mouth_keyed.png + mouth_interior.png (free); if it persists, regenerate ${file} ${ask}. Billed.`;
1883
+ const regenKeyed = recompose(
1884
+ "mouth_keyed.png",
1885
+ "with a closed outline and solid lips under it"
1886
+ );
1887
+ if (noInterior.length > 0) {
1888
+ warnings.push(
1889
+ `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")}`
1890
+ );
1891
+ }
1892
+ if (gap.length > 0) {
1893
+ warnings.push(
1894
+ `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}`
1895
+ );
1896
+ }
1897
+ if (noLine.length > 0) {
1898
+ warnings.push(
1899
+ `lip_upper: no line above the interior in ${columns(noLine)} \u2014 nothing closes the mouth there. ${regenKeyed}`
1900
+ );
1901
+ }
1902
+ if (skinGap.length > 0) {
1903
+ warnings.push(
1904
+ `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}`
1905
+ );
1906
+ }
1907
+ const width = opening.x1 - opening.x0 + 1;
1908
+ const centre = opening.at(opening.centre);
1909
+ if (width < MIN_OPENING_WIDTH * upper.w) {
1910
+ warnings.push(
1911
+ `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.`
1912
+ );
1913
+ }
1914
+ if (centre.H < MIN_OPENING_ROWS) {
1915
+ const w = Math.ceil(upper.w * MIN_OPENING_ROWS / centre.H);
1916
+ const retune = w <= inner.canvasW ? w : null;
1917
+ warnings.push(
1918
+ `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.`
1919
+ );
1920
+ }
1921
+ if (opening.w < MIN_LINE_ROWS) {
1922
+ warnings.push(
1923
+ `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.`
1924
+ );
1925
+ }
1926
+ if (green.length > 0) {
1927
+ warnings.push(
1928
+ `${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.`
1929
+ );
1930
+ }
1931
+ if (area > 0 && hollow > INTERIOR_GAP_FRACTION * area) {
1932
+ warnings.push(
1933
+ `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.`
1934
+ );
1935
+ }
1936
+ return {
1937
+ warnings,
1938
+ lips: {
1939
+ opening: { width, height: centre.H, line: opening.w },
1940
+ deadZone: centre.overlap / (centre.H + centre.overlap)
1941
+ }
1942
+ };
1943
+ }
1944
+
1153
1945
  // src/measure.ts
1154
1946
  var IRIS_RATIO_MIN = 0.45;
1155
1947
  var IRIS_RATIO_MAX = 0.72;
@@ -1278,8 +2070,8 @@ async function measureDir(absDir, noseSpeck) {
1278
2070
  const layers = {};
1279
2071
  const empty = [];
1280
2072
  for (const f of files) {
1281
- const role = path5.basename(f, ".png");
1282
- const m = await layerStats(path5.join(absDir, f));
2073
+ const role = path6.basename(f, ".png");
2074
+ const m = await layerStats(path6.join(absDir, f));
1283
2075
  if (!m) {
1284
2076
  empty.push(role);
1285
2077
  continue;
@@ -1288,6 +2080,7 @@ async function measureDir(absDir, noseSpeck) {
1288
2080
  }
1289
2081
  const warnings = [];
1290
2082
  for (const [role, m] of Object.entries(layers)) {
2083
+ if (isLipRole(role)) continue;
1291
2084
  const edges = [
1292
2085
  ["top", m.edgeTop, m.w, m.marginTop],
1293
2086
  ["left", m.edgeLeft, m.h, m.marginLeft],
@@ -1317,7 +2110,7 @@ async function measureDir(absDir, noseSpeck) {
1317
2110
  }
1318
2111
  }
1319
2112
  for (const [role, m] of Object.entries(layers)) {
1320
- if (role === "body") continue;
2113
+ if (role === "body" || isLipRole(role)) continue;
1321
2114
  if (m.flatCutRun > FLAT_CUT_MAX_FRAC * m.w && m.flatCutRun >= FLAT_CUT_MIN_PX) {
1322
2115
  warnings.push(
1323
2116
  `${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.`
@@ -1326,6 +2119,8 @@ async function measureDir(absDir, noseSpeck) {
1326
2119
  }
1327
2120
  warnings.push(...await armWarnings(absDir, layers));
1328
2121
  warnings.push(...await forearmPoseWarnings(absDir, layers));
2122
+ const lip = await lipWarnings(absDir, layers);
2123
+ warnings.push(...lip.warnings);
1329
2124
  for (const side of ["L", "R"]) {
1330
2125
  const eye = layers[`eye_${side}`];
1331
2126
  const iris = layers[`iris_${side}`];
@@ -1354,8 +2149,8 @@ async function measureDir(absDir, noseSpeck) {
1354
2149
  }
1355
2150
  if (lash) {
1356
2151
  const { opaque, off } = await lashOffSclera(
1357
- path5.join(absDir, `eye_${side}.png`),
1358
- path5.join(absDir, `lash_${side}.png`)
2152
+ path6.join(absDir, `eye_${side}.png`),
2153
+ path6.join(absDir, `lash_${side}.png`)
1359
2154
  );
1360
2155
  const dTop = lash.marginTop - eye.marginTop;
1361
2156
  const faults = [
@@ -1381,7 +2176,7 @@ async function measureDir(absDir, noseSpeck) {
1381
2176
  if (noseSpeck !== void 0) {
1382
2177
  warnings.push(noseSpeckWarning(noseSpeck, "compose"));
1383
2178
  } else if (layers.nose !== void 0) {
1384
- const nose = await decodePng(path5.join(absDir, "nose.png"));
2179
+ const nose = await decodePng(path6.join(absDir, "nose.png"));
1385
2180
  const core = denseCoreOf(nose.rgba, nose.width, nose.height);
1386
2181
  if (core !== null) {
1387
2182
  const crop = detectAlphaBbox(nose.rgba, nose.width, nose.height);
@@ -1399,7 +2194,12 @@ async function measureDir(absDir, noseSpeck) {
1399
2194
  ]) {
1400
2195
  if (layers[role] === void 0) warnings.push(`${role}: missing \u2014 ${why}.`);
1401
2196
  }
1402
- return { layers, empty, warnings };
2197
+ return {
2198
+ layers,
2199
+ empty,
2200
+ warnings,
2201
+ ...lip.lips === void 0 ? {} : { lips: lip.lips }
2202
+ };
1403
2203
  }
1404
2204
  async function measureLayers(input) {
1405
2205
  try {
@@ -1433,6 +2233,13 @@ function formatMeasureReport(result) {
1433
2233
  `${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}`
1434
2234
  );
1435
2235
  }
2236
+ if (result.lips !== void 0) {
2237
+ const { opening, deadZone } = result.lips;
2238
+ lines.push(
2239
+ "",
2240
+ `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)}`
2241
+ );
2242
+ }
1436
2243
  lines.push("", "# checks", "");
1437
2244
  if (result.warnings.length === 0) {
1438
2245
  lines.push("all geometry checks passed");
@@ -1444,23 +2251,23 @@ function formatMeasureReport(result) {
1444
2251
 
1445
2252
  // src/compose.ts
1446
2253
  import fs3 from "fs";
1447
- import path6 from "path";
1448
- import sharp3 from "sharp";
1449
- import { ALPHA_OPAQUE as ALPHA_OPAQUE2, detectAlphaBbox as scanAlphaBbox2 } from "@ikijs/editor";
2254
+ import path7 from "path";
2255
+ import sharp4 from "sharp";
2256
+ import { ALPHA_OPAQUE as ALPHA_OPAQUE5, detectAlphaBbox as scanAlphaBbox2 } from "@ikijs/editor";
1450
2257
 
1451
2258
  // src/compose-arms.ts
1452
- import sharp2 from "sharp";
2259
+ import sharp3 from "sharp";
1453
2260
  import {
1454
- LayerGeometryError as LayerGeometryError4,
2261
+ LayerGeometryError as LayerGeometryError5,
1455
2262
  armGeometry as armGeometry3,
1456
- createLayerSetMeasurer as createLayerSetMeasurer4,
2263
+ createLayerSetMeasurer as createLayerSetMeasurer6,
1457
2264
  forearmPoseGeometry as forearmPoseGeometry2
1458
2265
  } from "@ikijs/editor";
1459
2266
  var ARM_WIDTH = 0.4;
1460
2267
  var SHOULDER_DROP = 0.12;
1461
2268
  async function armPlacement(role, cfg, part, body) {
1462
- const { data } = await sharp2(part.buf).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1463
- const layer = createLayerSetMeasurer4({ width: part.w, height: part.h }).add({
2269
+ const { data } = await sharp3(part.buf).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2270
+ const layer = createLayerSetMeasurer6({ width: part.w, height: part.h }).add({
1464
2271
  role,
1465
2272
  fileName: "arm.png",
1466
2273
  rgba: data
@@ -1474,7 +2281,7 @@ async function armPlacement(role, cfg, part, body) {
1474
2281
  try {
1475
2282
  g = armGeometry3(layer, role === "arm_R" ? Infinity : -Infinity);
1476
2283
  } catch (err) {
1477
- if (err instanceof LayerGeometryError4) {
2284
+ if (err instanceof LayerGeometryError5) {
1478
2285
  throw new AutoRigInputError(`layout.${role}: ${err.message}`);
1479
2286
  }
1480
2287
  throw err;
@@ -1500,8 +2307,8 @@ async function armPlacement(role, cfg, part, body) {
1500
2307
  };
1501
2308
  }
1502
2309
  async function poseGeometryOf(role, png, size, when) {
1503
- const { data } = await sharp2(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1504
- const layer = createLayerSetMeasurer4({
2310
+ const { data } = await sharp3(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2311
+ const layer = createLayerSetMeasurer6({
1505
2312
  width: size.w,
1506
2313
  height: size.h
1507
2314
  }).add({ role, fileName: "forearm_pose.png", rgba: data });
@@ -1540,8 +2347,6 @@ var IRIS_W = 50;
1540
2347
  var EYEWHITE_SRC = "eyewhite.png";
1541
2348
  var EYE_LASH_LUMA = 120;
1542
2349
  var LASH_KEEP_FRACTION = 0.5;
1543
- var TRIM_THRESHOLD = 12;
1544
- var STRAY_SPECK_FRACTION = 0.01;
1545
2350
  var NOSE_TIP_AT = 0.66;
1546
2351
  var DEFAULT_LAYOUT = {
1547
2352
  // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir
@@ -1592,6 +2397,18 @@ var DEFAULT_LAYOUT = {
1592
2397
  w: 76,
1593
2398
  optional: true
1594
2399
  },
2400
+ // The lip set's ONE frame, mouth_open's place: the keyed mouth is split into
2401
+ // mouth_inner / lip_lower / lip_upper and all three land here, so a retune
2402
+ // moves them together. lip_lower and lip_upper have no key of their own
2403
+ // (LIP_FRAME). OPTIONAL and opt-in: with mouth_keyed.png + mouth_interior.png
2404
+ // it stands in for mouth and mouth_open.
2405
+ mouth_inner: {
2406
+ src: KEYED_SRC,
2407
+ cx: 550,
2408
+ cy: 596,
2409
+ w: 76,
2410
+ optional: true
2411
+ },
1595
2412
  // eye_* (sclera) and lash_* share the eyewhite's cropped frame via noTrim (so
1596
2413
  // they are NOT re-bboxed independently): the upper lash stays anchored ABOVE
1597
2414
  // the sclera center, so on blink it folds DOWN over the eye like the sample
@@ -1638,6 +2455,9 @@ var ORDER = [
1638
2455
  "nose",
1639
2456
  "mouth",
1640
2457
  "mouth_open",
2458
+ "mouth_inner",
2459
+ "lip_lower",
2460
+ "lip_upper",
1641
2461
  "eye_L",
1642
2462
  "eye_R",
1643
2463
  "iris_L",
@@ -1656,13 +2476,15 @@ var PART_FILES = [
1656
2476
  ...new Set(
1657
2477
  Object.values(DEFAULT_LAYOUT).map((cfg) => cfg.src).filter((src) => !src.startsWith("eyewhite_"))
1658
2478
  ),
1659
- EYEWHITE_SRC
2479
+ EYEWHITE_SRC,
2480
+ INTERIOR_SRC
1660
2481
  ];
1661
2482
  var FACE_FEATURES = [
1662
2483
  "blush_L",
1663
2484
  "blush_R",
1664
2485
  "mouth",
1665
2486
  "mouth_open",
2487
+ "mouth_inner",
1666
2488
  "eye_L",
1667
2489
  "eye_R",
1668
2490
  "iris_L",
@@ -1766,14 +2588,14 @@ function keyWhiteToAlpha(rgba) {
1766
2588
  return keyed;
1767
2589
  }
1768
2590
  async function coreAndBoundsOf(png) {
1769
- const { data, info } = await sharp3(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2591
+ const { data, info } = await sharp4(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1770
2592
  return {
1771
2593
  core: denseCoreOf(data, info.width, info.height),
1772
2594
  bounds: { x: 0, y: 0, w: info.width, h: info.height }
1773
2595
  };
1774
2596
  }
1775
2597
  async function hasCoverage(png) {
1776
- const { data, info } = await sharp3(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
2598
+ const { data, info } = await sharp4(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1777
2599
  return scanAlphaBbox2(data, info.width, info.height) !== null;
1778
2600
  }
1779
2601
  async function noseSizingOf(png) {
@@ -1794,24 +2616,24 @@ async function noseSizingOf(png) {
1794
2616
  async function trimmedPart(role, cfg, partsDir, inMemory, flipSource) {
1795
2617
  let img;
1796
2618
  if (inMemory !== void 0) {
1797
- img = sharp3(inMemory);
2619
+ img = sharp4(inMemory);
1798
2620
  } else {
1799
- const srcPath = path6.join(partsDir, cfg.src);
2621
+ const srcPath = path7.join(partsDir, cfg.src);
1800
2622
  if (!fs3.existsSync(srcPath)) {
1801
2623
  if (cfg.optional) return null;
1802
2624
  throw new AutoRigInputError(
1803
- `missing part source for role "${role}": ${srcPath}`
2625
+ `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" : "")
1804
2626
  );
1805
2627
  }
1806
2628
  const png = await decodePng(srcPath);
1807
- img = sharp3(png.hasAlpha ? png.rgba : keyWhiteToAlpha(png.rgba), {
2629
+ img = sharp4(png.hasAlpha ? png.rgba : keyWhiteToAlpha(png.rgba), {
1808
2630
  raw: { width: png.width, height: png.height, channels: 4 }
1809
2631
  });
1810
2632
  }
1811
2633
  if (!cfg.noTrim) {
1812
2634
  const kept = await img.trim({ threshold: TRIM_THRESHOLD }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
1813
2635
  const { width: keptW, height: keptH } = kept.info;
1814
- img = sharp3(kept.data, {
2636
+ img = sharp4(kept.data, {
1815
2637
  raw: { width: keptW, height: keptH, channels: 4 }
1816
2638
  });
1817
2639
  const box = boxWithoutStraySpecks(kept.data, keptW, keptH);
@@ -1837,7 +2659,7 @@ async function sizedPart(role, cfg, trimmed, canvas) {
1837
2659
  `layout.${role}.${field}: resized part ${width}x${height} exceeds the ${canvasName(canvas)} canvas`
1838
2660
  );
1839
2661
  }
1840
- const resized = await sharp3(trimmed.data).resize(cfg.h === void 0 ? { width } : { width, height, fit: "fill" }).png().toBuffer({ resolveWithObject: true });
2662
+ const resized = await sharp4(trimmed.data).resize(cfg.h === void 0 ? { width } : { width, height, fit: "fill" }).png().toBuffer({ resolveWithObject: true });
1841
2663
  return {
1842
2664
  buf: resized.data,
1843
2665
  w: resized.info.width,
@@ -1862,7 +2684,7 @@ function placement(role, cfg, w, h, canvas) {
1862
2684
  assertOnCanvas(`layout.${role}.cx/cy`, w, h, left, top, canvas);
1863
2685
  return { left, top };
1864
2686
  }
1865
- function nosePlacement(layout, box, w, h, canvas) {
2687
+ function nosePlacement(layout, mouthKey, box, w, h, canvas) {
1866
2688
  const { cx, cy } = layout.nose;
1867
2689
  const left = Math.round(cx - (box.x + box.w / 2));
1868
2690
  let top;
@@ -1871,12 +2693,12 @@ function nosePlacement(layout, box, w, h, canvas) {
1871
2693
  } else {
1872
2694
  const eyeRow = (layout.eye_L.cy + layout.eye_R.cy) / 2;
1873
2695
  const tipRow = Math.round(
1874
- eyeRow + NOSE_TIP_AT * (layout.mouth.cy - eyeRow)
2696
+ eyeRow + NOSE_TIP_AT * (layout[mouthKey].cy - eyeRow)
1875
2697
  );
1876
2698
  top = tipRow - (box.y + box.h - 1);
1877
2699
  }
1878
2700
  assertOnCanvas(
1879
- 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)",
2701
+ 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)`,
1880
2702
  w,
1881
2703
  h,
1882
2704
  left,
@@ -1886,7 +2708,7 @@ function nosePlacement(layout, box, w, h, canvas) {
1886
2708
  return { left, top };
1887
2709
  }
1888
2710
  function blankCanvas(canvas) {
1889
- return sharp3({
2711
+ return sharp4({
1890
2712
  create: {
1891
2713
  width: canvas.width,
1892
2714
  height: canvas.height,
@@ -1895,74 +2717,13 @@ function blankCanvas(canvas) {
1895
2717
  }
1896
2718
  });
1897
2719
  }
1898
- function luma(rgba, i) {
1899
- return 0.299 * rgba[i] + 0.587 * rgba[i + 1] + 0.114 * rgba[i + 2];
1900
- }
1901
- function boxWithoutStraySpecks(rgba, W, H) {
1902
- const n = W * H;
1903
- let kept = 0;
1904
- for (let p = 0; p < n; p++) if (rgba[p * 4 + 3] > TRIM_THRESHOLD) kept++;
1905
- const visited = new Uint8Array(n);
1906
- let stack = new Int32Array(1024);
1907
- const drawing = [W, H, -1, -1];
1908
- const strays = [W, H, -1, -1];
1909
- let anyOpaque = false;
1910
- for (let start = 0; start < n; start++) {
1911
- if (visited[start] || rgba[start * 4 + 3] <= TRIM_THRESHOLD) continue;
1912
- let setLeft = W;
1913
- let setTop = H;
1914
- let setRight = -1;
1915
- let setBottom = -1;
1916
- let size = 0;
1917
- let opaque = false;
1918
- let depth = 0;
1919
- visited[start] = 1;
1920
- stack[depth++] = start;
1921
- while (depth > 0) {
1922
- const p = stack[--depth];
1923
- size++;
1924
- if (rgba[p * 4 + 3] >= ALPHA_OPAQUE2) opaque = true;
1925
- const px2 = p % W;
1926
- const py = (p - px2) / W;
1927
- setLeft = Math.min(setLeft, px2);
1928
- setTop = Math.min(setTop, py);
1929
- setRight = Math.max(setRight, px2);
1930
- setBottom = Math.max(setBottom, py);
1931
- for (let y = Math.max(0, py - 1); y <= Math.min(H - 1, py + 1); y++) {
1932
- for (let x = Math.max(0, px2 - 1); x <= Math.min(W - 1, px2 + 1); x++) {
1933
- const q = y * W + x;
1934
- if (!visited[q] && rgba[q * 4 + 3] > TRIM_THRESHOLD) {
1935
- visited[q] = 1;
1936
- if (depth === stack.length) {
1937
- const grown = new Int32Array(Math.min(n, stack.length * 2));
1938
- grown.set(stack);
1939
- stack = grown;
1940
- }
1941
- stack[depth++] = q;
1942
- }
1943
- }
1944
- }
1945
- }
1946
- anyOpaque ||= opaque;
1947
- const into = !opaque && size < kept * STRAY_SPECK_FRACTION ? strays : drawing;
1948
- into[0] = Math.min(into[0], setLeft);
1949
- into[1] = Math.min(into[1], setTop);
1950
- into[2] = Math.max(into[2], setRight);
1951
- into[3] = Math.max(into[3], setBottom);
1952
- }
1953
- if (!anyOpaque || strays[2] < 0) return null;
1954
- const [left, top, right, bottom] = drawing;
1955
- if (strays[0] >= left && strays[1] >= top && strays[2] <= right && strays[3] <= bottom)
1956
- return null;
1957
- return { left, top, width: right - left + 1, height: bottom - top + 1 };
1958
- }
1959
2720
  function detachedAboveWhite(rgba, W, H) {
1960
2721
  const n = W * H;
1961
2722
  const ink = new Uint8Array(n);
1962
2723
  for (let p = 0; p < n; p++) {
1963
2724
  const alpha = rgba[p * 4 + 3];
1964
2725
  if (alpha > 0 && luma(rgba, p * 4) >= EYE_LASH_LUMA)
1965
- ink[p] = alpha >= ALPHA_OPAQUE2 ? 2 : 1;
2726
+ ink[p] = alpha >= ALPHA_OPAQUE5 ? 2 : 1;
1966
2727
  }
1967
2728
  const label = new Int32Array(n).fill(-1);
1968
2729
  const stack = new Int32Array(n);
@@ -2042,7 +2803,7 @@ function detachedAboveWhite(rgba, W, H) {
2042
2803
  return detached;
2043
2804
  }
2044
2805
  async function prepEyeSplit(partsDir) {
2045
- const srcPath = path6.join(partsDir, EYEWHITE_SRC);
2806
+ const srcPath = path7.join(partsDir, EYEWHITE_SRC);
2046
2807
  if (!fs3.existsSync(srcPath)) {
2047
2808
  throw new AutoRigInputError(`missing eyewhite source: ${srcPath}`);
2048
2809
  }
@@ -2094,6 +2855,50 @@ async function prepEyeSplit(partsDir) {
2094
2855
  lashLower: lowerInk ? await cropToBuffer(lashLower, W, H, region) : null
2095
2856
  };
2096
2857
  }
2858
+ function hasTransparency(rgba) {
2859
+ for (let p = 3; p < rgba.length; p += 4) if (rgba[p] < 255) return true;
2860
+ return false;
2861
+ }
2862
+ async function prepLipSources(partsDir, mirrored) {
2863
+ const has = (name) => fs3.existsSync(path7.join(partsDir, name));
2864
+ const keyed = has(KEYED_SRC);
2865
+ const interior = has(INTERIOR_SRC);
2866
+ if (keyed && !interior) {
2867
+ throw new AutoRigInputError(
2868
+ `${KEYED_SRC} needs ${INTERIOR_SRC}: the composer fits the drawn interior into the keyed opening \u2014 draw it (billed)`
2869
+ );
2870
+ }
2871
+ if (interior && !keyed) {
2872
+ throw new AutoRigInputError(
2873
+ `${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)`
2874
+ );
2875
+ }
2876
+ if (!keyed) return void 0;
2877
+ const legacy = ["mouth.png", "mouth_open.png"].filter(has);
2878
+ if (legacy.length > 0) {
2879
+ throw new AutoRigInputError(
2880
+ `${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 ")}`
2881
+ );
2882
+ }
2883
+ const k = await decodePng(path7.join(partsDir, KEYED_SRC));
2884
+ const keyedRgba = keyGreen(
2885
+ hasTransparency(k.rgba) ? k.rgba : keyWhiteToAlpha(k.rgba),
2886
+ k.width,
2887
+ k.height
2888
+ );
2889
+ const i = await decodePng(path7.join(partsDir, INTERIOR_SRC));
2890
+ const prepared = await prepInterior(
2891
+ hasTransparency(i.rgba) ? i.rgba : keyBorderWhite(i.rgba, i.width, i.height),
2892
+ i.width,
2893
+ i.height
2894
+ );
2895
+ return {
2896
+ keyedPng: await sharp4(keyedRgba, {
2897
+ raw: { width: k.width, height: k.height, channels: 4 }
2898
+ }).png().toBuffer(),
2899
+ interior: mirrored.has(INTERIOR_SRC) ? { ...prepared, png: await sharp4(prepared.png).flop().png().toBuffer() } : prepared
2900
+ };
2901
+ }
2097
2902
  async function composeLayersFromParts(input) {
2098
2903
  try {
2099
2904
  const outDir = resolveOutputDir(input.outDir);
@@ -2117,10 +2922,49 @@ async function composeLayersFromParts(input) {
2117
2922
  if (split.lashLower !== null) {
2118
2923
  splitSources.set(LOWER_LASH_SRC, split.lashLower);
2119
2924
  }
2925
+ const lips = await prepLipSources(partsDir, mirrored);
2926
+ let lipSplit;
2120
2927
  const placed = [];
2121
2928
  const skipped = [];
2122
2929
  let noseSpeck;
2123
2930
  for (const role of ORDER) {
2931
+ if (lips !== void 0 && (role === "mouth" || role === "mouth_open")) {
2932
+ continue;
2933
+ }
2934
+ if (role === "mouth_inner") {
2935
+ if (lips === void 0) continue;
2936
+ const cfg2 = layout.mouth_inner;
2937
+ const part2 = await partBuffer(
2938
+ role,
2939
+ cfg2,
2940
+ partsDir,
2941
+ lips.keyedPng,
2942
+ mirrored.has(KEYED_SRC),
2943
+ canvas
2944
+ );
2945
+ const split2 = await splitLipSet(
2946
+ part2.buf,
2947
+ part2.w,
2948
+ part2.h,
2949
+ lips.interior
2950
+ );
2951
+ const { left: left2, top: top2 } = placement(role, cfg2, part2.w, part2.h, canvas);
2952
+ lipSplit = { split: split2, w: part2.w, h: part2.h, left: left2, top: top2 };
2953
+ placed.push({
2954
+ role,
2955
+ part: { buf: split2.inner, w: part2.w, h: part2.h },
2956
+ left: left2,
2957
+ top: top2
2958
+ });
2959
+ continue;
2960
+ }
2961
+ if (role === "lip_lower" || role === "lip_upper") {
2962
+ if (lipSplit === void 0) continue;
2963
+ const { split: split2, w, h, left: left2, top: top2 } = lipSplit;
2964
+ const buf = role === "lip_lower" ? split2.lower : split2.upper;
2965
+ placed.push({ role, part: { buf, w, h }, left: left2, top: top2 });
2966
+ continue;
2967
+ }
2124
2968
  const lower = role === "lash_lower_L" || role === "lash_lower_R";
2125
2969
  const key = lower ? LOWER_LASH[role] : role;
2126
2970
  if (lower && split.lashLower === null) {
@@ -2129,7 +2973,7 @@ async function composeLayersFromParts(input) {
2129
2973
  }
2130
2974
  if (key === "arm_L" || key === "arm_R") {
2131
2975
  const arm = layout[key];
2132
- if (!fs3.existsSync(path6.join(partsDir, arm.src))) continue;
2976
+ if (!fs3.existsSync(path7.join(partsDir, arm.src))) continue;
2133
2977
  const body = placed.find((p) => p.role === "body");
2134
2978
  if (body === void 0) {
2135
2979
  throw new AutoRigInputError(
@@ -2172,7 +3016,7 @@ async function composeLayersFromParts(input) {
2172
3016
  }
2173
3017
  if (key === "forearm_pose_L" || key === "forearm_pose_R") {
2174
3018
  const pose = layout[key];
2175
- if (!fs3.existsSync(path6.join(partsDir, pose.src))) continue;
3019
+ if (!fs3.existsSync(path7.join(partsDir, pose.src))) continue;
2176
3020
  const armRole = key === "forearm_pose_L" ? "arm_L" : "arm_R";
2177
3021
  const arm = placed.find((p) => p.role === armRole);
2178
3022
  if (arm?.elbow === void 0 || arm.elbowRun === void 0) {
@@ -2243,7 +3087,14 @@ async function composeLayersFromParts(input) {
2243
3087
  noseSpeck = part.nose?.speck;
2244
3088
  const { core, bounds } = await coreAndBoundsOf(part.buf);
2245
3089
  const box = part.nose?.whole ? bounds : core ?? bounds;
2246
- ({ left, top } = nosePlacement(layout, box, part.w, part.h, canvas));
3090
+ ({ left, top } = nosePlacement(
3091
+ layout,
3092
+ lips === void 0 ? "mouth" : "mouth_inner",
3093
+ box,
3094
+ part.w,
3095
+ part.h,
3096
+ canvas
3097
+ ));
2247
3098
  } else {
2248
3099
  ({ left, top } = placement(key, layout[key], part.w, part.h, canvas));
2249
3100
  }
@@ -2258,20 +3109,39 @@ async function composeLayersFromParts(input) {
2258
3109
  }
2259
3110
  placed.push({ role, part, left, top });
2260
3111
  }
3112
+ const built = /* @__PURE__ */ new Map();
3113
+ for (const { role, part, left, top } of placed) {
3114
+ built.set(
3115
+ role,
3116
+ await blankCanvas(canvas).composite([{ input: part.buf, left, top }]).png().toBuffer()
3117
+ );
3118
+ }
3119
+ const closed = lipSplit === void 0 ? void 0 : await closedLips(
3120
+ lipSplit.split.upper,
3121
+ lipSplit.split.lower,
3122
+ await restShiftOf(
3123
+ {
3124
+ mouth_inner: built.get("mouth_inner"),
3125
+ lip_lower: built.get("lip_lower"),
3126
+ lip_upper: built.get("lip_upper")
3127
+ },
3128
+ canvas.width,
3129
+ canvas.height
3130
+ ),
3131
+ lipSplit.left
3132
+ );
2261
3133
  for (const role of ORDER) {
2262
3134
  if (placed.some((p) => p.role === role)) continue;
2263
- fs3.rmSync(path6.join(outDir, `${role}.png`), { force: true });
3135
+ fs3.rmSync(path7.join(outDir, `${role}.png`), { force: true });
2264
3136
  }
2265
3137
  const posed = (role) => role === "forearm_pose_L" || role === "forearm_pose_R";
2266
3138
  if (!placed.some((p) => posed(p.role))) {
2267
- fs3.rmSync(path6.join(outDir, "preview-pose.png"), { force: true });
3139
+ fs3.rmSync(path7.join(outDir, "preview-pose.png"), { force: true });
2268
3140
  }
2269
3141
  const layers = [];
2270
- const preview = [];
2271
3142
  for (const { role, part, left, top } of placed) {
2272
- const layer = await blankCanvas(canvas).composite([{ input: part.buf, left, top }]).png().toBuffer();
2273
- const outPath = path6.join(outDir, `${role}.png`);
2274
- writeFileAtomic(outPath, layer);
3143
+ const outPath = path7.join(outDir, `${role}.png`);
3144
+ writeFileAtomic(outPath, built.get(role));
2275
3145
  layers.push({
2276
3146
  role,
2277
3147
  path: outPath,
@@ -2280,9 +3150,20 @@ async function composeLayersFromParts(input) {
2280
3150
  left,
2281
3151
  top
2282
3152
  });
2283
- if (!posed(role)) preview.push({ input: part.buf, left, top });
2284
3153
  }
2285
- const previewPng = await sharp3({
3154
+ const restInput = (role, buf) => {
3155
+ if (role === "mouth_inner") return null;
3156
+ if (closed === void 0) return buf;
3157
+ if (role === "lip_upper") return closed.upper;
3158
+ if (role === "lip_lower") return closed.lower;
3159
+ return buf;
3160
+ };
3161
+ const preview = [];
3162
+ for (const { role, part, left, top } of placed) {
3163
+ const input2 = restInput(role, part.buf);
3164
+ if (!posed(role) && input2 !== null) preview.push({ input: input2, left, top });
3165
+ }
3166
+ const previewPng = await sharp4({
2286
3167
  create: {
2287
3168
  width: canvas.width,
2288
3169
  height: canvas.height,
@@ -2290,7 +3171,7 @@ async function composeLayersFromParts(input) {
2290
3171
  background: { r: 245, g: 245, b: 248, alpha: 1 }
2291
3172
  }
2292
3173
  }).composite(preview).png().toBuffer();
2293
- const previewPath = path6.join(outDir, "preview.png");
3174
+ const previewPath = path7.join(outDir, "preview.png");
2294
3175
  writeFileAtomic(previewPath, previewPng);
2295
3176
  let previewPosePath;
2296
3177
  if (placed.some((p) => posed(p.role))) {
@@ -2300,17 +3181,18 @@ async function composeLayersFromParts(input) {
2300
3181
  (p) => p.role === (role === "arm_L" ? "forearm_pose_L" : "forearm_pose_R")
2301
3182
  );
2302
3183
  if (!armPosed) {
2303
- pose.push({ input: part.buf, left, top });
3184
+ const input2 = restInput(role, part.buf);
3185
+ if (input2 !== null) pose.push({ input: input2, left, top });
2304
3186
  continue;
2305
3187
  }
2306
3188
  const rows = Math.min(part.h, Math.max(1, Math.round(elbow.y - top)));
2307
3189
  pose.push({
2308
- input: await sharp3(part.buf).extract({ left: 0, top: 0, width: part.w, height: rows }).png().toBuffer(),
3190
+ input: await sharp4(part.buf).extract({ left: 0, top: 0, width: part.w, height: rows }).png().toBuffer(),
2309
3191
  left,
2310
3192
  top
2311
3193
  });
2312
3194
  }
2313
- const posePng = await sharp3({
3195
+ const posePng = await sharp4({
2314
3196
  create: {
2315
3197
  width: canvas.width,
2316
3198
  height: canvas.height,
@@ -2318,7 +3200,7 @@ async function composeLayersFromParts(input) {
2318
3200
  background: { r: 245, g: 245, b: 248, alpha: 1 }
2319
3201
  }
2320
3202
  }).composite(pose).png().toBuffer();
2321
- previewPosePath = path6.join(outDir, "preview-pose.png");
3203
+ previewPosePath = path7.join(outDir, "preview-pose.png");
2322
3204
  writeFileAtomic(previewPosePath, posePng);
2323
3205
  }
2324
3206
  return {
@@ -2341,7 +3223,7 @@ async function composeLayersFromParts(input) {
2341
3223
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2342
3224
  import { z } from "zod";
2343
3225
  function createIkiMcpServer() {
2344
- const server = new McpServer({ name: "iki", version: "0.20.0" });
3226
+ const server = new McpServer({ name: "iki", version: "0.22.0" });
2345
3227
  server.registerTool(
2346
3228
  "validate_iki",
2347
3229
  {
@@ -2406,7 +3288,7 @@ function createIkiMcpServer() {
2406
3288
  server.registerTool(
2407
3289
  "auto_rig_from_layers",
2408
3290
  {
2409
- description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R, mouth required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, etc. optional; an arm needs the body, and a pose forearm needs its arm) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given.",
3291
+ 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.",
2410
3292
  inputSchema: {
2411
3293
  layers: z.array(
2412
3294
  z.object({
@@ -2461,7 +3343,7 @@ function createIkiMcpServer() {
2461
3343
  server.registerTool(
2462
3344
  "compose_layers_from_parts",
2463
3345
  {
2464
- 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`.",
3346
+ 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`.",
2465
3347
  inputSchema: {
2466
3348
  partsDir: z.string().describe(
2467
3349
  "Directory of the source part PNGs (resolved against cwd)."
@@ -2478,7 +3360,7 @@ function createIkiMcpServer() {
2478
3360
  h: z.number()
2479
3361
  }).partial()
2480
3362
  ).optional().describe(
2481
- "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."
3363
+ "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."
2482
3364
  ),
2483
3365
  mirrorParts: z.array(z.string()).optional().describe(
2484
3366
  "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."
@@ -2509,7 +3391,7 @@ function createIkiMcpServer() {
2509
3391
  server.registerTool(
2510
3392
  "measure_layers",
2511
3393
  {
2512
- 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.",
3394
+ 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.",
2513
3395
  inputSchema: {
2514
3396
  layersDir: z.string().describe(
2515
3397
  "Directory of role-named layer PNGs (resolved against cwd)."
@@ -2586,4 +3468,4 @@ export {
2586
3468
  composeLayersFromParts,
2587
3469
  createIkiMcpServer
2588
3470
  };
2589
- //# sourceMappingURL=chunk-6F4ZP5S4.mjs.map
3471
+ //# sourceMappingURL=chunk-SWRVRVYV.mjs.map