rig-parts 2.61.0 → 2.63.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
@@ -105,21 +105,25 @@
105
105
  import { createHash } from 'node:crypto';
106
106
  import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
107
107
  import { dirname, join, resolve } from 'node:path';
108
+ import { documentPageLookup, readModel, type ModelPageRegion } from '@rig-c/core/core';
109
+ import { CandidateAtlasError, CandidatePairError, CoreInputError, loadCandidate, PoserChoiceError, projector, renderFrame, SpineRuntimeError, throughPoser, type Piece, type Quad, type Viewport } from '@rig-c/core/render-shared';
108
110
  import { deformSliderCombinationProblem, type RigStop } from '@rig-c/core/rig';
109
111
  import { checkStage, gateThroughRigc, type Log } from './build.ts';
110
- import { ACCEPTABLE_BARS, barsNotMet, CHECK_SPEC, type CheckReport, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, type PackMode, parsePageSize, requirementsNotPass, type RigcRunner } from './check.ts';
112
+ import { ACCEPTABLE_BARS, barsNotMet, CHECK_SPEC, type CheckReport, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, IDLE_FPS, LOOP_SEAM_BAR_UNMET, type LoopSeamRequest, type PackMode, parsePageSize, requirementsNotPass, type RigcRunner } from './check.ts';
111
113
  import { CONSTRAINT_BONE_FIELDS, editorReceiptProblems, ROOT_BONE } from './config.ts';
112
114
  import { cropToSpineY } from './coords.ts';
113
115
  import { failLine, PartsError, type Problem, refuseIfAny } from './errors.ts';
114
116
  import { readParts } from './parts.ts';
115
117
  import { missingReceipts, readEditorReceipts, type EditorReceipts } from './editreceipt.ts';
118
+ import { edgeLength } from './length.ts';
116
119
  import type { MotionSpec } from './motion.ts';
117
120
  import { decodePngBytes } from './raster/png.ts';
121
+ import type { Raster } from './raster/types.ts';
118
122
  import { clearComposeRun, COMPOSE_RUN_FILE, COMPOSE_RUN_SPEC, type ComposeRun, type RunStampFileEntry } from './runstamp.ts';
119
123
  import { readRequirements, type RequirementsFile } from './requirements.ts';
120
124
  import { OFFSET_PLACES, rigJsonText, type RigSpec } from './rig.ts';
121
125
  import { pyRound } from './round.ts';
122
- import { mergeSceneAnimations, readSceneAnimations, sceneBoneContext, sceneClipLoopProblems, sceneRepeatSourceLoopProblems, type SceneAnimations, type ScenePlacementPivot } from './sceneclips.ts';
126
+ import { mergeSceneAnimations, readSceneAnimations, readSceneCamera, resolveSceneCamera, sceneBoneContext, sceneClipLoopProblems, sceneRepeatSourceLoopProblems, type ResolvedSceneCamera, type ResolvedSceneCameraTrack, type SceneAnimations, type SceneCamera, type SceneCameraSample, type ScenePlacementPivot } from './sceneclips.ts';
123
127
  import { repeatSceneKeys } from './scenerepeat.ts';
124
128
 
125
129
  /** The scene file's `spec`. */
@@ -127,6 +131,7 @@ export const SCENE_SPEC = 'spine-parts-scene/1';
127
131
 
128
132
  /** `scene.json`'s `spec`: what `compose` writes beside its outputs. */
129
133
  export const SCENE_REPORT_SPEC = 'spine-parts-scene-report/1';
134
+ export const SCENE_CAMERA_REPORT_SPEC = 'spine-parts-scene-report/2';
130
135
 
131
136
  /** The file `compose` writes beside `rig/` and `check/`. */
132
137
  export const SCENE_REPORT_FILE = 'scene.json';
@@ -210,6 +215,7 @@ export interface SceneFile {
210
215
  plate: ScenePlate | null;
211
216
  plates?: NamedScenePlate[];
212
217
  animations?: SceneAnimations;
218
+ camera?: SceneCamera;
213
219
  characters: SceneCharacter[];
214
220
  order: string[];
215
221
  }
@@ -283,6 +289,7 @@ export function loadScene(path: string): SceneFile {
283
289
  }
284
290
  if (!isRecord(raw)) refuseIfAny([{ code: 'SCENE_FILE', object: at, detail: `is ${show(raw)}; a JSON object is required` }]);
285
291
  const o = raw as Record<string, unknown>;
292
+ const { camera: rawCamera, ...fields } = o;
286
293
  const base = dirname(at);
287
294
  const problems: Problem[] = [];
