rig-parts 2.64.0 → 2.66.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/docs/AUTHORING.md CHANGED
@@ -7220,13 +7220,17 @@ and stay absent).
7220
7220
  | <a id="SCENE_ACCEPT_KNOWN"></a>`SCENE_ACCEPT_KNOWN` | an `--accept` name, or one in a character's `accept`, is not a bar `check` holds a build to: a problem code (`CHECK_LOOP_CLOSES`) where the bar's name (`loop`) belongs, a misspelling, or `gate`, which is rig-c's and never accepted | one of the names the message lists |
7221
7221
  | <a id="SCENE_BUILD_FIELD_KNOWN"></a>`SCENE_BUILD_FIELD_KNOWN` | a build's `rig.json` or `motion.json` carries a key compose does not know how to prefix or place, or a root with a transform of its own | a rig `build` wrote; a rig written by something else is `check`'s to measure (§7, *Measuring a rig rig-parts did not assemble*), not compose's to merge |
7222
7222
  | <a id="SCENE_RIG_SCALE_AGREES"></a>`SCENE_RIG_SCALE_AGREES` | the characters' `parts.json` `scale_rig_per_source` differ (each named) | one `assemble.rig_scale` for every character; `characters[].scale` sizes a placed character, it does not make two `rig_scale`s one |
7223
- | <a id="SCENE_SCALE_EXACT"></a>`SCENE_SCALE_EXACT` | a character at a `scale` other than 1 carries something no per-character value can scale: a physics constraint with a nonzero `wind` or `gravity`, or a physics track keying `wind` or `gravity` with a nonzero value (Spine applies both through the skeleton's `referenceScale`, which the composed skeleton holds once for every character), a track whose `property` compose does not know to be a length or not, or a translate key whose `v` is neither a list of numbers nor a map of them | `scale` 1 for that character, or rebuild it at another `assemble.rig_scale` |
7223
+ | <a id="SCENE_SCALE_EXACT"></a>`SCENE_SCALE_EXACT` | a character at a `scale` other than 1 declares a numeric `with_idle` count or carries an input that compose cannot scale exactly. Examples include a physics constraint or track with nonzero `wind` or `gravity` (Spine uses one `referenceScale` for the composed skeleton), a track whose `property` compose does not know how to scale, and a translate key whose `v` is neither a list of numbers nor a map of them | use `scale` 1, or rebuild at another `assemble.rig_scale` to change the built size. To leave a physics-only clip out of the idle, declare `false`. The side clip must still pass the scale checks |
7224
7224
  | <a id="SCENE_DURATION_AGREES"></a>`SCENE_DURATION_AGREES` | with no `idle_repeats`, the characters' idles are of different durations (each named), or `scene.animations.idle.duration` differs from the composed idle | declare the same duration; compose preserves the original key timing |
7225
- | <a id="SCENE_REPEAT_COUNT"></a>`SCENE_REPEAT_COUNT` | a character declares an invalid `idle_repeats` value | declare a safe integer of 2 or more, or omit the field to use one source period |
7225
+ | <a id="SCENE_REPEAT_COUNT"></a>`SCENE_REPEAT_COUNT` | an invalid count in `characters[].idle_repeats`, `characters[].with_idle` or `scene.repeats` | use a safe integer of at least 2 for `idle_repeats` or `scene.repeats`, and a safe integer of at least 1 or literal `false` for `with_idle` |
7226
7226
  | <a id="SCENE_REPEAT_IDLE_REQUIRED"></a>`SCENE_REPEAT_IDLE_REQUIRED` | a character opts in but the scene declares no `animations.idle` | declare the scene idle and its duration |
7227
- | <a id="SCENE_REPEAT_DURATION"></a>`SCENE_REPEAT_DURATION` | in an opted-in scene, the declared idle duration differs from a character's source period times its playback count, including a count of one for a character without `idle_repeats` | use the exact finite, positive product for every character |
7227
+ | <a id="SCENE_REPEAT_DURATION"></a>`SCENE_REPEAT_DURATION` | the declared idle duration disagrees with a character’s source period times its playback count, or `scene.repeats` names a take without a positive authored duration or with animation keys ending off the period clock | use the exact finite, positive product for every character. Declare the whole take duration and make the latest effective scene animation key end exactly at duration divided by the scene repeat count |
7228
+ | <a id="SCENE_PHYSICS_CLIP_DECLARED"></a>`SCENE_PHYSICS_CLIP_DECLARED` | a character’s physics-only clip beside `idle` lacks a declaration. The refusal names the character, clip and distinct keyed constraint count | declare literal `false` in `with_idle` at any scale, or declare a whole-period count at scale 1 |
7229
+ | <a id="SCENE_PHYSICS_CLIP_ONLY"></a>`SCENE_PHYSICS_CLIP_ONLY` | a `with_idle` entry names `idle`, an absent clip, a clip with no physics keys or a clip with other timelines | use the source name of a physics-only clip beside `idle`. This applies to counts and to `false` |
7230
+ | <a id="PHYSICS_CLIPS_MOTION"></a>`PHYSICS_CLIPS_MOTION` | `physicsOnlyClips` receives an invalid motion document | parse the source `motion.json` and supply a valid `rigc-motion/1` document |
7231
+ | <a id="SCENE_WITH_IDLE_DURATION"></a>`SCENE_WITH_IDLE_DURATION` | a numeric `with_idle` entry implies a duration different from the played idle. The refusal names the clip and the conflicting lengths. The diagnostic searches up to 10,000 copies of each source. Acceptance depends on exact duration equality regardless of that search bound | use the suggested whole-period counts when available. The diagnostic can also suggest a scene repeat count, total idle duration and camera terminal key when it knows the scene period. Otherwise determine the scene period before setting `scene.repeats.idle`. You can also retime the source clip supplied through `motion.animations_from`, adjust the source idle with `motion.duration`, or declare `false` |
7228
7232
  | <a id="SCENE_REPEAT_SOURCE_LOOP_CLOSES"></a>`SCENE_REPEAT_SOURCE_LOOP_CLOSES` | a repeated source idle has a loop flag other than `true`, or its original gated keyed poses at the start and stored end do not close or cannot be read | use a closed source idle with `loop: true` and correct the named pose channel |
7229
- | <a id="SCENE_REPEAT_KEY_SEAM"></a>`SCENE_REPEAT_KEY_SEAM` | a repeated source timeline cannot be spliced on its effective key clock, for example because of a setup gap, an unequal boundary state or left limit, or a reset at the boundary | author a timeline that starts at effective time zero and closes continuously, with any explicit reset strictly inside the source period and separate on Core's playback clock |
7233
+ | <a id="SCENE_REPEAT_KEY_SEAM"></a>`SCENE_REPEAT_KEY_SEAM` | a repeated source timeline cannot be spliced on its effective key clock, for example because of a setup gap, an unequal boundary state or left limit, a reset at the boundary or a period that collapses on the playback clock. Repeated scene animations also refuse timeline families without a defined splice | author a state timeline that starts at effective time zero and closes continuously, with any explicit reset strictly inside the source period and separate on Core's playback clock |
7230
7234
  | <a id="CE_COMPILE_ANIMATION_GROUP_UNKNOWN"></a>`CE_COMPILE_ANIMATION_GROUP_UNKNOWN` | a scene track names no own declared group, including inherited object names such as `constructor` | name an explicitly declared final group; prototype properties are not groups |
7231
7235
  | <a id="SCENE_ANIMATION_NAME_FREE"></a>`SCENE_ANIMATION_NAME_FREE` | a scene clip name already belongs to an imported character animation | choose a new name; only shared `idle` can be extended |
7232
7236
  | <a id="SCENE_DIAL_RANGE_DECLARED"></a>`SCENE_DIAL_RANGE_DECLARED` | a keyed slider has no readable explicit `from` and `max` bounds, or its bounds are reversed; the bone and slider are named | declare both finite bounds with `from <= max`; no limits are invented |
@@ -7234,8 +7238,8 @@ and stay absent).
7234
7238
  | <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 |
7235
7239
  | <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 |
7236
7240
  | <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 |
7237
- | <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 |
7238
- | <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 |
7241
+ | <a id="SCENE_CAMERA_TRACK"></a>`SCENE_CAMERA_TRACK` | a camera track names an unknown take, has invalid keys or easing, ends at the wrong time, or produces a nonfinite or collapsed view | correct the take name, key times, easing or camera values. End the keys exactly at the take duration, or at duration divided by the scene repeat count for a repeated take |
7242
+ | <a id="SCENE_CAMERA_LOOP_CLOSES"></a>`SCENE_CAMERA_LOOP_CLOSES` | a looping or repeated take's camera pan or zoom differs at the unwrapped endpoints of its authored keys | give its first and last keys the same pan and zoom |
7239
7243
  | <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 |
7240
7244
  | <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 |
7241
7245
  | <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 |
