@ikijs/mcp 0.11.2 → 0.12.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.
@@ -1,5 +1,20 @@
1
- // src/measure-turn.ts
1
+ // src/tools.ts
2
2
  import path2 from "path";
3
+ import {
4
+ parseIkiModel,
5
+ loadIkiModel,
6
+ IkiFormatError,
7
+ StandardParameter
8
+ } from "@ikijs/format";
9
+ import {
10
+ EditorDocument,
11
+ packAtlas,
12
+ uvRectFor,
13
+ createLayerSetMeasurer,
14
+ generateIkiFromLayerSet,
15
+ parseLayerRoles,
16
+ TurnTargetError
17
+ } from "@ikijs/editor";
3
18
 
4
19
  // src/node-images.ts
5
20
  import sharp from "sharp";
@@ -200,121 +215,445 @@ async function renderAtlasToDataUri(crops, layout, quantizeColors) {
200
215
  return `data:image/png;base64,${page.toString("base64")}`;
201
216
  }
202
217
 
203
- // src/measure-turn.ts
204
- var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
205
- var IRIS_V_MIN = 0.18;
206
- var IRIS_V_MAX = 0.95;
207
- var IRIS_MEAN_V_MIN = 0.32;
208
- var CLOSE_RADIUS = 3;
209
- var CLOSE_RADIUS_REFERENCE_PX = 1254;
210
- var BLOB_MAX_FRAC = 0.12;
211
- var KEYED_SPAN_MAX_FRAC = 0.95;
212
- var MIN_AREA_REFERENCE_PIXELS = 1254 * 1254;
213
- var MIN_AREA = 300;
214
- var PAIR_DX_MIN_FRAC = 0.08;
215
- var PAIR_DX_MAX_FRAC = 0.35;
216
- var PAIR_DY_MAX_FRAC = 0.05;
217
- var MAX_CANDIDATES = 12;
218
- var HEAD_BAND = 10;
219
- var ALPHA_OPAQUE = 128;
220
- var BG_HUE_MIN = 220;
221
- var BG_HUE_MAX = 260;
222
- var BG_SAT_MAX = 0.2;
223
- var BG_V_MIN = 0.55;
224
- var BG_V_BLACK = 0.03;
225
- function denseCoreOf(rgba, width, height) {
226
- let minX = width;
227
- let minY = height;
228
- let maxX = -1;
229
- let maxY = -1;
230
- for (let y = 0; y < height; y++) {
231
- for (let x = 0; x < width; x++) {
232
- if (rgba[(y * width + x) * 4 + 3] >= ALPHA_OPAQUE) {
233
- if (x < minX) minX = x;
234
- if (x > maxX) maxX = x;
235
- if (y < minY) minY = y;
236
- if (y > maxY) maxY = y;
237
- }
238
- }
218
+ // src/tools.ts
219
+ function coerceModel(model) {
220
+ try {
221
+ const parsed = typeof model === "string" ? loadIkiModel(model) : parseIkiModel(model);
222
+ return { ok: true, model: parsed };
223
+ } catch (e) {
224
+ if (e instanceof IkiFormatError) return { ok: false, error: e.message };
225
+ throw e;
239
226
  }
240
- if (maxX < 0) return null;
241
- return { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 };
242
- }
243
- var SPECK_CORE_FRACTION = 0.25;
244
- function isSpeckCore(core, part) {
245
- return core.w < SPECK_CORE_FRACTION * part.w || core.h < SPECK_CORE_FRACTION * part.h;
246
227
  }
247
- function rgbToHsv(r, g, b) {
248
- r /= 255;
249
- g /= 255;
250
- b /= 255;
251
- const max = Math.max(r, g, b);
252
- const min = Math.min(r, g, b);
253
- const d = max - min;
254
- let h = 0;
255
- if (d > 0) {
256
- if (max === r) h = (g - b) / d % 6;
257
- else if (max === g) h = (b - r) / d + 2;
258
- else h = (r - g) / d + 4;
259
- h *= 60;
260
- if (h < 0) h += 360;
261
- }
262
- return [h, max === 0 ? 0 : d / max, max];
228
+ function validateIki(model) {
229
+ const result = coerceModel(model);
230
+ if (!result.ok) return { ok: false, error: result.error };
231
+ return { ok: true };
263
232
  }
264
- function dilate(mask, width, height, r) {
265
- const out = new Uint8Array(width * height);
266
- for (let y = 0; y < height; y++) {
267
- for (let x = 0; x < width; x++) {
268
- if (!mask[y * width + x]) continue;
269
- for (let dy = -r; dy <= r; dy++) {
270
- for (let dx = -r; dx <= r; dx++) {
271
- const yy = y + dy;
272
- const xx = x + dx;
273
- if (yy >= 0 && yy < height && xx >= 0 && xx < width)
274
- out[yy * width + xx] = 1;
233
+ function describeIki(model) {
234
+ const result = coerceModel(model);
235
+ if (!result.ok) return { ok: false, error: result.error };
236
+ const m = result.model;
237
+ const parameters = m.parameters.map((p) => ({
238
+ id: p.id,
239
+ min: p.min,
240
+ max: p.max,
241
+ default: p.default
242
+ }));
243
+ const parts = m.parts.map((p) => {
244
+ const entry = {
245
+ id: p.id,
246
+ order: p.order
247
+ };
248
+ if (p.deformer !== void 0) entry.deformer = p.deformer;
249
+ return entry;
250
+ });
251
+ const deformers = (m.deformers ?? []).map(
252
+ (d) => {
253
+ const kind = d.kind === "warp" ? "warp" : "matrix";
254
+ const entry = { id: d.id, kind };
255
+ if (d.parent !== void 0) entry.parent = d.parent;
256
+ if (d.kind === "warp") {
257
+ if (d.warp2d !== void 0) {
258
+ entry.warp = {
259
+ mode: "2d",
260
+ parameterX: d.warp2d.parameter,
261
+ parameterY: d.warp2d.parameterY,
262
+ gridX: d.grid.cols,
263
+ gridY: d.grid.rows
264
+ };
265
+ } else if (d.warps !== void 0 && d.warps.length > 0) {
266
+ entry.warp = {
267
+ mode: "1d",
268
+ parameters: d.warps.map((w) => w.parameter)
269
+ };
275
270
  }
276
271
  }
272
+ return entry;
277
273
  }
274
+ );
275
+ const summary = {
276
+ name: m.name,
277
+ canvas: { width: m.canvas.width, height: m.canvas.height },
278
+ parameters,
279
+ parts,
280
+ deformers
281
+ };
282
+ return { ok: true, summary };
283
+ }
284
+ var STANDARD_PARAMETER_INFO = [
285
+ {
286
+ id: StandardParameter.MouthOpen,
287
+ description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
288
+ },
289
+ {
290
+ id: StandardParameter.MouthForm,
291
+ description: "Mouth form / smile (-1 .. 1)."
292
+ },
293
+ {
294
+ id: StandardParameter.EyeOpenLeft,
295
+ description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
296
+ },
297
+ {
298
+ id: StandardParameter.EyeOpenRight,
299
+ description: "Right eye open (0 closed .. 1 open)."
300
+ },
301
+ {
302
+ id: StandardParameter.EyeballX,
303
+ description: "Eyeball gaze, horizontal (-1 .. 1)."
304
+ },
305
+ {
306
+ id: StandardParameter.EyeballY,
307
+ description: "Eyeball gaze, vertical (-1 .. 1)."
308
+ },
309
+ {
310
+ id: StandardParameter.AngleX,
311
+ description: "Head angle, horizontal degrees."
312
+ },
313
+ {
314
+ id: StandardParameter.AngleY,
315
+ description: "Head angle, vertical degrees."
316
+ },
317
+ {
318
+ id: StandardParameter.AngleZ,
319
+ description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
320
+ },
321
+ {
322
+ id: StandardParameter.Breath,
323
+ description: "Idle breath (0 .. 1), cycled by the host."
324
+ },
325
+ {
326
+ id: StandardParameter.BrowLeftY,
327
+ description: "Left brow raise/lower (-1 .. 1)."
328
+ },
329
+ {
330
+ id: StandardParameter.BrowRightY,
331
+ description: "Right brow raise/lower (-1 .. 1)."
332
+ },
333
+ {
334
+ id: StandardParameter.BrowLeftAngle,
335
+ description: "Left brow tilt/angle (-1 .. 1)."
336
+ },
337
+ {
338
+ id: StandardParameter.BrowRightAngle,
339
+ description: "Right brow tilt/angle (-1 .. 1)."
340
+ },
341
+ {
342
+ id: StandardParameter.HairSwayX,
343
+ description: "Horizontal hair-sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
344
+ },
345
+ {
346
+ id: StandardParameter.HairSwayZ,
347
+ description: "Hair-sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
278
348
  }
279
- return out;
349
+ ];
350
+ function listStandardParameters() {
351
+ return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));
280
352
  }
281
- function erode(mask, width, height, r) {
282
- const out = new Uint8Array(width * height);
283
- for (let y = 0; y < height; y++) {
284
- for (let x = 0; x < width; x++) {
285
- if (!mask[y * width + x]) continue;
286
- let keep = true;
287
- for (let dy = -r; dy <= r && keep; dy++) {
288
- for (let dx = -r; dx <= r; dx++) {
289
- const yy = y + dy;
290
- const xx = x + dx;
291
- if (yy < 0 || yy >= height || xx < 0 || xx >= width || !mask[yy * width + xx]) {
292
- keep = false;
293
- break;
294
- }
295
- }
296
- }
297
- if (keep) out[y * width + x] = 1;
298
- }
353
+ function expectInput(label, fn) {
354
+ try {
355
+ return fn();
356
+ } catch (e) {
357
+ throw new AutoRigInputError(
358
+ `${label}: ${e instanceof Error ? e.message : String(e)}`
359
+ );
299
360
  }
300
- return out;
301
361
  }
302
- function closeMask(mask, width, height, r) {
303
- return erode(dilate(mask, width, height, r), width, height, r);
362
+ var LOSSLESS_PAGE_ROLE = "nose";
363
+ async function renderAtlasPage(crops, quantizeColors) {
364
+ const layout = packAtlas(
365
+ crops.map((c) => ({ id: c.id, width: c.width, height: c.height }))
366
+ );
367
+ if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {
368
+ throw new AutoRigInputError(
369
+ `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`
370
+ );
371
+ }
372
+ const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);
373
+ return { crops, layout, dataUri };
304
374
  }
305
- function components(mask, width, height, minArea) {
306
- const seen = new Uint8Array(width * height);
307
- const out = [];
308
- for (let i = 0; i < width * height; i++) {
309
- if (!mask[i] || seen[i]) continue;
310
- const stack = [i];
311
- seen[i] = 1;
312
- let x0 = width;
313
- let x1 = 0;
314
- let y0 = height;
315
- let y1 = 0;
316
- let n = 0;
317
- let sx = 0;
375
+ async function autoRigFromLayers(input) {
376
+ try {
377
+ const layers = input.layers;
378
+ if (!Array.isArray(layers) || layers.length === 0) {
379
+ throw new AutoRigInputError("layers must be a non-empty array");
380
+ }
381
+ if (layers.length > MAX_LAYERS) {
382
+ throw new AutoRigInputError(
383
+ `too many layers: ${layers.length} > ${MAX_LAYERS}`
384
+ );
385
+ }
386
+ const outPath = resolveOutputPath(
387
+ input.outputPath ?? "auto-rigged-model.iki"
388
+ );
389
+ const quantizeColors = input.quantizeColors;
390
+ if (quantizeColors !== void 0 && (!Number.isInteger(quantizeColors) || quantizeColors < 2 || quantizeColors > 256)) {
391
+ throw new AutoRigInputError(
392
+ `quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`
393
+ );
394
+ }
395
+ const turnTargets = input.turnTargets;
396
+ if (turnTargets !== void 0) {
397
+ if (typeof turnTargets !== "object" || turnTargets === null || Array.isArray(turnTargets)) {
398
+ throw new AutoRigInputError("turnTargets must be a plain object");
399
+ }
400
+ if (turnTargets.headHalfWidth !== void 0) {
401
+ throw new AutoRigInputError(
402
+ "turnTargets.headHalfWidth is measured off the layers, not accepted as input"
403
+ );
404
+ }
405
+ }
406
+ const resolvedLayers = layers.map((layer) => {
407
+ const resolved = resolveInputPath(layer.path);
408
+ return { resolved, fileName: layer.fileName ?? path2.basename(resolved) };
409
+ });
410
+ const rolePairs = expectInput(
411
+ "role parsing",
412
+ () => parseLayerRoles(resolvedLayers.map((r) => r.fileName))
413
+ );
414
+ const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));
415
+ let canvasW = 0;
416
+ let canvasH = 0;
417
+ let totalPixels = 0;
418
+ let measurer;
419
+ const crops = [];
420
+ for (let i = 0; i < resolvedLayers.length; i++) {
421
+ const { resolved, fileName } = resolvedLayers[i];
422
+ const png = await decodePng(resolved);
423
+ if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {
424
+ throw new AutoRigInputError(
425
+ `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`
426
+ );
427
+ }
428
+ totalPixels += png.width * png.height;
429
+ if (totalPixels > MAX_TOTAL_PIXELS) {
430
+ throw new AutoRigInputError(
431
+ `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`
432
+ );
433
+ }
434
+ if (i === 0) {
435
+ canvasW = png.width;
436
+ canvasH = png.height;
437
+ if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {
438
+ throw new AutoRigInputError(
439
+ `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`
440
+ );
441
+ }
442
+ measurer = createLayerSetMeasurer({ width: canvasW, height: canvasH });
443
+ } else if (png.width !== canvasW || png.height !== canvasH) {
444
+ throw new AutoRigInputError(
445
+ `layer "${fileName}" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
446
+ );
447
+ }
448
+ const role = roleByFileName.get(fileName);
449
+ if (role === void 0) {
450
+ throw new AutoRigInputError(`no role resolved for "${fileName}"`);
451
+ }
452
+ const layer = measurer.add({ role, fileName, rgba: png.rgba });
453
+ if (layer === null) {
454
+ throw new AutoRigInputError(
455
+ `role "${role}" file "${fileName}": layer is empty after alpha threshold`
456
+ );
457
+ }
458
+ const { bbox } = layer;
459
+ const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);
460
+ crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
461
+ }
462
+ const measurement = measurer.finish();
463
+ const { headHalfWidth, headHalfWidthApplied, turnOptions } = measurement;
464
+ const { headEdges, strandEdges } = turnOptions;
465
+ const noseCore = measurement.layers.find(
466
+ (l) => l.role === "nose"
467
+ )?.denseCore;
468
+ let turn;
469
+ let model;
470
+ try {
471
+ model = generateIkiFromLayerSet(
472
+ measurement.layers,
473
+ { width: canvasW, height: canvasH },
474
+ {
475
+ turnTargets: {
476
+ ...input.turnTargets,
477
+ ...turnOptions.turnTargets
478
+ },
479
+ onTurnSolved: (report) => {
480
+ turn = report;
481
+ },
482
+ ...input.style === void 0 ? {} : { style: input.style },
483
+ ...headEdges === void 0 ? {} : { headEdges },
484
+ ...strandEdges === void 0 ? {} : { strandEdges }
485
+ }
486
+ );
487
+ } catch (e) {
488
+ if (!(e instanceof TurnTargetError)) throw e;
489
+ throw new AutoRigInputError(e.message);
490
+ }
491
+ const doc = new EditorDocument(model);
492
+ const losslessCrop = quantizeColors === void 0 ? void 0 : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);
493
+ const pages = losslessCrop === void 0 ? [await renderAtlasPage(crops, quantizeColors)] : [
494
+ await renderAtlasPage(
495
+ crops.filter((c) => c !== losslessCrop),
496
+ quantizeColors
497
+ ),
498
+ await renderAtlasPage([losslessCrop], void 0)
499
+ ];
500
+ const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);
501
+ if (atlasBytes > MAX_OUTPUT_BYTES) {
502
+ throw new AutoRigInputError(
503
+ `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`
504
+ );
505
+ }
506
+ const partTextureAssignments = pages.flatMap(
507
+ ({ crops: pageCrops, layout }) => pageCrops.map((crop) => {
508
+ const placement2 = layout.placements.find((p) => p.id === crop.id);
509
+ if (placement2 === void 0) {
510
+ throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
511
+ }
512
+ return {
513
+ partId: crop.id,
514
+ uv: uvRectFor(placement2, {
515
+ width: layout.pageWidth,
516
+ height: layout.pageHeight
517
+ })
518
+ };
519
+ })
520
+ );
521
+ doc.applyAtlas({
522
+ textures: [{ source: pages[0].dataUri }],
523
+ partTextureAssignments
524
+ });
525
+ let patched = doc.getModel();
526
+ if (losslessCrop !== void 0) {
527
+ patched = structuredClone(patched);
528
+ patched.textures = pages.map((p) => ({ source: p.dataUri }));
529
+ patched.parts.find((p) => p.id === losslessCrop.id).texture.index = 1;
530
+ }
531
+ const finalModel = parseIkiModel(patched);
532
+ writeFileAtomic(outPath, JSON.stringify(finalModel));
533
+ return {
534
+ ok: true,
535
+ path: outPath,
536
+ canvas: { width: canvasW, height: canvasH },
537
+ partCount: finalModel.parts.length,
538
+ atlasBytes,
539
+ ...headHalfWidth === void 0 ? {} : { headHalfWidth },
540
+ headHalfWidthApplied,
541
+ ...headEdges === void 0 ? {} : { headEdges },
542
+ ...strandEdges === void 0 ? {} : { strandEdges },
543
+ ...noseCore === void 0 ? {} : { noseCore },
544
+ ...turn === void 0 ? {} : { turn }
545
+ };
546
+ } catch (err) {
547
+ if (err instanceof AutoRigInputError)
548
+ return { ok: false, error: err.message };
549
+ throw err;
550
+ }
551
+ }
552
+
553
+ // src/measure-turn.ts
554
+ import path3 from "path";
555
+ import {
556
+ ALPHA_OPAQUE,
557
+ HEAD_BAND,
558
+ foregroundSpan,
559
+ headHalfOf
560
+ } from "@ikijs/editor";
561
+ import {
562
+ SPECK_CORE_FRACTION,
563
+ denseCoreOf,
564
+ headHalfOf as headHalfOf2,
565
+ isSpeckCore
566
+ } from "@ikijs/editor";
567
+ var DEFAULT_IRIS = { hueMin: 230, hueMax: 300, satMin: 0.22 };
568
+ var IRIS_V_MIN = 0.18;
569
+ var IRIS_V_MAX = 0.95;
570
+ var IRIS_MEAN_V_MIN = 0.32;
571
+ var CLOSE_RADIUS = 3;
572
+ var CLOSE_RADIUS_REFERENCE_PX = 1254;
573
+ var BLOB_MAX_FRAC = 0.12;
574
+ var KEYED_SPAN_MAX_FRAC = 0.95;
575
+ var MIN_AREA_REFERENCE_PIXELS = 1254 * 1254;
576
+ var MIN_AREA = 300;
577
+ var PAIR_DX_MIN_FRAC = 0.08;
578
+ var PAIR_DX_MAX_FRAC = 0.35;
579
+ var PAIR_DY_MAX_FRAC = 0.05;
580
+ var MAX_CANDIDATES = 12;
581
+ var BG_HUE_MIN = 220;
582
+ var BG_HUE_MAX = 260;
583
+ var BG_SAT_MAX = 0.2;
584
+ var BG_V_MIN = 0.55;
585
+ var BG_V_BLACK = 0.03;
586
+ function rgbToHsv(r, g, b) {
587
+ r /= 255;
588
+ g /= 255;
589
+ b /= 255;
590
+ const max = Math.max(r, g, b);
591
+ const min = Math.min(r, g, b);
592
+ const d = max - min;
593
+ let h = 0;
594
+ if (d > 0) {
595
+ if (max === r) h = (g - b) / d % 6;
596
+ else if (max === g) h = (b - r) / d + 2;
597
+ else h = (r - g) / d + 4;
598
+ h *= 60;
599
+ if (h < 0) h += 360;
600
+ }
601
+ return [h, max === 0 ? 0 : d / max, max];
602
+ }
603
+ function dilate(mask, width, height, r) {
604
+ const out = new Uint8Array(width * height);
605
+ for (let y = 0; y < height; y++) {
606
+ for (let x = 0; x < width; x++) {
607
+ if (!mask[y * width + x]) continue;
608
+ for (let dy = -r; dy <= r; dy++) {
609
+ for (let dx = -r; dx <= r; dx++) {
610
+ const yy = y + dy;
611
+ const xx = x + dx;
612
+ if (yy >= 0 && yy < height && xx >= 0 && xx < width)
613
+ out[yy * width + xx] = 1;
614
+ }
615
+ }
616
+ }
617
+ }
618
+ return out;
619
+ }
620
+ function erode(mask, width, height, r) {
621
+ const out = new Uint8Array(width * height);
622
+ for (let y = 0; y < height; y++) {
623
+ for (let x = 0; x < width; x++) {
624
+ if (!mask[y * width + x]) continue;
625
+ let keep = true;
626
+ for (let dy = -r; dy <= r && keep; dy++) {
627
+ for (let dx = -r; dx <= r; dx++) {
628
+ const yy = y + dy;
629
+ const xx = x + dx;
630
+ if (yy < 0 || yy >= height || xx < 0 || xx >= width || !mask[yy * width + xx]) {
631
+ keep = false;
632
+ break;
633
+ }
634
+ }
635
+ }
636
+ if (keep) out[y * width + x] = 1;
637
+ }
638
+ }
639
+ return out;
640
+ }
641
+ function closeMask(mask, width, height, r) {
642
+ return erode(dilate(mask, width, height, r), width, height, r);
643
+ }
644
+ function components(mask, width, height, minArea) {
645
+ const seen = new Uint8Array(width * height);
646
+ const out = [];
647
+ for (let i = 0; i < width * height; i++) {
648
+ if (!mask[i] || seen[i]) continue;
649
+ const stack = [i];
650
+ seen[i] = 1;
651
+ let x0 = width;
652
+ let x1 = 0;
653
+ let y0 = height;
654
+ let y1 = 0;
655
+ let n = 0;
656
+ let sx = 0;
318
657
  let sy = 0;
319
658
  while (stack.length) {
320
659
  const p = stack.pop();
@@ -354,21 +693,6 @@ function components(mask, width, height, minArea) {
354
693
  }
355
694
  return out.sort((a, b) => b.area - a.area);
356
695
  }
357
- function foregroundSpan(mask, width, height, rowLo, rowHi) {
358
- let left = width;
359
- let right = -1;
360
- for (let y = Math.max(0, rowLo); y <= Math.min(height - 1, rowHi); y++) {
361
- for (let x = 0; x < width; x++) {
362
- if (!mask[y * width + x]) continue;
363
- if (x < left) left = x;
364
- if (x > right) right = x;
365
- }
366
- }
367
- return { left, right };
368
- }
369
- function headHalfOf(span) {
370
- return (span.right - span.left + 1) / 2;
371
- }
372
696
  function resolveIris(override) {
373
697
  const iris = { ...DEFAULT_IRIS, ...override };
374
698
  if (iris.hueMin < 0 || iris.hueMax > 360 || iris.hueMin >= iris.hueMax) {
@@ -481,599 +805,77 @@ async function measureTurnImage(filePath, iris) {
481
805
  if (maskMode === "keyed" && right - left + 1 > width * KEYED_SPAN_MAX_FRAC) {
482
806
  throw new AutoRigInputError(
483
807
  `head span at the eye row (y=${eyeRow}) in ${filePath} covers ${right - left + 1}/${width} px: background not keyed / not an engine render`
484
- );
485
- }
486
- return {
487
- file: filePath,
488
- width,
489
- height,
490
- maskMode,
491
- irisL,
492
- irisR,
493
- eyeRow,
494
- head: {
495
- left,
496
- right,
497
- cx: (left + right) / 2,
498
- half: headHalfOf({ left, right })
499
- },
500
- pairCx: (irisL.cx + irisR.cx) / 2,
501
- eyeGap: irisR.cx - irisL.cx
502
- };
503
- }
504
- function farNearWidths(m, turnSign) {
505
- return turnSign < 0 ? { far: m.irisL.w, near: m.irisR.w } : { far: m.irisR.w, near: m.irisL.w };
506
- }
507
- function overlaySvg(m) {
508
- const box = (b, stroke) => `<rect x="${b.x0}" y="${b.y0}" width="${b.w}" height="${b.h}" fill="none" stroke="${stroke}" stroke-width="3"/>`;
509
- const tick = (x, half, stroke) => `<line x1="${x}" y1="${m.eyeRow - half}" x2="${x}" y2="${m.eyeRow + half}" stroke="${stroke}" stroke-width="3"/>`;
510
- 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>";
511
- }
512
- async function writeOverlay(debugDir, label, m) {
513
- const outPath = path2.join(
514
- debugDir,
515
- `${label}-${path2.basename(m.file, ".png")}.debug.png`
516
- );
517
- writeFileAtomic(outPath, await encodeOverlayPng(m.file, overlaySvg(m)));
518
- return outPath;
519
- }
520
- var IRIS_HEIGHT_SCALE_TOLERANCE = 0.1;
521
- async function measureTurnReference(input) {
522
- try {
523
- const iris = resolveIris(input.iris);
524
- const frontPath = resolveInputPath(input.front);
525
- const turnedPath = resolveInputPath(input.turned);
526
- const debugDir = input.debugDir === void 0 ? null : resolveOutputDir(input.debugDir);
527
- const front = await measureTurnImage(frontPath, iris);
528
- const turned = await measureTurnImage(turnedPath, iris);
529
- const frontIrisH = (front.irisL.h + front.irisR.h) / 2;
530
- const turnedIrisH = (turned.irisL.h + turned.irisR.h) / 2;
531
- if (Math.abs(turnedIrisH - frontIrisH) / frontIrisH > IRIS_HEIGHT_SCALE_TOLERANCE) {
532
- throw new AutoRigInputError(
533
- `front and turned images are not at the same scale: mean iris height ${frontIrisH.toFixed(1)}px front vs ${turnedIrisH.toFixed(1)}px turned, more than ${(IRIS_HEIGHT_SCALE_TOLERANCE * 100).toFixed(0)}% apart \u2014 a yaw does not change iris height, so the pair must share the same framing and head size`
534
- );
535
- }
536
- const frontShift = front.pairCx - front.head.cx;
537
- const turnedShift = turned.pairCx - turned.head.cx;
538
- const shift = turnedShift - frontShift;
539
- const turnSign = shift < 0 ? -1 : 1;
540
- const f = farNearWidths(front, turnSign);
541
- const t = farNearWidths(turned, turnSign);
542
- const debug = debugDir === null ? void 0 : [
543
- await writeOverlay(debugDir, "front", front),
544
- await writeOverlay(debugDir, "turned", turned)
545
- ];
546
- return {
547
- ok: true,
548
- front,
549
- turned,
550
- farEyeRatio: t.far / t.near / (f.far / f.near),
551
- eyeShift: shift / front.head.half,
552
- silhouetteRatio: turned.head.half / front.head.half,
553
- turnSign,
554
- ...debug === void 0 ? {} : { debug }
555
- };
556
- } catch (err) {
557
- if (err instanceof AutoRigInputError)
558
- return { ok: false, error: err.message };
559
- throw err;
560
- }
561
- }
562
- var n1 = (v) => v.toFixed(1);
563
- var n3 = (v) => v.toFixed(3);
564
- function imageBlock(label, m) {
565
- return [
566
- `# ${label} ${m.file} ${m.width}x${m.height} mask: ${m.maskMode}`,
567
- `iris widths ${m.irisL.w} / ${m.irisR.w} px centres ${n1(m.irisL.cx)} / ${n1(m.irisR.cx)} eye row ${m.eyeRow} gap ${n1(m.eyeGap)}`,
568
- `head ${m.head.left}..${m.head.right} centre ${n1(m.head.cx)} half ${n1(m.head.half)} pair centre ${n1(m.pairCx)}`
569
- ];
570
- }
571
- function formatTurnReport(result) {
572
- const { front, turned } = result;
573
- const f = farNearWidths(front, result.turnSign);
574
- const t = farNearWidths(turned, result.turnSign);
575
- const lines = [
576
- `farEyeRatio ${n3(result.farEyeRatio)} far/near iris width ${t.far}/${t.near} turned over ${f.far}/${f.near} front`,
577
- `eyeShift ${n3(result.eyeShift)} pair-vs-head centre ${n1(turned.pairCx - turned.head.cx)} px turned, ${n1(front.pairCx - front.head.cx)} px front, over front head half ${n1(front.head.half)} px (hh)`,
578
- `silhouetteRatio ${n3(result.silhouetteRatio)} head half ${n1(turned.head.half)} px turned over ${n1(front.head.half)} px front`,
579
- `turnSign ${result.turnSign} (the head turned toward the image's ${result.turnSign < 0 ? "left" : "right"})`,
580
- "",
581
- ...imageBlock("front", front),
582
- "",
583
- ...imageBlock("turned", turned)
584
- ];
585
- if (result.debug !== void 0) {
586
- lines.push("", ...result.debug.map((p) => `debug overlay ${p}`));
587
- }
588
- return lines.join("\n");
589
- }
590
-
591
- // src/tools.ts
592
- import path3 from "path";
593
- import {
594
- parseIkiModel,
595
- loadIkiModel,
596
- IkiFormatError,
597
- StandardParameter
598
- } from "@ikijs/format";
599
- import {
600
- EditorDocument,
601
- packAtlas,
602
- uvRectFor,
603
- generateIkiFromLayerSet,
604
- parseLayerRoles,
605
- TurnTargetError
606
- } from "@ikijs/editor";
607
- function coerceModel(model) {
608
- try {
609
- const parsed = typeof model === "string" ? loadIkiModel(model) : parseIkiModel(model);
610
- return { ok: true, model: parsed };
611
- } catch (e) {
612
- if (e instanceof IkiFormatError) return { ok: false, error: e.message };
613
- throw e;
614
- }
615
- }
616
- function validateIki(model) {
617
- const result = coerceModel(model);
618
- if (!result.ok) return { ok: false, error: result.error };
619
- return { ok: true };
620
- }
621
- function describeIki(model) {
622
- const result = coerceModel(model);
623
- if (!result.ok) return { ok: false, error: result.error };
624
- const m = result.model;
625
- const parameters = m.parameters.map((p) => ({
626
- id: p.id,
627
- min: p.min,
628
- max: p.max,
629
- default: p.default
630
- }));
631
- const parts = m.parts.map((p) => {
632
- const entry = {
633
- id: p.id,
634
- order: p.order
635
- };
636
- if (p.deformer !== void 0) entry.deformer = p.deformer;
637
- return entry;
638
- });
639
- const deformers = (m.deformers ?? []).map(
640
- (d) => {
641
- const kind = d.kind === "warp" ? "warp" : "matrix";
642
- const entry = { id: d.id, kind };
643
- if (d.parent !== void 0) entry.parent = d.parent;
644
- if (d.kind === "warp") {
645
- if (d.warp2d !== void 0) {
646
- entry.warp = {
647
- mode: "2d",
648
- parameterX: d.warp2d.parameter,
649
- parameterY: d.warp2d.parameterY,
650
- gridX: d.grid.cols,
651
- gridY: d.grid.rows
652
- };
653
- } else if (d.warps !== void 0 && d.warps.length > 0) {
654
- entry.warp = {
655
- mode: "1d",
656
- parameters: d.warps.map((w) => w.parameter)
657
- };
658
- }
659
- }
660
- return entry;
661
- }
662
- );
663
- const summary = {
664
- name: m.name,
665
- canvas: { width: m.canvas.width, height: m.canvas.height },
666
- parameters,
667
- parts,
668
- deformers
669
- };
670
- return { ok: true, summary };
671
- }
672
- var STANDARD_PARAMETER_INFO = [
673
- {
674
- id: StandardParameter.MouthOpen,
675
- description: "Mouth open amount for lip-sync (0 closed .. 1 open)."
676
- },
677
- {
678
- id: StandardParameter.MouthForm,
679
- description: "Mouth form / smile (-1 .. 1)."
680
- },
681
- {
682
- id: StandardParameter.EyeOpenLeft,
683
- description: "Left eye open (0 closed .. 1 open). Drive with the right eye for a blink."
684
- },
685
- {
686
- id: StandardParameter.EyeOpenRight,
687
- description: "Right eye open (0 closed .. 1 open)."
688
- },
689
- {
690
- id: StandardParameter.EyeballX,
691
- description: "Eyeball gaze, horizontal (-1 .. 1)."
692
- },
693
- {
694
- id: StandardParameter.EyeballY,
695
- description: "Eyeball gaze, vertical (-1 .. 1)."
696
- },
697
- {
698
- id: StandardParameter.AngleX,
699
- description: "Head angle, horizontal degrees."
700
- },
701
- {
702
- id: StandardParameter.AngleY,
703
- description: "Head angle, vertical degrees."
704
- },
705
- {
706
- id: StandardParameter.AngleZ,
707
- description: "Head tilt / roll degrees; positive tilts the top of the head toward the viewer's right (clockwise), as in Live2D."
708
- },
709
- {
710
- id: StandardParameter.Breath,
711
- description: "Idle breath (0 .. 1), cycled by the host."
712
- },
713
- {
714
- id: StandardParameter.BrowLeftY,
715
- description: "Left brow raise/lower (-1 .. 1)."
716
- },
717
- {
718
- id: StandardParameter.BrowRightY,
719
- description: "Right brow raise/lower (-1 .. 1)."
720
- },
721
- {
722
- id: StandardParameter.BrowLeftAngle,
723
- description: "Left brow tilt/angle (-1 .. 1)."
724
- },
725
- {
726
- id: StandardParameter.BrowRightAngle,
727
- description: "Right brow tilt/angle (-1 .. 1)."
728
- },
729
- {
730
- id: StandardParameter.HairSwayX,
731
- description: "Horizontal hair-sway driver. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
732
- },
733
- {
734
- id: StandardParameter.HairSwayZ,
735
- description: "Hair-sway driver behind a head tilt. Physics OUTPUT \u2014 driven by the spring, hosts should not set it directly."
736
- }
737
- ];
738
- function listStandardParameters() {
739
- return STANDARD_PARAMETER_INFO.map((p) => ({ ...p }));
740
- }
741
- function expectInput(label, fn) {
742
- try {
743
- return fn();
744
- } catch (e) {
745
- throw new AutoRigInputError(
746
- `${label}: ${e instanceof Error ? e.message : String(e)}`
747
- );
748
- }
749
- }
750
- function eyeRowOf(layers) {
751
- const centreY = (role) => {
752
- const layer = layers.find((l) => l.role === role);
753
- return layer && layer.bbox.y + layer.bbox.h / 2;
754
- };
755
- const pairRow = (left, right) => {
756
- const a = centreY(left);
757
- const b = centreY(right);
758
- return a === void 0 || b === void 0 ? void 0 : (a + b) / 2;
759
- };
760
- const row = pairRow("iris_L", "iris_R") ?? pairRow("eye_L", "eye_R");
761
- if (row === void 0) {
762
- throw new Error("auto-rig: no eye pair to measure the head width at");
808
+ );
763
809
  }
764
- return Math.round(row);
810
+ return {
811
+ file: filePath,
812
+ width,
813
+ height,
814
+ maskMode,
815
+ irisL,
816
+ irisR,
817
+ eyeRow,
818
+ head: {
819
+ left,
820
+ right,
821
+ cx: (left + right) / 2,
822
+ half: headHalfOf({ left, right })
823
+ },
824
+ pairCx: (irisL.cx + irisR.cx) / 2,
825
+ eyeGap: irisR.cx - irisL.cx
826
+ };
765
827
  }
766
- function foregroundSpanOfRows(rowLeft, rowRight, rowLo, rowHi) {
767
- let left = Infinity;
768
- let right = -Infinity;
769
- for (let y = Math.max(0, rowLo); y <= Math.min(rowLeft.length - 1, rowHi); y++) {
770
- if (rowLeft[y] < left) left = rowLeft[y];
771
- if (rowRight[y] > right) right = rowRight[y];
772
- }
773
- return { left, right };
828
+ function farNearWidths(m, turnSign) {
829
+ return turnSign < 0 ? { far: m.irisL.w, near: m.irisR.w } : { far: m.irisR.w, near: m.irisL.w };
774
830
  }
775
- function facePlateHalfOf(layers) {
776
- const face = layers.find((l) => l.role === "face");
777
- if (face === void 0) {
778
- throw new Error("auto-rig: no face layer to measure the plate against");
779
- }
780
- return face.cropW / 2;
831
+ function overlaySvg(m) {
832
+ const box = (b, stroke) => `<rect x="${b.x0}" y="${b.y0}" width="${b.w}" height="${b.h}" fill="none" stroke="${stroke}" stroke-width="3"/>`;
833
+ const tick = (x, half, stroke) => `<line x1="${x}" y1="${m.eyeRow - half}" x2="${x}" y2="${m.eyeRow + half}" stroke="${stroke}" stroke-width="3"/>`;
834
+ 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>";
781
835
  }
782
- var STRAND_MIN_RUN_FRACTION = 0.5;
783
- var LOSSLESS_PAGE_ROLE = "nose";
784
- async function renderAtlasPage(crops, quantizeColors) {
785
- const layout = packAtlas(
786
- crops.map((c) => ({ id: c.id, width: c.width, height: c.height }))
836
+ async function writeOverlay(debugDir, label, m) {
837
+ const outPath = path3.join(
838
+ debugDir,
839
+ `${label}-${path3.basename(m.file, ".png")}.debug.png`
787
840
  );
788
- if (layout.pageWidth * layout.pageHeight > MAX_ATLAS_AREA) {
789
- throw new AutoRigInputError(
790
- `atlas page ${layout.pageWidth}x${layout.pageHeight} exceeds max area ${MAX_ATLAS_AREA}`
791
- );
792
- }
793
- const dataUri = await renderAtlasToDataUri(crops, layout, quantizeColors);
794
- return { crops, layout, dataUri };
841
+ writeFileAtomic(outPath, await encodeOverlayPng(m.file, overlaySvg(m)));
842
+ return outPath;
795
843
  }
796
- async function autoRigFromLayers(input) {
844
+ var IRIS_HEIGHT_SCALE_TOLERANCE = 0.1;
845
+ async function measureTurnReference(input) {
797
846
  try {
798
- const layers = input.layers;
799
- if (!Array.isArray(layers) || layers.length === 0) {
800
- throw new AutoRigInputError("layers must be a non-empty array");
801
- }
802
- if (layers.length > MAX_LAYERS) {
803
- throw new AutoRigInputError(
804
- `too many layers: ${layers.length} > ${MAX_LAYERS}`
805
- );
806
- }
807
- const outPath = resolveOutputPath(
808
- input.outputPath ?? "auto-rigged-model.iki"
809
- );
810
- const quantizeColors = input.quantizeColors;
811
- if (quantizeColors !== void 0 && (!Number.isInteger(quantizeColors) || quantizeColors < 2 || quantizeColors > 256)) {
847
+ const iris = resolveIris(input.iris);
848
+ const frontPath = resolveInputPath(input.front);
849
+ const turnedPath = resolveInputPath(input.turned);
850
+ const debugDir = input.debugDir === void 0 ? null : resolveOutputDir(input.debugDir);
851
+ const front = await measureTurnImage(frontPath, iris);
852
+ const turned = await measureTurnImage(turnedPath, iris);
853
+ const frontIrisH = (front.irisL.h + front.irisR.h) / 2;
854
+ const turnedIrisH = (turned.irisL.h + turned.irisR.h) / 2;
855
+ if (Math.abs(turnedIrisH - frontIrisH) / frontIrisH > IRIS_HEIGHT_SCALE_TOLERANCE) {
812
856
  throw new AutoRigInputError(
813
- `quantizeColors must be an integer in 2..256, got ${String(quantizeColors)}`
814
- );
815
- }
816
- const resolvedLayers = layers.map((layer) => {
817
- const resolved = resolveInputPath(layer.path);
818
- return { resolved, fileName: layer.fileName ?? path3.basename(resolved) };
819
- });
820
- const rolePairs = expectInput(
821
- "role parsing",
822
- () => parseLayerRoles(resolvedLayers.map((r) => r.fileName))
823
- );
824
- const roleByFileName = new Map(rolePairs.map((p) => [p.fileName, p.role]));
825
- let canvasW = 0;
826
- let canvasH = 0;
827
- let totalPixels = 0;
828
- let opaque = new Uint8Array(0);
829
- const layerInputs = [];
830
- const crops = [];
831
- const rowSpansByRole = [];
832
- let hairFrontMask;
833
- for (let i = 0; i < resolvedLayers.length; i++) {
834
- const { resolved, fileName } = resolvedLayers[i];
835
- const png = await decodePng(resolved);
836
- if (png.width > MAX_LAYER_DIM || png.height > MAX_LAYER_DIM) {
837
- throw new AutoRigInputError(
838
- `layer ${resolved} dimension ${png.width}x${png.height} exceeds ${MAX_LAYER_DIM}`
839
- );
840
- }
841
- totalPixels += png.width * png.height;
842
- if (totalPixels > MAX_TOTAL_PIXELS) {
843
- throw new AutoRigInputError(
844
- `total decoded pixels exceed ${MAX_TOTAL_PIXELS}`
845
- );
846
- }
847
- if (i === 0) {
848
- canvasW = png.width;
849
- canvasH = png.height;
850
- if (canvasW > MAX_CANVAS_DIM || canvasH > MAX_CANVAS_DIM) {
851
- throw new AutoRigInputError(
852
- `canvas ${canvasW}x${canvasH} exceeds ${MAX_CANVAS_DIM}`
853
- );
854
- }
855
- opaque = new Uint8Array(canvasW * canvasH);
856
- } else if (png.width !== canvasW || png.height !== canvasH) {
857
- throw new AutoRigInputError(
858
- `layer "${fileName}" size ${png.width}x${png.height} differs from canvas ${canvasW}x${canvasH}`
859
- );
860
- }
861
- const role = roleByFileName.get(fileName);
862
- if (role === void 0) {
863
- throw new AutoRigInputError(`no role resolved for "${fileName}"`);
864
- }
865
- let bbox;
866
- try {
867
- bbox = detectAlphaBbox(png.rgba, png.width, png.height);
868
- } catch (e) {
869
- const msg = e instanceof Error ? e.message : String(e);
870
- throw new AutoRigInputError(
871
- `role "${role}" file "${fileName}": ${msg}`
872
- );
873
- }
874
- const buffer = await cropToBuffer(png.rgba, png.width, png.height, bbox);
875
- const rowLeft = new Int32Array(canvasH).fill(canvasW);
876
- const rowRight = new Int32Array(canvasH).fill(-1);
877
- const ownMask = role === "hair_front" ? new Uint8Array(canvasW * canvasH) : void 0;
878
- for (let y = 0; y < canvasH; y++) {
879
- for (let x = 0; x < canvasW; x++) {
880
- const p = y * canvasW + x;
881
- if (png.rgba[p * 4 + 3] < ALPHA_OPAQUE) continue;
882
- opaque[p] = 1;
883
- if (ownMask !== void 0) ownMask[p] = 1;
884
- if (x < rowLeft[y]) rowLeft[y] = x;
885
- if (x > rowRight[y]) rowRight[y] = x;
886
- }
887
- }
888
- rowSpansByRole.push({ role, rowLeft, rowRight });
889
- if (ownMask !== void 0) hairFrontMask = ownMask;
890
- const layer = {
891
- role,
892
- fileName,
893
- canvasW,
894
- canvasH,
895
- bbox,
896
- cropW: bbox.w,
897
- cropH: bbox.h
898
- };
899
- if (role === "face") {
900
- const rowHalfWidths = [];
901
- for (let y = bbox.y; y < bbox.y + bbox.h; y++) {
902
- rowHalfWidths.push(
903
- rowRight[y] >= rowLeft[y] ? headHalfOf({ left: rowLeft[y], right: rowRight[y] }) : 0
904
- );
905
- }
906
- layer.rowHalfWidths = rowHalfWidths;
907
- } else if (role === "nose") {
908
- const core = denseCoreOf(png.rgba, canvasW, canvasH);
909
- if (core !== null && !isSpeckCore(core, bbox)) layer.denseCore = core;
910
- }
911
- layerInputs.push(layer);
912
- crops.push({ id: role, buffer, width: bbox.w, height: bbox.h });
913
- }
914
- const noseCore = layerInputs.find((l) => l.role === "nose")?.denseCore;
915
- const eyeRow = eyeRowOf(layerInputs);
916
- const span = foregroundSpan(
917
- opaque,
918
- canvasW,
919
- canvasH,
920
- eyeRow - HEAD_BAND,
921
- eyeRow + HEAD_BAND
922
- );
923
- const headHalfWidth = span.right > span.left ? headHalfOf(span) : void 0;
924
- const headHalfWidthApplied = headHalfWidth !== void 0 && headHalfWidth > facePlateHalfOf(layerInputs);
925
- let headEdges;
926
- if (headHalfWidthApplied) {
927
- const bandLo = eyeRow - HEAD_BAND;
928
- const bandHi = eyeRow + HEAD_BAND;
929
- const left = [];
930
- const right = [];
931
- for (const { role, rowLeft, rowRight } of rowSpansByRole) {
932
- const own = foregroundSpanOfRows(rowLeft, rowRight, bandLo, bandHi);
933
- if (own.right <= own.left) continue;
934
- left.push({ role, x: own.left - canvasW / 2 });
935
- right.push({ role, x: own.right - canvasW / 2 });
936
- }
937
- headEdges = { left, right };
938
- }
939
- let strandEdges;
940
- const irisLayers = layerInputs.filter((l) => l.role === "iris_L" || l.role === "iris_R").sort((a, b) => a.bbox.x + a.bbox.w / 2 - (b.bbox.x + b.bbox.w / 2));
941
- if (hairFrontMask !== void 0 && irisLayers.length === 2) {
942
- const mask = hairFrontMask;
943
- const half = canvasW / 2;
944
- const strandOn = (iris, other, side) => {
945
- const r = Math.floor(iris.bbox.y + iris.bbox.h / 2);
946
- const centre = iris.bbox.x + iris.bbox.w / 2;
947
- const otherX = other.bbox.x + other.bbox.w / 2 - half;
948
- const c = side < 0 ? Math.ceil(centre) - 1 : Math.floor(centre);
949
- const span2 = rowSpansByRole.find((s) => s.role === iris.role);
950
- if (span2.rowRight[r] < span2.rowLeft[r]) return void 0;
951
- const minRun = STRAND_MIN_RUN_FRACTION * (span2.rowRight[r] + 1 - span2.rowLeft[r]);
952
- const strand = new Uint8Array(canvasW);
953
- for (let a = 0; a < canvasW; ) {
954
- if (mask[r * canvasW + a] !== 1) {
955
- a++;
956
- continue;
957
- }
958
- let b = a;
959
- while (b < canvasW && mask[r * canvasW + b] === 1) b++;
960
- if (b - a >= minRun) strand.fill(1, a, b);
961
- a = b;
962
- }
963
- const strandAt = (x2) => x2 >= 0 && x2 < canvasW && strand[x2] === 1;
964
- const outerBoundary = (x2) => (side < 0 ? x2 : x2 + 1) - half;
965
- let x = c;
966
- let runFace;
967
- if (!strandAt(c)) {
968
- while (x >= 0 && x < canvasW && !strandAt(x)) x += side;
969
- if (x < 0 || x >= canvasW) return void 0;
970
- runFace = outerBoundary(x - side);
971
- } else {
972
- let f = c - side;
973
- while (strandAt(f)) f -= side;
974
- const face = outerBoundary(f);
975
- runFace = side * (face - otherX) > 0 ? face : null;
976
- }
977
- while (strandAt(x)) x += side;
978
- return {
979
- y: canvasH / 2 - (r + 0.5),
980
- irisOuter: (side < 0 ? span2.rowLeft[r] : span2.rowRight[r] + 1) - half,
981
- irisInner: (side < 0 ? span2.rowRight[r] + 1 : span2.rowLeft[r]) - half,
982
- runOuter: outerBoundary(x - side),
983
- runFace
984
- };
985
- };
986
- const [low, high] = irisLayers;
987
- const left = strandOn(low, high, -1);
988
- const right = strandOn(high, low, 1);
989
- if (left !== void 0 || right !== void 0) {
990
- strandEdges = {
991
- ...left === void 0 ? {} : { left },
992
- ...right === void 0 ? {} : { right }
993
- };
994
- }
995
- }
996
- let turn;
997
- let model;
998
- try {
999
- const { eyeShift, farEyeRatio, silhouetteRatio, noseShift, mouthShift } = input.turnTargets ?? {};
1000
- model = generateIkiFromLayerSet(
1001
- layerInputs,
1002
- { width: canvasW, height: canvasH },
1003
- {
1004
- turnTargets: {
1005
- eyeShift,
1006
- farEyeRatio,
1007
- silhouetteRatio,
1008
- noseShift,
1009
- mouthShift,
1010
- ...headHalfWidthApplied ? { headHalfWidth } : {}
1011
- },
1012
- onTurnSolved: (report) => {
1013
- turn = report;
1014
- },
1015
- ...headEdges === void 0 ? {} : { headEdges },
1016
- ...strandEdges === void 0 ? {} : { strandEdges }
1017
- }
857
+ `front and turned images are not at the same scale: mean iris height ${frontIrisH.toFixed(1)}px front vs ${turnedIrisH.toFixed(1)}px turned, more than ${(IRIS_HEIGHT_SCALE_TOLERANCE * 100).toFixed(0)}% apart \u2014 a yaw does not change iris height, so the pair must share the same framing and head size`
1018
858
  );
1019
- } catch (e) {
1020
- if (!(e instanceof TurnTargetError)) throw e;
1021
- throw new AutoRigInputError(e.message);
1022
859
  }
1023
- const doc = new EditorDocument(model);
1024
- const losslessCrop = quantizeColors === void 0 ? void 0 : crops.find((c) => c.id === LOSSLESS_PAGE_ROLE);
1025
- const pages = losslessCrop === void 0 ? [await renderAtlasPage(crops, quantizeColors)] : [
1026
- await renderAtlasPage(
1027
- crops.filter((c) => c !== losslessCrop),
1028
- quantizeColors
1029
- ),
1030
- await renderAtlasPage([losslessCrop], void 0)
860
+ const frontShift = front.pairCx - front.head.cx;
861
+ const turnedShift = turned.pairCx - turned.head.cx;
862
+ const shift = turnedShift - frontShift;
863
+ const turnSign = shift < 0 ? -1 : 1;
864
+ const f = farNearWidths(front, turnSign);
865
+ const t = farNearWidths(turned, turnSign);
866
+ const debug = debugDir === null ? void 0 : [
867
+ await writeOverlay(debugDir, "front", front),
868
+ await writeOverlay(debugDir, "turned", turned)
1031
869
  ];
1032
- const atlasBytes = pages.reduce((sum, p) => sum + p.dataUri.length, 0);
1033
- if (atlasBytes > MAX_OUTPUT_BYTES) {
1034
- throw new AutoRigInputError(
1035
- `atlas data URI ${atlasBytes} bytes exceeds ${MAX_OUTPUT_BYTES}`
1036
- );
1037
- }
1038
- const partTextureAssignments = pages.flatMap(
1039
- ({ crops: pageCrops, layout }) => pageCrops.map((crop) => {
1040
- const placement2 = layout.placements.find((p) => p.id === crop.id);
1041
- if (placement2 === void 0) {
1042
- throw new Error(`auto-rig: no atlas placement for "${crop.id}"`);
1043
- }
1044
- return {
1045
- partId: crop.id,
1046
- uv: uvRectFor(placement2, {
1047
- width: layout.pageWidth,
1048
- height: layout.pageHeight
1049
- })
1050
- };
1051
- })
1052
- );
1053
- doc.applyAtlas({
1054
- textures: [{ source: pages[0].dataUri }],
1055
- partTextureAssignments
1056
- });
1057
- let patched = doc.getModel();
1058
- if (losslessCrop !== void 0) {
1059
- patched = structuredClone(patched);
1060
- patched.textures = pages.map((p) => ({ source: p.dataUri }));
1061
- patched.parts.find((p) => p.id === losslessCrop.id).texture.index = 1;
1062
- }
1063
- const finalModel = parseIkiModel(patched);
1064
- writeFileAtomic(outPath, JSON.stringify(finalModel));
1065
870
  return {
1066
871
  ok: true,
1067
- path: outPath,
1068
- canvas: { width: canvasW, height: canvasH },
1069
- partCount: finalModel.parts.length,
1070
- atlasBytes,
1071
- ...headHalfWidth === void 0 ? {} : { headHalfWidth },
1072
- headHalfWidthApplied,
1073
- ...headEdges === void 0 ? {} : { headEdges },
1074
- ...strandEdges === void 0 ? {} : { strandEdges },
1075
- ...noseCore === void 0 ? {} : { noseCore },
1076
- ...turn === void 0 ? {} : { turn }
872
+ front,
873
+ turned,
874
+ farEyeRatio: t.far / t.near / (f.far / f.near),
875
+ eyeShift: shift / front.head.half,
876
+ silhouetteRatio: turned.head.half / front.head.half,
877
+ turnSign,
878
+ ...debug === void 0 ? {} : { debug }
1077
879
  };
1078
880
  } catch (err) {
1079
881
  if (err instanceof AutoRigInputError)
@@ -1081,6 +883,34 @@ async function autoRigFromLayers(input) {
1081
883
  throw err;
1082
884
  }
1083
885
  }
886
+ var n1 = (v) => v.toFixed(1);
887
+ var n3 = (v) => v.toFixed(3);
888
+ function imageBlock(label, m) {
889
+ return [
890
+ `# ${label} ${m.file} ${m.width}x${m.height} mask: ${m.maskMode}`,
891
+ `iris widths ${m.irisL.w} / ${m.irisR.w} px centres ${n1(m.irisL.cx)} / ${n1(m.irisR.cx)} eye row ${m.eyeRow} gap ${n1(m.eyeGap)}`,
892
+ `head ${m.head.left}..${m.head.right} centre ${n1(m.head.cx)} half ${n1(m.head.half)} pair centre ${n1(m.pairCx)}`
893
+ ];
894
+ }
895
+ function formatTurnReport(result) {
896
+ const { front, turned } = result;
897
+ const f = farNearWidths(front, result.turnSign);
898
+ const t = farNearWidths(turned, result.turnSign);
899
+ const lines = [
900
+ `farEyeRatio ${n3(result.farEyeRatio)} far/near iris width ${t.far}/${t.near} turned over ${f.far}/${f.near} front`,
901
+ `eyeShift ${n3(result.eyeShift)} pair-vs-head centre ${n1(turned.pairCx - turned.head.cx)} px turned, ${n1(front.pairCx - front.head.cx)} px front, over front head half ${n1(front.head.half)} px (hh)`,
902
+ `silhouetteRatio ${n3(result.silhouetteRatio)} head half ${n1(turned.head.half)} px turned over ${n1(front.head.half)} px front`,
903
+ `turnSign ${result.turnSign} (the head turned toward the image's ${result.turnSign < 0 ? "left" : "right"})`,
904
+ "",
905
+ ...imageBlock("front", front),
906
+ "",
907
+ ...imageBlock("turned", turned)
908
+ ];
909
+ if (result.debug !== void 0) {
910
+ lines.push("", ...result.debug.map((p) => `debug overlay ${p}`));
911
+ }
912
+ return lines.join("\n");
913
+ }
1084
914
 
1085
915
  // src/measure.ts
1086
916
  import fs2 from "fs";
@@ -1383,9 +1213,8 @@ var DEFAULT_LAYOUT = {
1383
1213
  // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir
1384
1214
  // without them still composes (head-only character).
1385
1215
  hair_back: { src: "hair_back.png", cx: 550, cy: 523, w: 800, optional: true },
1386
- // The torso, cut off by the canvas bottom. It rides its own `bodyDeformer`: a
1387
- // light share of the head turn and half its breath bob, so the character is
1388
- // not a floating head.
1216
+ // The torso, cut off by the canvas bottom, so the character is not a
1217
+ // floating head. It rides its own `bodyDeformer`, which only breathes.
1389
1218
  body: { src: "body.png", cx: 550, cy: 1017, w: 840, optional: true },
1390
1219
  face: { src: "face.png", cx: 550, cy: 475, w: 400 },
1391
1220
  // The nose, drawn on its own (the face is drawn without one): the auto-rig
@@ -1768,7 +1597,7 @@ async function composeLayersFromParts(input) {
1768
1597
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1769
1598
  import { z } from "zod";
1770
1599
  function createIkiMcpServer() {
1771
- const server = new McpServer({ name: "iki", version: "0.11.2" });
1600
+ const server = new McpServer({ name: "iki", version: "0.12.0" });
1772
1601
  server.registerTool(
1773
1602
  "validate_iki",
1774
1603
  {
@@ -1855,8 +1684,18 @@ function createIkiMcpServer() {
1855
1684
  silhouetteRatio: z.number().optional(),
1856
1685
  noseShift: z.number().optional(),
1857
1686
  mouthShift: z.number().optional()
1858
- }).optional().describe(
1859
- "What the head turn is fitted to, as `measure_turn_reference` reports it off a front/turned reference pair. `eyeShift` (and the optional `noseShift`/`mouthShift`, derived from it when absent) is how far that feature slides across the head at full turn, as a fraction of the head's half-width \u2014 a MAGNITUDE: the rig turns both ways, so the sign is ignored. `farEyeRatio` is the far/near eye width at full turn over that same ratio at rest, `silhouetteRatio` the head's half-width turned over at rest. The half-width the shifts are fractions of is measured off the layers themselves, so it is not an input. An omitted field falls back to a default, which is clamped to what this layer set can do, and so is a passed `eyeShift` past the room the art leaves the far eye \u2014 the face plate's edge, or the bangs' side strand over the far iris (the result's `turn.clamped` lists every clamped field, `turn.achieved` what the rig reaches, and `turn.strandOverlap` how much of a far iris the bangs still cover). Any other passed target this layer set cannot reach, including an `eyeShift` smaller than the slide the face's own turn already gives the eyes, comes back as `INVALID: \u2026` naming the field and the attainable range, since it is a measurement rather than a preference \u2014 except a passed `silhouetteRatio` when no ratio in its whole accepted range renders on this layer set: that refusal reads `\u2026 is unreachable for this layer set, and so is every silhouetteRatio in [0.5, 1.5]` and names no range, so leave the field out, since a defaulted one clamps."
1687
+ }).passthrough().optional().describe(
1688
+ "What the head turn is fitted to, as `measure_turn_reference` reports it off a front/turned reference pair. `eyeShift` (and the optional `noseShift`/`mouthShift`) is how far that feature slides across the head at full turn, as a fraction of the head's half-width \u2014 a MAGNITUDE: the rig turns both ways, so the sign is ignored. `farEyeRatio` is the far/near eye width at full turn over that same ratio at rest, `silhouetteRatio` the head's half-width turned over at rest. The half-width the shifts are fractions of is measured off the layers themselves, so it is not an input. An omitted field leaves that part of the turn at the Live2D profile the rig defaults to. A passed `eyeShift` is fitted by the turn's amount and clamped to the room the art leaves the far eye \u2014 the face plate's edge, or the bangs' side strand over the far iris (the result's `turn.clamped` lists every clamped field, `turn.achieved` what the rig reaches, and `turn.strandOverlap` how much of a far iris the bangs still cover). Any other passed target this layer set cannot reach comes back as `INVALID: \u2026` naming the field and the attainable range, since it is a measurement rather than a preference. A field not named here is refused the same way."
1689
+ ),
1690
+ style: z.object({
1691
+ turn: z.number().optional(),
1692
+ featureLead: z.number().optional(),
1693
+ hairFollow: z.number().optional(),
1694
+ outlineFollow: z.number().optional(),
1695
+ blink: z.number().optional(),
1696
+ sway: z.number().optional()
1697
+ }).passthrough().optional().describe(
1698
+ "Per-character tuning from the Live2D profile the rig defaults to \u2014 only what the Live2D samples themselves disagree on: `turn` scales the whole head turn (plate, features, hair and the eyes' foreshortening; 0..3, 1 = the profile; ignored when `turnTargets.eyeShift` is given), `featureLead` how far the features lead the face plate (0..3, 1 = the profile), `hairFollow` the front hair's share of the face's turn (0..2, profile 1.1), `outlineFollow` its outer edge's share where the front hair draws the head's outline (0..2, profile 0: the outline holds), `blink` how far the upper lid comes down over the eye's height (0.1..1, profile 0.58), `sway` the hair sway amplitude (0..5, 1 = the profile). A value out of range, or a knob not named here, comes back as `INVALID: \u2026`."
1860
1699
  )
1861
1700
  }
1862
1701
  },
@@ -1989,15 +1828,15 @@ function createIkiMcpServer() {
1989
1828
  }
1990
1829
 
1991
1830
  export {
1992
- measureTurnReference,
1993
- formatTurnReport,
1994
1831
  validateIki,
1995
1832
  describeIki,
1996
1833
  listStandardParameters,
1997
1834
  autoRigFromLayers,
1835
+ measureTurnReference,
1836
+ formatTurnReport,
1998
1837
  measureLayers,
1999
1838
  formatMeasureReport,
2000
1839
  composeLayersFromParts,
2001
1840
  createIkiMcpServer
2002
1841
  };
2003
- //# sourceMappingURL=chunk-ZWDX42O2.mjs.map
1842
+ //# sourceMappingURL=chunk-RMB5YVBU.mjs.map