288
295
  const fail = (code: string, object: string, detail: string): void => {
@@ -293,7 +300,7 @@ export function loadScene(path: string): SceneFile {
293
300
  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)`);
294
301
  }
295
302
  };
296
- known(o, 'scene', ['spec', 'canvas', 'plate', 'plates', 'characters', 'order', 'animations']);
303
+ known(fields, 'scene', ['spec', 'canvas', 'plate', 'plates', 'characters', 'order', 'animations']);
297
304
  if (o.spec !== SCENE_SPEC) fail('SCENE_SPEC', 'scene.spec', `is ${show(o.spec)}; "${SCENE_SPEC}" is required`);
298
305
 
299
306
  // canvas
@@ -475,13 +482,21 @@ export function loadScene(path: string): SceneFile {
475
482
  problems.push(...err.problems);
476
483
  }
477
484
  }
485
+ let camera: SceneCamera | undefined;
486
+ if ('camera' in o) {
487
+ try { camera = readSceneCamera(rawCamera); }
488
+ catch (err) {
489
+ if (!(err instanceof PartsError)) throw err;
490
+ problems.push(...err.problems);
491
+ }
492
+ }
478
493
  if (!(isRecord(o.animations) && Object.hasOwn(o.animations, 'idle'))) {
479
494
  for (const c of characters) if (c.idle_repeats !== undefined) {
480
495
  fail('SCENE_REPEAT_IDLE_REQUIRED', 'scene.animations.idle', `is absent for character ${show(c.id)} with idle_repeats ${c.idle_repeats}. Declare the scene idle and its duration`);
481
496
  }
482
497
  }
483
498
  refuseIfAny(problems);
484
- return { path: at, sha256, canvas, plate, ...('plates' in o ? { plates } : {}), ...(animations === undefined ? {} : { animations }), characters, order };
499
+ return { path: at, sha256, canvas, plate, ...('plates' in o ? { plates } : {}), ...(animations === undefined ? {} : { animations }), ...(camera === undefined ? {} : { camera }), characters, order };
485
500
  }
486
501
 
487
502
  // ---------------------------------------------------------------------------
@@ -1115,6 +1130,146 @@ export function sceneStage(canvas: SceneFile['canvas']): RigSpec['skeleton'] {
1115
1130
  return { x: -canvas.width / 2, y: 0, width: canvas.width, height: canvas.height };
1116
1131
  }
1117
1132
 
1133
+ type CameraPoint = [number, number];
1134
+ type CameraBox = [number, number, number, number];
1135
+
1136
+ interface CameraFrameReport {
1137
+ frame: number;
1138
+ compiled_time: number;
1139
+ authored_time: number;
1140
+ pan: CameraPoint;
1141
+ zoom: number;
1142
+ /** View and posed backdrop corners in scene pixels, x right and y down. */
1143
+ view: CameraBox;
1144
+ backdrop_quad: CameraPoint[];
1145
+ figures: Array<{ id: string; bounds: CameraBox | null; clipped_bounds: CameraBox | null; canvas_clipped: boolean; clip_slots: string[] }>;
1146
+ }
1147
+
1148
+ interface SceneCameraReport {
1149
+ backdrop: string;
1150
+ model_sha256: string;
1151
+ fps: number;
1152
+ coverage: { status: 'PASS'; max_edge_overrun_px: 0; nonopaque_source_texels: 0; nonopaque_output_pixels: 0 };
1153
+ tracks: Record<string, { keys: ResolvedSceneCameraTrack['keys']; duration: number; compiled_duration: number; loop: boolean; frames: CameraFrameReport[] }>;
1154
+ }
1155
+
1156
+ function cameraViewport(stage: RigSpec['skeleton'], { pan, zoom }: { pan: readonly [number, number]; zoom: number }): Viewport | null {
1157
+ const { width, height } = stage;
1158
+ const cx = stage.x + width / 2 + pan[0];
1159
+ const cy = stage.y + cropToSpineY(height / 2 + pan[1], height);
1160
+ const halfWidth = width / zoom / 2;
1161
+ const halfHeight = height / zoom / 2;
1162
+ const minX = cx - halfWidth, maxX = cx + halfWidth;
1163
+ const minY = cy - halfHeight, maxY = cy + halfHeight;
1164
+ const outputWidth = (maxX - minX) * zoom, outputHeight = (maxY - minY) * zoom;
1165
+ if (![minX, maxX, minY, maxY, zoom, outputWidth, outputHeight].every(Number.isFinite) || zoom <= 0 || outputWidth <= 0 || outputHeight <= 0) return null;
1166
+ return { minX, minY, maxX, maxY, scale: zoom, width, height };
1167
+ }
1168
+
1169
+ function cameraPoint(x: number, y: number, stage: RigSpec['skeleton']): CameraPoint {
1170
+ return [x - stage.x, cropToSpineY(y - stage.y, stage.height)];
1171
+ }
1172
+
1173
+ function cameraCorners(view: Viewport): CameraPoint[] {
1174
+ const { minX, minY, maxX, maxY } = view;
1175
+ return [[minX, minY], [minX, maxY], [maxX, maxY], [maxX, minY]];
1176
+ }
1177
+
1178
+ function backdropQuad(piece: Quad, region: ModelPageRegion): { corners: CameraPoint[]; determinant: number } | null {
1179
+ if (piece.world.length !== 8 || !piece.world.every(Number.isFinite)) return null;
1180
+ const [blx, bly, tlx, tly, trx, topRightY, brx, bry] = piece.world;
1181
+ const posed: CameraPoint[] = [[blx, bly], [tlx, tly], [trx, topRightY], [brx, bry]];
1182
+ // The poser gives the packed quad, whose vertices retain the art's order
1183
+ // even when the packing turns it on the page. Extend a trimmed quad into
1184
+ // its authored image space so transparent trim is tested as alpha.
1185
+ const { offsetX, offsetY, width, height, originalWidth, originalHeight } = region;
1186
+ const corners = offsetX === 0 && offsetY === 0 && width === originalWidth && height === originalHeight ? posed :
1187
+ ([[0, 0], [0, originalHeight], [originalWidth, originalHeight], [originalWidth, 0]] as CameraPoint[])
1188
+ .map(([x, y]): CameraPoint => {
1189
+ const u = (x - offsetX) / width, v = (y - offsetY) / height;
1190
+ return [blx + u * (brx - blx) + v * (tlx - blx), bly + u * (bry - bly) + v * (tly - bly)];
1191
+ });
1192
+ const [bottomLeft, topLeft, , bottomRight] = corners;
1193
+ const determinant = (bottomRight[0] - bottomLeft[0]) * (topLeft[1] - bottomLeft[1])
1194
+ - (bottomRight[1] - bottomLeft[1]) * (topLeft[0] - bottomLeft[0]);
1195
+ if (!Number.isFinite(determinant) || determinant === 0 || !corners.flat().every(Number.isFinite)) return null;
1196
+ return { corners, determinant };
1197
+ }
1198
+
1199
+ function cameraEdgeOverruns(view: CameraPoint[], corners: CameraPoint[], determinant: number): Array<{ side: string; overrun: number }> {
1200
+ // The viewport and Core's posed corners arrive by different double-precision
1201
+ // calculations. Cancel the rounding of flush coordinates before measuring
1202
+ // distance. Packed opacity still uses the unmodified viewport and geometry.
1203
+ const precision = 4 * Number.EPSILON * Math.max(1, ...[...view, ...corners].flat().map(Math.abs));
1204
+ return ['left', 'top', 'right', 'bottom'].map((side, i) => {
1205
+ const [x, y] = corners[i];
1206
+ const [nextX, nextY] = corners[(i + 1) % corners.length];
1207
+ const dx = nextX - x, dy = nextY - y;
1208
+ // The region order is bottom-left, top-left, top-right, bottom-right in
1209
+ // art space. The determinant keeps the outside sign under reflections.
1210
+ const distances = view.map(([vx, vy]) => dx * (vy - y) - dy * (vx - x));
1211
+ const overrun = Math.max(0, ...distances.map(d => Math.sign(determinant) * d)) / edgeLength(dx, dy);
1212
+ return { side, overrun: overrun <= precision ? 0 : overrun };
1213
+ });
1214
+ }
1215
+
1216
+ /** Test the loose art's nonzero bilinear support against the entire inverse view. */
1217
+ function nonopaqueSourceTexel(art: Raster, view: Viewport, window: CameraPoint[], quad: CameraPoint[], det: number): { x: number; y: number; alpha: number } | null {
1218
+ const [bottomLeft, topLeft, , bottomRight] = quad;
1219
+ const [ox, oy] = bottomLeft;
1220
+ const [ax, ay] = [bottomRight[0] - ox, bottomRight[1] - oy];
1221
+ const [bx, by] = [topLeft[0] - ox, topLeft[1] - oy];
1222
+ const artWindow = window.map(([x, y]) => {
1223
+ const dx = x - ox, dy = y - oy;
1224
+ return [(dx * by - dy * bx) / det * art.width, cropToSpineY((ax * dy - ay * dx) / det * art.height, art.height)];
1225
+ });
1226
+ const x0 = Math.min(...artWindow.map(p => p[0])), x1 = Math.max(...artWindow.map(p => p[0]));
1227
+ const y0 = Math.min(...artWindow.map(p => p[1])), y1 = Math.max(...artWindow.map(p => p[1]));
1228
+ // A texel center contributes at distances strictly below one texel. A
1229
+ // clamped image-edge tap obeys the same bound on this in-image view.
1230
+ // Test the four separating axes in art and world coordinates so rotated
1231
+ // views do not count defects in empty corners of the bounding box.
1232
+ const radiusX = Math.abs(ax / art.width) + Math.abs(bx / art.height);
1233
+ const radiusY = Math.abs(ay / art.width) + Math.abs(by / art.height);
1234
+ for (let y = Math.max(0, Math.floor(y0 - 1)); y < Math.min(art.height, Math.ceil(y1 + 1)); y++) {
1235
+ for (let x = Math.max(0, Math.floor(x0 - 1)); x < Math.min(art.width, Math.ceil(x1 + 1)); x++) {
1236
+ const alpha = art.data[(y * art.width + x) * 4 + 3];
1237
+ if (alpha === 255 || x + 1.5 <= x0 || x - 0.5 >= x1 || y + 1.5 <= y0 || y - 0.5 >= y1) continue;
1238
+ const s = (x + 0.5) / art.width;
1239
+ const t = cropToSpineY(y + 0.5, art.height) / art.height;
1240
+ const wx = ox + s * ax + t * bx, wy = oy + s * ay + t * by;
1241
+ if (wx + radiusX > view.minX && wx - radiusX < view.maxX && wy + radiusY > view.minY && wy - radiusY < view.maxY) return { x, y, alpha };
1242
+ }
1243
+ }
1244
+ return null;
1245
+ }
1246
+
1247
+ function cameraFigureBounds(pieces: readonly Piece[], view: Viewport, ids: readonly string[], owners: ReadonlyMap<string, string>, object: string): CameraFrameReport['figures'] {
1248
+ const project = projector(view);
1249
+ const figures: CameraFrameReport['figures'] = ids.map(id => ({ id, bounds: null, clipped_bounds: null, canvas_clipped: false, clip_slots: [] }));
1250
+ const byId = new Map(figures.map(row => [row.id, row]));
1251
+ for (const piece of pieces) {
1252
+ const id = owners.get(piece.slot);
1253
+ const row = id === undefined ? undefined : byId.get(id);
1254
+ if (row === undefined) continue;
1255
+ if (piece.kind === 'mesh' && piece.source !== undefined) row.clip_slots.push(piece.slot);
1256
+ for (let i = 0; i < piece.world.length; i += 2) {
1257
+ const [x, y] = project(piece.world[i], piece.world[i + 1]);
1258
+ if (!Number.isFinite(x) || !Number.isFinite(y)) cameraProblem('SCENE_CAMERA_TRACK', object,
1259
+ `figure slot ${show(piece.slot)} projects to [${x}, ${y}]; finite output coordinates are required`);
1260
+ const b = row.bounds;
1261
+ row.bounds = b === null ? [x, y, x, y] : [Math.min(x, b[0]), Math.min(y, b[1]), Math.max(x, b[2]), Math.max(y, b[3])];
1262
+ }
1263
+ }
1264
+ for (const row of figures) if (row.bounds !== null) {
1265
+ const [x0, y0, x1, y1] = row.bounds;
1266
+ row.canvas_clipped = x0 < 0 || y0 < 0 || x1 > view.width || y1 > view.height;
1267
+ const clipped: CameraBox = [Math.max(0, x0), Math.max(0, y0), Math.min(view.width, x1), Math.min(view.height, y1)];
1268
+ if (clipped[0] < clipped[2] && clipped[1] < clipped[3]) row.clipped_bounds = clipped;
1269
+ }
1270
+ return figures;
1271
+ }
1272
+
1118
1273
  /** One character's row of `scene.json`. */
1119
1274
  export interface SceneCharacterReport {
1120
1275
  id: string;
@@ -1145,7 +1300,7 @@ export interface SceneCharacterReport {
1145
1300
  accepted?: string[];
1146
1301
  }
1147
1302
 
1148
- export interface SceneReport {
1303
+ interface SceneReportV1 {
1149
1304
  spec: typeof SCENE_REPORT_SPEC;
1150
1305
  scene: string;
1151
1306
  canvas: { width: number; height: number };
@@ -1159,6 +1314,11 @@ export interface SceneReport {
1159
1314
  idle_duration: number;
1160
1315
  }
1161
1316
 
1317
+ export type SceneReport = SceneReportV1 | (Omit<SceneReportV1, 'spec'> & {
1318
+ spec: typeof SCENE_CAMERA_REPORT_SPEC;
1319
+ camera: SceneCameraReport;
1320
+ });
1321
+
1162
1322
  export interface ComposedScene {
1163
1323
  rig: RigSpec;
1164
1324
  motion: MotionSpec;
@@ -1167,6 +1327,7 @@ export interface ComposedScene {
1167
1327
  report: SceneReport;
1168
1328
  /** Opt-in declaration retained for pre-emission pose measurement; never serialized. */
1169
1329
  sceneAnimations?: SceneAnimations;
1330
+ sceneCamera?: ResolvedSceneCamera;
1170
1331
  }
1171
1332
 
1172
1333
  /** The plate image's bytes and size, read by the caller. */
@@ -1176,6 +1337,168 @@ export interface PlateImage {
1176
1337
  height: number;
1177
1338
  }
1178
1339
 
1340
+ interface CameraEvidence {
1341
+ report: SceneCameraReport;
1342
+ files: ReadonlyMap<string, string>;
1343
+ }
1344
+
1345
+ const CAMERA_MODEL = 'skeleton.model.json';
1346
+ const CAMERA_DRAW = { subset: undefined, unclipped: false, texture: false, regionInfo: true };
1347
+
1348
+ function cameraProblem(code: string, object: string, detail: string): never {
1349
+ throw new PartsError([{ code, object, detail }]);
1350
+ }
1351
+
1352
+ function packedFileHash(build: string, file: string): string {
1353
+ const path = join(build, file);
1354
+ if (!existsSync(path)) cameraProblem('SCENE_CAMERA_BACKDROP', 'check/build', `${show(file)} is absent; the camera requires the complete green packed artifact`);
1355
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
1356
+ }
1357
+
1358
+ function measureSceneCamera(build: string, composed: ComposedScene, camera: ResolvedSceneCamera): CameraEvidence {
1359
+ const stage = composed.rig.skeleton;
1360
+ const ids = composed.report.characters.map(c => c.id);
1361
+ const layerNames = new Set([PLATE, ...(composed.report.plates ?? []).map(p => p.slot)]);
1362
+ const owners = new Map(composed.rig.slots.filter(s => !layerNames.has(s.name)).map(s => [s.name, s.name.slice(0, s.name.indexOf(PREFIX_SEP))]));
1363
+ const slot = camera.backdrop;
1364
+ const image = slot === PLATE ? PLATE_IMAGE : plateImageName((composed.report.plates ?? []).findIndex(p => p.slot === slot));
1365
+ const bytes = composed.images.find(([file]) => file === image)?.[1];
1366
+ if (bytes === undefined) cameraProblem('SCENE_CAMERA_BACKDROP', 'scene.camera.backdrop', `${show(slot)} has no composed plate image; its exact loose pixels are required`);
1367
+ const art = decodePngBytes(bytes, image);
1368
+ const artHasAlpha = art.data.some((value, i) => i % 4 === 3 && value < 255);
1369
+ const region = image.slice(0, -'.png'.length);
1370
+ const skel = 'skeleton.json';
1371
+ const atlas = 'skeleton.atlas';
1372
+ const files = new Map([CAMERA_MODEL, skel, atlas].map(file => [file, packedFileHash(build, file)]));
1373
+ const skeleton = join(build, skel);
1374
+ const atlasPath = join(build, atlas);
1375
+ const trackReports: Array<[string, SceneCameraReport['tracks'][string]]> = [];
1376
+ const problems: Problem[] = [];
1377
+ let object = 'scene.camera.backdrop';
1378
+ try {
1379
+ const modelPath = join(build, CAMERA_MODEL);
1380
+ const packedModel = readModel(readFileSync(modelPath, 'utf8'), modelPath);
1381
+ const binding = documentPageLookup(packedModel.pages ?? [])(region);
1382
+ if (binding === null || binding.region.originalWidth !== art.width || binding.region.originalHeight !== art.height) {
1383
+ cameraProblem('SCENE_CAMERA_BACKDROP', object, `slot ${show(slot)} needs packed region ${show(region)} over its ${art.width}x${art.height} source image`);
1384
+ }
1385
+ const candidate = loadCandidate({ skeletonText: readFileSync(skeleton, 'utf8'), atlasText: readFileSync(atlasPath, 'utf8'), atlasDir: build, label: 'scene camera' }, { skeleton, atlas: atlasPath }, 'core');
1386
+ if (candidate.choice.core === null) cameraProblem('SCENE_CAMERA_BACKDROP', object, `the packed artifact cannot be read by the Core poser: ${candidate.choice.why}`);
1387
+ for (const page of candidate.pages.keys()) files.set(page, packedFileHash(build, page));
1388
+ throughPoser(candidate.choice, poser => {
1389
+ for (const [name, track] of camera.tracks) {
1390
+ const field = `scene.camera.tracks[${show(name)}]`;
1391
+ object = field;
1392
+ const compiledDuration = poser.animations.find(animation => animation.name === name)?.duration;
1393
+ if (compiledDuration === undefined || !Number.isFinite(compiledDuration) || compiledDuration < 0 || (compiledDuration === 0) !== (track.duration === 0)) {
1394
+ problems.push({ code: 'SCENE_CAMERA_TRACK', object: field, detail: `compiled duration ${String(compiledDuration)} s cannot map to the authored ${track.duration} s take` });
1395
+ continue;
1396
+ }
1397
+ const ticks = Math.ceil(track.duration * IDLE_FPS);
1398
+ // The poser takes a JavaScript array of times, including the closing pose.
1399
+ if (ticks >= 0xffffffff) {
1400
+ problems.push({ code: 'SCENE_CAMERA_TRACK', object: field, detail: `authored duration ${track.duration} s cannot fit a ${IDLE_FPS} fps pose schedule with its endpoint` });
1401
+ continue;
1402
+ }
1403
+ const authoredTimes = [0];
1404
+ for (let i = 1; i < ticks && i / IDLE_FPS < track.duration; i++) authoredTimes.push(i / IDLE_FPS);
1405
+ if (track.duration > 0) authoredTimes.push(track.duration);
1406
+ // Keep authored ticks exact, including keys on that grid. Both the camera
1407
+ // and the packed pose read the same phase at their own clock precision.
1408
+ const times = authoredTimes.map(time => time === track.duration ? compiledDuration : time / track.duration * compiledDuration);
1409
+ const frames: CameraFrameReport[] = [];
1410
+ // The track remains unwrapped through the closing pose, with one
1411
+ // physics clock stepping the entire schedule, including a short end step.
1412
+ poser.animation(name, undefined, IDLE_FPS, times.length - 1, (index, posed) => {
1413
+ const time = times[index];
1414
+ const authored = authoredTimes[index];
1415
+ object = `${field} frame ${index} (t=${time} s, authored ${authored} s)`;
1416
+ const fail = (code: string, detail: string): void => { problems.push({ code, object, detail }); };
1417
+ let sample: SceneCameraSample;
1418
+ try { sample = track.sample(authored); }
1419
+ catch (err) {
1420
+ if (!(err instanceof PartsError)) throw err;
1421
+ for (const problem of err.problems) fail(problem.code, problem.detail);
1422
+ return;
1423
+ }
1424
+ const view = cameraViewport(stage, sample);
1425
+ if (view === null) {
1426
+ fail('SCENE_CAMERA_TRACK', `evaluated pan ${show(sample.pan)} and zoom ${sample.zoom}; a finite, positive, noncollapsed view is required`);
1427
+ return;
1428
+ }
1429
+ const pieces = posed.pieces(CAMERA_DRAW);
1430
+ const at = pieces.findIndex(piece => piece.slot === slot);
1431
+ const plate = pieces[at];
1432
+ const name = show(slot);
1433
+ if (plate === undefined) {
1434
+ fail('SCENE_CAMERA_BACKDROP', `slot ${name} is absent; its bound region must draw behind the figure`);
1435
+ return;
1436
+ }
1437
+ if (plate.kind !== 'region') {
1438
+ fail('SCENE_CAMERA_BACKDROP', `slot ${name} ${plate.source === undefined ? 'draws a mesh' : 'is cut by clipping'}; an uncut bound region is required`);
1439
+ return;
1440
+ }
1441
+ const info = plate.regionInfo;
1442
+ if (info === undefined || info.attachment !== slot || info.region !== region || plate.page !== binding.page.name) {
1443
+ fail('SCENE_CAMERA_BACKDROP', `slot ${name} draws ${show(info)}; attachment ${name} and packed region ${show(region)} on ${show(binding.page.name)} are required`);
1444
+ return;
1445
+ }
1446
+ const front = pieces.slice(0, at).find(piece => owners.has(piece.slot) && piece.world.length > 0);
1447
+ if (front !== undefined) {
1448
+ fail('SCENE_CAMERA_BACKDROP', `slot ${name} draws after figure slot ${show(front.slot)}; it must draw behind the figure`);
1449
+ return;
1450
+ }
1451
+ const quad = backdropQuad(plate, binding.region);
1452
+ if (quad === null) {
1453
+ fail('SCENE_CAMERA_BACKDROP', `slot ${name} has nonfinite or degenerate posed corners; a finite drawable quad is required`);
1454
+ return;
1455
+ }
1456
+ const window = cameraCorners(view);
1457
+ const over = cameraEdgeOverruns(window, quad.corners, quad.determinant).filter(edge => edge.overrun !== 0);
1458
+ if (over.length > 0) {
1459
+ for (const edge of over) fail('SCENE_CAMERA_PLATE_EDGE', `slot ${name} ${edge.side} edge overrun ${edge.overrun} scene px; 0 is required`);
1460
+ return;
1461
+ }
1462
+ const source = artHasAlpha ? nonopaqueSourceTexel(art, view, window, quad.corners, quad.determinant) : null;
1463
+ if (source !== null) fail('SCENE_CAMERA_PLATE_ALPHA', `slot ${name} samples source texel [${source.x}, ${source.y}] with alpha ${source.alpha}; 255 is required throughout the view footprint`);
1464
+ const backdrop = renderFrame({ index, time, pieces: [plate] }, candidate.pages, view, [0, 0, 0, 0]);
1465
+ let nonopaque = 0;
1466
+ let minAlpha = 255;
1467
+ for (let i = 3; i < backdrop.data.length; i += 4) {
1468
+ const alpha = backdrop.data[i];
1469
+ if (alpha < 255) nonopaque++;
1470
+ minAlpha = Math.min(minAlpha, alpha);
1471
+ }
1472
+ if (plate.tint[3] !== 1 || nonopaque > 0) {
1473
+ fail('SCENE_CAMERA_PLATE_ALPHA', `slot ${name} tint alpha ${plate.tint[3]}, ${nonopaque} nonopaque packed output pixel(s), minimum alpha ${minAlpha}; tint 1 and every pixel 255 are required`);
1474
+ }
1475
+ const [x0, y0] = cameraPoint(view.minX, view.maxY, stage);
1476
+ const [x1, y1] = cameraPoint(view.maxX, view.minY, stage);
1477
+ frames.push({
1478
+ frame: index, compiled_time: time, authored_time: authored, pan: sample.pan, zoom: sample.zoom,
1479
+ view: [x0, y0, x1, y1], backdrop_quad: quad.corners.map(([x, y]) => cameraPoint(x, y, stage)),
1480
+ figures: cameraFigureBounds(pieces, view, ids, owners, object),
1481
+ });
1482
+ }, undefined, undefined, times);
1483
+ trackReports.push([name, { keys: track.keys, duration: track.duration, compiled_duration: compiledDuration, loop: track.loop, frames }]);
1484
+ }
1485
+ });
1486
+ } catch (err) {
1487
+ if (!(err instanceof CandidateAtlasError || err instanceof CandidatePairError || err instanceof CoreInputError || err instanceof PoserChoiceError || err instanceof SpineRuntimeError)) throw err;
1488
+ problems.push({ code: 'SCENE_CAMERA_BACKDROP', object, detail: `the packed pose could not be read: ${err.message}` });
1489
+ }
1490
+ refuseIfAny(problems);
1491
+ const modelSha256 = files.get(CAMERA_MODEL)!;
1492
+ return {
1493
+ files,
1494
+ report: {
1495
+ backdrop: slot, model_sha256: modelSha256, fps: IDLE_FPS,
1496
+ coverage: { status: 'PASS', max_edge_overrun_px: 0, nonopaque_source_texels: 0, nonopaque_output_pixels: 0 },
1497
+ tracks: Object.fromEntries(trackReports),
1498
+ },
1499
+ };
1500
+ }
1501
+
1179
1502
  type Attachment = Record<string, unknown>;
1180
1503
 
1181
1504
  /**
@@ -1231,6 +1554,9 @@ export function composeScene(
1231
1554
 
1232
1555
  const layers = scene.plates ?? [];
1233
1556
  const layerNames = new Set(layers.map(p => p.name));
1557
+ if (scene.camera !== undefined && !(scene.camera.backdrop === PLATE ? scene.plate !== null : layerNames.has(scene.camera.backdrop))) {
1558
+ fail('SCENE_CAMERA_BACKDROP', 'scene.camera.backdrop', `selects ${show(scene.camera.backdrop)}; the legacy plate or a declared named plate is required`);
1559
+ }
1234
1560
  const reserved = new Set([ROOT_BONE, PLATE, 'idle', ...ids, ...generatedBones, ...ready.flatMap(b => [
1235
1561
  ...b.rig.bones.map(x => prefixed(b.id, x.name)),
1236
1562
  ...b.rig.slots.map(x => prefixed(b.id, x.name)),
@@ -1825,6 +2151,14 @@ export function composeScene(
1825
2151
  refuseIfAny(problems);
1826
2152
  }
1827
2153
  if (scene.animations !== undefined || pivots.size > 0) mergeSceneAnimations(rig, motion, scene.animations ?? {}, [...pivots.values()]);
2154
+ const sceneCamera = scene.camera === undefined ? undefined : resolveSceneCamera(scene.camera, motion);
2155
+ if (sceneCamera !== undefined) {
2156
+ for (const [name, track] of sceneCamera.tracks) for (const key of track.keys) {
2157
+ if (cameraViewport(stage, key) === null) fail('SCENE_CAMERA_TRACK', `scene.camera.tracks[${show(name)}]`,
2158
+ `key at ${key.t} s has pan ${show(key.pan)} and zoom ${key.zoom}; a finite, positive, noncollapsed view is required`);
2159
+ }
2160
+ refuseIfAny(problems);
2161
+ }
1828
2162
 
1829
2163
  const report: SceneReport = {
1830
2164
  spec: SCENE_REPORT_SPEC,
@@ -1841,7 +2175,7 @@ export function composeScene(
1841
2175
  order: { declared: [...scene.order], slots: slots.map((s) => s.name), judged_by: 'nothing' },
1842
2176
  idle_duration: idleDuration,
1843
2177
  };
1844
- return { rig, motion, images, report, ...(scene.animations === undefined ? {} : { sceneAnimations: scene.animations }) };
2178
+ return { rig, motion, images, report, ...(scene.animations === undefined ? {} : { sceneAnimations: scene.animations }), ...(sceneCamera === undefined ? {} : { sceneCamera }) };
1845
2179
  }
1846
2180
 
1847
2181
  // ---------------------------------------------------------------------------
@@ -2078,6 +2412,8 @@ export interface ComposeInput {
2078
2412
  /** The packed builds' `--page-size`; rigc's default when absent (issue #1352). */
2079
2413
  pageSize?: number;
2080
2414
  requirements?: string;
2415
+ /** Declared RGBA loop seam bar and warm-up cap for the composed idle render (issue #1590). */
2416
+ loopSeam?: LoopSeamRequest;
2081
2417
  /** `--accept`: the bars every character's own check may fail and still be composed (issue #203). */
2082
2418
  accept?: readonly string[];
2083
2419
  }
@@ -2116,7 +2452,10 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
2116
2452
  const refused = (stage: ComposeStage, err: unknown, composed: ComposedScene | null = null): ComposeResult => {
2117
2453
  if (!(err instanceof PartsError)) throw err;
2118
2454
  const p = prefix(stage);
2119
- for (const x of err.problems) p(failLine(x));
2455
+ for (const x of err.problems) {
2456
+ if (x.code === LOOP_SEAM_BAR_UNMET) log(x.detail);
2457
+ else p(failLine(x));
2458
+ }
2120
2459
  p(`refused: ${err.problems.length} problem(s)`);
2121
2460
  log(`compose: stopped at ${stage}; nothing ${stage === 'compose' ? 'was written' : 'after the check was written'}`);
2122
2461
  return { stoppedAt: stage, composed, check: null };
@@ -2162,12 +2501,33 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
2162
2501
  ['rig.json', rigJsonText(composed.rig)],
2163
2502
  ['motion.json', rigJsonText(composed.motion)],
2164
2503
  ];
2504
+ const camera = composed.sceneCamera;
2505
+ const gated: { camera?: CameraEvidence } = {};
2165
2506
  let gate: ReturnType<typeof gateThroughRigc>;
2166
2507
  try {
2167
2508
  const clips = composed.sceneAnimations;
2168
- gate = gateThroughRigc(composed.images, texts, run.rig, run.scratch, mode, clips === undefined ? undefined : build => {
2509
+ const readLoop = (build: string): void => {
2510
+ if (clips === undefined) return;
2169
2511
  refuseIfAny(sceneClipLoopProblems(readFileSync(join(build, 'skeleton.model.json'), 'utf8'), clips, r.characters.some(c => c.idle_repeats !== undefined)));
2170
- });
2512
+ };
2513
+ if (camera === undefined) {
2514
+ gate = gateThroughRigc(composed.images, texts, run.rig, run.scratch, mode, clips === undefined ? undefined : readLoop);
2515
+ } else {
2516
+ // Core binds the model to skeleton.json, whose image path is relative
2517
+ // to the build. Mirror check's rig/ and check/build/ in gate scratch.
2518
+ const scratch = join(run.scratch, 'rig');
2519
+ const build = join(run.scratch, 'check', 'build');
2520
+ rmSync(run.scratch, { recursive: true, force: true });
2521
+ try {
2522
+ const packed: RigcRunner = args => run.rig(args.map((arg, i) => args[i - 1] === '--out' ? build : arg));
2523
+ gate = gateThroughRigc(composed.images, texts, packed, scratch, mode, () => {
2524
+ readLoop(build);
2525
+ gated.camera = measureSceneCamera(build, composed, camera);
2526
+ });
2527
+ } finally {
2528
+ rmSync(run.scratch, { recursive: true, force: true });
2529
+ }
2530
+ }
2171
2531
  } catch (err) { return refused('compose', err); }
2172
2532
  if (composed.sceneAnimations !== undefined) for (const g of gate) {
2173
2533
  g.lines = g.lines.map(line => sceneBoneContext(line, composed.report.characters.map(c => c.id)));
@@ -2193,8 +2553,12 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
2193
2553
  mkdirSync(join(rigDir, 'images'), { recursive: true });
2194
2554
  for (const [file, bytes] of composed.images) writeFileSync(join(rigDir, 'images', file), bytes);
2195
2555
  for (const [file, text] of texts) writeFileSync(join(rigDir, file), text);
2196
- writeFileSync(join(input.out, SCENE_REPORT_FILE), rigJsonText(r));
2197
- 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)}`);
2556
+ const reportPath = join(input.out, SCENE_REPORT_FILE);
2557
+ const wroteRig = `wrote ${join(rigDir, 'rig.json')}, motion.json and ${composed.images.length} image(s) under ${join(rigDir, 'images')}`;
2558
+ if (gated.camera === undefined) {
2559
+ writeFileSync(reportPath, rigJsonText(r));
2560
+ say(`${wroteRig}, and ${reportPath}`);
2561
+ }
2198
2562
  let checkRigc = run.check;
