@rig-c/parts 2.43.0 → 2.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/scene.ts CHANGED
@@ -96,17 +96,19 @@ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync }
96
96
  import { dirname, join, resolve } from 'node:path';
97
97
  import type { RigStop } from '@rig-c/core/rig';
98
98
  import { checkStage, gateThroughRigc, type Log } from './build.ts';
99
- import { ACCEPTABLE_BARS, barsNotMet, type CheckReport, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, type PackMode, requirementsNotPass, type RigcRunner } from './check.ts';
99
+ import { ACCEPTABLE_BARS, barsNotMet, CHECK_SPEC, type CheckReport, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, type PackMode, parsePageSize, requirementsNotPass, type RigcRunner } from './check.ts';
100
100
  import { CONSTRAINT_BONE_FIELDS, editorReceiptProblems, ROOT_BONE } from './config.ts';
101
101
  import { cropToSpineY } from './coords.ts';
102
102
  import { failLine, PartsError, type Problem, refuseIfAny } from './errors.ts';
103
103
  import { readParts } from './parts.ts';
104
104
  import { missingReceipts, readEditorReceipts, type EditorReceipts } from './editreceipt.ts';
105
105
  import type { MotionSpec } from './motion.ts';
106
- import { readPng } from './raster/png.ts';
106
+ import { decodePngBytes } from './raster/png.ts';
107
+ import { clearComposeRun, COMPOSE_RUN_FILE, COMPOSE_RUN_SPEC, type ComposeRun, type RunStampFileEntry } from './runstamp.ts';
107
108
  import { readRequirements, type RequirementsFile } from './requirements.ts';
108
109
  import { OFFSET_PLACES, rigJsonText, type RigSpec } from './rig.ts';
109
110
  import { pyRound } from './round.ts';
111
+ import { mergeSceneAnimations, readSceneAnimations, sceneBoneContext, sceneClipLoopProblems, type SceneAnimations } from './sceneclips.ts';
110
112
 
111
113
  /** The scene file's `spec`. */
112
114
  export const SCENE_SPEC = 'spine-parts-scene/1';
@@ -132,7 +134,7 @@ export const PROVENANCES = ['observed', 'generated', 'unknown'] as const;
132
134
  export type Provenance = (typeof PROVENANCES)[number];
133
135
 
134
136
  /** Every path `compose` writes under `--out`, relative — and so every path it clears first. */
135
- export const COMPOSE_OWNS: readonly string[] = ['rig', 'check', SCENE_REPORT_FILE];
137
+ export const COMPOSE_OWNS: readonly string[] = ['rig', 'check', SCENE_REPORT_FILE, COMPOSE_RUN_FILE];
136
138
 
137
139
  /** `<id>:<name>`. */
138
140
  export function prefixed(id: string, name: string): string {
@@ -168,10 +170,26 @@ export interface ScenePlate {
168
170
  note: string | null;
169
171
  }
170
172
 
173
+ /** An opt-in layer. at is the image top-left in canvas pixels, y down; no scale. */
174
+ export interface NamedScenePlate extends ScenePlate {
175
+ name: string;
176
+ at: [number, number];
177
+ opaque_backdrop?: boolean;
178
+ }
179
+
180
+ /** Separate from character image names; collisions are still refused before emission. */
181
+ export function plateImageName(index: number): string {
182
+ return `scene-plate.${index}.png`;
183
+ }
184
+
171
185
  export interface SceneFile {
172
186
  path: string;
187
+ /** Hash of the exact bytes parsed by loadScene, before any gate runs. */
188
+ sha256: string;
173
189
  canvas: { width: number; height: number };
174
190
  plate: ScenePlate | null;
191
+ plates?: NamedScenePlate[];
192
+ animations?: SceneAnimations;
175
193
  characters: SceneCharacter[];
176
194
  order: string[];
177
195
  }
@@ -235,8 +253,11 @@ export function loadScene(path: string): SceneFile {
235
253
  const at = resolve(path);
236
254
  if (!existsSync(at) || !statSync(at).isFile()) refuseIfAny([{ code: 'SCENE_FILE', object: at, detail: `no such file; a ${SCENE_SPEC} file is required` }]);
237
255
  let raw: unknown;
256
+ let sha256 = '';
238
257
  try {
239
- raw = JSON.parse(readFileSync(at, 'utf8'));
258
+ const bytes = readFileSync(at);
259
+ raw = JSON.parse(bytes.toString('utf8'));
260
+ sha256 = createHash('sha256').update(bytes).digest('hex');
240
261
  } catch (err) {
241
262
  refuseIfAny([{ code: 'SCENE_FILE', object: at, detail: `${(err as Error).message}; a JSON object is required` }]);
242
263
  }
@@ -252,7 +273,7 @@ export function loadScene(path: string): SceneFile {
252
273
  if (!keys.includes(k) && !freeKey(k, v)) fail('SCENE_KEY_KNOWN', `${where}.${k}`, `is a key ${SCENE_SPEC} does not read; it reads ${keys.join(', ')} (and "note", "…_note" strings and "x-…" records, which nothing reads)`);
253
274
  }
254
275
  };
255
- known(o, 'scene', ['spec', 'canvas', 'plate', 'characters', 'order']);
276
+ known(o, 'scene', ['spec', 'canvas', 'plate', 'plates', 'characters', 'order', 'animations']);
256
277
  if (o.spec !== SCENE_SPEC) fail('SCENE_SPEC', 'scene.spec', `is ${show(o.spec)}; "${SCENE_SPEC}" is required`);
257
278
 
258
279
  // canvas
@@ -291,6 +312,40 @@ export function loadScene(path: string): SceneFile {
291
312
  }
292
313
  }
293
314
 
315
+ // Named layers are opt-in; keep the legacy plate reader and its bytes intact.
316
+ const plates: NamedScenePlate[] = [];
317
+ if ('plates' in o) {
318
+ if (!Array.isArray(o.plates)) fail('SCENE_FIELD_TYPE', 'scene.plates', `is ${show(o.plates)}; a list of named plates is required`);
319
+ else {
320
+ const seen = new Map<string, number>();
321
+ o.plates.forEach((p, i) => {
322
+ const where = `scene.plates[${i}]`;
323
+ if (!isRecord(p)) { fail('SCENE_FIELD_TYPE', where, `is ${show(p)}; {name, image, provenance, at} is required`); return; }
324
+ known(p, where, ['name', 'image', 'provenance', 'at', 'opaque_backdrop', 'editor_receipts', 'note']);
325
+ for (const key of ['name', 'image', 'provenance']) {
326
+ if (!(key in p)) fail('SCENE_FIELD_PRESENT', `${where}.${key}`, 'is absent and required');
327
+ else if (typeof p[key] !== 'string' || p[key] === '') fail('SCENE_FIELD_TYPE', `${where}.${key}`, `is ${show(p[key])}; a nonempty string is required`);
328
+ }
329
+ if (typeof p.name === 'string' && p.name !== '') {
330
+ const first = seen.get(p.name);
331
+ if (first !== undefined) fail('SCENE_PLATE_NAME_UNIQUE', `${where}.name`, `is ${show(p.name)}, also declared at scene.plates[${first}]; every plate has one name`);
332
+ else seen.set(p.name, i);
333
+ }
334
+ if (typeof p.provenance === 'string' && !(PROVENANCES as readonly string[]).includes(p.provenance)) fail('SCENE_PLATE_PROVENANCE', `${where}.provenance`, `is ${show(p.provenance)}; one of ${PROVENANCES.join(', ')} is required`);
335
+ const at = p.at;
336
+ const placed = Array.isArray(at) && at.length === 2 && at.every(v => typeof v === 'number' && Number.isFinite(v) && Number.isInteger(v));
337
+ if (!placed) fail('SCENE_PLATE_AT', `${where}.at`, `is ${show(at)}; [x, y], two finite integers locating the image top-left in canvas pixels (y down), is required; negative and outside coordinates are allowed`);
338
+ if ('opaque_backdrop' in p && typeof p.opaque_backdrop !== 'boolean') fail('SCENE_FIELD_TYPE', `${where}.opaque_backdrop`, `is ${show(p.opaque_backdrop)}; a boolean is required`);
339
+ if ('editor_receipts' in p) problems.push(...editorReceiptProblems(p.editor_receipts, `${where}.editor_receipts`).map(problem => ({ ...problem, code: 'SCENE_EDITOR_RECEIPT' })));
340
+ if (typeof p.name === 'string' && p.name !== '' && typeof p.image === 'string' && p.image !== '' && (PROVENANCES as readonly unknown[]).includes(p.provenance) && placed) {
341
+ plates.push({ name: p.name, image: p.image, imagePath: resolve(base, p.image), provenance: p.provenance as Provenance, at: at as [number, number], note: typeof p.note === 'string' ? p.note : null,
342
+ ...('opaque_backdrop' in p ? { opaque_backdrop: p.opaque_backdrop as boolean } : {}),
343
+ ...('editor_receipts' in p ? { editor_receipts: p.editor_receipts as EditorReceipts } : {}) });
344
+ }
345
+ });
346
+ }
347
+ }
348
+
294
349
  // characters
295
350
  const characters: SceneCharacter[] = [];
296
351
  if (!('characters' in o)) fail('SCENE_FIELD_PRESENT', 'scene.characters', 'is absent and required; a list of {"id", "build", "offset"}, at least one');
@@ -366,8 +421,16 @@ export function loadScene(path: string): SceneFile {
366
421
  else order.push(e);
367
422
  });
368
423
  }