@@ -8072,8 +8076,10 @@ the composed idle under `<out>/check/`, at the viewport used for the shipped fra
8072
8076
  | `characters[].canvas_clip` | optional literal `true` for intentional overflow (issue #1491). The placed part bounds must be finite, extend past at least one canvas edge and overlap the canvas with positive width and height. Omitting the key requires containment, with flush edges allowed. Every explicit value other than `true` is `SCENE_FIELD_TYPE` |
8073
8077
  | `characters[].placement_pivot` | optional literal `true` (issue #1498). Generates an identity `<id>:placement` under `root` and requires a scene-authored `translate`, `translatex` or `translatey` key on it. Every explicit value other than `true` is `SCENE_FIELD_TYPE` |
8074
8078
  | `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 |
8079
+ | `characters[].with_idle` | map from each source physics-only clip beside `idle` to a safe integer of at least 1 or literal `false` (issue #1615). A count requires character scale 1 and folds whole periods into the played idle. `false` leaves that clip out of the idle at any character scale. Both retain the prefixed side clip, which must pass the character's scale checks. See [Physics clips and scene repeats](#physics-clips-and-scene-repeats-issue-1615) |
8075
8080
  | `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 |
8076
- | `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) |
8081
+ | `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 the resulting tracks and timelines 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`). See `repeats` for period-authored tracks and deforms |
8082
+ | `repeats` | optional map from authored take names to safe integers of at least 2 (issue #1615). Repeats the scene-authored tracks, deforms and camera keys on a single period clock. `animations.<take>.duration` is the whole take duration. `scene.json` echoes the map in declared order as its final top-level key after `idle_duration` and omits it when absent. See [Physics clips and scene repeats](#physics-clips-and-scene-repeats-issue-1615) |
8077
8083
  | `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 |
8078
8084
  | `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` |
8079
8085
 
@@ -8242,9 +8248,9 @@ What is composed:
8242
8248
  declares it.
8243
8249
  - **Every animation beside a character's idle** — what `motion.animations_from`
8244
8250
  wrote into its `motion.json` (§3) — rides along as `<id>:<name>` after the idle,
8245
- its tracks' bones, groups, physics constraints and easings prefixed as the idle's are and every other
8246
- value as written; the scene schedules none of them, they are the consumer's to
8247
- play. Each is read with the idle's own key lists, so a key compose does not know
8251
+ with its tracks' names prefixed and its length retained. A numeric `with_idle`
8252
+ declaration also folds that physics-only clip into the played idle. Each side
8253
+ clip is read with the idle's own key lists, so a key compose does not know
8248
8254
  how to prefix is `SCENE_BUILD_FIELD_KNOWN`, as it is on the idle, and a track of
8249
8255
  one that keys `root` is `SCENE_ROOT_SHARED` (issues #183, #1485).
8250
8256
  - **Turn producer output** (issue #1344) is admitted explicitly: yaw/pitch
@@ -8394,6 +8400,130 @@ Both files must remain under `check/idle_frames/` for readers to verify the
8394
8400
  seam evidence after the run. This refusal clears `rig/`, `check/`, `scene.json` and
8395
8401
  `compose-run.json` under `--out` before the gate.
8396
8402
 
8403
+ #### Physics clips and scene repeats (issue #1615)
8404
+
8405
+ A physics-only side clip typically enters a character build through
8406
+ `motion.animations_from`. It has at least one track, every track targets only
8407
+ a named physics constraint, and every other animation payload is empty or
8408
+ absent. Clip metadata such as `loop` and `note` is allowed.
8409
+
8410
+ To discover the source clip names for `with_idle`, import `physicsOnlyClips`
8411
+ from `@rig-c/parts/physics-clips` and pass the parsed `rigc-motion/1` value from
8412
+ the character's `motion.json`. `compose` uses the same export. It returns
8413
+ `{ name, duration, constraints }` rows in source animation order, excluding
8414
+ `idle`. Constraint names are distinct and follow first-keyed order. If no clips
8415
+ match, it returns `[]`. Invalid motion raises [`PHYSICS_CLIPS_MOTION`](#PHYSICS_CLIPS_MOTION).
8416
+
8417
+ Declare each such clip by its source name in `characters[].with_idle`. A count
8418
+ copies that many whole periods into the composed `idle` with the character's
8419
+ prefix. Literal `false` plays the idle without that clip. The standalone
8420
+ `<id>:<clip>` ships in either case, and the character's row in `scene.json`
8421
+ echoes the declaration. A single-animation player plays the folded keys by
8422
+ selecting `idle`.
8423
+
8424
+ Literal `false` is accepted at any character scale. The side clip still passes
8425
+ through the character's scale checks, which refuse nonzero `wind` or `gravity`
8426
+ at scales other than 1. A numeric declaration requires character scale 1 and
8427
+ an exact match between the source clip period times its count and the played
8428
+ idle duration. A count of 1 can fold an equal-duration clip without authoring
8429
+ `scene.animations.idle`.
8430
+ Use `idle_repeats` and an explicit scene idle duration when the character idle
8431
+ also needs to fill multiple periods. The counts for the idle and the physics
8432
+ clip may differ as long as their products agree exactly.
8433
+
8434
+ For example, when the diagnostic finds a shared 3 s duration and the scene's
8435
+ own period also fits, it can advise `idle_repeats: 3`, `with_idle.wind: 2`,
8436
+ `scene.repeats.idle: 3`, and `scene.animations.idle.duration: 3`. The composed
8437
+ camera ends at 3 s and its authored terminal key stays at 1 s. When the
8438
+ scene's period is undeclared, the advice gives
8439
+ `idle_repeats: 3` and `with_idle.wind: 2` (3 s) and explains that a
8440
+ `scene.repeats` count requires the scene's own period. When one source idle
8441
+ period is enough, omit `idle_repeats`. For a matching untiled scene, also
8442
+ omit `scene.repeats.idle` and keep the current scene duration and camera end.
8443
+
8444
+ Set `scene.repeats.<take>` to author the scene animation and any camera track
8445
+ for that take over a shared period. Give `scene.animations.<take>.duration`
8446
+ the positive whole take length and divide it by the scene repeat count to get
8447
+ the authored period. The latest effective animation key across tracks and
8448
+ deforms, if present, and the final camera key, if present, must end exactly
8449
+ there. A state channel that has already closed may hold to the splice.
8450
+ The splice repeats tracks and deforms. Populated `ik`, `transform`,
8451
+ `sequence`, `drawOrder` and `events` collections are refused. A repeated camera
8452
+ must close on its authored period even for a non-looping take.
8453
+
8454
+ The splice requires the held end key state to equal the start state and
8455
+ checks the left limit at the boundary. It shares equivalent boundary keys,
8456
+ offsets absolute curve times and keeps resets strictly inside each physics
8457
+ period. Compose's pose loop check omits physics. The splice checks keyed
8458
+ physics inputs, while Core's render loop-seam measurement reads the resulting
8459
+ physics-on frames.
8460
+
8461
+ On a frame-aligned tiled camera with a backdrop that follows the same period,
8462
+ `pan`, `zoom`, `view` and `backdrop_quad` repeat at the same phase. The player's
8463
+ coverage guard compares the view with the backdrop quad, so the repeated rows
8464
+ yield the same guard verdict. `figures` contains bounds measured from each
8465
+ frame's pose, with physics stepping through the whole take.
8466
+
8467
+ ##### Compose the generated fixture
8468
+
8469
+ From the repository root, generate the fixture, compose its tiled scene and
8470
+ single-period reference, then render only `idle` with Core 3.11.0.
8471
+
8472
+ ```sh
8473
+ bun fixtures/scene.ts scratch/fixture
8474
+ bun cli.ts compose --scene scratch/fixture/scene.json --out scratch/folded
8475
+ bun cli.ts compose --scene scratch/fixture/period.json --out scratch/period
8476
+ bunx --no-install rigc render --candidate scratch/folded/check/build --animation idle --fps 12 --loop-seam --out scratch/physics-on
8477
+ bunx --no-install rigc render --candidate scratch/folded/check/build --animation idle --fps 12 --physics off --out scratch/physics-off
8478
+ ```
8479
+
8480
+ Both compose runs reported `PASS` on Linux. In
8481
+ `scratch/folded/rig/motion.json`, the 3 s `idle` contains `wind` and `mix`
8482
+ tracks targeting `figure:hem_spring`, with five keys each from 0 to 3 s.
8483
+ The prefixed side clip is retained. Select `idle` when opening the packed
8484
+ model in a single-animation player.
8485
+
8486
+ Core's `loop-seam.json` records an unjudged seam at warmup 0, with 183
8487
+ differing pixels and a maximum RGBA channel delta of 95. At 0.75 s, the
8488
+ 256 × 204 `f0009.png` differs by 253 pixels between the physics-on and
8489
+ physics-off renders, with a maximum RGBA channel delta of 128. To compare
8490
+ the two frames, use the frame-set directory named in each `frames.json`.
8491
+
8492
+ ```sh
8493
+ bun - <<'TS'
8494
+ import { readPng } from './src/raster/png.ts';
8495
+
8496
+ async function frame(root: string) {
8497
+ const { sets } = await Bun.file(`${root}/frames.json`).json();
8498
+ return readPng(`${root}/${sets[0].dir}/f0009.png`);
8499
+ }
8500
+
8501
+ const on = await frame('scratch/physics-on');
8502
+ const off = await frame('scratch/physics-off');
8503
+ if (on.width !== off.width || on.height !== off.height) {
8504
+ throw new Error('Frame dimensions differ');
8505
+ }
8506
+ let pixels = 0;
8507
+ let maxDelta = 0;
8508
+ for (let i = 0; i < on.data.length; i += 4) {
8509
+ let pixelDelta = 0;
8510
+ for (let channel = 0; channel < 4; channel++) {
8511
+ pixelDelta = Math.max(pixelDelta, Math.abs(on.data[i + channel] - off.data[i + channel]));
8512
+ }
8513
+ if (pixelDelta > 0) pixels++;
8514
+ maxDelta = Math.max(maxDelta, pixelDelta);
8515
+ }
8516
+ console.log({ width: on.width, height: on.height, pixels, maxDelta });
8517
+ TS
8518
+ ```
8519
+
8520
+ The `scene.json` reports contain 13 period rows and 37 tiled rows in
8521
+ `camera.tracks.idle.frames`. Comparing each tiled row with its period phase
8522
+ (the terminal row uses the period endpoint) found zero mismatches in `pan`,
8523
+ `zoom`, `view` and `backdrop_quad`, with the same coverage guard verdict.
8524
+ Figure rows differed from the reference phase on 36 of 37 frames, with
8525
+ zero outside the view.
8526
+
8397
8527
  #### Keyed scene camera (issue #1596)
8398
8528
 
8399
8529
  A camera projects an already posed scene into the fixed canvas. It follows the
@@ -8418,7 +8548,8 @@ The example object is the value of `camera`. `backdrop` names one scene plate
8418
8548
  behind the characters. A track names a final composed animation, including
8419
8549
  `idle` or a prefixed clip. A take without a track uses the existing view.
8420
8550
  Times are seconds, strictly increasing from zero through the declared
8421
- duration. Pan offsets the view center from the stage center in canvas pixels,
8551
+ duration. For a take listed in `scene.repeats`, author the camera through
8552
+ duration divided by its repeat count. Pan offsets the view center from the stage center in canvas pixels,
8422
8553
  with positive X right and positive Y down. Zoom is positive and finite.
8423
8554
  Zoom 1 shows a stage-sized window. Zoom 2 halves its visible width and height
8424
8555
  about the panned center. The first and last pan and zoom must agree on a
package/docs/STABILITY.md CHANGED
@@ -457,6 +457,22 @@ the sorted field names whose presence or digest changed. It returns an empty
457
457
  array for matching or legacy manifests. See the workflow in
458
458
  [Keeping assembled parts current](AUTHORING.md#keeping-assembled-parts-current).
459
459
 
460
+ ## Programmatic physics-only clip discovery
461
+
462
+ The stable named subpath `@rig-c/parts/physics-clips` exports
463
+ `physicsOnlyClips(motion: unknown): Array<{ name: string; duration: number; constraints: string[] }>`.
464
+ Pass a parsed `rigc-motion/1` document. Results follow the document's
465
+ `animations` order, excluding `idle`. A clip qualifies when it has at least one
466
+ track, every track targets only a named physics constraint, and other animation
467
+ payloads are empty or absent. Clip metadata such as `loop` and `note` is allowed.
468
+ Each result carries the source clip name and duration, with distinct constraint
469
+ names in first-keyed order. An input with no qualifying clips returns `[]`.
470
+ Invalid motion is refused with
471
+ `PHYSICS_CLIPS_MOTION`.
472
+
473
+ `compose` uses the same export to discover clips for `characters[].with_idle`.
474
+ See [Physics clips and scene repeats](AUTHORING.md#physics-clips-and-scene-repeats-issue-1615).
475
+
460
476
  ## Programmatic parts file references
461
477
 
462
478
  `@rig-c/parts/src/parts.ts` exports `partsFileReferences(dir: string):
@@ -1196,8 +1212,9 @@ execution in historical evidence is inferred from a current export.
1196
1212
  | 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
1213
  | `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. 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`), then optional `output_profile` (`"preview"` or `"no-extremes"`, issue #1610). 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. Identical inputs at identical supplied paths with the same output profile give identical record bytes. The receipt inventories the listed inputs and selected profile, without clocks. 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. |
1198
1214
  | compose output profiles | `compose` | Issue #1610 adds `--no-extremes` to omit only the extremes diagnostic renders, and `--output-profile preview` to also omit `check/idle_frames/`, `check/contact.png` and `check/motion_heat.png`. Preview takes precedence when both flags are given. Preview uses the stock idle render and existing readers. Before preview success, Parts removes the idle render directory, including Core's temporary contact sheet, skips copying the sheet to the check root, and skips generating heat. Each omission has a diagnostic `SKIP` line naming its selected flag. The gate, camera binding and check requirements still apply. Success prints `compose: PREVIEW — checks met; …` or `compose: NO EXTREMES — checks met; …`, respectively, and writes `output_profile` as `"preview"` or `"no-extremes"`. Default compose keeps its existing file bytes (with the nested Core receipt clock comparison described above), output paths and `compose: PASS — …` line. `COMPOSE_PREVIEW_REQUIRED_CHECK` refuses a valid loop seam pair in preview with `found=preview, required=default or no-extremes`, because the `loop_seam` record in `check.json` binds the paths and hashes of first and wrap PNGs that must remain under `check/idle_frames/`. Compose clears its owned outputs before this refusal. See [Compose output profiles](AUTHORING.md#compose-output-profiles-issue-1610). |
1199
- | 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`) |
1215
+ | 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`). `scene.json` echoes the optional `repeats` map in declared order as the final top-level key after `idle_duration`, omitting it when absent. |
1200
1216
  | 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) |
1217
+ | physics clips and scene repeats | `compose` | Issue #1615 adds `characters[].with_idle` and top-level `repeats` to `spine-parts-scene/1`. Each physics-only side clip requires literal `false` at any character scale or a safe integer count of at least 1 at scale 1. Numeric declarations fold whole periods into `idle` with exact duration equality. Both values retain `<id>:<clip>` subject to the character's scale checks, and the character report row echoes `with_idle` when declared. A scene repeat count is a safe integer of at least 2 on an authored take. Its duration remains the whole take length. Its tracks, deforms and camera keys use the exact duration divided by the count as their period. Repeated camera keys are expanded in report /2, with coverage on the full take clock and per-frame figure measurements. See [Physics clips and scene repeats](AUTHORING.md#physics-clips-and-scene-repeats-issue-1615) |
1201
1218
  | `idle.png`, `idle-indexed.png`, `idle.gif` | `loop`, `build --loop` | APNG and GIF encodings of the rendered idle |
1202
1219
  | `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 |
1203
1220
  | 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,10 +1,11 @@
1
1
  {
2
2
  "name": "rig-parts",
3
- "version": "2.64.0",
3
+ "version": "2.66.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": {
7
7
  "./assembly-reading": "./src/assembly-reading.ts",
8
+ "./physics-clips": "./src/physics-clips.ts",
8
9
  "./cloth-targets.json": "./src/cloth-targets.json",
9
10
  "./*": "./*"
10
11
  },
@@ -0,0 +1,50 @@
1
+ import { PartsError, type Problem, refuseIfAny } from './errors.ts';
2
+
3
+ function isRecord(value: unknown): value is Record<string, unknown> {
4
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
5
+ }
6
+
7
+ function kind(value: unknown): string {
8
+ return value === null ? 'null' : Array.isArray(value) ? 'array' : value === undefined ? 'absent' : typeof value;
9
+ }
10
+
11
+ const CLIP_FIELDS = new Set(['duration', 'loop', 'note', 'tracks']);
12
+ const OTHER_TARGETS = ['bone', 'group', 'slot', 'path', 'slider'];
13
+
14
+ /** The side clips that need a compose `with_idle` declaration, in motion order. */
15
+ export function physicsOnlyClips(motion: unknown): Array<{ name: string; duration: number; constraints: string[] }> {
16
+ const code = 'PHYSICS_CLIPS_MOTION';
17
+ if (!isRecord(motion) || motion.spec !== 'rigc-motion/1' || !isRecord(motion.animations)) {
18
+ const found = isRecord(motion)
19
+ ? `spec ${typeof motion.spec === 'string' ? JSON.stringify(motion.spec) : kind(motion.spec)}; animations ${kind(motion.animations)}`
20
+ : kind(motion);
21
+ throw new PartsError([{ code, object: 'motion', detail: `found ${found}. Pass a parsed rigc-motion/1 with an animations object` }]);
22
+ }
23
+ const clips: ReturnType<typeof physicsOnlyClips> = [];
24
+ const problems: Problem[] = [];
25
+ for (const [name, clip] of Object.entries(motion.animations)) {
26
+ if (!isRecord(clip) || typeof clip.duration !== 'number' || !Number.isFinite(clip.duration) ||
27
+ !Array.isArray(clip.tracks) || !clip.tracks.every(isRecord)) {
28
+ const found = isRecord(clip)
29
+ ? `duration ${typeof clip.duration === 'number' ? clip.duration : kind(clip.duration)}, tracks ${kind(clip.tracks)}`
30
+ : kind(clip);
31
+ problems.push({ code, object: `motion.animations[${JSON.stringify(name)}]`, detail: `found ${found}. Requires a finite duration and an array of track objects` });
32
+ continue;
33
+ }
34
+ if (name === 'idle' || clip.tracks.length === 0 || Object.entries(clip).some(([key, value]) =>
35
+ !CLIP_FIELDS.has(key) && value !== undefined && !(Array.isArray(value) && value.length === 0))) continue;
36
+
37
+ const constraints = new Set<string>();
38
+ for (const track of clip.tracks) {
39
+ if (typeof track.physics !== 'string' || track.physics === '' ||
40
+ OTHER_TARGETS.some(key => Object.hasOwn(track, key))) {
41
+ constraints.clear();
42
+ break;
43
+ }
44
+ constraints.add(track.physics);
45
+ }
46
+ if (constraints.size > 0) clips.push({ name, duration: clip.duration, constraints: [...constraints] });
47
+ }
48
+ refuseIfAny(problems);
49
+ return clips;
50
+ }
package/src/scene.ts CHANGED
@@ -82,6 +82,9 @@
82
82
  * `generated`, `unknown`) is copied into `scene.json` and nothing reads it.
83
83
  * - **The idle**: one `idle` holding every character's tracks. It can play
84
84
  * whole source periods per character when the scene declares `idle_repeats`.
85
+ * A physics-only clip needs a `with_idle` count at scale 1 or an explicit
86
+ * `false` at any scale that the character supports.
87
+ * `scene.repeats` splices scene-authored animation and camera keys.
85
88
  * - **A failing bar, by name (issue #203).** A build whose own check is not
86
89
  * green is refused (`SCENE_BUILD_GREEN`) unless every bar it failed is named
87
90
  * in `compose --accept` or the character's `accept` — the two lists are
@@ -113,6 +116,7 @@ import { ACCEPTABLE_BARS, barsNotMet, CHECK_SPEC, type CheckReport, COMPOSE_PREV
113
116
  import { CONSTRAINT_BONE_FIELDS, editorReceiptProblems, ROOT_BONE } from './config.ts';
114
117
  import { cropToSpineY } from './coords.ts';
115
118
  import { failLine, PartsError, type Problem, refuseIfAny } from './errors.ts';
119
+ import { physicsOnlyClips } from './physics-clips.ts';
116
120
  import { readParts } from './parts.ts';
117
121
  import { missingReceipts, readEditorReceipts, type EditorReceipts } from './editreceipt.ts';
118
122
  import { edgeLength } from './length.ts';
@@ -123,8 +127,8 @@ import { clearComposeRun, COMPOSE_RUN_FILE, COMPOSE_RUN_SPEC, type ComposeRun, t
123
127
  import { readRequirements, type RequirementsFile } from './requirements.ts';
124
128
  import { OFFSET_PLACES, rigJsonText, type RigSpec } from './rig.ts';
125
129
  import { pyRound } from './round.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';
127
- import { repeatSceneKeys } from './scenerepeat.ts';
130
+ import { mergeSceneAnimations, readSceneAnimations, readSceneCamera, repeatSceneAnimations, resolveSceneCamera, sceneBoneContext, sceneClipLoopProblems, sceneRepeatCurveProblems, sceneRepeatSourceLoopProblems, type ResolvedSceneCamera, type ResolvedSceneCameraTrack, type SceneAnimations, type SceneCamera, type SceneCameraSample, type ScenePlacementPivot } from './sceneclips.ts';
131
+ import { repeatSceneKeys, type SceneRepeatSeam } from './scenerepeat.ts';
128
132
 
129
133
  /** The scene file's `spec`. */
130
134
  export const SCENE_SPEC = 'spine-parts-scene/1';
@@ -183,6 +187,8 @@ export interface SceneCharacter {
183
187
  placement_pivot?: true;
184
188
  /** Total number of source idle periods within the declared scene idle. */
185
189
  idle_repeats?: number;
190
+ /** Physics-only clips carried into idle by whole periods, or explicitly left beside it. */
191
+ with_idle?: Record<string, number | false>;
186
192
  /** The bars this character's own check may have failed and still be taken (issue #203), as the file lists them; empty when it lists none. */
187
193
  accept: string[];
188
194
  }
@@ -215,6 +221,7 @@ export interface SceneFile {
215
221
  plate: ScenePlate | null;
216
222
  plates?: NamedScenePlate[];
217
223
  animations?: SceneAnimations;
224
+ repeats?: Record<string, number>;
218
225
  camera?: SceneCamera;
219
226
  characters: SceneCharacter[];
220
227
  order: string[];
@@ -300,7 +307,9 @@ export function loadScene(path: string): SceneFile {
300
307
  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)`);
301
308
  }
302
309
  };
303
- known(fields, 'scene', ['spec', 'canvas', 'plate', 'plates', 'characters', 'order', 'animations']);
310
+ const sceneKeys = ['spec', 'canvas', 'plate', 'plates', 'characters', 'order', 'animations'];
311
+ if ('repeats' in o) sceneKeys.push('repeats');
312
+ known(fields, 'scene', sceneKeys);
304
313
  if (o.spec !== SCENE_SPEC) fail('SCENE_SPEC', 'scene.spec', `is ${show(o.spec)}; "${SCENE_SPEC}" is required`);
305
314
 
306
315
  // canvas
@@ -388,6 +397,7 @@ export function loadScene(path: string): SceneFile {
388
397
  const keys = ['id', 'build', 'offset', 'scale', 'accept', 'canvas_clip'];
389
398
  if ('placement_pivot' in c) keys.push('placement_pivot'); // Keep the default unknown-key diagnostic byte-stable.
390
399
  if ('idle_repeats' in c) keys.push('idle_repeats');
400
+ if ('with_idle' in c) keys.push('with_idle');
391
401
  known(c, where, keys);
392
402
  let ok = true;
393
403
  for (const k of ['id', 'build', 'offset']) {
@@ -439,6 +449,23 @@ export function loadScene(path: string): SceneFile {
439
449
  fail('SCENE_REPEAT_COUNT', `${where}.idle_repeats`, `is ${show(repeats)}. Declare a safe integer of 2 or more, or omit the field to use one source period`);
440
450
  ok = false;
441
451
  }
452
+ let withIdle: SceneCharacter['with_idle'];
453
+ if ('with_idle' in c) {
454
+ if (!isRecord(c.with_idle)) {
455
+ fail('SCENE_FIELD_TYPE', `${where}.with_idle`, `is ${show(c.with_idle)}. An object mapping physics-only clip names to repeat counts or false is required`);
456
+ ok = false;
457
+ } else {
458
+ const entries: Array<[string, number | false]> = [];
459
+ for (const [clip, count] of Object.entries(c.with_idle)) {
460
+ if (count === false || (typeof count === 'number' && Number.isSafeInteger(count) && count >= 1)) entries.push([clip, count]);
461
+ else {
462
+ fail('SCENE_REPEAT_COUNT', `${where}.with_idle[${show(clip)}]`, `is ${show(count)}. A safe integer of 1 or more, or false, is required`);
463
+ ok = false;
464
+ }
465
+ }
466
+ withIdle = Object.fromEntries(entries);
467
+ }
468
+ }
442
469
  const acc = c.accept;
443
470
  if ('accept' in c) {
444
471
  if (!(Array.isArray(acc) && acc.every((v) => typeof v === 'string'))) {
@@ -460,6 +487,7 @@ export function loadScene(path: string): SceneFile {
460
487
  ...(c.canvas_clip === true ? { canvas_clip: true } : {}),
461
488
  ...(c.placement_pivot === true ? { placement_pivot: true } : {}),
462
489
  ...(typeof repeats === 'number' ? { idle_repeats: repeats } : {}),
490
+ ...(withIdle === undefined ? {} : { with_idle: withIdle }),
463
491
  });
464
492
  });
465
493
  }
@@ -490,13 +518,26 @@ export function loadScene(path: string): SceneFile {
490
518
  problems.push(...err.problems);
491
519
  }
492
520
  }
521
+ let repeats: SceneFile['repeats'];
522
+ if ('repeats' in o) {
523
+ if (!isRecord(o.repeats)) fail('SCENE_FIELD_TYPE', 'scene.repeats', `is ${show(o.repeats)}. An object mapping take names to repeat counts is required`);
524
+ else {
525
+ const entries: Array<[string, number]> = [];
526
+ for (const [take, count] of Object.entries(o.repeats)) {
527
+ if (typeof count === 'number' && Number.isSafeInteger(count) && count >= 2) entries.push([take, count]);
528
+ else fail('SCENE_REPEAT_COUNT', `scene.repeats[${show(take)}]`, `is ${show(count)}. A safe integer of 2 or more is required`);
529
+ }
530
+ repeats = Object.fromEntries(entries);
531
+ }
532
+ }
493
533
  if (!(isRecord(o.animations) && Object.hasOwn(o.animations, 'idle'))) {
494
534
  for (const c of characters) if (c.idle_repeats !== undefined) {
495
535
  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`);
496
536
  }
497
537
  }
498
538
  refuseIfAny(problems);
499
- return { path: at, sha256, canvas, plate, ...('plates' in o ? { plates } : {}), ...(animations === undefined ? {} : { animations }), ...(camera === undefined ? {} : { camera }), characters, order };
539
+ return { path: at, sha256, canvas, plate, ...('plates' in o ? { plates } : {}), ...(animations === undefined ? {} : { animations }),
540
+ ...(repeats === undefined ? {} : { repeats }), ...(camera === undefined ? {} : { camera }), characters, order };
500
541
  }
501
542
 
502
543
  // ---------------------------------------------------------------------------
@@ -549,6 +590,47 @@ function animationsOf(motion: MotionSpec): Record<string, SceneAnimation> {
549
590
  return motion.animations as unknown as Record<string, SceneAnimation>;
550
591
  }
551
592
 
593
+ /** Maximum copies of each source searched for a diagnostic hint. Acceptance compares the declared counts directly. */
594
+ const WITH_IDLE_DIAGNOSTIC_COPY_LIMIT = 10_000;
595
+
596
+ function compareRepeatDurations(left: number, right: number): -1 | 0 | 1 {
597
+ return left === right ? 0 : left < right ? -1 : 1;
598
+ }
599
+
600
+ function idleRepeatAdvice(name: string, idlePeriod: number, clipPeriod: number, scenePeriodMatchesIdle: boolean): string {
601
+ if (Number.isFinite(idlePeriod) && idlePeriod > 0 && Number.isFinite(clipPeriod) && clipPeriod > 0) {
602
+ let idleCount = 1;
603
+ let clipCount = 1;
604
+ while (idleCount <= WITH_IDLE_DIAGNOSTIC_COPY_LIMIT && clipCount <= WITH_IDLE_DIAGNOSTIC_COPY_LIMIT) {
605
+ const idleDuration = idleCount * idlePeriod;
606
+ const clipDuration = clipCount * clipPeriod;
607
+ if (!Number.isFinite(idleDuration) || !Number.isFinite(clipDuration)) break;
608
+ // Only the smaller product can catch the other, so the first match has the least idle count and then clip count.
609
+ const order = compareRepeatDurations(idleDuration, clipDuration);
610
+ if (order === 0) {
611
+ const clipField = `with_idle.${name}: ${clipCount}`;
612
+ const unknownScenePeriod = "Cannot name a scene.repeats count because the scene's own period is not declared.";
613
+ if (idleCount === 1) {
614
+ const sceneAdvice = scenePeriodMatchesIdle
615
+ ? `Omit scene.repeats.idle and keep scene.animations.idle.duration: ${idleDuration} (camera terminal key ${idleDuration} s).`
616
+ : unknownScenePeriod;
617
+ return `Omit idle_repeats and write ${clipField} (${idleDuration} s). ${sceneAdvice}`;
618
+ }
619
+ if (scenePeriodMatchesIdle) {
620
+ return `Write idle_repeats: ${idleCount}, ${clipField}, scene.repeats.idle: ${idleCount}, and scene.animations.idle.duration: ${idleDuration} ` +
621
+ `(composed camera terminal key ${idleDuration} s, authored terminal key stays at ${idlePeriod} s).`;
622
+ }
623
+ return `Write idle_repeats: ${idleCount} and ${clipField} (${idleDuration} s). ${unknownScenePeriod}`;
624
+ }
625
+ if (order < 0) idleCount++;
626
+ else clipCount++;
627
+ }
628
+ }
629
+ const limit = String(WITH_IDLE_DIAGNOSTIC_COPY_LIMIT).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
630
+ return `No pair within ${limit} copies of each for source idle ${idlePeriod} s and source clip ${clipPeriod} s. ` +
631
+ 'Retime the clip at its source in motion.animations_from, change the source idle\'s motion.duration, or declare false.';
632
+ }
633
+
552
634
  function readJson(path: string, what: string, problems: Problem[], consumed: (bytes: Uint8Array) => void): unknown {
553
635
  if (!existsSync(path)) {
554
636
  problems.push({ code: 'SCENE_BUILD_PRESENT', object: path, detail: `no such file; ${what}` });
@@ -1296,6 +1378,7 @@ export interface SceneCharacterReport {
1296
1378
  constraints: number;
1297
1379
  idle_duration: number;
1298
1380
  idle_repeats?: number;
1381
+ with_idle?: Record<string, number | false>;
1299
1382
  /** The bars the character's own check failed that `--accept` or its `accept` took (issue #203); written only when there are any, so a scene of green builds writes the bytes it wrote before the field existed. */
1300
1383
  accepted?: string[];
1301
1384
  }
@@ -1312,6 +1395,7 @@ interface SceneReportV1 {
1312
1395
  characters: SceneCharacterReport[];
1313
1396
  order: { declared: string[]; slots: string[]; judged_by: 'nothing' };
1314
1397
  idle_duration: number;
1398
+ repeats?: Record<string, number>;
1315
1399
  }
1316
1400
 
1317
1401
  export type SceneReport = SceneReportV1 | (Omit<SceneReportV1, 'spec'> & {
@@ -1327,6 +1411,8 @@ export interface ComposedScene {
1327
1411
  report: SceneReport;
1328
1412
  /** Opt-in declaration retained for pre-emission pose measurement; never serialized. */
1329
1413
  sceneAnimations?: SceneAnimations;
1414
+ /** Compiled timeline addresses checked at the final gate; never serialized. */
1415
+ repeatSeams: SceneRepeatSeam[];
1330
1416
  sceneCamera?: ResolvedSceneCamera;
1331
1417
  }
1332
1418
 
@@ -1406,6 +1492,11 @@ function measureSceneCamera(build: string, composed: ComposedScene, camera: Reso
1406
1492
  // Keep authored ticks exact, including keys on that grid. Both the camera
1407
1493
  // and the packed pose read the same phase at their own clock precision.
1408
1494
  const times = authoredTimes.map(time => time === track.duration ? compiledDuration : time / track.duration * compiledDuration);
1495
+ const { period } = track;
1496
+ const periodTicks = period === undefined ? 0 : Math.round(period * IDLE_FPS);
1497
+ const totalTicks = Math.round(track.duration * IDLE_FPS);
1498
+ const samplePeriod = periodTicks > 0 && periodTicks / IDLE_FPS === period && totalTicks / IDLE_FPS === track.duration &&
1499
+ totalTicks % periodTicks === 0 ? track.samplePeriod : undefined;
1409
1500
  const frames: CameraFrameReport[] = [];
1410
1501
  // The track remains unwrapped through the closing pose, with one
1411
1502
  // physics clock stepping the entire schedule, including a short end step.
@@ -1415,7 +1506,12 @@ function measureSceneCamera(build: string, composed: ComposedScene, camera: Reso
1415
1506
  object = `${field} frame ${index} (t=${time} s, authored ${authored} s)`;
1416
1507
  const fail = (code: string, detail: string): void => { problems.push({ code, object, detail }); };
1417
1508
  let sample: SceneCameraSample;
1418
- try { sample = track.sample(authored); }
1509
+ try {
1510
+ // The player still reads the global i/fps grid. Exact frame phase
1511
+ // avoids subtracting two rounded global times on each tiled copy.
1512
+ sample = samplePeriod === undefined ? track.sample(authored) :
1513
+ samplePeriod(index === times.length - 1 ? periodTicks / IDLE_FPS : (index % periodTicks) / IDLE_FPS);
1514
+ }
1419
1515
  catch (err) {
1420
1516
  if (!(err instanceof PartsError)) throw err;
1421
1517
  for (const problem of err.problems) fail(problem.code, problem.detail);
@@ -1599,6 +1695,10 @@ export function composeScene(
1599
1695
  const hasRepeats = scene.characters.some(c => c.idle_repeats !== undefined);
1600
1696
  const clip = scene.animations?.idle;
1601
1697
  const idleDuration = hasRepeats ? clip?.duration ?? 0 : durations[0];
1698
+ const sceneIdleRepeat = scene.repeats !== undefined && Object.hasOwn(scene.repeats, 'idle') ? scene.repeats.idle : undefined;
1699
+ const sceneIdleClock = sceneIdleRepeat === undefined ? 'scene.animations.idle.duration' : `scene.animations.idle.duration for scene.repeats["idle"]: ${sceneIdleRepeat}`;
1700
+ const idleClockFields: string[] = [];
1701
+ const importedIdleMismatches: Array<{ field: string; found: number; problem: Problem }> = [];
1602
1702
  if (hasRepeats) scene.characters.forEach((c, i) => {
1603
1703
  if (clip === undefined) {
1604
1704
  if (c.idle_repeats !== undefined) 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`);
@@ -1608,8 +1708,13 @@ export function composeScene(
1608
1708
  if (idle === undefined) return;
1609
1709
  const count = c.idle_repeats ?? 1;
1610
1710
  const period = idle.duration;
1611
- if (!Number.isFinite(period) || period <= 0 || !Number.isFinite(idleDuration) || idleDuration <= 0 || idleDuration !== count * period) {
1612
- fail('SCENE_REPEAT_DURATION', 'scene.animations.idle.duration', `is ${idleDuration} s for character ${show(c.id)}. Its ${period} s idle repeated ${count} times requires exactly ${count * period} s (tolerance 0 s)`);
1711
+ const field = `scene.characters[${i}].idle_repeats`;
1712
+ if (c.idle_repeats !== undefined) idleClockFields.push(`${field} for character ${show(c.id)} implies ${count * period} s (${count} × ${period} s)`);
1713
+ if (!Number.isFinite(period) || period <= 0 || !Number.isFinite(idleDuration) || idleDuration <= 0 || compareRepeatDurations(idleDuration, count * period) !== 0) {
1714
+ const problem = { code: 'SCENE_REPEAT_DURATION', object: 'scene.animations.idle.duration',
1715
+ detail: `is ${idleDuration} s for character ${show(c.id)}. Its ${period} s idle repeated ${count} times requires exactly ${count * period} s (tolerance 0 s)` };
1716
+ problems.push(problem);
1717
+ importedIdleMismatches.push({ field, found: count * period, problem });
1613
1718
  }
1614
1719
  if (c.idle_repeats !== undefined && idle.loop !== true) {
1615
1720
  fail('SCENE_REPEAT_SOURCE_LOOP_CLOSES', `scene.characters[${i}] motion.json animations.idle`, `loop is ${show(idle.loop)}; repeating requires a closed source idle with loop: true`);
@@ -1619,6 +1724,62 @@ export function composeScene(
1619
1724
  fail('SCENE_DURATION_AGREES', 'scene.characters', `have idles of ${ready.map((b, i) => `"${b.id}" ${durations[i]} s`).join(', ')}; one idle holds every character's tracks, so one duration is required — rebuild with one motion.duration`);
1620
1725
  }
1621
1726
 
1727
+ const foldedClips = new Map<string, Map<string, SceneAnimation>>();
1728
+ const withIdleClockFields: string[] = [];
1729
+ for (const [i, c] of scene.characters.entries()) {
1730
+ const character = `scene.characters[${i}]`;
1731
+ const declarations = c.with_idle ?? {};
1732
+ if (c.scale !== 1 && Object.values(declarations).some(count => typeof count === 'number')) {
1733
+ fail('SCENE_SCALE_EXACT', `${character}.with_idle`, `character ${show(c.id)} has scale ${c.scale}. with_idle applies at scale 1 only`);
1734
+ }
1735
+ const b = byId.get(c.id);
1736
+ if (b === undefined) continue;
1737
+ const animations = animationsOf(b.motion);
1738
+ const physicsClips = new Map(physicsOnlyClips(b.motion).map(row => [row.name, row]));
1739
+ const clips = new Map<string, SceneAnimation>();
1740
+ for (const { name, constraints } of physicsClips.values()) {
1741
+ if (!Object.hasOwn(declarations, name)) {
1742
+ const count = constraints.length;
1743
+ const advice = c.scale === 1
1744
+ ? 'Declare its whole-period repeat count to carry it into idle or false to play idle without it'
1745
+ : `At scale ${c.scale}, declare false to play idle without it. A repeat count applies at scale 1 only`;
1746
+ fail('SCENE_PHYSICS_CLIP_DECLARED', `${character}.with_idle[${JSON.stringify(name)}]`,
1747
+ `character ${show(c.id)} carries physics-only clip ${show(name)} keying ${count} physics constraint${count === 1 ? '' : 's'}. ${advice}`);
1748
+ }
1749
+ }
1750
+ for (const [name, count] of Object.entries(declarations)) {
1751
+ const object = `${character}.with_idle[${JSON.stringify(name)}]`;
1752
+ const source = name !== 'idle' && Object.hasOwn(animations, name) ? animations[name] : undefined;
1753
+ const physicsClip = physicsClips.get(name);
1754
+ if (source === undefined || physicsClip === undefined) {
1755
+ fail('SCENE_PHYSICS_CLIP_ONLY', object, `character ${show(c.id)} ${source === undefined ? 'has no clip beside idle named' : 'has a clip with other timelines or no physics keys named'} ${show(name)}. Name a clip beside idle with only physics-constraint tracks`);
1756
+ continue;
1757
+ }
1758
+ if (count === false || c.scale !== 1) continue;
1759
+ const period = physicsClip.duration;
1760
+ const foldedDuration = count * period;
1761
+ if (Number.isFinite(foldedDuration)) withIdleClockFields.push(`${object} for character ${show(c.id)} implies ${foldedDuration} s (${count} × ${period} s)`);
1762
+ const sourceIdle = animations.idle.duration;
1763
+ if (!Number.isFinite(foldedDuration) || foldedDuration <= 0 || compareRepeatDurations(idleDuration, foldedDuration) !== 0) {
1764
+ const idleField = c.idle_repeats === undefined ? `character ${show(c.id)}'s source idle` : `${character}.idle_repeats: ${c.idle_repeats} (implies ${c.idle_repeats * sourceIdle} s)`;
1765
+ const sceneField = clip === undefined ? '' : ` ${sceneIdleClock} declares ${clip.duration} s.`;
1766
+ const advice = idleRepeatAdvice(name, sourceIdle, period, sceneIdleRepeat === undefined && clip?.duration === sourceIdle);
1767
+ fail('SCENE_WITH_IDLE_DURATION', object, `character ${show(c.id)} clip ${show(name)} at ${count} × ${period} s implies ${foldedDuration} s. The played idle is ${idleDuration} s with ${idleField}.${sceneField} ${advice}`);
1768
+ continue;
1769
+ }
1770
+ clips.set(name, source);
1771
+ }
1772
+ foldedClips.set(c.id, clips);
1773
+ }
1774
+ for (const mismatch of importedIdleMismatches) {
1775
+ const opts = [
1776
+ ...(sceneIdleRepeat === undefined ? [] : [`${sceneIdleClock} declares ${idleDuration} s`]),
1777
+ ...withIdleClockFields,
1778
+ ];
1779
+ if (opts.length > 0) mismatch.problem.detail += `. ${mismatch.field} implies ${mismatch.found} s. ${opts.join('. ')}.`;
1780
+ }
1781
+ idleClockFields.push(...withIdleClockFields);
1782
+
1622
1783
  // ---- placed bounds --------------------------------------------------------
1623
1784
  const rows: SceneCharacterReport[] = [];
1624
1785
  scene.characters.forEach((c, i) => {
@@ -1679,6 +1840,7 @@ export function composeScene(
1679
1840
  constraints: b.rig.constraints?.length ?? 0,
1680
1841
  idle_duration: b.motion.animations.idle.duration,
1681
1842
  ...(c.idle_repeats === undefined ? {} : { idle_repeats: c.idle_repeats }),
1843
+ ...(c.with_idle === undefined ? {} : { with_idle: { ...c.with_idle } }),
1682
1844
  ...(b.accepted.length === 0 ? {} : { accepted: [...b.accepted] }),
1683
1845
  });
1684
1846
  });
@@ -2083,8 +2245,9 @@ export function composeScene(
2083
2245
  const groups: MotionSpec['groups'] = {};
2084
2246
  const tracks: MotionSpec['animations']['idle']['tracks'] = [];
2085
2247
  const idleDeform: SceneDeform[] = [];
2086
- // Every animation beside a character's idle rides along under its character's prefix (issue #183), its tracks
2087
- // prefixed as the idle's are and nothing else changed: the scene plays the idle, and schedules none of these.
2248
+ const repeatSeams: SceneRepeatSeam[] = [];
2249
+ // Every animation beside a character's idle rides along under its character's prefix (issue #183).
2250
+ // A with_idle count also folds the declared physics clip into the composed idle (#1615).
2088
2251
  const beside: Record<string, SceneAnimation> = {};
2089
2252
  const notes = new Set(ready.map((b) => b.motion.animations.idle.note));
2090
2253
  for (const [i, c] of scene.characters.entries()) {
@@ -2092,7 +2255,7 @@ export function composeScene(
2092
2255
  const id = c.id;
2093
2256
  for (const [k, v] of Object.entries(b.motion.easings)) easings[prefixed(id, k)] = v;
2094
2257
  for (const [k, v] of Object.entries(b.motion.groups)) groups[prefixed(id, k)] = v.map((n) => P(id, n));
2095
- const prefixTrack = (t: MotionSpec['animations']['idle']['tracks'][number], repeatedIdle = false): MotionSpec['animations']['idle']['tracks'][number] => {
2258
+ const prefixTrack = (t: MotionSpec['animations']['idle']['tracks'][number], literalStepped = false): MotionSpec['animations']['idle']['tracks'][number] => {
2096
2259
  const tr = { ...t } as Record<string, unknown>;
2097
2260
  if (typeof tr.bone === 'string') tr.bone = P(id, tr.bone);
2098
2261
  if (typeof tr.group === 'string') tr.group = prefixed(id, tr.group);
@@ -2100,7 +2263,7 @@ export function composeScene(
2100
2263
  const memberMap = (v: Record<string, unknown>): Record<string, unknown> => Object.fromEntries(Object.entries(v).map(([n, value]) => [P(id, n), value]));
2101
2264
  tr.keys = (t.keys as unknown as Array<Record<string, unknown>>).map((k) => ({
2102
2265
  ...k,
2103
- ...(typeof k.ease === 'string' && !(repeatedIdle && k.ease === 'stepped') ? { ease: prefixed(id, k.ease) } : {}),
2266
+ ...(typeof k.ease === 'string' && !(literalStepped && k.ease === 'stepped') ? { ease: prefixed(id, k.ease) } : {}),
2104
2267
  ...(isRecord(k.v) ? { v: memberMap(k.v) } : {}),
2105
2268
  ...(isRecord(k.derive) ? { derive: { ...k.derive, ...(isRecord(k.derive.depth) ? { depth: memberMap(k.derive.depth) } : {}) } } : {}),
2106
2269
  }));
@@ -2124,7 +2287,18 @@ export function composeScene(
2124
2287
  }
2125
2288
  for (const t of idle.tracks) tracks.push(scaledTrack(prefixTrack(t, repeats !== undefined), c.scale));
2126
2289
  idleDeform.push(...(deforms(idle, repeats !== undefined).deform ?? []));
2127
- for (const [n, a] of Object.entries(animations)) if (n !== 'idle') beside[prefixed(id, n)] = { ...a, tracks: a.tracks.map((t) => scaledTrack(prefixTrack(t), c.scale)), ...deforms(a) };
2290
+ for (const [n, a] of Object.entries(animations)) if (n !== 'idle') {
2291
+ const source = foldedClips.get(id)?.get(n);
2292
+ const count = c.with_idle?.[n];
2293
+ const declared = c.with_idle !== undefined && Object.hasOwn(c.with_idle, n);
2294
+ beside[prefixed(id, n)] = { ...a, tracks: a.tracks.map(t => scaledTrack(prefixTrack(t, declared), c.scale)), ...deforms(a) };
2295
+ if (source === undefined || typeof count !== 'number') continue;
2296
+ const object = `scene.characters[${i}].with_idle[${JSON.stringify(n)}]`;
2297
+ const folded = repeatSceneKeys(source, count, idleDuration, b.motion.groups, object, undefined, {
2298
+ take: 'idle', into: repeatSeams, mapTarget: name => prefixed(id, name),
2299
+ });
2300
+ for (const t of folded.tracks) tracks.push(prefixTrack(t, true));
2301
+ }
2128
2302
  }
2129
2303
  const note = notes.size === 1 ? [...notes][0] : ready.map((b) => `${b.id}: ${b.motion.animations.idle.note}`).join(' | ');
2130
2304
  const motion: MotionSpec = { spec: 'rigc-motion/1', archetype: name, cut: name, easings, groups, animations: { idle: { duration: idleDuration, loop: true, note, tracks, ...(idleDeform.length === 0 ? {} : { deform: idleDeform }) }, ...beside } };
@@ -2150,8 +2324,23 @@ export function composeScene(
2150
2324
  }
2151
2325
  refuseIfAny(problems);
2152
2326
  }
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);
2327
+ let sceneAnimations = scene.animations;
2328
+ let sceneCamera: ResolvedSceneCamera | undefined;
2329
+ try {
2330
+ if (scene.repeats !== undefined) {
2331
+ const repeated = repeatSceneAnimations(scene.animations, motion.groups, scene.repeats, repeatSeams);
2332
+ if (scene.animations !== undefined) sceneAnimations = repeated;
2333
+ }
2334
+ if (sceneAnimations !== undefined || pivots.size > 0) mergeSceneAnimations(rig, motion, sceneAnimations ?? {}, [...pivots.values()]);
2335
+ if (scene.camera !== undefined) sceneCamera = resolveSceneCamera(scene.camera, motion, scene.repeats);
2336
+ } catch (err) {
2337
+ if (!(err instanceof PartsError) || sceneIdleRepeat === undefined || idleClockFields.length === 0) throw err;
2338
+ throw new PartsError(err.problems.map(problem => {
2339
+ if (!['SCENE_REPEAT_DURATION', 'SCENE_CAMERA_TRACK', 'SCENE_DURATION_AGREES'].includes(problem.code) ||
2340
+ !['scene.animations.idle', 'scene.animations["idle"]', 'scene.camera.tracks["idle"]', 'scene.repeats["idle"]'].some(field => problem.object.startsWith(field))) return problem;
2341
+ return { ...problem, detail: `${problem.detail} ${idleClockFields.join('. ')}.` };
2342
+ }));
2343
+ }
2155
2344
  if (sceneCamera !== undefined) {
2156
2345
  for (const [name, track] of sceneCamera.tracks) for (const key of track.keys) {
2157
2346
  if (cameraViewport(stage, key) === null) fail('SCENE_CAMERA_TRACK', `scene.camera.tracks[${show(name)}]`,
@@ -2174,8 +2363,9 @@ export function composeScene(
2174
2363
  characters: rows,
2175
2364
  order: { declared: [...scene.order], slots: slots.map((s) => s.name), judged_by: 'nothing' },
2176
2365
  idle_duration: idleDuration,
2366
+ ...(scene.repeats === undefined ? {} : { repeats: { ...scene.repeats } }),
2177
2367
  };
2178
- return { rig, motion, images, report, ...(scene.animations === undefined ? {} : { sceneAnimations: scene.animations }), ...(sceneCamera === undefined ? {} : { sceneCamera }) };
2368
+ return { rig, motion, images, report, repeatSeams, ...(sceneAnimations === undefined ? {} : { sceneAnimations }), ...(sceneCamera === undefined ? {} : { sceneCamera }) };
2179
2369
  }
2180
2370
 
2181
2371
  // ---------------------------------------------------------------------------
@@ -2513,6 +2703,9 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
2513
2703
  for (const c of r.characters) {
2514
2704
  const clipped = c.clipped_bounds === undefined ? '' : `; clipped bounds [${c.clipped_bounds.join(', ')}]`;
2515
2705
  say(` ${c.id}: ${c.build} at offset [${c.offset.join(', ')}], scale ${c.scale ?? 1}, bounds [${c.bounds.join(', ')}], shift [${c.shift.join(', ')}] on ${c.shifted.bones.length} first-level bone(s), ${c.shifted.root_regions.length} region(s) on root and ${c.shifted.root_weights} weight(s) bound to root; ${c.bones} bone(s), ${c.slots} slot(s), ${c.tracks} track(s), ${c.constraints} constraint(s), rig_scale ${c.rig_scale}, idle ${c.idle_duration} s${c.accepted === undefined ? '' : `; its own check FAILED ${c.accepted.join(', ')}, accepted — the scene is for looking, not shipping`}${clipped}`);
2706
+ for (const [clip, count] of Object.entries(c.with_idle ?? {})) {
2707
+ say(` ${prefixed(c.id, clip)} ${count === false ? 'plays beside idle only (with_idle: false)' : `carried into idle for ${count} source period${count === 1 ? '' : 's'} and retained beside it`}`);
2708
+ }
2516
2709
  }
2517
2710
  say(` order (declared, judged by nothing): ${r.order.declared.join(', ')} -> ${r.order.slots.length} slot(s), back to front`);
2518
2711
  const texts: Array<[string, string]> = [
@@ -2523,13 +2716,15 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
2523
2716
  const gated: { camera?: CameraEvidence } = {};
2524
2717
  let gate: ReturnType<typeof gateThroughRigc>;
2525
2718
  try {
2526
- const clips = composed.sceneAnimations;
2527
- const readLoop = (build: string): void => {
2528
- if (clips === undefined) return;
2529
- refuseIfAny(sceneClipLoopProblems(readFileSync(join(build, 'skeleton.model.json'), 'utf8'), clips, r.characters.some(c => c.idle_repeats !== undefined)));
2719
+ const { sceneAnimations: clips, repeatSeams } = composed;
2720
+ const checkMotion = (build: string): void => {
2721
+ if (clips === undefined && repeatSeams.length === 0) return;
2722
+ const modelText = readFileSync(join(build, CAMERA_MODEL), 'utf8');
2723
+ refuseIfAny(sceneRepeatCurveProblems(modelText, repeatSeams));
2724
+ if (clips !== undefined) refuseIfAny(sceneClipLoopProblems(modelText, clips, r.characters.some(c => c.idle_repeats !== undefined)));
2530
2725
  };
2531
2726
  if (camera === undefined) {
2532
- gate = gateThroughRigc(composed.images, texts, run.rig, run.scratch, mode, clips === undefined ? undefined : readLoop);
2727
+ gate = gateThroughRigc(composed.images, texts, run.rig, run.scratch, mode, clips === undefined && repeatSeams.length === 0 ? undefined : checkMotion);
2533
2728
  } else {
2534
2729
  // Core binds the model to skeleton.json, whose image path is relative
2535
2730
  // to the build. Mirror check's rig/ and check/build/ in gate scratch.
@@ -2539,7 +2734,7 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
2539
2734
  try {
2540
2735
  const packed: RigcRunner = args => run.rig(args.map((arg, i) => args[i - 1] === '--out' ? build : arg));
2541
2736
  gate = gateThroughRigc(composed.images, texts, packed, scratch, mode, () => {
2542
- readLoop(build);
2737
+ checkMotion(build);
2543
2738
  gated.camera = measureSceneCamera(build, composed, camera);
2544
2739
  });
2545
2740
  } finally {
@@ -2606,7 +2801,8 @@ export function composeStage(input: ComposeInput, run: ComposeRunners, log: Log)
2606
2801
  }
2607
2802
  const writeCameraReport = (): void => {
2608
2803
  if (evidence === undefined || !cameraBound) return;
2609
- composed.report = { ...r, spec: SCENE_CAMERA_REPORT_SPEC, camera: evidence.report };
2804
+ const { repeats, ...base } = r;
2805
+ composed.report = { ...base, spec: SCENE_CAMERA_REPORT_SPEC, camera: evidence.report, ...(repeats === undefined ? {} : { repeats }) };
2610
2806
  writeFileSync(reportPath, rigJsonText(composed.report));
2611
2807
  say(`${wroteRig}, and ${reportPath}`);
2612
2808
  };
package/src/sceneclips.ts CHANGED
@@ -2,10 +2,11 @@
2
2
  import { bezierForChannel, f32 } from '@rig-c/core/compile';
3
3
  import { CompileError } from '@rig-c/core/errors';
4
4
  import { parseMotionSpec, type MotionSpec as CoreMotion } from '@rig-c/core/motion';
5
- import { bezierPolyline, CORE_DOCUMENT_SPEC, CoreInputError, poseRawAnimation, readModel, type RawPose } from '@rig-c/core/core';
5
+ import { bezierPolyline, CORE_DOCUMENT_SPEC, CoreInputError, poseRawAnimation, readModel, type CompiledDocument, type RawPose } from '@rig-c/core/core';
6
6
  import { PartsError, refuseIfAny, type Problem } from './errors.ts';
7
7
  import type { MotionSpec } from './motion.ts';
8
8
  import type { RigSpec } from './rig.ts';
9
+ import { repeatSceneKeys, repeatSceneTimeline, type SceneRepeatSeam } from './scenerepeat.ts';
9
10
 
10
11
  export type SceneAnimations = CoreMotion['animations'];
11
12
 
@@ -30,6 +31,9 @@ export interface ResolvedSceneCameraTrack {
30
31
  keys: Omit<SceneCameraKey, 'ease'>[];
31
32
  duration: number;
32
33
  loop: boolean;
34
+ /** The source clock for exact per-period coverage phases. */
35
+ period?: number;
36
+ samplePeriod?(time: number): SceneCameraSample;
33
37
  /** Sample on the authored clock, including the unwrapped terminal time. */
34
38
  sample(time: number): SceneCameraSample;
35
39
  }
@@ -198,7 +202,7 @@ function cameraLoopProblem(first: SceneCameraSample, last: SceneCameraSample, du
198
202
  }
199
203
 
200
204
  /** Resolve only declared tracks, against the final take and easing names. */
201
- export function resolveSceneCamera(camera: SceneCamera, motion: MotionSpec): ResolvedSceneCamera {
205
+ export function resolveSceneCamera(camera: SceneCamera, motion: MotionSpec, repeats?: Readonly<Record<string, number>>): ResolvedSceneCamera {
202
206
  const problems: Problem[] = [];
203
207
  const tracks = new Map<string, ResolvedSceneCameraTrack>();
204
208
  for (const [name, authored] of Object.entries(camera.tracks)) {
@@ -210,14 +214,21 @@ export function resolveSceneCamera(camera: SceneCamera, motion: MotionSpec): Res
210
214
  }
211
215
  const { duration } = take;
212
216
  const loop = take.loop === true;
217
+ const count = repeats !== undefined && Object.hasOwn(repeats, name) ? repeats[name] : undefined;
218
+ const period = count === undefined ? duration : duration / count;
219
+ const closedPeriod = loop || count !== undefined;
213
220
  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` });
221
+ if (last === undefined || last.t !== period) {
222
+ const found = last === undefined ? 'no key' : `${last.t} s`;
223
+ const detail = count === undefined
224
+ ? `Take ${JSON.stringify(name)} declares ${duration} s and the terminal key must match exactly`
225
+ : `Take ${JSON.stringify(name)} declares ${duration} s and scene.repeats[${JSON.stringify(name)}] is ${count}. The terminal key must match the ${period} s period exactly`;
226
+ problems.push({ code: CAMERA_TRACK, object, detail: `ends at ${found}. ${detail}` });
216
227
  continue;
217
228
  }
218
229
  const before = problems.length;
219
- if (loop) {
220
- const problem = cameraLoopProblem(first, last, duration, object, 'Authored');
230
+ if (closedPeriod) {
231
+ const problem = cameraLoopProblem(first, last, period, object, 'Authored');
221
232
  if (problem !== null) problems.push(problem);
222
233
  }
223
234
 
@@ -256,14 +267,22 @@ export function resolveSceneCamera(camera: SceneCamera, motion: MotionSpec): Res
256
267
  let coreStart: SceneCameraSample | undefined, coreEnd: SceneCameraSample | undefined;
257
268
  if (eased) {
258
269
  try {
259
- coreSample = cameraCoreSampler(keys, times, duration, object);
270
+ coreSample = cameraCoreSampler(keys, times, period, object);
260
271
  const storedEnd = Math.fround(times[times.length - 1]);
261
272
  coreStart = coreSample(0);
262
273
  coreEnd = coreSample(storedEnd);
263
- if (loop) {
274
+ if (closedPeriod) {
264
275
  const problem = cameraLoopProblem(coreStart, coreEnd, storedEnd, object, 'Core-evaluated');
265
276
  if (problem !== null) problems.push(problem);
266
277
  }
278
+ if (count !== undefined && problems.length === before) {
279
+ const penultimate = keys.length - 2;
280
+ const curve = keys[penultimate]?.curve;
281
+ if (Array.isArray(curve)) {
282
+ const problem = curveSeamProblem(curve, times[penultimate], times[times.length - 1], storedEnd, object);
283
+ if (problem !== null) problems.push(problem);
284
+ }
285
+ }
267
286
  } catch (err) {
268
287
  if (err instanceof PartsError) problems.push(...err.problems);
269
288
  else if (err instanceof CoreInputError) problems.push({ code: CAMERA_TRACK, object, detail: err.message });
@@ -273,32 +292,55 @@ export function resolveSceneCamera(camera: SceneCamera, motion: MotionSpec): Res
273
292
  }
274
293
  const easedStart = keys[0].curve !== undefined;
275
294
  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
- });
295
+ const easedSeam = closedPeriod && (easedStart || easedEnd);
296
+ const checkTime = (time: number, end: number): void => {
297
+ if (!Number.isFinite(time) || time < 0 || time > end) {
298
+ throw new PartsError([{ code: CAMERA_TRACK, object, detail: `cannot sample t=${time} s. Authored time in [0, ${end}] s is required` }]);
299
+ }
300
+ };
301
+ const samplePeriod = (time: number): SceneCameraSample => {
302
+ checkTime(time, period);
303
+ // At a curved loop seam use both unwrapped Core reads. The linear-only
304
+ // seam uses both authored values, so the two ends share a precision.
305
+ const endpoint = time === 0 && (easedSeam || easedStart) ? coreStart
306
+ : time === period && (easedSeam || easedEnd) ? coreEnd : undefined;
307
+ if (endpoint !== undefined) return { pan: [...endpoint.pan], zoom: endpoint.zoom };
308
+ let low = 0, high = keys.length - 1;
309
+ while (low < high) {
310
+ const mid = Math.ceil((low + high) / 2);
311
+ if (keys[mid].t <= time) low = mid;
312
+ else high = mid - 1;
313
+ }
314
+ const from = keys[low], to = keys[low + 1];
315
+ if (from.curve !== undefined && coreSample !== undefined) return coreSample(time);
316
+ if (from.t === time || to === undefined) return checkCameraSample([...from.pan], from.zoom, time, object);
317
+ const phase = (time - from.t) / (to.t - from.t);
318
+ const mix = (a: number, b: number): number => a + (b - a) * phase;
319
+ 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);
320
+ };
321
+ if (count === undefined) {
322
+ tracks.set(name, { keys, duration, loop, sample: samplePeriod });
323
+ } else if (problems.length === before) {
324
+ try {
325
+ tracks.set(name, {
326
+ keys: repeatSceneTimeline(keys, count, period, duration, object), duration, loop,
327
+ period, samplePeriod,
328
+ sample(time) {
329
+ checkTime(time, duration);
330
+ if (time === duration) return samplePeriod(period);
331
+ // Locate the splice by its emitted clock, including a quotient
332
+ // that may round to an adjacent integer at a boundary.
333
+ let copy = Math.min(Math.floor(time / period), count - 1);
334
+ if (copy * period > time) copy--;
335
+ else if (copy + 1 < count && (copy + 1) * period <= time) copy++;
336
+ return samplePeriod(Math.min(time - copy * period, period));
337
+ },
338
+ });
339
+ } catch (err) {
340
+ if (!(err instanceof PartsError)) throw err;
341
+ problems.push(...err.problems);
342
+ }
343
+ }
302
344
  }
303
345
  refuseIfAny(problems);
304
346
  return { backdrop: camera.backdrop, tracks };
@@ -355,6 +397,40 @@ export function readSceneAnimations(raw: unknown, where: string): SceneAnimation
355
397
  }
356
398
  }
357
399
 
400
+ /** Expand scene-authored keys on the composed clock before merging timelines. */
401
+ export function repeatSceneAnimations(clips: SceneAnimations | undefined, groups: Readonly<Record<string, string[]>>,
402
+ repeats?: Readonly<Record<string, number>>, repeatSeams?: SceneRepeatSeam[]): SceneAnimations {
403
+ const authored = clips ?? {};
404
+ if (repeats === undefined) return authored;
405
+ const problems: Problem[] = [];
406
+ const expanded = { ...authored };
407
+ for (const [name, count] of Object.entries(repeats)) {
408
+ const field = `scene.repeats[${JSON.stringify(name)}]`;
409
+ const object = `scene.animations.${name}`;
410
+ const clip = Object.hasOwn(authored, name) ? authored[name] : undefined;
411
+ if (clip === undefined || !(clip.duration > 0)) {
412
+ problems.push({ code: 'SCENE_REPEAT_DURATION', object: field,
413
+ detail: `is ${count} and ${object}.duration is ${clip === undefined ? 'absent' : `${clip.duration} s`}. Declare a positive whole take duration` });
414
+ continue;
415
+ }
416
+ const before = problems.length;
417
+ for (const family of ['ik', 'transform', 'sequence', 'drawOrder', 'events'] as const) {
418
+ if ((clip[family]?.length ?? 0) > 0) problems.push({ code: 'SCENE_REPEAT_KEY_SEAM', object: `${object}.${family}`,
419
+ detail: `${field} is ${count}. This declaration splices scene tracks, deforms and camera keys; this timeline has no defined repeat splice` });
420
+ }
421
+ if (problems.length !== before) continue;
422
+ try {
423
+ const capture = repeatSeams === undefined ? undefined : { take: name, into: repeatSeams };
424
+ expanded[name] = repeatSceneKeys({ ...clip, duration: clip.duration / count }, count, clip.duration, groups, object, field, capture);
425
+ } catch (err) {
426
+ if (!(err instanceof PartsError)) throw err;
427
+ problems.push(...err.problems);
428
+ }
429
+ }
430
+ refuseIfAny(problems);
431
+ return expanded;
432
+ }
433
+
358
434
  /** Core slider source properties and the bone timeline channels that feed them. */
359
435
  function sliderInputChannel(source: unknown, property: string): number | null {
360
436
  switch (source) {
@@ -531,6 +607,87 @@ function storedIdleLoopDifference(modelText: string): { difference: string | nul
531
607
  interface StoredCurveKey { time: number; curve?: number[] | 'stepped' }
532
608
  interface StoredTrackTarget { name: string; timelines: Array<{ name: string; keys: StoredCurveKey[] }> }
533
609
 
610
+ function curveSeamProblem(curve: number[], start: number, end: number, duration: number, object: string): Problem | null {
611
+ for (let i = 0; i < curve.length; i += 4) {
612
+ const points = bezierPolyline(start, 0, curve[i], 0, curve[i + 2], 0, end, 0);
613
+ const overlap = points.find((n, j) => j % 2 === 0 && n >= duration);
614
+ if (overlap !== undefined) return { code: 'SCENE_REPEAT_KEY_SEAM', object,
615
+ detail: `Bezier channel ${i / 4} has a stored time sample ${overlap} s at or past the closing key ${duration} s. The source channel must splice without changing its keyed motion` };
616
+ }
617
+ return null;
618
+ }
619
+
620
+ type CompiledSceneAnimation = CompiledDocument['animations'][number];
621
+ interface CompiledSeamKey {
622
+ time: number;
623
+ stated: number | { time: number };
624
+ curve: number[] | 'linear' | 'stepped';
625
+ }
626
+
627
+ function compiledSeamKeys(animation: CompiledSceneAnimation, address: SceneRepeatSeam['timeline']): readonly CompiledSeamKey[] | null | undefined {
628
+ const { timelines, constraints } = animation;
629
+ if (address.family === 'deform') {
630
+ return timelines.attachments.find(a => a.skin === address.skin && a.slot === address.slot && a.attachment === address.attachment)?.deform;
631
+ }
632
+ const { family, target, property } = address;
633
+ if (family === 'path') {
634
+ const track = constraints.path.find(t => t.name === target);
635
+ return property === 'position' || property === 'spacing' || property === 'mix' ? track?.[property] : undefined;
636
+ }
637
+ if (family === 'slider') {
638
+ const track = constraints.slider.find(t => t.name === target);
639
+ return property === 'time' || property === 'mix' ? track?.[property] : undefined;
640
+ }
641
+ const bone = family === 'bone' || family === 'group'
642
+ ? timelines.bones.find(t => t.name === target)?.timelines.find(t => t.kind === property)?.keys : undefined;
643
+ const slot = family === 'slot' || family === 'group'
644
+ ? timelines.slots.find(t => t.name === target)?.timelines.find(t => t.kind === property)?.keys : undefined;
645
+ const physics = family === 'physics' || family === 'group'
646
+ ? constraints.physicsKeyed?.find(t => t.name === target && t.kind === property)?.keys : undefined;
647
+ const matches = [bone, slot, physics].filter(keys => keys !== undefined);
648
+ return matches.length === 1 ? matches[0] : undefined;
649
+ }
650
+
651
+ /** Read the final Core model so both raw curves and expanded named easings use
652
+ * the actual stored handles. Key ordinals identify the splice after quantizing
653
+ * the clock; a different timeline can have a key at the same time.
654
+ */
655
+ export function sceneRepeatCurveProblems(modelText: string, seams: readonly SceneRepeatSeam[]): Problem[] {
656
+ if (seams.length === 0) return [];
657
+ let doc: CompiledDocument;
658
+ try { doc = readModel(modelText, 'composed repeat model'); }
659
+ catch (err) {
660
+ if (!(err instanceof CoreInputError)) throw err;
661
+ return [{ code: 'SCENE_REPEAT_KEY_SEAM', object: seams[0].object, detail: err.message }];
662
+ }
663
+ const problems: Problem[] = [];
664
+ const statedTime = (key: CompiledSeamKey): number => typeof key.stated === 'number' ? key.stated : key.stated.time;
665
+ for (const { take, object, timeline, stride, count } of seams) {
666
+ const animation = doc.animations.find(a => a.name === take);
667
+ const keys = animation === undefined ? undefined : compiledSeamKeys(animation, timeline);
668
+ const timelineName = timeline.family === 'deform' ? `deform ${timeline.skin}/${timeline.slot}/${timeline.attachment}`
669
+ : `${timeline.family} ${JSON.stringify(timeline.target)} ${timeline.property}`;
670
+ const where = `${object} (${timelineName} in take ${JSON.stringify(take)})`;
671
+ const expected = stride * count + 1;
672
+ if (keys?.length !== expected) {
673
+ problems.push({ code: 'SCENE_REPEAT_KEY_SEAM', object: where,
674
+ detail: `compiled timeline has ${keys === undefined || keys === null ? 'no uniquely resolved key list' : `${keys.length} keys`}. The splice requires ${expected} keys to locate its closing segments` });
675
+ continue;
676
+ }
677
+ for (let copy = 1; copy <= count; copy++) {
678
+ const i = copy * stride;
679
+ const before = keys[i - 1], end = keys[i];
680
+ if (!Array.isArray(before.curve)) continue;
681
+ const problem = curveSeamProblem(before.curve, statedTime(before), statedTime(end), end.time, where);
682
+ if (problem !== null) {
683
+ problems.push(problem);
684
+ break;
685
+ }
686
+ }
687
+ }
688
+ return problems;
689
+ }
690
+
534
691
  /** At a splice, Core's sampled Bezier must reach the closing key from the left.
535
692
  * Check the stored polyline, including curves generated from named easings.
536
693
  */
@@ -548,17 +705,10 @@ function sourceCurveSeamProblems(modelText: string, duration: number, object: st
548
705
  const check = (keys: StoredCurveKey[], timeline: string, deform = false): void => {
549
706
  const before = keys.at(-2), end = keys.at(-1);
550
707
  if (end === undefined || Math.fround(end.time) !== duration || !Array.isArray(before?.curve)) return;
551
- const curve = before.curve;
552
- for (let i = 0; i < curve.length; i += 4) {
553
- // Only the time axis is needed. Core's deform polyline uses the stored
554
- // float for the leading key time; bone and physics curves use its name.
555
- const points = bezierPolyline(deform ? Math.fround(before.time) : before.time, 0, curve[i], 0, curve[i + 2], 0, end.time, 0);
556
- const overlap = points.find((n, j) => j % 2 === 0 && n >= duration);
557
- if (overlap === undefined) continue;
558
- problems.push({ code: 'SCENE_REPEAT_KEY_SEAM', object: `${object}.${timeline}`,
559
- detail: `Bezier channel ${i / 4} has a stored time sample ${overlap} s at or past the closing key ${duration} s. The source channel must splice without changing its keyed motion` });
560
- break;
561
- }
708
+ // Core's deform polyline uses the stored float for the leading key time;
709
+ // bone and physics curves use its name.
710
+ const problem = curveSeamProblem(before.curve, deform ? Math.fround(before.time) : before.time, end.time, duration, `${object}.${timeline}`);
711
+ if (problem !== null) problems.push(problem);
562
712
  };
563
713
  for (const [family, targets] of [['bone', idle.bones], ['slot', idle.slots], ['physics', idle.constraints.physics]] as const) {
564
714
  for (const target of targets) for (const track of target.timelines) check(track.keys, `${family} ${JSON.stringify(target.name)} ${track.name}`);
@@ -1,4 +1,4 @@
1
- /** Periodic splicing for the imported character idle only. */
1
+ /** Periodic splicing for character motion, scene motion and camera keys. */
2
2
  import { isDeepStrictEqual } from 'node:util';
3
3
  import { PartsError } from './errors.ts';
4
4
 
@@ -10,8 +10,26 @@ interface Key {
10
10
 
11
11
  interface Idle {
12
12
  duration: number;
13
- tracks: Array<{ property: string; bone?: string; group?: string; physics?: string; lag?: number; stagger?: number; keys: Key[] }>;
14
- deform?: Array<{ slot: string; attachment: string; keys: Key[] }>;
13
+ tracks: Array<{ property: string; bone?: string; slot?: string; group?: string; physics?: string; path?: string; slider?: string; lag?: number; stagger?: number; keys: Key[] }>;
14
+ deform?: Array<{ skin?: string; slot: string; attachment: string; keys: Key[] }>;
15
+ }
16
+
17
+ type TrackFamily = 'bone' | 'slot' | 'physics' | 'path' | 'slider' | 'group';
18
+
19
+ export interface SceneRepeatSeam {
20
+ take: string;
21
+ object: string;
22
+ timeline: { family: TrackFamily; target: string; property: string }
23
+ | { family: 'deform'; skin: string; slot: string; attachment: string };
24
+ /** The closing key of copy i is at i * stride, including the final key. */
25
+ stride: number;
26
+ count: number;
27
+ }
28
+
29
+ interface SceneRepeatSeamCapture {
30
+ take: string;
31
+ into: SceneRepeatSeam[];
32
+ mapTarget?: (name: string) => string;
15
33
  }
16
34
 
17
35
  function refuse(object: string, detail: string): never {
@@ -42,7 +60,7 @@ function atOffset<K extends Key>(key: K, offset: number, time = key.t + offset):
42
60
  }
43
61
 
44
62
  function repeatTimeline<K extends Key>(keys: K[], count: number, period: number, duration: number, object: string,
45
- clocks: ReadonlyArray<{ target: string; shift: number }>, property?: string): K[] {
63
+ clocks: ReadonlyArray<{ target: string; shift: number }>, property?: string, captureCurveSeam?: (stride: number) => void): K[] {
46
64
  const first = keys[0], last = keys[keys.length - 1], before = keys[keys.length - 2];
47
65
  if (first === undefined) refuse(object, 'has no source keys');
48
66
  const startState = state(first), endState = state(last);
@@ -85,27 +103,77 @@ function repeatTimeline<K extends Key>(keys: K[], count: number, period: number,
85
103
  out.push(atOffset(keys[j], k * period, terminal));
86
104
  }
87
105
  }
106
+ if (sharesKey && before !== undefined && (Array.isArray(before.curve) || (typeof before.ease === 'string' && before.ease !== 'stepped'))) {
107
+ captureCurveSeam?.(stride);
108
+ }
88
109
  return out;
89
110
  }
90
111
 
91
- export function repeatSceneKeys<T extends Idle>(idle: T, count: number, duration: number, groups: Readonly<Record<string, string[]>>, object: string): T {
92
- const period = idle.duration;
112
+ function checkRepeatClock(count: number, period: number, duration: number, object: string): void {
93
113
  if (!Number.isFinite(Math.fround(duration)) || Math.fround(period) === 0 || Math.fround((count - 1) * period) === Math.fround(duration)) {
94
114
  refuse(object, `the source period ${period} s cannot separate ${count} copies on the float32 playback clock at ${duration} s`);
95
115
  }
116
+ }
117
+
118
+ export function repeatSceneTimeline<K extends Key>(keys: K[], count: number, period: number, duration: number, object: string): K[] {
119
+ checkRepeatClock(count, period, duration, object);
120
+ return repeatTimeline(keys, count, period, duration, object, [{ target: object, shift: 0 }]);
121
+ }
122
+
123
+ export function repeatSceneKeys<T extends Idle>(idle: T, count: number, duration: number, groups: Readonly<Record<string, string[]>>, object: string,
124
+ sceneRepeatField?: string, capture?: SceneRepeatSeamCapture): T {
125
+ const period = idle.duration;
126
+ checkRepeatClock(count, period, duration, object);
127
+ const recordSeam = (timeline: SceneRepeatSeam['timeline'], where: string, stride: number): void => {
128
+ if (capture !== undefined) capture.into.push({ take: capture.take, object: where, timeline, stride, count });
129
+ };
130
+ const trackClocks = (track: Idle['tracks'][number], where: string) => {
131
+ const sceneTarget = sceneRepeatField === undefined ? undefined : track.slot ?? track.path ?? track.slider;
132
+ const targets = track.group === undefined ? [track.bone ?? track.physics ?? sceneTarget ?? track.property]
133
+ : Object.hasOwn(groups, track.group) ? groups[track.group] : [];
134
+ if (targets.length === 0) refuse(where, `group ${JSON.stringify(track.group)} has no resolved members`);
135
+ return targets.map((name, index) => ({ name, target: JSON.stringify(name), shift: (track.lag ?? 0) + (track.stagger ?? 0) * index }));
136
+ };
137
+ if (sceneRepeatField !== undefined) {
138
+ // A clip's end is the latest effective key across its timelines. Closed
139
+ // state channels can hold through a gap, and resets must stay interior.
140
+ let end = -Infinity;
141
+ for (const [i, track] of idle.tracks.entries()) {
142
+ const key = track.keys.at(-1);
143
+ if (key === undefined) continue;
144
+ for (const { shift } of trackClocks(track, `${object}.tracks[${i}]`)) end = Math.max(end, key.t + shift);
145
+ }
146
+ for (const deform of idle.deform ?? []) {
147
+ const key = deform.keys.at(-1);
148
+ if (key !== undefined) end = Math.max(end, key.t);
149
+ }
150
+ if (end !== -Infinity && end !== period) throw new PartsError([{
151
+ code: 'SCENE_REPEAT_DURATION', object,
152
+ detail: `keys end at ${end} s. ${object}.duration declares ${duration} s and ${sceneRepeatField} is ${count}. The terminal time must match the ${period} s period exactly`,
153
+ }]);
154
+ }
96
155
  return {
97
156
  ...idle,
98
157
  duration,
99
158
  tracks: idle.tracks.map((track, i) => {
100
159
  const where = `${object}.tracks[${i}]`;
101
- const targets = track.group === undefined ? [track.bone ?? track.physics ?? track.property] : Object.hasOwn(groups, track.group) ? groups[track.group] : [];
102
- if (targets.length === 0) refuse(where, `group ${JSON.stringify(track.group)} has no resolved members`);
103
- const clocks = targets.map((target, index) => ({ target: JSON.stringify(target), shift: (track.lag ?? 0) + (track.stagger ?? 0) * index }));
104
- return { ...track, keys: repeatTimeline(track.keys, count, period, duration, where, clocks, track.property) };
160
+ const clocks = trackClocks(track, where);
161
+ const record = capture === undefined ? undefined : (stride: number): void => {
162
+ const family = (['bone', 'slot', 'physics', 'path', 'slider', 'group'] as const).find(field => track[field] !== undefined);
163
+ if (family === undefined) return; // Core refuses a track with no target before the seam check.
164
+ for (const { name } of clocks) {
165
+ recordSeam({ family, target: capture.mapTarget?.(name) ?? name, property: track.property }, where, stride);
166
+ }
167
+ };
168
+ return { ...track, keys: repeatTimeline(track.keys, count, period, duration, where, clocks, track.property, record) };
105
169
  }),
106
- ...(idle.deform === undefined ? {} : { deform: idle.deform.map((deform, i) => ({
107
- ...deform,
108
- keys: repeatTimeline(deform.keys, count, period, duration, `${object}.deform[${i}]`, [{ target: `${deform.slot}/${deform.attachment}`, shift: 0 }]),
109
- })) }),
170
+ ...(idle.deform === undefined ? {} : { deform: idle.deform.map((deform, i) => {
171
+ const where = `${object}.deform[${i}]`;
172
+ const clocks = [{ target: `${deform.slot}/${deform.attachment}`, shift: 0 }];
173
+ const record = capture === undefined ? undefined : (stride: number): void => {
174
+ recordSeam({ family: 'deform', skin: deform.skin ?? 'default', slot: deform.slot, attachment: deform.attachment }, where, stride);
175
+ };
176
+ return { ...deform, keys: repeatTimeline(deform.keys, count, period, duration, where, clocks, undefined, record) };
177
+ }) }),
110
178
  };
111
179
  }