2199
2563
  if (r.characters.some(c => c.canvas_clip === true)) {
2200
2564
  const stage = composed.rig.skeleton;
@@ -2203,12 +2567,52 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
2203
2567
  ? [...args, '--viewport', viewport]
2204
2568
  : args);
2205
2569
  }
2570
+ let cameraBound = false;
2571
+ let cameraBindingFailed = false;
2572
+ const evidence = gated.camera;
2573
+ if (evidence !== undefined) {
2574
+ const build = resolve(input.out, 'check', 'build');
2575
+ const stock = checkRigc;
2576
+ checkRigc = args => {
2577
+ const result = stock(args);
2578
+ if (result.status !== 0 || args[0] !== 'build' || args[args.indexOf('--out') + 1] !== build) return result;
2579
+ cameraBindingFailed = true;
2580
+ for (const [file, expected] of evidence.files) {
2581
+ const found = packedFileHash(build, file);
2582
+ if (found !== expected) cameraProblem('SCENE_CAMERA_BACKDROP', 'check/build', `${show(file)} has SHA-256 ${found}; expected ${expected} from the green camera audit`);
2583
+ }
2584
+ cameraBindingFailed = false;
2585
+ cameraBound = true;
2586
+ return result;
2587
+ };
2588
+ }
2589
+ const writeCameraReport = (): void => {
2590
+ if (evidence === undefined || !cameraBound) return;
2591
+ composed.report = { ...r, spec: SCENE_CAMERA_REPORT_SPEC, camera: evidence.report };
2592
+ writeFileSync(reportPath, rigJsonText(composed.report));
2593
+ say(`${wroteRig}, and ${reportPath}`);
2594
+ };
2206
2595
  let report: CheckReport;