424
+ let animations: SceneAnimations | undefined;
425
+ if ('animations' in o) {
426
+ try { animations = readSceneAnimations(o.animations, at); }
427
+ catch (err) {
428
+ if (!(err instanceof PartsError)) throw err;
429
+ problems.push(...err.problems);
430
+ }
431
+ }
369
432
  refuseIfAny(problems);
370
- return { path: at, canvas, plate, characters, order };
433
+ return { path: at, sha256, canvas, plate, ...('plates' in o ? { plates } : {}), ...(animations === undefined ? {} : { animations }), characters, order };
371
434
  }
372
435
 
373
436
  // ---------------------------------------------------------------------------
@@ -386,43 +449,70 @@ export interface CharacterBuild {
386
449
  artBox: [number, number, number, number];
387
450
  /** Every image the build's skin names, as `rig/images/<file>` holds it, in the order the skin names them. */
388
451
  images: Array<[string, Uint8Array]>;
452
+ /** Build-relative paths and hashes of the JSON and image bytes consumed here. */
453
+ files: RunStampFileEntry[];
389
454
  /** The bars its own check failed that were accepted (issue #203), in check's order; empty for a green build. */
390
455
  accepted: string[];
391
456
  }
392
457
 
393
- const BONE_KEYS = ['name', 'parent', 'length', 'rotation', 'x', 'y'];
458
+ const BONE_KEYS = ['name', 'parent', 'length', 'rotation', 'x', 'y', 'inherit'];
394
459
  const SLOT_KEYS = ['name', 'bone', 'attachment'];
395
- const ATTACHMENT_KEYS = ['type', 'path', 'image', 'width', 'height', 'uvs', 'triangles', 'hull', 'weights', 'x', 'y', 'rotation'];
460
+ const ATTACHMENT_KEYS = ['type', 'path', 'image', 'width', 'height', 'uvs', 'triangles', 'hull', 'weights', 'x', 'y', 'rotation', 'generator'];
396
461
  const RIG_KEYS = ['spec', 'name', 'images', 'skeleton', 'bones', 'slots', 'skins', 'constraints', 'stops', 'invariants'];
397
462
  const STOP_KEYS = ['chain', 'links', 'against', 'at', 'inward', 'outward', 'lower'];
398
463
  const STOP_LOWER_KEYS = ['inward', 'outward'];
399
- const INVARIANT_KEYS = ['idleDrivesMeshes', 'detached', 'axes'];
464
+ const INVARIANT_KEYS = ['idleDrivesMeshes', 'detached', 'axes', 'meshSlots', 'meshTriangles', 'deformMayFold'];
400
465
  const MOTION_KEYS = ['spec', 'archetype', 'cut', 'easings', 'groups', 'animations'];
401
- const IDLE_KEYS = ['duration', 'loop', 'note', 'tracks'];
466
+ const IDLE_KEYS = ['duration', 'loop', 'note', 'tracks', 'deform'];
402
467
  const TRACK_KEYS = ['bone', 'group', 'property', 'keys'];
403
- const KEY_KEYS = ['t', 'v', 'curve', 'ease'];
468
+ const KEY_KEYS = ['t', 'v', 'curve', 'ease', 'derive'];
469
+ // Only the turn producer's models, not Core's general transform vocabulary.
470
+ const DERIVE_KEYS = ['kind', 'degrees', 'depth', 'carried', 'about', 'narrowing'];
471
+ const DEFORM_KEYS = ['skin', 'slot', 'attachment', 'keys'];
472
+ const DEFORM_KEY_KEYS = ['t', 'vertices', 'transform'];
473
+ const TURN_TRANSFORM_KEYS = ['kind', 'degrees', 'depth', 'narrowing'];
474
+ type SceneDeform = { skin?: string; slot: string; attachment: string; keys: Array<Record<string, unknown>> };
404
475
 
405
476
  /** One animation of a motion.json: the idle, or one beside it as the file `motion.animations_from` named it (issue #183). */
406
- type SceneAnimation = { duration: number; loop?: boolean; note?: string; tracks: MotionSpec['animations']['idle']['tracks'] };
477
+ type SceneAnimation = { duration: number; loop?: boolean; note?: string; tracks: MotionSpec['animations']['idle']['tracks']; deform?: SceneDeform[] };
407
478
 
408
479
  /** Every animation a motion.json holds, the idle first, in its own order. */
409
480
  function animationsOf(motion: MotionSpec): Record<string, SceneAnimation> {
410
481
  return motion.animations as unknown as Record<string, SceneAnimation>;
411
482
  }
412
483
 
413
- function readJson(path: string, what: string, problems: Problem[]): unknown {
484
+ function readJson(path: string, what: string, problems: Problem[], consumed: (bytes: Uint8Array) => void): unknown {
414
485
  if (!existsSync(path)) {
415
486
  problems.push({ code: 'SCENE_BUILD_PRESENT', object: path, detail: `no such file; ${what}` });
416
487
  return undefined;
417
488
  }
418
489
  try {
419
- return JSON.parse(readFileSync(path, 'utf8'));
490
+ const bytes = readFileSync(path);
491
+ const parsed: unknown = JSON.parse(bytes.toString('utf8'));
492
+ consumed(bytes);
493
+ return parsed;
420
494
  } catch (err) {
421
495
  problems.push({ code: 'SCENE_BUILD_PRESENT', object: path, detail: `${(err as Error).message}; ${what}` });
422
496
  return undefined;
423
497
  }
424
498
  }
425
499
 
500
+ /**
501
+ * The bars a character's `check/check.json` says failed: on a versioned
502
+ * {@link CHECK_SPEC} report, the declared `bar_outcomes` ids whose outcome
503
+ * status is `'FAIL'` in the report's order (issue #1373); on a report without
504
+ * that spec, {@link barsNotMet}'s legacy figure reading.
505
+ */
506
+ export function checkBarsFailed(ck: Readonly<Record<string, unknown>>): string[] {
507
+ if (ck.spec === CHECK_SPEC) {
508
+ const outcomes = isRecord(ck.bar_outcomes) ? ck.bar_outcomes : {};
509
+ return Object.entries(outcomes)
510
+ .filter(([, outcome]) => isRecord(outcome) && outcome.status === 'FAIL')
511
+ .map(([id]) => id);
512
+ }
513
+ return barsNotMet(ck);
514
+ }
515
+
426
516
  /**
427
517
  * Read one character's build, collecting every problem: the files `build`
428
518
  * writes (`SCENE_BUILD_PRESENT`), its own check green (`SCENE_BUILD_GREEN`:
@@ -433,24 +523,32 @@ function readJson(path: string, what: string, problems: Problem[]): unknown {
433
523
  * `accept` (issue #203) is `compose --accept`, joined with the character's own
434
524
  * `accept`: a check that is not green is taken when every bar it failed is
435
525
  * named in that join, its gate green and every declared requirement PASS;
436
- * otherwise it is `SCENE_BUILD_GREEN`, naming the bars not accepted. Without
437
- * an accept list the refusal reads as it always did.
526
+ * otherwise it is `SCENE_BUILD_GREEN`, naming the bars not accepted. When the
527
+ * report declares `spec: "rig-parts-check/1"`, the failing bars are read from
528
+ * `bar_outcomes` ({@link checkBarsFailed}, issue #1373); without that spec,
529
+ * from {@link barsNotMet}. Without an accept list the refusal reads as it
530
+ * always did.
438
531
  */
439
532
  export function readCharacterBuild(c: SceneCharacter, problems: Problem[], accept: readonly string[] = []): CharacterBuild | null {
440
533
  const before = problems.length;
441
534
  const dir = c.buildDir;
442
535
  const who = `character "${c.id}" (${c.build})`;
536
+ const files: RunStampFileEntry[] = [];
537
+ const consumed = (path: string, bytes: Uint8Array): void => {
538
+ files.push({ path, sha256: createHash('sha256').update(bytes).digest('hex') });
539
+ };
540
+ const json = (path: string, what: string): unknown => readJson(join(dir, path), what, problems, bytes => consumed(path, bytes));
443
541
  if (!existsSync(dir) || !statSync(dir).isDirectory()) {
444
542
  problems.push({ code: 'SCENE_BUILD_PRESENT', object: who, detail: `${dir} is not a directory; the --out of a green \`rig-parts build\` is required` });
445
543
  return null;
446
544
  }
447
- const check = readJson(join(dir, 'check', 'check.json'), "the build's own check; a build that ran its check writes it", problems);
545
+ const check = json('check/check.json', "the build's own check; a build that ran its check writes it");
448
546
  const joined = new Set([...accept, ...c.accept]);
449
547
  let accepted: string[] = [];
450
548
  if (check !== undefined) {
451
549
  const ck = isRecord(check) ? check : {};
452
550
  if ((ck.PASS !== true || ck.gate_spine_html_green !== true) && joined.size > 0) {
453
- const failed = barsNotMet(ck);
551
+ const failed = checkBarsFailed(ck);
454
552
  const reqs = requirementsNotPass(ck);
455
553
  const not = failed.filter((b) => !joined.has(b));
456
554
  if (not.length === 0 && reqs.length === 0 && failed.length > 0) accepted = failed;
@@ -474,7 +572,7 @@ export function readCharacterBuild(c: SceneCharacter, problems: Problem[], accep
474
572
  });
475
573
  }
476
574
  }
477
- const parts = readJson(join(dir, 'parts.json'), "assemble's parts.json, which holds the rig_scale and the art's place", problems);
575
+ const parts = json('parts.json', "assemble's parts.json, which holds the rig_scale and the art's place");
478
576
  // Legacy scene records keep their existing checks; a declared package raster
479
577
  // goes through the same file binding reader as rig, check, sheet and propose.
480
578
  if (isRecord(parts) && 'painting_in_rig' in parts) {
@@ -484,8 +582,8 @@ export function readCharacterBuild(c: SceneCharacter, problems: Problem[], accep
484
582
  problems.push(...err.problems);
485
583
  }
486
584
  }
487
- const rigRaw = readJson(join(dir, 'rig', 'rig.json'), "the rig stage's rig.json", problems);
488
- const motionRaw = readJson(join(dir, 'rig', 'motion.json'), "the rig stage's motion.json", problems);
585
+ const rigRaw = json('rig/rig.json', "the rig stage's rig.json");
586
+ const motionRaw = json('rig/motion.json', "the rig stage's motion.json");
489
587
  const unknown = (where: string, obj: unknown, keys: readonly string[]): void => {
490
588
  if (!isRecord(obj)) {
491
589
  problems.push({ code: 'SCENE_BUILD_FIELD_KNOWN', object: `${who} ${where}`, detail: `is ${show(obj)}; an object is required` });
@@ -565,19 +663,51 @@ export function readCharacterBuild(c: SceneCharacter, problems: Problem[], accep
565
663
  });
566
664
  }
567
665
  }
