rig-parts 2.62.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/cli.ts +4 -3
- package/docs/AUTHORING.md +71 -0
- package/docs/STABILITY.md +1 -0
- package/package.json +1 -1
- package/src/scene.ts +404 -10
- package/src/sceneclips.ts +297 -1
package/cli.ts
CHANGED
|
@@ -55,7 +55,7 @@ import { RETUNE_FILE, RETUNE_SPEC, retuneStage } from './src/retune.ts';
|
|
|
55
55
|
import { checkPainting, DEFAULT_PAINTING_FORM, isPaintingForm, PAINTING_FORMS, paintingFormOf } from './src/paintcheck.ts';
|
|
56
56
|
import { decodePngBytes, readPng, writePng } from './src/raster/png.ts';
|
|
57
57
|
import { REQUIREMENTS_SENTENCE } from './src/requirements.ts';
|
|
58
|
-
import { composeStage, IMAGE_SEP, PLATE, PROVENANCES, SCENE_REPORT_FILE, SCENE_REPORT_SPEC, SCENE_SPEC } from './src/scene.ts';
|
|
58
|
+
import { composeStage, IMAGE_SEP, PLATE, PROVENANCES, SCENE_CAMERA_REPORT_SPEC, SCENE_REPORT_FILE, SCENE_REPORT_SPEC, SCENE_SPEC } from './src/scene.ts';
|
|
59
59
|
import { buildSheet, defaultCaption, type Tile, tilesFrom } from './src/sheet.ts';
|
|
60
60
|
import { loadComparison, requiredProblems, structureLines } from './src/structure.ts';
|
|
61
61
|
import { type ArgvTable, assembleOutputFiles, BUILD_RUN_FILE, CHECK_RUN_FILE, clearComposeRun, clearRunRecord, clearRunStamp, readPackageIdentity, recordArgv, rigOutputFiles, RUN_STAMP_FILE, RUN_STAMP_SPEC, writeRunRecord, writeRunStamp } from './src/runstamp.ts';
|
|
@@ -1082,10 +1082,11 @@ usage:
|
|
|
1082
1082
|
rig or motion compose does not know. The result is gated through
|
|
1083
1083
|
rig-c as rig gates its own (build --profile rig-play --pack, the
|
|
1084
1084
|
compile and the packed pages on disk); --out receives rig/ (rig.json,
|
|
1085
|
-
motion.json, images/) and ${SCENE_REPORT_FILE} (spec "${SCENE_REPORT_SPEC}"
|
|
1085
|
+
motion.json, images/) and ${SCENE_REPORT_FILE} (spec "${SCENE_REPORT_SPEC}"
|
|
1086
|
+
without a camera, "${SCENE_CAMERA_REPORT_SPEC}" with a camera):
|
|
1086
1087
|
every setting, each character's offset, scale, bounds and shift (and what it
|
|
1087
1088
|
moved),
|
|
1088
|
-
the plate's provenance, the declared and the composed order
|
|
1089
|
+
the plate's provenance, the declared and the composed order, only when
|
|
1089
1090
|
it is green; then check runs over rig/ into check/, as on a rig it did
|
|
1090
1091
|
not build (no parts.json: the seam, BREATH_VISIBLE, BLINK_NO_HOLE,
|
|
1091
1092
|
TIP_OVER_ROOT, STILL_REGIONS_DARK and RECOMPOSITE_HOLES say SKIP and
|
package/docs/AUTHORING.md
CHANGED
|
@@ -7222,6 +7222,11 @@ and stay absent).
|
|
|
7222
7222
|
| <a id="SCENE_DIAL_KEY_DECLARED"></a>`SCENE_DIAL_KEY_DECLARED` | a scene key uses `derive` on a slider's input property, including one that also carries a raw `v`; derived slider inputs are not a supported scene dial dialect | declare an explicit numeric `v` for the named dial, within the named slider's own range; group member values are checked separately |
|
|
7223
7223
|
| <a id="SCENE_ANIMATION_LOOP_CLOSES"></a>`SCENE_ANIMATION_LOOP_CLOSES` | the gated posed values at 0 and the scene clip's declared duration differ with physics omitted, for a new clip or an idle extension (physics-on frames are not measured by this check) | close the posed bone, slot, geometry, alpha, clip and draw-order values with physics omitted; comparison never wraps the endpoint to zero, and physics-on frame closure is not measured here |
|
|
7224
7224
|
| <a id="SCENE_ANIMATION_POSE_READABLE"></a>`SCENE_ANIMATION_POSE_READABLE` | Core cannot read or pose the compiled scene clip for its endpoint comparison | correct the construct named by Core; unreadable poses never count as closed and no scene is emitted |
|
|
7225
|
+
| <a id="SCENE_CAMERA_TRACK"></a>`SCENE_CAMERA_TRACK` | a camera track names an unknown take, has invalid keys or easing, or produces a nonfinite or collapsed view | correct the take name, key times, easing or camera values |
|
|
7226
|
+
| <a id="SCENE_CAMERA_LOOP_CLOSES"></a>`SCENE_CAMERA_LOOP_CLOSES` | a looping take's camera pan or zoom differs at the unwrapped endpoints | give its first and last keys the same pan and zoom |
|
|
7227
|
+
| <a id="SCENE_CAMERA_BACKDROP"></a>`SCENE_CAMERA_BACKDROP` | a camera backdrop does not resolve to its declared, measurable region behind the figures | select a plate that draws its bound region behind the figures throughout the keyed take |
|
|
7228
|
+
| <a id="SCENE_CAMERA_PLATE_EDGE"></a>`SCENE_CAMERA_PLATE_EDGE` | the camera view extends past the posed backdrop on the named frame | adjust the camera or plate motion, or extend the plate to cover the required view |
|
|
7229
|
+
| <a id="SCENE_CAMERA_PLATE_ALPHA"></a>`SCENE_CAMERA_PLATE_ALPHA` | the posed backdrop admits transparent coverage on the named camera frame | fill the transparent area or move the view into opaque art |
|
|
7225
7230
|
| <a id="SCENE_PIVOT_NAME_FREE"></a>`SCENE_PIVOT_NAME_FREE` | an opted-in character's source build already has a bone named `placement` that resolves to the generated name | rename the source bone or omit `placement_pivot` |
|
|
7226
7231
|
| <a id="SCENE_PIVOT_DECLARED"></a>`SCENE_PIVOT_DECLARED` | a scene track keys an unresolved `<id>:placement` directly or through a bone group, and the character has not opted in | declare `"placement_pivot": true` on the named character |
|
|
7227
7232
|
| <a id="SCENE_PIVOT_UNUSED"></a>`SCENE_PIVOT_UNUSED` | an opted-in character has no scene-authored translation key on its generated pivot | add a `translate`, `translatex` or `translatey` track with a key on `<id>:placement` in `animations`, or omit `placement_pivot` |
|
|
@@ -8056,6 +8061,7 @@ the same viewport compose uses for the shipped frames.
|
|
|
8056
8061
|
| `characters[].idle_repeats` | optional safe integer of 2 or more (issue #1511). Counts total plays of this character's source idle within an explicit `scene.animations.idle`. Its declared duration must equal `idle_repeats * source idle duration` exactly. In the same scene, each character without the key must fill the duration once. In `scene.json`, `characters[].idle_duration` gives the source period, `characters[].idle_repeats` appears on opted-in rows, and top-level `idle_duration` gives the scene period |
|
|
8057
8062
|
| `characters[].accept` | optional, a list of bar names: the bars this character's own check may have failed and still be composed (issue #203). `compose --accept <bar>[,<bar>…]` is the same list for every character; the two are joined, so the command line applies to every character and a character's list adds to it. Each name is one of the bars `check`'s summary names, less the gate — `loop`, `seam`, `BREATH_VISIBLE`, `BLINK_NO_HOLE`, `CHAIN_LAG`, `TIP_OVER_ROOT`, `STILL_REGIONS_DARK`, `TEXTURE_STRETCH`, `ANIMATIONS_DO_NOT_FOLD` (issue #320), `STRESS_OFF_CHAIN` (issue #347), `SEAM_OVER_MOTION` (the body-root bar, issue #686); anything else is `SCENE_ACCEPT_KNOWN`. When `check/check.json` declares `spec: "rig-parts-check/1"`, `compose` reads its `bar_outcomes` for the bars whose outcome status is `FAIL` in the report's order (issue #1373); without that spec it keeps the legacy `barsNotMet` reading. A build is taken when every bar its `check.json` failed is named; its gate red, a declared requirement not PASS, or a bar not named is `SCENE_BUILD_GREEN` as before. **It is for looking, not for shipping:** the `[compose]` line says which failing bars were accepted, `scene.json` records them as the character's `accepted`, the composed rig's own check measures them again and reports them as it finds them, and the run exits 1 even when that check is PASS (a composed rig has no `parts.json`, so the seam and four judgement lines say SKIP there). A list that accepts nothing — every build green — composes to the bytes a scene without one writes |
|
|
8058
8063
|
| `animations` | optional map by scene clip name, each value a rigc `MotionAnimation` (`duration`, `tracks`, optional `loop`, `note`, and core timeline collections). Names resolve against the final scene without another prefix or unit conversion: `root`, `plate`, declared named plate bones and `<id>:<bone>`, including generated dials. Keying `root` moves the whole scene. A new name adds a clip. `idle` appends tracks and timelines once to the composed idle, preserving character metadata and physics constraints. Its duration must exactly equal the composed idle (`SCENE_DURATION_AGREES`, or `SCENE_REPEAT_DURATION` when a character opts in to repetition). Imported animation names are reserved (`SCENE_ANIMATION_NAME_FREE`). Absent declaration preserves legacy bytes and output paths (issue #1346) |
|
|
8064
|
+
| `camera` | optional keyed view over composed animation names. See [Keyed scene camera](#keyed-scene-camera-issue-1596) for the camera clock, coverage requirements and opt-in report version |
|
|
8059
8065
|
| `order` | the draw order, back to front: a character id (its slots not named elsewhere, in its own order) or one `<id>:<slot>`. Every slot of every character is drawn exactly once. Interleaving is written by naming slots: `["a", "b:arm_l", "b"]` draws `b`'s left arm between `a` and the rest of `b` |
|
|
8060
8066
|
|
|
8061
8067
|
A `root` key moves plates together with figures. For layered travel, key the plate bones and the character's `<id>:placement` bone enabled by `placement_pivot`.
|
|
@@ -8345,6 +8351,71 @@ character's input arrives isolated); a composed `parts.json`, so the bars that
|
|
|
8345
8351
|
read See-through tags are measured per character by its own `build`, not over the
|
|
8346
8352
|
scene; a rig `build` did not write.
|
|
8347
8353
|
|
|
8354
|
+
#### Keyed scene camera (issue #1596)
|
|
8355
|
+
|
|
8356
|
+
A camera projects an already posed scene into the fixed canvas. It follows the
|
|
8357
|
+
selected animation clock and leaves the rig, physics, stretch, fold and stock
|
|
8358
|
+
check viewport unchanged. Assign one or more camera tracks in the scene input.
|
|
8359
|
+
This example uses an existing two-second take called `shot`.
|
|
8360
|
+
|
|
8361
|
+
```json
|
|
8362
|
+
{
|
|
8363
|
+
"backdrop": "background",
|
|
8364
|
+
"tracks": {
|
|
8365
|
+
"shot": [
|
|
8366
|
+
{ "t": 0, "pan": [0, 0], "zoom": 1 },
|
|
8367
|
+
{ "t": 1, "pan": [12, -4], "zoom": 1.2 },
|
|
8368
|
+
{ "t": 2, "pan": [0, 0], "zoom": 1 }
|
|
8369
|
+
]
|
|
8370
|
+
}
|
|
8371
|
+
}
|
|
8372
|
+
```
|
|
8373
|
+
|
|
8374
|
+
The example object is the value of `camera`. `backdrop` names one scene plate
|
|
8375
|
+
behind the characters. A track names a final composed animation, including
|
|
8376
|
+
`idle` or a prefixed clip. A take without a track uses the existing view.
|
|
8377
|
+
Times are seconds, strictly increasing from zero through the declared
|
|
8378
|
+
duration. Pan offsets the view center from the stage center in canvas pixels,
|
|
8379
|
+
with positive X right and positive Y down. Zoom is positive and finite.
|
|
8380
|
+
Zoom 1 shows a stage-sized window. Zoom 2 halves its visible width and height
|
|
8381
|
+
about the panned center. The first and last pan and zoom must agree on a
|
|
8382
|
+
looping take at its unwrapped endpoints.
|
|
8383
|
+
|
|
8384
|
+
Between keys the default interpolation is linear in pan and reciprocal zoom.
|
|
8385
|
+
The outgoing key may use the same `ease` or `curve` as the scene's animation
|
|
8386
|
+
keys. Named easings use the composed easing table. Explicit curve channels
|
|
8387
|
+
are pan X, pan Y and reciprocal zoom, in that order. Controls use absolute
|
|
8388
|
+
time in seconds and the corresponding channel's absolute value units.
|
|
8389
|
+
|
|
8390
|
+
Compose checks every camera frame at 12 fps, including the exact take
|
|
8391
|
+
endpoint. The frame grid uses authored seconds, and each frame poses the
|
|
8392
|
+
packed model at the corresponding compiled animation phase. The selected
|
|
8393
|
+
plate can move with its own animation, its parents,
|
|
8394
|
+
or the whole scene. The posed plate must cover the view with opaque art at
|
|
8395
|
+
every sampled frame. Figure bounds and projected clipping are reported as
|
|
8396
|
+
framing evidence. Coverage is measured on the camera frame grid.
|
|
8397
|
+
|
|
8398
|
+
Coverage refusals name the take, plate and affected frame. See
|
|
8399
|
+
[`SCENE_CAMERA_PLATE_EDGE`](#SCENE_CAMERA_PLATE_EDGE) and
|
|
8400
|
+
[`SCENE_CAMERA_PLATE_ALPHA`](#SCENE_CAMERA_PLATE_ALPHA).
|
|
8401
|
+
|
|
8402
|
+
Camera scenes write `spine-parts-scene-report/2` to the existing
|
|
8403
|
+
`<out>/scene.json` path. The `camera` record contains `backdrop`,
|
|
8404
|
+
`model_sha256`, `fps`, `coverage` and `tracks`. The three coverage measures
|
|
8405
|
+
`max_edge_overrun_px`, `nonopaque_source_texels` and
|
|
8406
|
+
`nonopaque_output_pixels` are zero on `PASS`. Each keyed take lists its
|
|
8407
|
+
normalized `keys`, authored `duration`, `compiled_duration`, `loop` flag
|
|
8408
|
+
and `frames`. Named easings are resolved to absolute curves in the report.
|
|
8409
|
+
Each frame lists its index, both clock readings, pan, zoom, view rectangle,
|
|
8410
|
+
posed backdrop quad and projected figure bounds. The view and backdrop quad
|
|
8411
|
+
are in scene pixels, with X right and Y down. Figure bounds are in output
|
|
8412
|
+
pixels. The model hash names the exact packed
|
|
8413
|
+
`<out>/check/build/skeleton.model.json` whose poses were measured.
|
|
8414
|
+
|
|
8415
|
+
Backdrop raster coverage and figure framing are computed in memory. The
|
|
8416
|
+
compose input record keeps `rig-compose-run/1`. Existing scenes without a
|
|
8417
|
+
camera retain the report /1 schema and the same output bytes.
|
|
8418
|
+
|
|
8348
8419
|
#### Animate a character's placement (issue #1498)
|
|
8349
8420
|
|
|
8350
8421
|
Set `"placement_pivot": true` on a character and key `<id>:placement` in
|
package/docs/STABILITY.md
CHANGED
|
@@ -1196,6 +1196,7 @@ execution in historical evidence is inferred from a current export.
|
|
|
1196
1196
|
| scene placement pivot | `compose` | Issue #1498 adds optional literal `true` at `characters[].placement_pivot` in `spine-parts-scene/1`. It emits the identity `<id>:placement` under `root` and requires a scene-authored `translate`, `translatex` or `translatey` key in final scene pixels. The existing placement math stays on the original first-level bones, root regions and root weights. Source root bindings use the unkeyed identity `<id>:root` child when needed. `SCENE_FIELD_TYPE` refuses other explicit values, `SCENE_PIVOT_NAME_FREE` a source bone collision, `SCENE_PIVOT_DECLARED` an unresolved pivot targeted directly or through a bone group without an opt-in, `SCENE_PIVOT_UNUSED` an unused declaration and `SCENE_PIVOT_TRACK` a forbidden property or carrier key. `SCENE_PLATE_NAME_FREE` still governs named plate collisions. Core's unknown-bone refusal, rig gate, scene clip timing and endpoint closure still apply. `scene.json` adds `placement_pivot` with the generated name after the bounds fields and counts the generated bones for that character. `compose-run.json` binds the declaration through `scene.sha256` with its existing shape and key order. Omitting the declaration preserves default output bytes at the same paths, subject to the existing Core receipt clocks. |
|
|
1197
1197
|
| `compose-run.json` | `compose` | spec `rig-compose-run/1` (issue #1348), separate from `rig-run/1`; a stable contract as of 2.44.0. Written at the `--out` root only after the gate and check are green and no accepted failing character remains, so an `--accept` preview writes none. Fixed keys in order: `spec`, `scene` (`path`, `sha256`), `characters` (each `id`, `build`, `files`, each file `path`, `sha256`, then optional `placement`), `plate` (`path`, `sha256`, or null), `plates` (each `name`, `path`, `sha256`). Scene and plate paths are the supplied and declared paths; character file paths are build-relative. Characters sort by `id`, files by `path`, named plates by `name`, in code-unit order. Each character's files are exactly `check/check.json`, `parts.json`, `rig/rig.json`, `rig/motion.json` and each distinct image the default skin names under `rig/images/`, including a generator's depth image. Every `sha256` is of the raw file bytes compose consumed before the gate. Only a character with `canvas_clip: true` has `placement`, with `canvas_clip: true`, `bounds` and `clipped_bounds` in that order from the scene report. There are no clocks, directory extras, requirements or CLI-option inventory, so identical inputs at identical supplied paths give identical record bytes. Compose owns the name: a file of that name at the `--out` root is deleted at the start of every compose, before stage validation, so a refused rerun leaves none. For scenes without opt-in, legacy outputs retain stable bytes, with the existing nested Core receipt clock comparison described above. |
|
|
1198
1198
|
| the scene report | `compose` | spec `spine-parts-scene-report/1`; the plate block carries `sha256` of the plate PNG's bytes after `size` (issue #1183, additive under *What "stable" means here*: a new report key in a minor version, so the spec stays `/1`); `pack_mode` records `page_size` only when `--page-size <px>` is given (issue #1352, additive; without `--page-size`, rigc's default 2048 px page and padding 2 on each side bound any plate or region side to at most 2044 px before `CE_ATLAS_REGION_EXCEEDS_PAGE`) |
|
|
1199
|
+
| keyed scene camera | `compose` | optional `camera` in `spine-parts-scene/1` (issue #1596). A camera scene writes `spine-parts-scene-report/2` at the existing `scene.json` path with its keyed camera, sampled coverage and framing verdict, and packed model SHA-256. Report /1 and the existing output inventory and bytes are preserved for scenes without a camera, subject to the existing Core receipt clocks. The camera path uses Core animation easing and the posed backdrop at each sampled frame. Rig, motion and stock check outputs retain their existing semantics. The compose input receipt stays `rig-compose-run/1`. See [Keyed scene camera](AUTHORING.md#keyed-scene-camera-issue-1596) |
|
|
1199
1200
|
| `idle.png`, `idle-indexed.png`, `idle.gif` | `loop`, `build --loop` | APNG and GIF encodings of the rendered idle |
|
|
1200
1201
|
| `run.json` | `rig`, `assemble` | spec `rig-run/1` (issue #1165, additive): `spec`, `package` (`name`, `version`), `command` (`"rig"` or `"assemble"`), `started_at` and `finished_at` (UTC ISO-8601 millisecond timestamps ending in `Z`, read in the CLI layer), `config` (`path` relative to `--out`, `sha256` of the config file on disk), `inputs` on `assemble` (issues #1316, #1554, additive: one `{role, path, sha256}` entry for each of `--source`, `--full` and `--head` that was given, in that order, with `path` relative to `--out` by the per-platform link rule — naming `<dir>/layers.json` when given a directory — and `sha256` of the file `path` names), and `outputs` (`path` relative to `--out`, `sha256` of each written output file on disk, sorted by `path` in code-unit order and excluding `run.json` itself); written only after the command's gate is green |
|
|
1201
1202
|
| the difference inventory (`--out`) | `diff-components` | spec `rig-parts-diff-components/1` by default (issue #1005: `stack`, `painting`, `definition`, `error_px`, `uncovered_error_px`, `components` — each `id`, `px`, `box`, `coverage`, `uncovered_px`, `borders` — and `below_floor`, byte-identical to 2.38.1), and spec `rig-parts-diff-components/2` under `--owners` (issue #1291: adds `owners` — each `{part, px}`, the topmost `parts.json` part above `COVERED_ALPHA` per covered pixel, back to front — before `borders` on every component); `--verify` verifies both `/1` and `/2` reports (with `--owners`, `/2` is required), while a `/1`-only reader (`readDiffComponents(text, input, [DIFF_COMPONENTS_SPEC])`) refuses `/2` by name |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rig-parts",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.63.0",
|
|
4
4
|
"description": "AI-authored 2D character parts from one anime painting and its See-through layer decomposition: measured parts, weighted-mesh rig specs, verified through rig-c before anything is written. A CLI for agents that cannot see the image.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
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, LOOP_SEAM_BAR_UNMET, type LoopSeamRequest, 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(
|
|
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
|
-
|
|
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
|
// ---------------------------------------------------------------------------
|
|
@@ -2167,12 +2501,33 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
|
|
|
2167
2501
|
['rig.json', rigJsonText(composed.rig)],
|
|
2168
2502
|
['motion.json', rigJsonText(composed.motion)],
|
|
2169
2503
|
];
|
|
2504
|
+
const camera = composed.sceneCamera;
|
|
2505
|
+
const gated: { camera?: CameraEvidence } = {};
|
|
2170
2506
|
let gate: ReturnType<typeof gateThroughRigc>;
|
|
2171
2507
|
try {
|
|
2172
2508
|
const clips = composed.sceneAnimations;
|
|
2173
|
-
|
|
2509
|
+
const readLoop = (build: string): void => {
|
|
2510
|
+
if (clips === undefined) return;
|
|
2174
2511
|
refuseIfAny(sceneClipLoopProblems(readFileSync(join(build, 'skeleton.model.json'), 'utf8'), clips, r.characters.some(c => c.idle_repeats !== undefined)));
|
|
2175
|
-
}
|
|
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
|
+
}
|
|
2176
2531
|
} catch (err) { return refused('compose', err); }
|
|
2177
2532
|
if (composed.sceneAnimations !== undefined) for (const g of gate) {
|
|
2178
2533
|
g.lines = g.lines.map(line => sceneBoneContext(line, composed.report.characters.map(c => c.id)));
|
|
@@ -2198,8 +2553,12 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
|
|
|
2198
2553
|
mkdirSync(join(rigDir, 'images'), { recursive: true });
|
|
2199
2554
|
for (const [file, bytes] of composed.images) writeFileSync(join(rigDir, 'images', file), bytes);
|
|
2200
2555
|
for (const [file, text] of texts) writeFileSync(join(rigDir, file), text);
|
|
2201
|
-
|
|
2202
|
-
|
|
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
|
+
}
|
|
2203
2562
|
let checkRigc = run.check;
|
|
2204
2563
|
if (r.characters.some(c => c.canvas_clip === true)) {
|
|
2205
2564
|
const stage = composed.rig.skeleton;
|
|
@@ -2208,6 +2567,31 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
|
|
|
2208
2567
|
? [...args, '--viewport', viewport]
|
|
2209
2568
|
: args);
|
|
2210
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
|
+
};
|
|
2211
2595
|
let report: CheckReport;
|
|
2212
2596
|
try {
|
|
2213
2597
|
report = checkStage({
|
|
@@ -2217,8 +2601,18 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
|
|
|
2217
2601
|
...(input.loopSeam === undefined ? {} : { loopSeam: input.loopSeam }),
|
|
2218
2602
|
}, checkRigc, run.checkBin, prefix('check'));
|
|
2219
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();
|
|
2220
2609
|
return refused('check', err, composed);
|
|
2221
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();
|
|
2222
2616
|
// Issue #203: a character taken with an accepted failing bar never makes the scene green, even where the composed
|
|
2223
2617
|
// rig's check cannot measure that bar (no parts.json: the seam and four judgement lines say SKIP).
|
|
2224
2618
|
const taken = r.characters.filter((c) => c.accepted !== undefined).map((c) => `"${c.id}" (${(c.accepted as string[]).join(', ')})`);
|
package/src/sceneclips.ts
CHANGED
|
@@ -1,13 +1,309 @@
|
|
|
1
1
|
/** Scene-authored clips use final names and Core's motion parser and poser. */
|
|
2
|
+
import { bezierForChannel, f32 } from '@rig-c/core/compile';
|
|
2
3
|
import { CompileError } from '@rig-c/core/errors';
|
|
3
4
|
import { parseMotionSpec, type MotionSpec as CoreMotion } from '@rig-c/core/motion';
|
|
4
|
-
import { bezierPolyline, CoreInputError, poseRawAnimation, readModel, type RawPose } from '@rig-c/core/core';
|
|
5
|
+
import { bezierPolyline, CORE_DOCUMENT_SPEC, CoreInputError, poseRawAnimation, readModel, type RawPose } from '@rig-c/core/core';
|
|
5
6
|
import { PartsError, refuseIfAny, type Problem } from './errors.ts';
|
|
6
7
|
import type { MotionSpec } from './motion.ts';
|
|
7
8
|
import type { RigSpec } from './rig.ts';
|
|
8
9
|
|
|
9
10
|
export type SceneAnimations = CoreMotion['animations'];
|
|
10
11
|
|
|
12
|
+
export interface SceneCameraSample {
|
|
13
|
+
pan: [number, number];
|
|
14
|
+
zoom: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface SceneCameraKey extends SceneCameraSample {
|
|
18
|
+
t: number;
|
|
19
|
+
ease?: string;
|
|
20
|
+
curve?: number[] | 'stepped';
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface SceneCamera {
|
|
24
|
+
backdrop: string;
|
|
25
|
+
tracks: Record<string, SceneCameraKey[]>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface ResolvedSceneCameraTrack {
|
|
29
|
+
/** Authored seconds, pan and zoom, with easings resolved to outgoing absolute curves. */
|
|
30
|
+
keys: Omit<SceneCameraKey, 'ease'>[];
|
|
31
|
+
duration: number;
|
|
32
|
+
loop: boolean;
|
|
33
|
+
/** Sample on the authored clock, including the unwrapped terminal time. */
|
|
34
|
+
sample(time: number): SceneCameraSample;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface ResolvedSceneCamera {
|
|
38
|
+
backdrop: string;
|
|
39
|
+
tracks: ReadonlyMap<string, ResolvedSceneCameraTrack>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const CAMERA_TRACK = 'SCENE_CAMERA_TRACK';
|
|
43
|
+
const CAMERA_LOOP = 'SCENE_CAMERA_LOOP_CLOSES';
|
|
44
|
+
const CAMERA_PAN_CURVE_LENGTH = 8;
|
|
45
|
+
const CAMERA_CURVE_LENGTH = CAMERA_PAN_CURVE_LENGTH + 4; // Four handles each for pan X, pan Y and reciprocal zoom.
|
|
46
|
+
|
|
47
|
+
const cameraRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
48
|
+
const cameraNumber = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
|
49
|
+
const cameraFloat = (v: unknown): boolean => cameraNumber(v) && Number.isFinite(Math.fround(v));
|
|
50
|
+
const cameraTrackField = (name: string): string => `scene.camera.tracks[${JSON.stringify(name)}]`;
|
|
51
|
+
|
|
52
|
+
function cameraValue(v: unknown): string {
|
|
53
|
+
if (typeof v === 'number') return String(v);
|
|
54
|
+
const json = JSON.stringify(v);
|
|
55
|
+
return json === undefined ? String(v) : json.length > 80 ? `${json.slice(0, 77)}...` : json;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function cameraUnknownFields(raw: Record<string, unknown>, allowed: readonly string[], object: string, problems: Problem[]): void {
|
|
59
|
+
for (const field of Object.keys(raw)) if (!allowed.includes(field)) {
|
|
60
|
+
problems.push({ code: CAMERA_TRACK, object: `${object}.${field}`, detail: `is not a camera field. Use ${allowed.join(', ')}` });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function usableZoom(zoom: number): boolean {
|
|
65
|
+
const span = 1 / zoom;
|
|
66
|
+
return Number.isFinite(zoom) && zoom > 0 && Number.isFinite(span) && span > 0;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function readCameraKeys(raw: unknown, object: string, problems: Problem[]): SceneCameraKey[] {
|
|
70
|
+
if (!Array.isArray(raw) || raw.length === 0) {
|
|
71
|
+
problems.push({ code: CAMERA_TRACK, object, detail: `is ${cameraValue(raw)}. A nonempty list of { t, pan, zoom } keys is required` });
|
|
72
|
+
return [];
|
|
73
|
+
}
|
|
74
|
+
const keys: SceneCameraKey[] = [];
|
|
75
|
+
let previous = -Infinity;
|
|
76
|
+
for (const [i, key] of raw.entries()) {
|
|
77
|
+
const at = `${object}[${i}]`;
|
|
78
|
+
if (!cameraRecord(key)) {
|
|
79
|
+
problems.push({ code: CAMERA_TRACK, object: at, detail: `is ${cameraValue(key)}. An object with t, pan and zoom is required` });
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const before = problems.length;
|
|
83
|
+
cameraUnknownFields(key, ['t', 'pan', 'zoom', 'ease', 'curve'], at, problems);
|
|
84
|
+
const { t, pan, zoom, ease, curve } = key;
|
|
85
|
+
const validTime = cameraNumber(t) && (i === 0 ? t === 0 : t > previous && t > 0);
|
|
86
|
+
if (!validTime) problems.push({ code: CAMERA_TRACK, object: `${at}.t`, detail: `is ${cameraValue(t)} s. ${i === 0
|
|
87
|
+
? 'The first key must be at exactly 0 s'
|
|
88
|
+
: `Each subsequent key must be at a finite positive time strictly after the previous key (${previous} s)`}` });
|
|
89
|
+
if (cameraNumber(t)) previous = t;
|
|
90
|
+
|
|
91
|
+
const validPan = Array.isArray(pan) && pan.length === 2 && cameraNumber(pan[0]) && cameraNumber(pan[1]);
|
|
92
|
+
if (!validPan) problems.push({ code: CAMERA_TRACK, object: `${at}.pan`, detail: `is ${cameraValue(pan)}. Two finite scene pixel offsets [x, y] are required` });
|
|
93
|
+
const validZoom = cameraNumber(zoom) && usableZoom(zoom);
|
|
94
|
+
if (!validZoom) problems.push({ code: CAMERA_TRACK, object: `${at}.zoom`, detail: `is ${cameraValue(zoom)}. Positive finite zoom and reciprocal zoom are required` });
|
|
95
|
+
|
|
96
|
+
if (ease !== undefined && (typeof ease !== 'string' || ease.length === 0)) {
|
|
97
|
+
problems.push({ code: CAMERA_TRACK, object: `${at}.ease`, detail: `is ${cameraValue(ease)}. Use a nonempty easing name or "stepped"` });
|
|
98
|
+
}
|
|
99
|
+
if (curve !== undefined && curve !== 'stepped' && !(Array.isArray(curve) && curve.length === CAMERA_CURVE_LENGTH && [...curve].every(cameraFloat))) {
|
|
100
|
+
problems.push({ code: CAMERA_TRACK, object: `${at}.curve`, detail: `is ${cameraValue(curve)}. Use "stepped" or ${CAMERA_CURVE_LENGTH} finite numbers at float32 precision` });
|
|
101
|
+
}
|
|
102
|
+
if (ease !== undefined && curve !== undefined) {
|
|
103
|
+
problems.push({ code: CAMERA_TRACK, object: at, detail: 'carries both ease and curve. Use one outgoing curve declaration' });
|
|
104
|
+
} else if (i === raw.length - 1 && (curve !== undefined || ease !== undefined)) {
|
|
105
|
+
problems.push({ code: CAMERA_TRACK, object: at, detail: 'carries an outgoing easing or curve. The terminal key has no following segment' });
|
|
106
|
+
}
|
|
107
|
+
if (problems.length === before && validTime && validPan && validZoom) {
|
|
108
|
+
keys.push({ t, pan: [pan[0], pan[1]], zoom, ...(typeof ease === 'string' ? { ease } : {}),
|
|
109
|
+
...(curve === 'stepped' || Array.isArray(curve) ? { curve: Array.isArray(curve) ? [...curve] : curve } : {}) });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return keys;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Read the declaration before the scene's composed take names and easings are available. */
|
|
116
|
+
export function readSceneCamera(raw: unknown): SceneCamera {
|
|
117
|
+
if (!cameraRecord(raw)) {
|
|
118
|
+
throw new PartsError([{ code: CAMERA_TRACK, object: 'scene.camera', detail: `is ${cameraValue(raw)}. A { backdrop, tracks } object is required` }]);
|
|
119
|
+
}
|
|
120
|
+
const problems: Problem[] = [];
|
|
121
|
+
cameraUnknownFields(raw, ['backdrop', 'tracks'], 'scene.camera', problems);
|
|
122
|
+
const backdrop = typeof raw.backdrop === 'string' ? raw.backdrop : '';
|
|
123
|
+
if (backdrop.length === 0) problems.push({ code: 'SCENE_CAMERA_BACKDROP', object: 'scene.camera.backdrop', detail: `is ${cameraValue(raw.backdrop)}. Name the legacy plate or a declared plate` });
|
|
124
|
+
const tracks: Array<[string, SceneCameraKey[]]> = [];
|
|
125
|
+
if (cameraRecord(raw.tracks)) {
|
|
126
|
+
for (const [name, keys] of Object.entries(raw.tracks)) tracks.push([name, readCameraKeys(keys, cameraTrackField(name), problems)]);
|
|
127
|
+
if (tracks.length === 0) problems.push({ code: CAMERA_TRACK, object: 'scene.camera.tracks', detail: 'is empty. Name at least one composed take and its camera keys' });
|
|
128
|
+
} else {
|
|
129
|
+
problems.push({ code: CAMERA_TRACK, object: 'scene.camera.tracks', detail: `is ${cameraValue(raw.tracks)}. An object mapping take names to key lists is required` });
|
|
130
|
+
}
|
|
131
|
+
refuseIfAny(problems);
|
|
132
|
+
return { backdrop, tracks: Object.fromEntries(tracks) };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const cameraChannels = (key: SceneCameraKey): [number, number, number] => [key.pan[0], key.pan[1], 1 / key.zoom];
|
|
136
|
+
|
|
137
|
+
/** Match the compiled bone timeline's stored time on the eased path. Off-grid
|
|
138
|
+
* times use the lower adjacent float32 when nearest rounding would go up.
|
|
139
|
+
*/
|
|
140
|
+
function cameraStoredTime(time: number): number {
|
|
141
|
+
const named = f32(time);
|
|
142
|
+
const nearest = Math.fround(time);
|
|
143
|
+
if (named === time || nearest <= time || !Number.isFinite(nearest)) return named;
|
|
144
|
+
const bits = new DataView(new ArrayBuffer(4));
|
|
145
|
+
bits.setFloat32(0, nearest);
|
|
146
|
+
bits.setUint32(0, bits.getUint32(0) - 1);
|
|
147
|
+
return f32(bits.getFloat32(0));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Lower three camera channels onto two independent root translations. Their
|
|
151
|
+
* unrounded world coordinates are Core's evaluated channel values directly.
|
|
152
|
+
* The document is synthetic and stays in memory. Its digest is a field the
|
|
153
|
+
* parser requires, and the camera report binds the actual packed model separately.
|
|
154
|
+
*/
|
|
155
|
+
function cameraCoreSampler(keys: ResolvedSceneCameraTrack['keys'], times: number[], duration: number, object: string): ResolvedSceneCameraTrack['sample'] {
|
|
156
|
+
const name = 'camera';
|
|
157
|
+
const doc = readModel(JSON.stringify({
|
|
158
|
+
spec: CORE_DOCUMENT_SPEC, referenceScale: 1, stage: null,
|
|
159
|
+
bones: [{ name: 'pan' }, { name: 'span' }], slots: [], skins: [], constraints: [], events: [],
|
|
160
|
+
animations: [{ name, duration, slots: [], constraints: { ik: [], transform: [], path: [], physics: [], slider: [] }, attachments: [], drawOrder: [], events: [],
|
|
161
|
+
bones: [
|
|
162
|
+
{ name: 'pan', timelines: [{ name: 'translate', keys: keys.map((key, i) => ({
|
|
163
|
+
time: times[i], x: f32(key.pan[0]), y: f32(key.pan[1]),
|
|
164
|
+
curve: Array.isArray(key.curve) ? key.curve.slice(0, CAMERA_PAN_CURVE_LENGTH) : key.curve,
|
|
165
|
+
})) }] },
|
|
166
|
+
{ name: 'span', timelines: [{ name: 'translatex', keys: keys.map((key, i) => ({
|
|
167
|
+
time: times[i], value: f32(1 / key.zoom),
|
|
168
|
+
curve: Array.isArray(key.curve) ? key.curve.slice(CAMERA_PAN_CURVE_LENGTH) : key.curve,
|
|
169
|
+
})) }] },
|
|
170
|
+
] }],
|
|
171
|
+
editorOrder: { skins: [], animations: [name] },
|
|
172
|
+
images: [], pageGrids: [], droppedStates: [], absentParts: [], meshBones: [], meshes: [], physics: [], deformTransforms: [], trackDerivations: [], rig: {},
|
|
173
|
+
pages: [], spine: { sha256: '0'.repeat(64) },
|
|
174
|
+
}), object);
|
|
175
|
+
return time => {
|
|
176
|
+
try {
|
|
177
|
+
const pose = poseRawAnimation(doc, name, time === 0 ? [] : [time]).at(-1);
|
|
178
|
+
if (pose === undefined) throw new CoreInputError('Core returned no camera pose');
|
|
179
|
+
const [pan, span] = pose.bones;
|
|
180
|
+
return checkCameraSample([pan.worldX, pan.worldY], 1 / span.worldX, time, object);
|
|
181
|
+
} catch (err) {
|
|
182
|
+
if (!(err instanceof CoreInputError)) throw err;
|
|
183
|
+
throw new PartsError([{ code: CAMERA_TRACK, object, detail: `cannot evaluate the eased camera at t=${time} s. ${err.message}` }]);
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function checkCameraSample(pan: [number, number], zoom: number, time: number, object: string): SceneCameraSample {
|
|
189
|
+
if (!pan.every(Number.isFinite) || !usableZoom(zoom)) {
|
|
190
|
+
throw new PartsError([{ code: CAMERA_TRACK, object, detail: `evaluates at t=${time} s to pan [${pan.join(', ')}] and zoom ${zoom}. A finite pan and a finite positive window are required` }]);
|
|
191
|
+
}
|
|
192
|
+
return { pan, zoom };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function cameraLoopProblem(first: SceneCameraSample, last: SceneCameraSample, duration: number, object: string, phase: string): Problem | null {
|
|
196
|
+
if (first.pan[0] === last.pan[0] && first.pan[1] === last.pan[1] && first.zoom === last.zoom) return null;
|
|
197
|
+
return { code: CAMERA_LOOP, object, detail: `${phase} start at t=0 s has pan [${first.pan.join(', ')}] and zoom ${first.zoom}. End at t=${duration} s has pan [${last.pan.join(', ')}] and zoom ${last.zoom}. A looping camera requires exact equality` };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Resolve only declared tracks, against the final take and easing names. */
|
|
201
|
+
export function resolveSceneCamera(camera: SceneCamera, motion: MotionSpec): ResolvedSceneCamera {
|
|
202
|
+
const problems: Problem[] = [];
|
|
203
|
+
const tracks = new Map<string, ResolvedSceneCameraTrack>();
|
|
204
|
+
for (const [name, authored] of Object.entries(camera.tracks)) {
|
|
205
|
+
const object = cameraTrackField(name);
|
|
206
|
+
const take = Object.hasOwn(motion.animations, name) ? motion.animations[name] : undefined;
|
|
207
|
+
if (!cameraRecord(take) || !cameraNumber(take.duration) || take.duration < 0) {
|
|
208
|
+
problems.push({ code: CAMERA_TRACK, object, detail: `requires a composed take named ${JSON.stringify(name)} with a finite nonnegative declared duration` });
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
const { duration } = take;
|
|
212
|
+
const loop = take.loop === true;
|
|
213
|
+
const first = authored[0], last = authored.at(-1);
|
|
214
|
+
if (last === undefined || last.t !== duration) {
|
|
215
|
+
problems.push({ code: CAMERA_TRACK, object, detail: `ends at ${last === undefined ? 'no key' : `${last.t} s`}. Take ${JSON.stringify(name)} declares ${duration} s and the terminal key must match exactly` });
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
const before = problems.length;
|
|
219
|
+
if (loop) {
|
|
220
|
+
const problem = cameraLoopProblem(first, last, duration, object, 'Authored');
|
|
221
|
+
if (problem !== null) problems.push(problem);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const eased = authored.some(key => key.curve !== undefined || key.ease !== undefined);
|
|
225
|
+
const times = authored.map(key => eased ? cameraStoredTime(key.t) : key.t);
|
|
226
|
+
const keys = authored.map((key, i): ResolvedSceneCameraTrack['keys'][number] => {
|
|
227
|
+
const at = `${object}[${i}]`;
|
|
228
|
+
const normalized: ResolvedSceneCameraTrack['keys'][number] = { t: key.t, pan: [...key.pan], zoom: key.zoom };
|
|
229
|
+
const from = cameraChannels(key);
|
|
230
|
+
if (eased && (!Number.isFinite(times[i]) || (i > 0 && times[i] <= times[i - 1])
|
|
231
|
+
|| !from.every(cameraFloat) || Math.fround(from[2]) === 0)) {
|
|
232
|
+
problems.push({ code: CAMERA_TRACK, object: at,
|
|
233
|
+
detail: `at t=${key.t} s stores time ${times[i]} s and has channels [${from.join(', ')}]. ` +
|
|
234
|
+
'Eased tracks require strictly increasing float32 times and finite float32 channels with a positive reciprocal zoom',
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
if (key.curve === 'stepped' || key.ease === 'stepped') return { ...normalized, curve: 'stepped' };
|
|
238
|
+
if (key.curve !== undefined) return { ...normalized, curve: key.curve.map(f32) };
|
|
239
|
+
if (key.ease === undefined) return normalized;
|
|
240
|
+
const handles = key.ease !== '' && Object.hasOwn(motion.easings, key.ease) ? motion.easings[key.ease] : undefined;
|
|
241
|
+
if (!Array.isArray(handles) || handles.length !== 4 || ![...handles].every(cameraFloat)) {
|
|
242
|
+
problems.push({ code: CAMERA_TRACK, object: `${at}.ease`, detail: `names ${JSON.stringify(key.ease)}. Declare that easing in the composed motion with four finite handles at float32 precision` });
|
|
243
|
+
return normalized;
|
|
244
|
+
}
|
|
245
|
+
const to = cameraChannels(authored[i + 1]);
|
|
246
|
+
if (from.every((v, c) => Math.fround(v) === Math.fround(to[c]))) return { ...normalized, curve: 'stepped' };
|
|
247
|
+
const curve = from.flatMap((v, c) => bezierForChannel(handles, times[i], times[i + 1], v, to[c]));
|
|
248
|
+
if (!curve.every(Number.isFinite)) {
|
|
249
|
+
problems.push({ code: CAMERA_TRACK, object: `${at}.ease`, detail: `easing ${JSON.stringify(key.ease)} produces non-finite absolute handles at t=${key.t} s. Finite float32 handles are required` });
|
|
250
|
+
}
|
|
251
|
+
return { ...normalized, curve };
|
|
252
|
+
});
|
|
253
|
+
if (problems.length !== before) continue;
|
|
254
|
+
|
|
255
|
+
let coreSample: ResolvedSceneCameraTrack['sample'] | undefined;
|
|
256
|
+
let coreStart: SceneCameraSample | undefined, coreEnd: SceneCameraSample | undefined;
|
|
257
|
+
if (eased) {
|
|
258
|
+
try {
|
|
259
|
+
coreSample = cameraCoreSampler(keys, times, duration, object);
|
|
260
|
+
const storedEnd = Math.fround(times[times.length - 1]);
|
|
261
|
+
coreStart = coreSample(0);
|
|
262
|
+
coreEnd = coreSample(storedEnd);
|
|
263
|
+
if (loop) {
|
|
264
|
+
const problem = cameraLoopProblem(coreStart, coreEnd, storedEnd, object, 'Core-evaluated');
|
|
265
|
+
if (problem !== null) problems.push(problem);
|
|
266
|
+
}
|
|
267
|
+
} catch (err) {
|
|
268
|
+
if (err instanceof PartsError) problems.push(...err.problems);
|
|
269
|
+
else if (err instanceof CoreInputError) problems.push({ code: CAMERA_TRACK, object, detail: err.message });
|
|
270
|
+
else throw err;
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
const easedStart = keys[0].curve !== undefined;
|
|
275
|
+
const easedEnd = keys.at(-2)?.curve !== undefined;
|
|
276
|
+
const easedSeam = loop && (easedStart || easedEnd);
|
|
277
|
+
tracks.set(name, {
|
|
278
|
+
keys, duration, loop,
|
|
279
|
+
sample(time) {
|
|
280
|
+
if (!Number.isFinite(time) || time < 0 || time > duration) {
|
|
281
|
+
throw new PartsError([{ code: CAMERA_TRACK, object, detail: `cannot sample t=${time} s. Authored time in [0, ${duration}] s is required` }]);
|
|
282
|
+
}
|
|
283
|
+
// At a curved loop seam use both unwrapped Core reads. The linear-only
|
|
284
|
+
// seam uses both authored values, so the two ends share a precision.
|
|
285
|
+
const endpoint = time === 0 && (easedSeam || easedStart) ? coreStart
|
|
286
|
+
: time === duration && (easedSeam || easedEnd) ? coreEnd : undefined;
|
|
287
|
+
if (endpoint !== undefined) return { pan: [...endpoint.pan], zoom: endpoint.zoom };
|
|
288
|
+
let low = 0, high = keys.length - 1;
|
|
289
|
+
while (low < high) {
|
|
290
|
+
const mid = Math.ceil((low + high) / 2);
|
|
291
|
+
if (keys[mid].t <= time) low = mid;
|
|
292
|
+
else high = mid - 1;
|
|
293
|
+
}
|
|
294
|
+
const from = keys[low], to = keys[low + 1];
|
|
295
|
+
if (from.curve !== undefined && coreSample !== undefined) return coreSample(time);
|
|
296
|
+
if (from.t === time || to === undefined) return checkCameraSample([...from.pan], from.zoom, time, object);
|
|
297
|
+
const phase = (time - from.t) / (to.t - from.t);
|
|
298
|
+
const mix = (a: number, b: number): number => a + (b - a) * phase;
|
|
299
|
+
return checkCameraSample([mix(from.pan[0], to.pan[0]), mix(from.pan[1], to.pan[1])], 1 / mix(1 / from.zoom, 1 / to.zoom), time, object);
|
|
300
|
+
},
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
refuseIfAny(problems);
|
|
304
|
+
return { backdrop: camera.backdrop, tracks };
|
|
305
|
+
}
|
|
306
|
+
|
|
11
307
|
export interface ScenePlacementPivot {
|
|
12
308
|
name: string;
|
|
13
309
|
rootBinding?: string;
|