2207
2596
  try {
2208
- report = checkStage({ rig: rigDir, out: join(input.out, 'check'), pageEdges: mode.pageEdges, packShape: mode.packShape, ...(pageSize === undefined ? {} : { pageSize }), ...(input.requirements === undefined ? {} : { requirements: input.requirements }) }, checkRigc, run.checkBin, prefix('check'));
2597
+ report = checkStage({
2598
+ rig: rigDir, out: join(input.out, 'check'), pageEdges: mode.pageEdges, packShape: mode.packShape,
2599
+ ...(pageSize === undefined ? {} : { pageSize }),
2600
+ ...(input.requirements === undefined ? {} : { requirements: input.requirements }),
2601
+ ...(input.loopSeam === undefined ? {} : { loopSeam: input.loopSeam }),
2602
+ }, checkRigc, run.checkBin, prefix('check'));
2209
2603
  } catch (err) {
2604
+ if (cameraBindingFailed) {
2605
+ for (const p of COMPOSE_OWNS) rmSync(join(input.out, p), { recursive: true, force: true });
2606
+ return refused('compose', err);
2607
+ }
2608
+ writeCameraReport();
2210
2609
  return refused('check', err, composed);
2211
2610
  }
2611
+ if (evidence !== undefined && (!cameraBound || report.figures.build.model_sha256 !== evidence.report.model_sha256)) {
2612
+ for (const p of COMPOSE_OWNS) rmSync(join(input.out, p), { recursive: true, force: true });
2613
+ return refused('compose', new PartsError([{ code: 'SCENE_CAMERA_BACKDROP', object: 'check/build', detail: 'the checked model did not bind to the green camera audit; an exact packed artifact match is required' }]));
2614
+ }
2615
+ writeCameraReport();
2212
2616
  // Issue #203: a character taken with an accepted failing bar never makes the scene green, even where the composed
2213
2617
  // rig's check cannot measure that bar (no parts.json: the seam and four judgement lines say SKIP).
2214
2618
  const taken = r.characters.filter((c) => c.accepted !== undefined).map((c) => `"${c.id}" (${(c.accepted as string[]).join(', ')})`);