568
- if (isRecord(r.invariants)) unknown('rig.json invariants', r.invariants, INVARIANT_KEYS);
666
+ if (isRecord(r.invariants)) {
667
+ unknown('rig.json invariants', r.invariants, INVARIANT_KEYS);
668
+ for (const key of ['meshSlots', 'meshTriangles']) if (key in r.invariants && !(typeof r.invariants[key] === 'number' && Number.isSafeInteger(r.invariants[key]) && r.invariants[key] >= 0)) {
669
+ problems.push({ code: 'SCENE_BUILD_FIELD_KNOWN', object: `${who} rig.json invariants.${key}`, detail: `is ${show(r.invariants[key])}; a non-negative integer mesh budget is required` });
670
+ }
671
+ if ('deformMayFold' in r.invariants) {
672
+ if (!Array.isArray(r.invariants.deformMayFold)) unknown('rig.json invariants.deformMayFold', r.invariants.deformMayFold, []);
673
+ else r.invariants.deformMayFold.forEach((entry, i) => unknown(`rig.json invariants.deformMayFold[${i}]`, entry, ['slot', 'why']));
674
+ }
675
+ }
569
676
  const skins = isRecord(r.skins) ? r.skins : {};
570
677
  unknown('rig.json skins', skins, ['default']);
571
678
  const seen = new Set<string>();
572
679
  for (const [slot, atts] of Object.entries(isRecord(skins.default) ? skins.default : {})) {
573
680
  for (const [name, att] of Object.entries(isRecord(atts) ? atts : {})) {
574
681
  unknown(`rig.json skins.default.${slot}.${name}`, att, ATTACHMENT_KEYS);
575
- const file = isRecord(att) ? att.image : undefined;
576
- if (typeof file !== 'string' || seen.has(file)) continue;
577
- seen.add(file);
578
- const png = join(dir, 'rig', 'images', file);
579
- if (!existsSync(png)) problems.push({ code: 'SCENE_BUILD_PRESENT', object: `${who} skins.default.${slot}.${name}`, detail: `names the image "${file}", and ${png} does not exist` });
580
- else images.push([file, new Uint8Array(readFileSync(png))]);
682
+ const at = `rig.json skins.default.${slot}.${name}`;
683
+ let depthImage: unknown;
684
+ if (isRecord(att) && 'generator' in att) {
685
+ const g = att.generator;
686
+ unknown(`${at}.generator`, g, ['kind', 'cols', 'rows', 'depth']);
687
+ const shape = (field: string, detail: string): void => { problems.push({ code: 'SCENE_BUILD_FIELD_KNOWN', object: `${who} ${at}.generator.${field}`, detail }); };
688
+ if (isRecord(g)) {
689
+ if (g.kind !== 'grid') shape('kind', `is ${show(g.kind)}; only the rig producer's depth grid is supported`);
690
+ for (const key of ['cols', 'rows']) if (!(typeof g[key] === 'number' && Number.isSafeInteger(g[key]) && g[key] >= 2)) shape(key, `is ${show(g[key])}; an integer grid count of at least two is required`);
691
+ unknown(`${at}.generator.depth`, g.depth, ['image', 'near', 'zScale']);
692
+ if (isRecord(g.depth)) {
693
+ depthImage = g.depth.image;
694
+ if (typeof depthImage !== 'string' || depthImage === '') shape('depth.image', `is ${show(depthImage)}; a depth PNG name is required`);
695
+ if (g.depth.near !== 'white' && g.depth.near !== 'black') shape('depth.near', `is ${show(g.depth.near)}; white or black is required`);
696
+ if (!(typeof g.depth.zScale === 'number' && Number.isFinite(g.depth.zScale) && g.depth.zScale > 0)) shape('depth.zScale', `is ${show(g.depth.zScale)}; a positive finite depth scale is required`);
697
+ }
698
+ }
699
+ }
700
+ for (const file of [isRecord(att) ? att.image : undefined, depthImage]) {
701
+ if (typeof file !== 'string' || seen.has(file)) continue;
702
+ seen.add(file);
703
+ const png = join(dir, 'rig', 'images', file);
704
+ if (!existsSync(png)) problems.push({ code: 'SCENE_BUILD_PRESENT', object: `${who} skins.default.${slot}.${name}`, detail: `names the image "${file}", and ${png} does not exist` });
705
+ else {
706
+ const bytes = new Uint8Array(readFileSync(png));
707
+ images.push([file, bytes]);
708
+ consumed(`rig/images/${file}`, bytes);
709
+ }
710
+ }
581
711
  }
582
712
  }
583
713
  }
@@ -611,8 +741,54 @@ export function readCharacterBuild(c: SceneCharacter, problems: Problem[], accep
611
741
  } else problems.push({ code: 'SCENE_BUILD_PRESENT', object: `${who} motion.json animations.idle`, detail: 'is absent; the rig stage writes one idle, which the scene holds every character\'s tracks in' });
612
742
  }
613
743
  }
744
+ if (isRecord(motionRaw) && isRecord(motionRaw.animations)) {
745
+ const shape = (where: string, detail: string): void => { problems.push({ code: 'SCENE_BUILD_FIELD_KNOWN', object: `${who} ${where}`, detail }); };
746
+ const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
747
+ const turn = (v: unknown, at: string, model: 'derive' | 'transform'): void => {
748
+ unknown(at, v, model === 'derive' ? DERIVE_KEYS : TURN_TRANSFORM_KEYS);
749
+ if (!isRecord(v)) return;
750
+ if (v.kind !== 'yaw' && v.kind !== 'pitch') shape(`${at}.kind`, `is ${show(v.kind)}; the turn producer's yaw or pitch is required`);
751
+ if (!finite(v.degrees)) shape(`${at}.degrees`, `is ${show(v.degrees)}; finite degrees are required`);
752
+ if (model === 'derive') {
753
+ if (!finite(v.depth) && !(isRecord(v.depth) && Object.values(v.depth).every(finite))) shape(`${at}.depth`, `is ${show(v.depth)}; a finite depth or a map of bone to finite depth is required`);
754
+ for (const k of ['carried', 'about']) if (k in v && !finite(v[k])) shape(`${at}.${k}`, `is ${show(v[k])}; a finite length is required`);
755
+ } else if (v.depth !== true) shape(`${at}.depth`, `is ${show(v.depth)}; the turn producer's depth: true is required`);
756
+ if ('narrowing' in v && typeof v.narrowing !== 'boolean') shape(`${at}.narrowing`, `is ${show(v.narrowing)}; a boolean is required`);
757
+ };
758
+ for (const [name, anim] of Object.entries(motionRaw.animations)) {
759
+ if (!isRecord(anim)) continue;
760
+ const at = `motion.json animations.${name}`;
761
+ for (const [i, tr] of (Array.isArray(anim.tracks) ? anim.tracks : []).entries()) {
762
+ if (!isRecord(tr) || !Array.isArray(tr.keys)) continue;
763
+ for (const [j, key] of tr.keys.entries()) if (isRecord(key) && 'derive' in key) {
764
+ const where = `${at}.tracks[${i}].keys[${j}]`;
765
+ turn(key.derive, `${where}.derive`, 'derive');
766
+ if ('v' in key) shape(where, 'carries both v and derive; one source of values is required');
767
+ }
768
+ }
769
+ if (!('deform' in anim)) continue;
770
+ if (!Array.isArray(anim.deform)) { shape(`${at}.deform`, `is ${show(anim.deform)}; a list of turn deform timelines is required`); continue; }
771
+ for (const [i, deform] of anim.deform.entries()) {
772
+ const where = `${at}.deform[${i}]`;
773
+ unknown(where, deform, DEFORM_KEYS);
774
+ if (!isRecord(deform)) continue;
775
+ for (const k of ['slot', 'attachment']) if (typeof deform[k] !== 'string' || deform[k] === '') shape(`${where}.${k}`, `is ${show(deform[k])}; a non-empty name is required`);
776
+ if (!Array.isArray(deform.keys)) { shape(`${where}.keys`, `is ${show(deform.keys)}; a list of turn deform keys is required`); continue; }
777
+ for (const [j, key] of deform.keys.entries()) {
778
+ const keyAt = `${where}.keys[${j}]`;
779
+ unknown(keyAt, key, DEFORM_KEY_KEYS);
780
+ if (!isRecord(key)) continue;
781
+ if (!finite(key.t)) shape(`${keyAt}.t`, `is ${show(key.t)}; a finite time is required`);
782
+ if ('vertices' in key && !(Array.isArray(key.vertices) && key.vertices.every(finite))) shape(`${keyAt}.vertices`, `is ${show(key.vertices)}; finite offset pairs are required`);
783
+ if ('transform' in key) turn(key.transform, `${keyAt}.transform`, 'transform');
784
+ if ('vertices' in key && 'transform' in key) shape(keyAt, 'carries both vertices and transform; one source of offsets is required');
785
+ }
786
+ }
787
+ }
788
+ }
614
789
  if (problems.length > before) return null;
