rig-parts 2.62.0 → 2.63.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/sceneclips.ts CHANGED
@@ -1,13 +1,309 @@
1
1
  /** Scene-authored clips use final names and Core's motion parser and poser. */
2
+ import { bezierForChannel, f32 } from '@rig-c/core/compile';
2
3
  import { CompileError } from '@rig-c/core/errors';
3
4
  import { parseMotionSpec, type MotionSpec as CoreMotion } from '@rig-c/core/motion';
4
- import { bezierPolyline, CoreInputError, poseRawAnimation, readModel, type RawPose } from '@rig-c/core/core';
5
+ import { bezierPolyline, CORE_DOCUMENT_SPEC, CoreInputError, poseRawAnimation, readModel, type RawPose } from '@rig-c/core/core';
5
6
  import { PartsError, refuseIfAny, type Problem } from './errors.ts';
6
7
  import type { MotionSpec } from './motion.ts';
7
8
  import type { RigSpec } from './rig.ts';
8
9
 
9
10
  export type SceneAnimations = CoreMotion['animations'];
10
11
 
12
+ export interface SceneCameraSample {
13
+ pan: [number, number];
14
+ zoom: number;
15
+ }
16
+
17
+ export interface SceneCameraKey extends SceneCameraSample {
18
+ t: number;
19
+ ease?: string;
20
+ curve?: number[] | 'stepped';
21
+ }
22
+
23
+ export interface SceneCamera {
24
+ backdrop: string;
25
+ tracks: Record<string, SceneCameraKey[]>;
26
+ }
27
+
28
+ export interface ResolvedSceneCameraTrack {
29
+ /** Authored seconds, pan and zoom, with easings resolved to outgoing absolute curves. */
30
+ keys: Omit<SceneCameraKey, 'ease'>[];
31
+ duration: number;
32
+ loop: boolean;
33
+ /** Sample on the authored clock, including the unwrapped terminal time. */
34
+ sample(time: number): SceneCameraSample;
35
+ }
36
+
37
+ export interface ResolvedSceneCamera {
38
+ backdrop: string;
39
+ tracks: ReadonlyMap<string, ResolvedSceneCameraTrack>;
40
+ }
41
+
42
+ const CAMERA_TRACK = 'SCENE_CAMERA_TRACK';
43
+ const CAMERA_LOOP = 'SCENE_CAMERA_LOOP_CLOSES';
44
+ const CAMERA_PAN_CURVE_LENGTH = 8;
45
+ const CAMERA_CURVE_LENGTH = CAMERA_PAN_CURVE_LENGTH + 4; // Four handles each for pan X, pan Y and reciprocal zoom.
46
+
47
+ const cameraRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
48
+ const cameraNumber = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
49
+ const cameraFloat = (v: unknown): boolean => cameraNumber(v) && Number.isFinite(Math.fround(v));
50
+ const cameraTrackField = (name: string): string => `scene.camera.tracks[${JSON.stringify(name)}]`;
51
+
52
+ function cameraValue(v: unknown): string {
53
+ if (typeof v === 'number') return String(v);
54
+ const json = JSON.stringify(v);
55
+ return json === undefined ? String(v) : json.length > 80 ? `${json.slice(0, 77)}...` : json;
56
+ }
57
+
58
+ function cameraUnknownFields(raw: Record<string, unknown>, allowed: readonly string[], object: string, problems: Problem[]): void {
59
+ for (const field of Object.keys(raw)) if (!allowed.includes(field)) {
60
+ problems.push({ code: CAMERA_TRACK, object: `${object}.${field}`, detail: `is not a camera field. Use ${allowed.join(', ')}` });
61
+ }
62
+ }
63
+
64
+ function usableZoom(zoom: number): boolean {
65
+ const span = 1 / zoom;
66
+ return Number.isFinite(zoom) && zoom > 0 && Number.isFinite(span) && span > 0;
67
+ }
68
+
69
+ function readCameraKeys(raw: unknown, object: string, problems: Problem[]): SceneCameraKey[] {
70
+ if (!Array.isArray(raw) || raw.length === 0) {
71
+ problems.push({ code: CAMERA_TRACK, object, detail: `is ${cameraValue(raw)}. A nonempty list of { t, pan, zoom } keys is required` });
72
+ return [];
73
+ }
74
+ const keys: SceneCameraKey[] = [];
75
+ let previous = -Infinity;
76
+ for (const [i, key] of raw.entries()) {
77
+ const at = `${object}[${i}]`;
78
+ if (!cameraRecord(key)) {
79
+ problems.push({ code: CAMERA_TRACK, object: at, detail: `is ${cameraValue(key)}. An object with t, pan and zoom is required` });
80
+ continue;
81
+ }
82
+ const before = problems.length;
83
+ cameraUnknownFields(key, ['t', 'pan', 'zoom', 'ease', 'curve'], at, problems);
84
+ const { t, pan, zoom, ease, curve } = key;
85
+ const validTime = cameraNumber(t) && (i === 0 ? t === 0 : t > previous && t > 0);
86
+ if (!validTime) problems.push({ code: CAMERA_TRACK, object: `${at}.t`, detail: `is ${cameraValue(t)} s. ${i === 0
87
+ ? 'The first key must be at exactly 0 s'
88
+ : `Each subsequent key must be at a finite positive time strictly after the previous key (${previous} s)`}` });
89
+ if (cameraNumber(t)) previous = t;
90
+
91
+ const validPan = Array.isArray(pan) && pan.length === 2 && cameraNumber(pan[0]) && cameraNumber(pan[1]);
92
+ if (!validPan) problems.push({ code: CAMERA_TRACK, object: `${at}.pan`, detail: `is ${cameraValue(pan)}. Two finite scene pixel offsets [x, y] are required` });
93
+ const validZoom = cameraNumber(zoom) && usableZoom(zoom);
94
+ if (!validZoom) problems.push({ code: CAMERA_TRACK, object: `${at}.zoom`, detail: `is ${cameraValue(zoom)}. Positive finite zoom and reciprocal zoom are required` });
95
+
96
+ if (ease !== undefined && (typeof ease !== 'string' || ease.length === 0)) {
97
+ problems.push({ code: CAMERA_TRACK, object: `${at}.ease`, detail: `is ${cameraValue(ease)}. Use a nonempty easing name or "stepped"` });
98
+ }
99
+ if (curve !== undefined && curve !== 'stepped' && !(Array.isArray(curve) && curve.length === CAMERA_CURVE_LENGTH && [...curve].every(cameraFloat))) {
100
+ problems.push({ code: CAMERA_TRACK, object: `${at}.curve`, detail: `is ${cameraValue(curve)}. Use "stepped" or ${CAMERA_CURVE_LENGTH} finite numbers at float32 precision` });
101
+ }
102
+ if (ease !== undefined && curve !== undefined) {
103
+ problems.push({ code: CAMERA_TRACK, object: at, detail: 'carries both ease and curve. Use one outgoing curve declaration' });
104
+ } else if (i === raw.length - 1 && (curve !== undefined || ease !== undefined)) {
105
+ problems.push({ code: CAMERA_TRACK, object: at, detail: 'carries an outgoing easing or curve. The terminal key has no following segment' });
106
+ }
107
+ if (problems.length === before && validTime && validPan && validZoom) {
108
+ keys.push({ t, pan: [pan[0], pan[1]], zoom, ...(typeof ease === 'string' ? { ease } : {}),
109
+ ...(curve === 'stepped' || Array.isArray(curve) ? { curve: Array.isArray(curve) ? [...curve] : curve } : {}) });
110
+ }
111
+ }
112
+ return keys;
113
+ }
114
+
115
+ /** Read the declaration before the scene's composed take names and easings are available. */
116
+ export function readSceneCamera(raw: unknown): SceneCamera {
117
+ if (!cameraRecord(raw)) {
118
+ throw new PartsError([{ code: CAMERA_TRACK, object: 'scene.camera', detail: `is ${cameraValue(raw)}. A { backdrop, tracks } object is required` }]);
119
+ }
120
+ const problems: Problem[] = [];
121
+ cameraUnknownFields(raw, ['backdrop', 'tracks'], 'scene.camera', problems);
122
+ const backdrop = typeof raw.backdrop === 'string' ? raw.backdrop : '';
123
+ if (backdrop.length === 0) problems.push({ code: 'SCENE_CAMERA_BACKDROP', object: 'scene.camera.backdrop', detail: `is ${cameraValue(raw.backdrop)}. Name the legacy plate or a declared plate` });
124
+ const tracks: Array<[string, SceneCameraKey[]]> = [];
125
+ if (cameraRecord(raw.tracks)) {
126
+ for (const [name, keys] of Object.entries(raw.tracks)) tracks.push([name, readCameraKeys(keys, cameraTrackField(name), problems)]);
127
+ if (tracks.length === 0) problems.push({ code: CAMERA_TRACK, object: 'scene.camera.tracks', detail: 'is empty. Name at least one composed take and its camera keys' });
128
+ } else {
129
+ problems.push({ code: CAMERA_TRACK, object: 'scene.camera.tracks', detail: `is ${cameraValue(raw.tracks)}. An object mapping take names to key lists is required` });
130
+ }
131
+ refuseIfAny(problems);
132
+ return { backdrop, tracks: Object.fromEntries(tracks) };
133
+ }
134
+
135
+ const cameraChannels = (key: SceneCameraKey): [number, number, number] => [key.pan[0], key.pan[1], 1 / key.zoom];
136
+
137
+ /** Match the compiled bone timeline's stored time on the eased path. Off-grid
138
+ * times use the lower adjacent float32 when nearest rounding would go up.
139
+ */
140
+ function cameraStoredTime(time: number): number {
141
+ const named = f32(time);
142
+ const nearest = Math.fround(time);
143
+ if (named === time || nearest <= time || !Number.isFinite(nearest)) return named;
144
+ const bits = new DataView(new ArrayBuffer(4));
145
+ bits.setFloat32(0, nearest);
146
+ bits.setUint32(0, bits.getUint32(0) - 1);
147
+ return f32(bits.getFloat32(0));
148
+ }
149
+
150
+ /** Lower three camera channels onto two independent root translations. Their
151
+ * unrounded world coordinates are Core's evaluated channel values directly.
152
+ * The document is synthetic and stays in memory. Its digest is a field the
153
+ * parser requires, and the camera report binds the actual packed model separately.
154
+ */
155
+ function cameraCoreSampler(keys: ResolvedSceneCameraTrack['keys'], times: number[], duration: number, object: string): ResolvedSceneCameraTrack['sample'] {
156
+ const name = 'camera';
157
+ const doc = readModel(JSON.stringify({
158
+ spec: CORE_DOCUMENT_SPEC, referenceScale: 1, stage: null,
159
+ bones: [{ name: 'pan' }, { name: 'span' }], slots: [], skins: [], constraints: [], events: [],
160
+ animations: [{ name, duration, slots: [], constraints: { ik: [], transform: [], path: [], physics: [], slider: [] }, attachments: [], drawOrder: [], events: [],
161
+ bones: [
162
+ { name: 'pan', timelines: [{ name: 'translate', keys: keys.map((key, i) => ({
163
+ time: times[i], x: f32(key.pan[0]), y: f32(key.pan[1]),
164
+ curve: Array.isArray(key.curve) ? key.curve.slice(0, CAMERA_PAN_CURVE_LENGTH) : key.curve,
165
+ })) }] },
166
+ { name: 'span', timelines: [{ name: 'translatex', keys: keys.map((key, i) => ({
167
+ time: times[i], value: f32(1 / key.zoom),
168
+ curve: Array.isArray(key.curve) ? key.curve.slice(CAMERA_PAN_CURVE_LENGTH) : key.curve,
169
+ })) }] },
170
+ ] }],
171
+ editorOrder: { skins: [], animations: [name] },
172
+ images: [], pageGrids: [], droppedStates: [], absentParts: [], meshBones: [], meshes: [], physics: [], deformTransforms: [], trackDerivations: [], rig: {},
173
+ pages: [], spine: { sha256: '0'.repeat(64) },
174
+ }), object);
175
+ return time => {
176
+ try {
177
+ const pose = poseRawAnimation(doc, name, time === 0 ? [] : [time]).at(-1);
178
+ if (pose === undefined) throw new CoreInputError('Core returned no camera pose');
179
+ const [pan, span] = pose.bones;
180
+ return checkCameraSample([pan.worldX, pan.worldY], 1 / span.worldX, time, object);
181
+ } catch (err) {
182
+ if (!(err instanceof CoreInputError)) throw err;
183
+ throw new PartsError([{ code: CAMERA_TRACK, object, detail: `cannot evaluate the eased camera at t=${time} s. ${err.message}` }]);
184
+ }
185
+ };
186
+ }
187
+
188
+ function checkCameraSample(pan: [number, number], zoom: number, time: number, object: string): SceneCameraSample {
189
+ if (!pan.every(Number.isFinite) || !usableZoom(zoom)) {
190
+ throw new PartsError([{ code: CAMERA_TRACK, object, detail: `evaluates at t=${time} s to pan [${pan.join(', ')}] and zoom ${zoom}. A finite pan and a finite positive window are required` }]);
191
+ }
192
+ return { pan, zoom };
193
+ }
194
+
195
+ function cameraLoopProblem(first: SceneCameraSample, last: SceneCameraSample, duration: number, object: string, phase: string): Problem | null {
196
+ if (first.pan[0] === last.pan[0] && first.pan[1] === last.pan[1] && first.zoom === last.zoom) return null;
197
+ return { code: CAMERA_LOOP, object, detail: `${phase} start at t=0 s has pan [${first.pan.join(', ')}] and zoom ${first.zoom}. End at t=${duration} s has pan [${last.pan.join(', ')}] and zoom ${last.zoom}. A looping camera requires exact equality` };
198
+ }
199
+
200
+ /** Resolve only declared tracks, against the final take and easing names. */
201
+ export function resolveSceneCamera(camera: SceneCamera, motion: MotionSpec): ResolvedSceneCamera {
202
+ const problems: Problem[] = [];
203
+ const tracks = new Map<string, ResolvedSceneCameraTrack>();
204
+ for (const [name, authored] of Object.entries(camera.tracks)) {
205
+ const object = cameraTrackField(name);
206
+ const take = Object.hasOwn(motion.animations, name) ? motion.animations[name] : undefined;
207
+ if (!cameraRecord(take) || !cameraNumber(take.duration) || take.duration < 0) {
208
+ problems.push({ code: CAMERA_TRACK, object, detail: `requires a composed take named ${JSON.stringify(name)} with a finite nonnegative declared duration` });
209
+ continue;
210
+ }
211
+ const { duration } = take;
212
+ const loop = take.loop === true;
213
+ const first = authored[0], last = authored.at(-1);
214
+ if (last === undefined || last.t !== duration) {
215
+ problems.push({ code: CAMERA_TRACK, object, detail: `ends at ${last === undefined ? 'no key' : `${last.t} s`}. Take ${JSON.stringify(name)} declares ${duration} s and the terminal key must match exactly` });
216
+ continue;
217
+ }
218
+ const before = problems.length;
219
+ if (loop) {
220
+ const problem = cameraLoopProblem(first, last, duration, object, 'Authored');
221
+ if (problem !== null) problems.push(problem);
222
+ }
223
+
224
+ const eased = authored.some(key => key.curve !== undefined || key.ease !== undefined);
225
+ const times = authored.map(key => eased ? cameraStoredTime(key.t) : key.t);
226
+ const keys = authored.map((key, i): ResolvedSceneCameraTrack['keys'][number] => {
227
+ const at = `${object}[${i}]`;
228
+ const normalized: ResolvedSceneCameraTrack['keys'][number] = { t: key.t, pan: [...key.pan], zoom: key.zoom };
229
+ const from = cameraChannels(key);
230
+ if (eased && (!Number.isFinite(times[i]) || (i > 0 && times[i] <= times[i - 1])
231
+ || !from.every(cameraFloat) || Math.fround(from[2]) === 0)) {
232
+ problems.push({ code: CAMERA_TRACK, object: at,
233
+ detail: `at t=${key.t} s stores time ${times[i]} s and has channels [${from.join(', ')}]. ` +
234
+ 'Eased tracks require strictly increasing float32 times and finite float32 channels with a positive reciprocal zoom',
235
+ });
236
+ }
237
+ if (key.curve === 'stepped' || key.ease === 'stepped') return { ...normalized, curve: 'stepped' };
238
+ if (key.curve !== undefined) return { ...normalized, curve: key.curve.map(f32) };
239
+ if (key.ease === undefined) return normalized;
240
+ const handles = key.ease !== '' && Object.hasOwn(motion.easings, key.ease) ? motion.easings[key.ease] : undefined;
241
+ if (!Array.isArray(handles) || handles.length !== 4 || ![...handles].every(cameraFloat)) {
242
+ problems.push({ code: CAMERA_TRACK, object: `${at}.ease`, detail: `names ${JSON.stringify(key.ease)}. Declare that easing in the composed motion with four finite handles at float32 precision` });
243
+ return normalized;
244
+ }
245
+ const to = cameraChannels(authored[i + 1]);
246
+ if (from.every((v, c) => Math.fround(v) === Math.fround(to[c]))) return { ...normalized, curve: 'stepped' };
247
+ const curve = from.flatMap((v, c) => bezierForChannel(handles, times[i], times[i + 1], v, to[c]));
248
+ if (!curve.every(Number.isFinite)) {
249
+ problems.push({ code: CAMERA_TRACK, object: `${at}.ease`, detail: `easing ${JSON.stringify(key.ease)} produces non-finite absolute handles at t=${key.t} s. Finite float32 handles are required` });
250
+ }
251
+ return { ...normalized, curve };
252
+ });
253
+ if (problems.length !== before) continue;
254
+
255
+ let coreSample: ResolvedSceneCameraTrack['sample'] | undefined;
256
+ let coreStart: SceneCameraSample | undefined, coreEnd: SceneCameraSample | undefined;
257
+ if (eased) {
258
+ try {
259
+ coreSample = cameraCoreSampler(keys, times, duration, object);
260
+ const storedEnd = Math.fround(times[times.length - 1]);
261
+ coreStart = coreSample(0);
262
+ coreEnd = coreSample(storedEnd);
263
+ if (loop) {
264
+ const problem = cameraLoopProblem(coreStart, coreEnd, storedEnd, object, 'Core-evaluated');
265
+ if (problem !== null) problems.push(problem);
266
+ }
267
+ } catch (err) {
268
+ if (err instanceof PartsError) problems.push(...err.problems);
269
+ else if (err instanceof CoreInputError) problems.push({ code: CAMERA_TRACK, object, detail: err.message });
270
+ else throw err;
271
+ continue;
272
+ }
273
+ }
274
+ const easedStart = keys[0].curve !== undefined;
275
+ const easedEnd = keys.at(-2)?.curve !== undefined;
276
+ const easedSeam = loop && (easedStart || easedEnd);
277
+ tracks.set(name, {
278
+ keys, duration, loop,
279
+ sample(time) {
280
+ if (!Number.isFinite(time) || time < 0 || time > duration) {
281
+ throw new PartsError([{ code: CAMERA_TRACK, object, detail: `cannot sample t=${time} s. Authored time in [0, ${duration}] s is required` }]);
282
+ }
283
+ // At a curved loop seam use both unwrapped Core reads. The linear-only
284
+ // seam uses both authored values, so the two ends share a precision.
285
+ const endpoint = time === 0 && (easedSeam || easedStart) ? coreStart
286
+ : time === duration && (easedSeam || easedEnd) ? coreEnd : undefined;
287
+ if (endpoint !== undefined) return { pan: [...endpoint.pan], zoom: endpoint.zoom };
288
+ let low = 0, high = keys.length - 1;
289
+ while (low < high) {
290
+ const mid = Math.ceil((low + high) / 2);
291
+ if (keys[mid].t <= time) low = mid;
292
+ else high = mid - 1;
293
+ }
294
+ const from = keys[low], to = keys[low + 1];
295
+ if (from.curve !== undefined && coreSample !== undefined) return coreSample(time);
296
+ if (from.t === time || to === undefined) return checkCameraSample([...from.pan], from.zoom, time, object);
297
+ const phase = (time - from.t) / (to.t - from.t);
298
+ const mix = (a: number, b: number): number => a + (b - a) * phase;
299
+ return checkCameraSample([mix(from.pan[0], to.pan[0]), mix(from.pan[1], to.pan[1])], 1 / mix(1 / from.zoom, 1 / to.zoom), time, object);
300
+ },
301
+ });
302
+ }
303
+ refuseIfAny(problems);
304
+ return { backdrop: camera.backdrop, tracks };
305
+ }
306
+
11
307
  export interface ScenePlacementPivot {
12
308
  name: string;
13
309
  rootBinding?: string;