615
- return { id: c.id, dir, rig: rigRaw as RigSpec, motion: motionRaw as MotionSpec, rigSize, rigScale, artBox, images, accepted };
790
+ files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
791
+ return { id: c.id, dir, rig: rigRaw as RigSpec, motion: motionRaw as MotionSpec, rigSize, rigScale, artBox, images, files, accepted };
616
792
  }
617
793
 
618
794
  // ---------------------------------------------------------------------------
@@ -701,12 +877,15 @@ export function scaleProblems(c: SceneCharacter, b: CharacterBuild): Problem[] {
701
877
  (t.keys as unknown as Array<Record<string, unknown>>).forEach((key, j) => {
702
878
  const v = key.v;
703
879
  const numbers = (x: unknown): boolean => Array.isArray(x) && x.every((n) => typeof n === 'number');
704
- if (!numbers(v) && !(isRecord(v) && Object.values(v).every(numbers))) {
880
+ if (!isRecord(key.derive) && !numbers(v) && !(isRecord(v) && Object.values(v).every(numbers))) {
705
881
  out.push({ code: 'SCENE_SCALE_EXACT', object: `${where}.keys[${j}].v`, detail: `is ${show(v)}; a ${prop} key's value is a length, which compose scales in a list of numbers or a map of member to list, and this is neither` });
706
882
  }
707
883
  });
708
884
  });
709
885
  }
886
+ for (const [slot, atts] of Object.entries(b.rig.skins.default)) for (const [name, att] of Object.entries(atts)) {
887
+ if ('generator' in att) out.push({ code: 'SCENE_SCALE_EXACT', object: `${who} rig.json skins.default.${slot}.${name}.generator`, detail: 'is an image-sized depth grid; scaling its bone offsets and zScale does not scale its generated bind geometry — compose it at scale 1, or rebuild it at another assemble.rig_scale' });
888
+ }
710
889
  (b.rig.constraints ?? []).forEach((con, k) => {
711
890
  const forces = con.type === 'physics' ? physicsForce(con as Record<string, unknown>) : [];
712
891
  if (forces.length > 0) {
@@ -808,6 +987,15 @@ function scaledTrack<T extends { property: string; keys: unknown[] }>(t: T, s: n
808
987
  const list = (v: unknown): unknown => (Array.isArray(v) ? v.map((n) => scaledBy(n as number, s)) : v);
809
988
  const keys = (t.keys as Array<Record<string, unknown>>).map((k) => {
810
989
  const out: Record<string, unknown> = { ...k, v: isRecord(k.v) ? Object.fromEntries(Object.entries(k.v).map(([m, x]) => [m, list(x)])) : list(k.v) };
990
+ if (isRecord(k.derive)) {
991
+ const d = { ...k.derive };
992
+ for (const field of ['depth', 'carried', 'about']) {
993
+ const v = d[field];
994
+ if (typeof v === 'number') d[field] = scaledBy(v, s);
995
+ else if (isRecord(v)) d[field] = Object.fromEntries(Object.entries(v).map(([name, n]) => [name, scaledBy(n as number, s)]));
996
+ }
997
+ out.derive = d;
998
+ }
811
999
  // A raw curve is four numbers per channel, (time, value, time, value): the values are at the odd places.
812
1000
  if (Array.isArray(k.curve)) out.curve = (k.curve as number[]).map((n, i) => (i % 2 === 1 ? scaledBy(n, s) : n));
813
1001
  return out;
@@ -849,9 +1037,10 @@ export interface SceneReport {
849
1037
  scene: string;
850
1038
  canvas: { width: number; height: number };
851
1039
  rig_name: string;
852
- pack_mode: { page_edges: string; pack_shape: string };
1040
+ pack_mode: { page_edges: string; pack_shape: string; page_size?: number };
853
1041
  /** `sha256` (issue #1183) is of the plate PNG's bytes as compose read them, so a verdict can bind to them. */
854
1042
  plate: { image: string; provenance: Provenance; note: string | null; bone: string; slot: string; size: [number, number]; sha256: string; judged_by: 'nothing' } | null;
1043
+ plates?: Array<{ name: string; image: string; provenance: Provenance; note: string | null; at: [number, number]; opaque_backdrop: boolean; bone: string; slot: string; size: [number, number]; sha256: string; judged_by: 'nothing' }>;
855
1044
  characters: SceneCharacterReport[];
856
1045
  order: { declared: string[]; slots: string[]; judged_by: 'nothing' };
857
1046
  idle_duration: number;
@@ -863,6 +1052,8 @@ export interface ComposedScene {
863
1052
  /** Every image file of the composed rig, by its composed name: the plate's first, then each character's. */
864
1053
  images: Array<[string, Uint8Array]>;
865
1054
  report: SceneReport;
1055
+ /** Opt-in declaration retained for pre-emission pose measurement; never serialized. */
1056
+ sceneAnimations?: SceneAnimations;
866
1057
  }
867
1058
 
868
1059
  /** The plate image's bytes and size, read by the caller. */
@@ -889,7 +1080,9 @@ export function composeScene(
889
1080
  problems: Problem[],
890
1081
  mode: PackMode = { pageEdges: DEFAULT_PAGE_EDGES, packShape: DEFAULT_PACK_SHAPE },
891
1082
  requirements: RequirementsFile | null = null,
1083
+ plateLayers: ReadonlyArray<PlateImage | null> = [],
892
1084
  ): ComposedScene {
1085
+ const pageSize = parsePageSize(mode.pageSize);
893
1086
  const fail = (code: string, object: string, detail: string): void => {
894
1087
  problems.push({ code, object, detail });
895
1088
  };
@@ -904,6 +1097,41 @@ export function composeScene(
904
1097
  fail('SCENE_PLATE_SIZE', `scene.plate.image (${scene.plate.image})`, `is ${plate.width}x${plate.height}; the canvas's size, ${canvas.width}x${canvas.height}, is required — the plate is drawn at canvas (0, 0) and is never scaled`);
905
1098
  }
906
1099
 
1100
+ const layers = scene.plates ?? [];
1101
+ const layerNames = new Set(layers.map(p => p.name));
1102
+ const reserved = new Set([ROOT_BONE, PLATE, 'idle', ...ids, ...ready.flatMap(b => [
1103
+ ...b.rig.bones.map(x => prefixed(b.id, x.name)),
1104
+ ...b.rig.slots.map(x => prefixed(b.id, x.name)),
1105
+ ...Object.keys(b.motion.animations).map(n => prefixed(b.id, n)),
1106
+ ])]);
1107
+ const refusedLayerNames = new Set<string>();
1108
+ layers.forEach((p, i) => {
1109
+ const where = `scene.plates[${i}] (${show(p.name)})`;
1110
+ if (reserved.has(p.name)) {
1111
+ refusedLayerNames.add(p.name);
1112
+ fail('SCENE_PLATE_NAME_FREE', `${where}.name`, `is ${show(p.name)}, reserved by the shared root, legacy plate, character id, bone, slot or animation; a distinct name is required`);
1113
+ }
1114
+ if (layers.findIndex(q => q.name === p.name) !== i) {
1115
+ refusedLayerNames.add(p.name);
1116
+ fail('SCENE_PLATE_NAME_UNIQUE', `${where}.name`, `is ${show(p.name)}, already declared; every plate has one name`);
1117
+ }
1118
+ if (!(Array.isArray(p.at) && p.at.length === 2 && p.at.every(v => Number.isFinite(v) && Number.isInteger(v)))) fail('SCENE_PLATE_AT', `${where}.at`, `is ${show(p.at)}; two finite integers of canvas pixels locating the image top-left are required`);
1119
+ const img = plateLayers[i];
1120
+ if (img === undefined || img === null) {
1121
+ fail('SCENE_PLATE_PRESENT', `${where}.image`, 'has no decoded PNG; an image with its own dimensions is required');
1122
+ return;
1123
+ }
1124
+ const raster = decodePngBytes(img.bytes, `${where}.image`);
1125
+ if (raster.width !== img.width || raster.height !== img.height) fail('SCENE_PLATE_SIZE', `${where}.image`, `decoded ${raster.width}x${raster.height}, declared ${img.width}x${img.height}; the image dimensions must agree`);
1126
+ const transparent = raster.data.some((v, k) => k % 4 === 3 && v < 255);
1127
+ if (!transparent) {
1128
+ if (p.opaque_backdrop !== true) fail('SCENE_PLATE_ALPHA', `${where}.image`, `is opaque in every texel; a layer must use alpha below 255 unless this layer explicitly declares opaque_backdrop: true; A19_OVERLAY_PNGS_HAVE_ALPHA remains enabled`);
1129
+ // Core 3.8.0 a19.ts:38-39,64-69: no named rig-spec base plate;
1130
+ // both attachment dimensions must meet the stage, which sceneStage makes the canvas.
1131
+ else if (img.width < stage.width || img.height < stage.height) fail('SCENE_PLATE_BACKDROP_SIZE', `${where}.image`, `is an opaque backdrop of ${img.width}x${img.height}; width >= ${stage.width} and height >= ${stage.height} (the ${canvas.width}x${canvas.height} canvas stage) are required by rigc A19's size inference; use transparency or a sufficiently sized backdrop`);
1132
+ }
1133
+ });
1134
+
907
1135
  // ---- one rig_scale, one idle length -------------------------------------
908
1136
  const scales = ready.map((b) => `"${b.id}" ${b.rigScale}`);
909
1137
  if (new Set(ready.map((b) => b.rigScale)).size > 1) {
@@ -958,8 +1186,16 @@ export function composeScene(
958
1186
  const slotsOf = new Map(ready.map((b) => [b.id, b.rig.slots.map((s) => s.name)]));
959
1187
  const explicit = new Map<string, number>();
960
1188
  const idAt = new Map<string, number>();
1189
+ const layerAt = new Map<string, number>();
961
1190
  scene.order.forEach((e, i) => {
962
1191
  const at = `scene.order[${i}]`;
1192
+ const isCharOrSlot = ids.includes(e) || (e.includes(PREFIX_SEP) && ids.includes(e.slice(0, e.indexOf(PREFIX_SEP))));
1193
+ if (layerNames.has(e) && !(refusedLayerNames.has(e) && isCharOrSlot)) {
1194
+ const first = layerAt.get(e);
1195
+ if (first !== undefined) fail('SCENE_ORDER_ONCE', at, `names the plate ${show(e)} again (first at scene.order[${first}]); every plate slot is drawn exactly once`);
1196
+ else layerAt.set(e, i);
1197
+ return;
1198
+ }
963
1199
  const cut = e.indexOf(PREFIX_SEP);
964
1200
  if (cut < 0) {
965
1201
  if (!ids.includes(e)) {
@@ -995,8 +1231,10 @@ export function composeScene(
995
1231
  fail('SCENE_ORDER_COMPLETE', `scene.order (character "${id}")`, `names ${missing.length} of the ${own.length} slot(s) of "${id}" nowhere: ${missing.map((s) => `"${prefixed(id, s)}"`).join(', ')}; every slot is drawn exactly once — name "${id}" (its remaining slots, in its own order) or each slot`);
996
1232
  }
997
1233
  }
1234
+ for (const p of layers) if (!refusedLayerNames.has(p.name) && !layerAt.has(p.name)) fail('SCENE_ORDER_COMPLETE', 'scene.order', `names plate ${show(p.name)} nowhere; every plate slot is drawn exactly once`);
998
1235
  const drawn: string[] = [];
999
1236
  for (const e of scene.order) {
1237
+ if (layerNames.has(e)) { drawn.push(e); continue; }
1000
1238
  if (e.includes(PREFIX_SEP)) {
1001
1239
  if (explicit.has(e)) drawn.push(e);
1002
1240
  continue;
@@ -1047,6 +1285,37 @@ export function composeScene(
1047
1285
  ax.bones.forEach((n, j) => ownBone(b.id, n, `character "${b.id}" rig.json invariants.axes[${k}].bones[${j}]`));
1048
1286
  }
1049
1287
  }
1288
+ // Turn names are resolved before any output or call to Core, including map keys.
1289
+ for (const b of ready) {
1290
+ const anims = animationsOf(b.motion);
1291
+ const missing = (where: string, detail: string): void => { fail('SCENE_NAME_RESOLVES', `character "${b.id}" ${where}`, detail); };
1292
+ for (const [name, anim] of Object.entries(anims)) {
1293
+ for (const [i, tr] of anim.tracks.entries()) {
1294
+ const t = tr as unknown as Record<string, unknown>;
1295
+ const members = typeof t.bone === 'string' ? [t.bone] : typeof t.group === 'string' ? b.motion.groups[t.group] : undefined;
1296
+ for (const [j, key] of (t.keys as Array<Record<string, unknown>>).entries()) {
1297
+ const at = `motion.json animations.${name}.tracks[${i}].keys[${j}]`;
1298
+ const maps: Array<[string, unknown]> = [['v', key.v], ['derive.depth', isRecord(key.derive) ? key.derive.depth : undefined]];
1299
+ for (const [field, map] of maps) if (isRecord(map)) for (const member of Object.keys(map)) {
1300
+ ownBone(b.id, member, `character "${b.id}" ${at}.${field}.${member}`);
1301
+ if (members === undefined || !members.includes(member)) missing(`${at}.${field}.${member}`, `names "${member}", which is not a member of this track's target; a named member of that target is required`);
1302
+ }
1303
+ }
1304
+ }
1305
+ for (const [i, d] of (anim.deform ?? []).entries()) {
1306
+ const at = `motion.json animations.${name}.deform[${i}]`;
1307
+ if (d.skin !== undefined && d.skin !== 'default') missing(`${at}.skin`, `names ${show(d.skin)}; the composed rig shares only the default skin`);
1308
+ if (!(slotsOf.get(b.id) ?? []).includes(d.slot)) missing(`${at}.slot`, `names "${d.slot}", which this character does not declare`);
1309
+ if (b.rig.skins.default[d.slot]?.[d.attachment] === undefined) missing(`${at}.attachment`, `names "${d.attachment}" on slot "${d.slot}", which this character's default skin does not hold`);
1310
+ }
1311
+ }
1312
+ for (const [i, entry] of (b.rig.invariants?.deformMayFold ?? []).entries()) {
1313
+ if (!(slotsOf.get(b.id) ?? []).includes(entry.slot)) missing(`rig.json invariants.deformMayFold[${i}].slot`, `names ${show(entry.slot)}, which this character does not declare`);
1314
+ }
1315
+ for (const [i, con] of (b.rig.constraints ?? []).entries()) if (con.type === 'slider') {
1316
+ if (typeof con.animation !== 'string' || !(con.animation in anims)) missing(`rig.json constraints[${i}].animation`, `names ${show(con.animation)}, which this character's motion does not declare; an animation of its own is required`);
1317
+ }
1318
+ }
1050
1319
  // The root is shared: a character that drives it would move every character.
1051
1320
  for (const b of ready) {
1052
1321
  const where = `character "${b.id}"`;
@@ -1078,6 +1347,7 @@ export function composeScene(
1078
1347
  // ---- image names ------------------------------------------------------------
1079
1348
  const taken = new Map<string, string>();
1080
1349
  if (scene.plate !== null) taken.set(PLATE_IMAGE, 'the plate');
1350
+ layers.forEach((p, i) => taken.set(plateImageName(i), `plate ${show(p.name)}`));
1081
1351
  for (const b of ready) {
1082
1352
  for (const [file] of b.images) {
1083
1353
  const n = imageName(b.id, file);
@@ -1086,7 +1356,7 @@ export function composeScene(
1086
1356
  else taken.set(n, `character "${b.id}" image "${file}"`);
1087
1357
  }
1088
1358
  }
1089
- if (requirements !== null) problems.push(...requirementPrefixProblems(requirements, ready, scene.plate !== null));
1359
+ if (requirements !== null) problems.push(...requirementPrefixProblems(requirements, ready, scene.plate !== null, [...layerNames]));
1090
1360
  refuseIfAny(problems);
1091
1361
 
1092
1362
  // ---- the rig ----------------------------------------------------------------
@@ -1114,6 +1384,13 @@ export function composeScene(
1114
1384
  skin[PLATE] = { [PLATE]: { image: PLATE_IMAGE, x: stage.x + canvas.width / 2, y: cropToSpineY(canvas.height / 2, canvas.height) } };
1115
1385
  images.push([PLATE_IMAGE, plate.bytes]);
1116
1386
  }
1387
+ layers.forEach((p, i) => {
1388
+ const img = plateLayers[i] as PlateImage;
1389
+ bones.push({ name: p.name, parent: ROOT_BONE, x: 0, y: 0 });
1390
+ skin[p.name] = { [p.name]: { image: plateImageName(i), x: stage.x + p.at[0] + img.width / 2, y: cropToSpineY(p.at[1] + img.height / 2, canvas.height) } };
1391
+ slotDefs.set(p.name, { name: p.name, bone: p.name, attachment: p.name });
1392
+ images.push([plateImageName(i), img.bytes]);
1393
+ });
1117
1394
  const constraints: Array<Record<string, unknown>> = [];
1118
1395
  const stops: RigStop[] = [];
1119
1396
  const detached: NonNullable<NonNullable<RigSpec['invariants']>['detached']> = [];
@@ -1146,6 +1423,9 @@ export function composeScene(
1146
1423
  ...(typeof att.path === 'string' ? { path: imageName(id, att.path) } : {}),
1147
1424
  image: imageName(id, att.image as string),
1148
1425
  };
1426
+ if (isRecord(att.generator) && isRecord(att.generator.depth)) {
1427
+ a.generator = { ...att.generator, depth: { ...att.generator.depth, image: imageName(id, att.generator.depth.image as string) } };
1428
+ }
1149
1429
  if (Array.isArray(att.weights)) {
1150
1430
  a.weights = (att.weights as Array<Array<Record<string, unknown>>>).map((v) =>
1151
1431
  v.map((w) =>
@@ -1180,6 +1460,7 @@ export function composeScene(
1180
1460
  out[field] = arity === 'one' ? P(id, con[field] as string) : (con[field] as string[]).map((n) => P(id, n));
1181
1461
  }
1182
1462
  if (type === 'path' && typeof con.slot === 'string') out.slot = prefixed(id, con.slot);
1463
+ if (type === 'slider' && typeof con.animation === 'string') out.animation = con.animation === 'idle' ? 'idle' : prefixed(id, con.animation);
1183
1464
  constraints.push(out);
1184
1465
  }
1185
1466
  for (const st of b.rig.stops ?? []) {
@@ -1207,12 +1488,32 @@ export function composeScene(
1207
1488
  if (whys.length === 1) invariants.idleDrivesMeshes = { why: whys[0] };
1208
1489
  if (detached.length > 0) invariants.detached = detached;
1209
1490
  if (axes.length > 0) invariants.axes = axes;
1491
+ const mayFold = ready.flatMap(b => (b.rig.invariants?.deformMayFold ?? []).map(e => ({ ...e, slot: prefixed(b.id, e.slot) })));
1492
+ if (mayFold.length > 0) invariants.deformMayFold = mayFold;
1493
+ const meshCounts = (b: CharacterBuild): { meshSlots: number; meshTriangles: number } => {
1494
+ let meshSlots = 0, meshTriangles = 0;
1495
+ for (const atts of Object.values(b.rig.skins.default)) {
1496
+ let mesh = false;
1497
+ for (const att of Object.values(atts)) if ('type' in att && att.type === 'mesh') {
1498
+ mesh = true;
1499
+ const triangles = att.generator?.kind === 'grid' ? 2 * (att.generator.cols - 1) * (att.generator.rows - 1) : att.triangles.length / 3;
1500
+ meshTriangles = Math.max(meshTriangles, triangles);
1501
+ }
1502
+ if (mesh) meshSlots++;
1503
+ }
1504
+ return { meshSlots, meshTriangles };
1505
+ };
1506
+ for (const field of ['meshSlots', 'meshTriangles'] as const) if (ready.some(b => b.rig.invariants?.[field] !== undefined)) {
1507
+ const values = ready.map(b => b.rig.invariants?.[field] ?? meshCounts(b)[field]);
1508
+ invariants[field] = field === 'meshSlots' ? values.reduce((a, b) => a + b, 0) : Math.max(...values);
1509
+ }
1210
1510
  if (Object.keys(invariants).length > 0) rig.invariants = invariants;
1211
1511
 
1212
1512
  // ---- the motion ---------------------------------------------------------------
1213
1513
  const easings: MotionSpec['easings'] = {};
1214
1514
  const groups: MotionSpec['groups'] = {};
1215
1515
  const tracks: MotionSpec['animations']['idle']['tracks'] = [];
1516
+ const idleDeform: SceneDeform[] = [];
1216
1517
  // Every animation beside a character's idle rides along under its character's prefix (issue #183), its tracks
1217
1518
  // prefixed as the idle's are and nothing else changed: the scene plays the idle, and schedules none of these.
1218
1519
  const beside: Record<string, SceneAnimation> = {};
@@ -1226,27 +1527,45 @@ export function composeScene(
1226
1527
  const tr = { ...t } as Record<string, unknown>;
1227
1528
  if (typeof tr.bone === 'string') tr.bone = P(id, tr.bone);
1228
1529
  if (typeof tr.group === 'string') tr.group = prefixed(id, tr.group);
1229
- tr.keys = (t.keys as unknown as Array<Record<string, unknown>>).map((k) => (typeof k.ease === 'string' ? { ...k, ease: prefixed(id, k.ease) } : k));
1530
+ const memberMap = (v: Record<string, unknown>): Record<string, unknown> => Object.fromEntries(Object.entries(v).map(([n, value]) => [P(id, n), value]));
1531
+ tr.keys = (t.keys as unknown as Array<Record<string, unknown>>).map((k) => ({
1532
+ ...k,
1533
+ ...(typeof k.ease === 'string' ? { ease: prefixed(id, k.ease) } : {}),
1534
+ ...(isRecord(k.v) ? { v: memberMap(k.v) } : {}),
1535
+ ...(isRecord(k.derive) ? { derive: { ...k.derive, ...(isRecord(k.derive.depth) ? { depth: memberMap(k.derive.depth) } : {}) } } : {}),
1536
+ }));
1230
1537
  return tr as unknown as MotionSpec['animations']['idle']['tracks'][number];
1231
1538
  };
1232
1539
  for (const t of b.motion.animations.idle.tracks) tracks.push(scaledTrack(prefixTrack(t), c.scale));
1233
- for (const [n, a] of Object.entries(animationsOf(b.motion))) if (n !== 'idle') beside[prefixed(id, n)] = { ...a, tracks: a.tracks.map((t) => scaledTrack(prefixTrack(t), c.scale)) };
1540
+ const deforms = (a: SceneAnimation): { deform?: SceneDeform[] } => a.deform === undefined ? {} : { deform: a.deform.map((d) => ({
1541
+ ...d, slot: prefixed(id, d.slot), attachment: prefixed(id, d.attachment),
1542
+ // default is the one shared skin, not a per-character name.
1543
+ keys: d.keys.map((k) => ({ ...k, ...(Array.isArray(k.vertices) && c.scale !== 1 ? { vertices: k.vertices.map((v) => scaledBy(v as number, c.scale)) } : {}) })),
1544
+ })) };
1545
+ idleDeform.push(...(deforms(animationsOf(b.motion).idle).deform ?? []));
1546
+ for (const [n, a] of Object.entries(animationsOf(b.motion))) if (n !== 'idle') beside[prefixed(id, n)] = { ...a, tracks: a.tracks.map((t) => scaledTrack(prefixTrack(t), c.scale)), ...deforms(a) };
1234
1547
  }
1235
1548
  const note = notes.size === 1 ? [...notes][0] : ready.map((b) => `${b.id}: ${b.motion.animations.idle.note}`).join(' | ');
1236
- const motion: MotionSpec = { spec: 'rigc-motion/1', archetype: name, cut: name, easings, groups, animations: { idle: { duration: durations[0], loop: true, note, tracks }, ...beside } };
1549
+ const motion: MotionSpec = { spec: 'rigc-motion/1', archetype: name, cut: name, easings, groups, animations: { idle: { duration: durations[0], loop: true, note, tracks, ...(idleDeform.length === 0 ? {} : { deform: idleDeform }) }, ...beside } };
1550
+
1551
+ if (scene.animations !== undefined) mergeSceneAnimations(rig, motion, scene.animations);
1237
1552
 
1238
1553
  const report: SceneReport = {
1239
1554
  spec: SCENE_REPORT_SPEC,
1240
1555
  scene: scene.path,
1241
1556
  canvas: { ...canvas },
1242
1557
  rig_name: name,
1243
- pack_mode: { page_edges: mode.pageEdges, pack_shape: mode.packShape },
1558
+ pack_mode: { page_edges: mode.pageEdges, pack_shape: mode.packShape, ...(pageSize === undefined ? {} : { page_size: pageSize }) },
1244
1559
  plate: scene.plate === null || plate === null ? null : { image: scene.plate.image, provenance: scene.plate.provenance, note: scene.plate.note, bone: PLATE, slot: PLATE, size: [plate.width, plate.height], sha256: createHash('sha256').update(plate.bytes).digest('hex'), judged_by: 'nothing' },
1560
+ ...(scene.plates === undefined ? {} : { plates: layers.map((p, i) => {
1561
+ const img = plateLayers[i] as PlateImage;
1562
+ return { name: p.name, image: p.image, provenance: p.provenance, note: p.note, at: [...p.at] as [number, number], opaque_backdrop: p.opaque_backdrop === true, bone: p.name, slot: p.name, size: [img.width, img.height] as [number, number], sha256: createHash('sha256').update(img.bytes).digest('hex'), judged_by: 'nothing' as const };
1563
+ }) }),
1245
1564
  characters: rows,
1246
1565
  order: { declared: [...scene.order], slots: slots.map((s) => s.name), judged_by: 'nothing' },
1247
1566
  idle_duration: durations[0],
1248
1567
  };
1249
- return { rig, motion, images, report };
1568
+ return { rig, motion, images, report, ...(scene.animations === undefined ? {} : { sceneAnimations: scene.animations }) };
1250
1569
  }
1251
1570
 
1252
1571
  // ---------------------------------------------------------------------------
@@ -1260,7 +1579,7 @@ export function composeScene(
1260
1579
  * refused naming the prefixed names it could have meant. Any other miss is
1261
1580
  * left to `check`'s own `REQUIREMENTS_RESOLVES`, which names it in its words.
1262
1581
  */
1263
- export function requirementPrefixProblems(file: RequirementsFile, builds: readonly CharacterBuild[], plate: boolean): Problem[] {
1582
+ export function requirementPrefixProblems(file: RequirementsFile, builds: readonly CharacterBuild[], plate: boolean, plates: readonly string[] = []): Problem[] {
1264
1583
  const out: Problem[] = [];
1265
1584
  const bare = {
1266
1585
  bone: (b: CharacterBuild) => b.rig.bones.map((x) => x.name).filter((n) => n !== ROOT_BONE),
@@ -1269,7 +1588,7 @@ export function requirementPrefixProblems(file: RequirementsFile, builds: readon
1269
1588
  attachment: (b: CharacterBuild) => Object.values(b.rig.skins.default).flatMap((a) => Object.keys(a)),
1270
1589
  } as const;
1271
1590
  // What the composed rig will hold, by kind: each character's names under its prefix, and the shared root and plate.
1272
- const own = (kind: keyof typeof bare): Set<string> => new Set([...builds.flatMap((b) => bare[kind](b).map((n) => prefixed(b.id, n))), ...(kind === 'bone' ? [ROOT_BONE] : []), ...(plate && kind !== 'constraint' ? [PLATE] : [])]);
1591
+ const own = (kind: keyof typeof bare): Set<string> => new Set([...builds.flatMap((b) => bare[kind](b).map((n) => prefixed(b.id, n))), ...(kind === 'bone' ? [ROOT_BONE] : []), ...(plate && kind !== 'constraint' ? [PLATE] : []), ...(kind !== 'constraint' ? plates : [])]);
1273
1592
  const kinds = {
1274
1593
  bone: { have: own('bone'), bare: bare.bone },
1275
1594
  constraint: { have: own('constraint'), bare: bare.constraint },
@@ -1314,9 +1633,9 @@ export function requirementPrefixProblems(file: RequirementsFile, builds: readon
1314
1633
  * control runs over what `compose` wrote. Each entry is `<where> "<name>"`.
1315
1634
  * Images are held to `<id>.` the same way.
1316
1635
  */
1317
- export function unprefixedNames(rig: RigSpec, motion: MotionSpec, ids: readonly string[], plate: boolean): string[] {
1636
+ export function unprefixedNames(rig: RigSpec, motion: MotionSpec, ids: readonly string[], plate: boolean, plates: readonly string[] = [], sceneAnimations: readonly string[] = []): string[] {
1318
1637
  const bad: string[] = [];
1319
- const ok = (n: string, allowPlate: boolean): boolean => n === ROOT_BONE || (allowPlate && plate && n === PLATE) || ids.some((id) => n.startsWith(`${id}${PREFIX_SEP}`) && n.length > id.length + 1);
1638
+ const ok = (n: string, allowPlate: boolean): boolean => n === ROOT_BONE || (allowPlate && ((plate && n === PLATE) || plates.includes(n))) || ids.some((id) => n.startsWith(`${id}${PREFIX_SEP}`) && n.length > id.length + 1);
1320
1639
  const name = (where: string, n: unknown, allowPlate = true): void => {
1321
1640
  if (typeof n !== 'string' || !ok(n, allowPlate)) bad.push(`${where} ${show(n)}`);
1322
1641
  };
@@ -1335,7 +1654,12 @@ export function unprefixedNames(rig: RigSpec, motion: MotionSpec, ids: readonly
1335
1654
  for (const [a, att] of Object.entries(atts)) {
1336
1655
  name(`skin ${slot} attachment`, a);
1337
1656
  const img = (att as unknown as Attachment).image;
1338
- if (typeof img !== 'string' || !((plate && img === PLATE_IMAGE) || ids.some((id) => img.startsWith(`${id}${IMAGE_SEP}`)))) bad.push(`skin ${slot} ${a} image ${show(img)}`);
1657
+ if (typeof img !== 'string' || !((plate && img === PLATE_IMAGE) || plates.some((_, i) => img === plateImageName(i)) || ids.some((id) => img.startsWith(`${id}${IMAGE_SEP}`)))) bad.push(`skin ${slot} ${a} image ${show(img)}`);
1658
+ const generator = (att as unknown as Attachment).generator;
1659
+ if (isRecord(generator) && isRecord(generator.depth)) {
1660
+ const image = generator.depth.image;
1661
+ if (typeof image !== 'string' || !ids.some(id => image.startsWith(`${id}${IMAGE_SEP}`))) bad.push(`skin ${slot} ${a} depth image ${show(image)}`);
1662
+ }
1339
1663
  const w = (att as unknown as Attachment).weights;
1340
1664
  if (Array.isArray(w)) for (const v of w as Array<Array<{ bone: string }>>) for (const e of v) name(`skin ${slot} ${a} weight bone`, e.bone, false);
1341
1665
  }
@@ -1348,12 +1672,14 @@ export function unprefixedNames(rig: RigSpec, motion: MotionSpec, ids: readonly
1348
1672
  else if (Array.isArray(v)) for (const n of v) name(`constraint ${String(c.name)} ${field}`, n, false);
1349
1673
  }
1350
1674
  if (c.type === 'path') name(`constraint ${String(c.name)} slot`, c.slot, false);
1675
+ if (c.type === 'slider' && c.animation !== 'idle') name(`constraint ${String(c.name)} animation`, c.animation, false);
1351
1676
  }
1352
1677
  for (const s of rig.stops ?? []) {
1353
1678
  name('stop chain', s.chain, false);
1354
1679
  for (const l of s.links) name(`stop ${s.chain} link`, l, false);
1355
1680
  name(`stop ${s.chain} against`, s.against, false);
1356
1681
  }
1682
+ for (const entry of rig.invariants?.deformMayFold ?? []) name('invariants.deformMayFold slot', entry.slot, false);
1357
1683
  for (const d of rig.invariants?.detached ?? []) {
1358
1684
  name('invariants.detached bone', d.bone, false);
1359
1685
  name('invariants.detached notUnder', d.notUnder, false);
@@ -1367,11 +1693,22 @@ export function unprefixedNames(rig: RigSpec, motion: MotionSpec, ids: readonly
1367
1693
  name('group', g, false);
1368
1694
  for (const m of members) name(`group ${g} member`, m, false);
1369
1695
  }
1370
- for (const t of Object.values(animationsOf(motion)).flatMap((a) => a.tracks)) {
1696
+ for (const [animation, a] of Object.entries(animationsOf(motion))) for (const t of a.tracks) {
1371
1697
  const tr = t as unknown as Record<string, unknown>;
1372
- if ('bone' in tr) name('track bone', tr.bone, false);
1698
+ if ('bone' in tr) name('track bone', tr.bone, sceneAnimations.includes(animation));
1373
1699
  if ('group' in tr) name('track group', tr.group, false);
1374
- for (const k of (tr.keys as Array<Record<string, unknown>>) ?? []) if (typeof k.ease === 'string') name('key ease', k.ease, false);
1700
+ for (const k of (tr.keys as Array<Record<string, unknown>>) ?? []) {
1701
+ if (typeof k.ease === 'string') name('key ease', k.ease, false);
1702
+ for (const map of [k.v, isRecord(k.derive) ? k.derive.depth : undefined]) if (isRecord(map)) for (const member of Object.keys(map)) name('key member', member, false);
1703
+ }
1704
+ }
1705
+ for (const [animation, a] of Object.entries(animationsOf(motion))) {
1706
+ if (animation !== 'idle' && !sceneAnimations.includes(animation)) name('animation', animation, false);
1707
+ for (const d of a.deform ?? []) {
1708
+ name('deform slot', d.slot, false);
1709
+ name('deform attachment', d.attachment, false);
1710
+ if (d.skin !== undefined && d.skin !== 'default') bad.push(`deform skin ${show(d.skin)}`);
1711
+ }
1375
1712
  }
1376
1713
  return bad;
1377
1714
  }
@@ -1387,7 +1724,7 @@ export function unprefixedNames(rig: RigSpec, motion: MotionSpec, ids: readonly
1387
1724
  * {@link composeScene} — one refusal naming every problem the
1388
1725
  * files hold. Pure but for the reads.
1389
1726
  */
1390
- export function composeFromFiles(scenePath: string, requirementsPath?: string, mode: PackMode = { pageEdges: DEFAULT_PAGE_EDGES, packShape: DEFAULT_PACK_SHAPE }, accept: readonly string[] = []): ComposedScene {
1727
+ export function composeFromFiles(scenePath: string, requirementsPath?: string, mode: PackMode = { pageEdges: DEFAULT_PAGE_EDGES, packShape: DEFAULT_PACK_SHAPE }, accept: readonly string[] = []): ComposedScene & { runRecord: ComposeRun } {
1391
1728
  const scene = loadScene(scenePath);
1392
1729
  const problems: Problem[] = acceptProblems(accept, '--accept');
1393
1730
  const builds = scene.characters.map((c) => readCharacterBuild(c, problems, accept));
@@ -1405,13 +1742,28 @@ export function composeFromFiles(scenePath: string, requirementsPath?: string, m
1405
1742
  if (!existsSync(scene.plate.imagePath)) problems.push({ code: 'SCENE_PLATE_PRESENT', object: where, detail: `${scene.plate.imagePath} does not exist; a PNG of the canvas's size is required` });
1406
1743
  else {
1407
1744
  try {
1408
- const r = readPng(scene.plate.imagePath);
1409
- plate = { bytes: new Uint8Array(readFileSync(scene.plate.imagePath)), width: r.width, height: r.height };
1745
+ const bytes = new Uint8Array(readFileSync(scene.plate.imagePath));
1746
+ const r = decodePngBytes(bytes, scene.plate.imagePath);
1747
+ plate = { bytes, width: r.width, height: r.height };
1410
1748
  } catch (err) {
1411
1749
  problems.push({ code: 'SCENE_PLATE_PRESENT', object: where, detail: `${(err as Error).message}; a PNG is required` });
1412
1750
  }
1413
1751
  }
1414
1752
  }
1753
+ const plateLayers = (scene.plates ?? []).map((p, i): PlateImage | null => {
1754
+ const where = `scene.plates[${i}]`;
1755
+ const ledger = readEditorReceipts(p.editor_receipts, scene.path, `${where}.editor_receipts`, 'scene file');
1756
+ const codes: Readonly<Record<string, string>> = { ASSEMBLE_EDITOR_RECEIPT_FILE: 'SCENE_EDITOR_RECEIPT_FILE', ASSEMBLE_EDITOR_RECEIPT_SHA256: 'SCENE_EDITOR_RECEIPT_SHA256', ASSEMBLE_EDITOR_RECEIPT_MISSING: 'SCENE_EDITOR_RECEIPT_MISSING' };
1757
+ problems.push(...[...ledger.problems, ...missingReceipts(ledger, [{ object: `${where}.image`, path: p.imagePath }])].map(problem => ({ ...problem, code: codes[problem.code] ?? problem.code })));
1758
+ try {
1759
+ const bytes = new Uint8Array(readFileSync(p.imagePath));
1760
+ const r = decodePngBytes(bytes, `${where}.image`);
1761
+ return { bytes, width: r.width, height: r.height };
1762
+ } catch (err) {
1763
+ problems.push({ code: 'SCENE_PLATE_PRESENT', object: `${where}.image (${p.image})`, detail: `${(err as Error).message}; a PNG is required` });
1764
+ return null;
1765
+ }
1766
+ });
1415
1767
  let req: RequirementsFile | null = null;
1416
1768
  if (requirementsPath !== undefined) {
1417
1769
  try {
@@ -1421,12 +1773,24 @@ export function composeFromFiles(scenePath: string, requirementsPath?: string, m
1421
1773
  problems.push(...err.problems);
1422
1774
  }
1423
1775
  }
1424
- return composeScene(scene, builds, plate, problems, mode, req);
1776
+ const composed = composeScene(scene, builds, plate, problems, mode, req, plateLayers);
1777
+ const runRecord: ComposeRun = {
1778
+ spec: COMPOSE_RUN_SPEC,
1779
+ scene: { path: scenePath, sha256: scene.sha256 },
1780
+ characters: scene.characters.map(c => ({ id: c.id, build: c.build, files: builds.find(b => b?.id === c.id)!.files }))
1781
+ .sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0),
1782
+ plate: scene.plate === null || plate === null ? null : { path: scene.plate.image, sha256: createHash('sha256').update(plate.bytes).digest('hex') },
1783
+ plates: (scene.plates ?? []).map((p, i) => ({ name: p.name, path: p.image, sha256: createHash('sha256').update(plateLayers[i]!.bytes).digest('hex') }))
1784
+ .sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0),
1785
+ };
1786
+ return { ...composed, runRecord };
1425
1787
  }
1426
1788
 
1427
1789
  export interface ComposeInput {
1428
1790
  scene: string;
1429
1791
  out: string;
1792
+ /** The packed builds' `--page-size`; rigc's default when absent (issue #1352). */
1793
+ pageSize?: number;
1430
1794
  requirements?: string;
1431
1795
  /** `--accept`: the bars every character's own check may fail and still be composed (issue #203). */
1432
1796
  accept?: readonly string[];
@@ -1459,6 +1823,8 @@ export interface ComposeResult {
1459
1823
  * first. A crash that is not a refusal is rethrown.
1460
1824
  */
1461
1825
  export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log): ComposeResult {
1826
+ // Clear before even option validation: a refused rerun cannot retain an earlier receipt.
1827
+ clearComposeRun(input.out);
1462
1828
  const prefix = (stage: ComposeStage): Log => (line) => log(`[${stage}] ${line}`);
1463
1829
  const say = prefix('compose');
1464
1830
  const refused = (stage: ComposeStage, err: unknown, composed: ComposedScene | null = null): ComposeResult => {
@@ -1469,11 +1835,12 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
1469
1835
  log(`compose: stopped at ${stage}; nothing ${stage === 'compose' ? 'was written' : 'after the check was written'}`);
1470
1836
  return { stoppedAt: stage, composed, check: null };
1471
1837
  };
1838
+ const pageSize = parsePageSize(input.pageSize);
1472
1839
  mkdirSync(input.out, { recursive: true });
1473
1840
  for (const p of COMPOSE_OWNS) rmSync(join(input.out, p), { recursive: true, force: true });
1474
- const mode: PackMode = { pageEdges: DEFAULT_PAGE_EDGES, packShape: DEFAULT_PACK_SHAPE };
1841
+ const mode: PackMode = { pageEdges: DEFAULT_PAGE_EDGES, packShape: DEFAULT_PACK_SHAPE, ...(pageSize === undefined ? {} : { pageSize }) };
1475
1842
  log(`rig-parts compose: ${input.scene} -> ${input.out}, page edges ${mode.pageEdges}, pack shape ${mode.packShape}`);
1476
- let composed: ComposedScene;
1843
+ let composed: ReturnType<typeof composeFromFiles>;
1477
1844
  try {
1478
1845
  composed = composeFromFiles(input.scene, input.requirements, mode, input.accept ?? []);
1479
1846
  } catch (err) {
@@ -1481,7 +1848,16 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
1481
1848
  }
1482
1849
  const r = composed.report;
1483
1850
  r.scene = input.scene;
1484
- say(`${r.characters.length} character(s) on a ${r.canvas.width}x${r.canvas.height} canvas, rig "${r.rig_name}"${r.plate === null ? ', no plate' : `, plate ${r.plate.image} (provenance ${r.plate.provenance}, judged by nothing)`}`);
1851
+ const namedPlates = r.plates ?? [];
1852
+ const plateClause =
1853
+ r.plate !== null && namedPlates.length > 0
1854
+ ? `, plate ${r.plate.image} (provenance ${r.plate.provenance}, judged by nothing), ${namedPlates.length} named plate(s): ${namedPlates.map((p) => p.name).join(', ')}`
1855
+ : r.plate !== null
1856
+ ? `, plate ${r.plate.image} (provenance ${r.plate.provenance}, judged by nothing)`
1857
+ : namedPlates.length > 0
1858
+ ? `, ${namedPlates.length} named plate(s): ${namedPlates.map((p) => p.name).join(', ')}`
1859
+ : ', no plate';
1860
+ say(`${r.characters.length} character(s) on a ${r.canvas.width}x${r.canvas.height} canvas, rig "${r.rig_name}"${plateClause}`);
1485
1861
  for (const c of r.characters) {
1486
1862
  say(` ${c.id}: ${c.build} at offset [${c.offset.join(', ')}], scale ${c.scale ?? 1}, bounds [${c.bounds.join(', ')}], shift [${c.shift.join(', ')}] on ${c.shifted.bones.length} first-level bone(s), ${c.shifted.root_regions.length} region(s) on root and ${c.shifted.root_weights} weight(s) bound to root; ${c.bones} bone(s), ${c.slots} slot(s), ${c.tracks} track(s), ${c.constraints} constraint(s), rig_scale ${c.rig_scale}, idle ${c.idle_duration} s${c.accepted === undefined ? '' : `; its own check FAILED ${c.accepted.join(', ')}, accepted — the scene is for looking, not shipping`}`);
1487
1863
  }
@@ -1490,7 +1866,16 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
1490
1866
  ['rig.json', rigJsonText(composed.rig)],
1491
1867
  ['motion.json', rigJsonText(composed.motion)],
1492
1868
  ];
1493
- const gate = gateThroughRigc(composed.images, texts, run.rig, run.scratch, mode);
1869
+ let gate: ReturnType<typeof gateThroughRigc>;
1870
+ try {
1871
+ const clips = composed.sceneAnimations;
1872
+ gate = gateThroughRigc(composed.images, texts, run.rig, run.scratch, mode, clips === undefined ? undefined : build => {
1873
+ refuseIfAny(sceneClipLoopProblems(readFileSync(join(build, 'skeleton.model.json'), 'utf8'), clips));
1874
+ });
1875
+ } catch (err) { return refused('compose', err); }
1876
+ if (composed.sceneAnimations !== undefined) for (const g of gate) {
1877
+ g.lines = g.lines.map(line => sceneBoneContext(line, composed.report.characters.map(c => c.id)));
1878
+ }
1494
1879
  for (const g of gate) {
1495
1880
  say(` rigc ${g.label}: exit ${g.status}`);
1496
1881
  for (const l of g.lines) say(` ${l.trim()}`);
@@ -1516,7 +1901,7 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
1516
1901
  say(`wrote ${join(rigDir, 'rig.json')}, motion.json and ${composed.images.length} image(s) under ${join(rigDir, 'images')}, and ${join(input.out, SCENE_REPORT_FILE)}`);
1517
1902
  let report: CheckReport;
1518
1903
  try {
1519
- report = checkStage({ rig: rigDir, out: join(input.out, 'check'), pageEdges: mode.pageEdges, packShape: mode.packShape, ...(input.requirements === undefined ? {} : { requirements: input.requirements }) }, run.check, run.checkBin, prefix('check'));
1904
+ report = checkStage({ rig: rigDir, out: join(input.out, 'check'), pageEdges: mode.pageEdges, packShape: mode.packShape, ...(pageSize === undefined ? {} : { pageSize }), ...(input.requirements === undefined ? {} : { requirements: input.requirements }) }, run.check, run.checkBin, prefix('check'));
1520
1905
  } catch (err) {
1521
1906
  return refused('check', err, composed);
1522
1907
  }
@@ -1532,6 +1917,7 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
1532
1917
  log(`compose: stopped at check; the composed rig's check is PASS${acceptedLine} (the composed rig and scene.json are written; the scene is for looking, not shipping)`);
1533
1918
  return { stoppedAt: 'check', composed, check: report };
1534
1919
  }
1920
+ writeFileSync(join(input.out, COMPOSE_RUN_FILE), rigJsonText(composed.runRecord));
1535
1921
  log(`compose: PASS — ${report.bars.measured.length} of ${report.bars.measured.length + report.bars.skipped.length} bar(s) measured; the packed atlas under ${join(input.out, 'check', 'build')} is the artifact`);
1536
1922
  return { stoppedAt: null, composed, check: report };
1537
1923
  }