@rig-c/play 1.26.0 → 1.28.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.
@@ -0,0 +1,1536 @@
1
+ import { r as readModel, C as CORE_DOCUMENT_SPEC, p as poseRawAnimation, a as CoreInputError, l as loadModel, b as CanvasRenderer, R as RigPlayer, d as discoverTurnDials, n as normalizedDial, u as underNoSkin, c as poseRawSetup, f as frameOf, e as frameSource, g as rememberComposedClip } from "./_play-runtime.js";
2
+ const ORIGIN = { x: 0, y: 0 };
3
+ const GAINS = { background: -0.55, figure: 0, foreground: 0.55 };
4
+ const TIME_CONSTANT = 0.12;
5
+ const NEUTRAL_THRESHOLD = 1e-5;
6
+ function pointerTarget(clientX, clientY, viewport) {
7
+ const clamp = (value) => Math.max(-1, Math.min(1, value));
8
+ return {
9
+ x: clamp(2 * (clientX - viewport.left) / viewport.width - 1),
10
+ y: clamp(1 - 2 * (clientY - viewport.top) / viewport.height)
11
+ };
12
+ }
13
+ function easeCamera(current, target, elapsed) {
14
+ const weight = -Math.expm1(-elapsed / TIME_CONSTANT);
15
+ const ease = (value, goal) => {
16
+ const next = value + (goal - value) * weight;
17
+ return goal === 0 && Math.abs(next) <= NEUTRAL_THRESHOLD ? 0 : next;
18
+ };
19
+ return { x: ease(current.x, target.x), y: ease(current.y, target.y) };
20
+ }
21
+ function cameraLimits(width, height) {
22
+ return { x: Math.min(64, width * 0.1), y: Math.min(40, height * 0.1) };
23
+ }
24
+ function planeShift(camera, gain) {
25
+ const x = -gain * camera.x;
26
+ const y = gain * camera.y;
27
+ return { x: x === 0 ? 0 : x, y: y === 0 ? 0 : y };
28
+ }
29
+ function createCameraHandoff(transitionSeconds) {
30
+ let phase = "automatic";
31
+ let weight = 0;
32
+ let pointer = ORIGIN;
33
+ let fromWeight = 0;
34
+ let fromPointer = ORIGIN;
35
+ let elapsed = 0;
36
+ function retarget(next) {
37
+ phase = next;
38
+ fromWeight = weight;
39
+ fromPointer = pointer;
40
+ elapsed = 0;
41
+ }
42
+ return {
43
+ get weight() {
44
+ return weight;
45
+ },
46
+ get pointer() {
47
+ return pointer;
48
+ },
49
+ enter() {
50
+ retarget("acquiring");
51
+ },
52
+ leave() {
53
+ retarget("releasing");
54
+ },
55
+ reset() {
56
+ phase = "automatic";
57
+ pointer = ORIGIN;
58
+ weight = 0;
59
+ },
60
+ painted() {
61
+ if (phase === "centered") phase = "tracking";
62
+ },
63
+ advance(dt, target) {
64
+ if (!(dt > 0)) return;
65
+ if (phase === "tracking") pointer = easeCamera(pointer, target, dt);
66
+ if (phase !== "acquiring" && phase !== "releasing") return;
67
+ elapsed += dt;
68
+ const entering = phase === "acquiring";
69
+ if (elapsed >= transitionSeconds * (1 - Number.EPSILON)) {
70
+ weight = entering ? 1 : 0;
71
+ pointer = ORIGIN;
72
+ phase = entering ? "centered" : "automatic";
73
+ return;
74
+ }
75
+ const u = elapsed / transitionSeconds;
76
+ const s = u * u * (3 - 2 * u);
77
+ weight = (1 - s) * fromWeight + s * Number(entering);
78
+ if (entering) pointer = { x: (1 - s) * fromPointer.x, y: (1 - s) * fromPointer.y };
79
+ }
80
+ };
81
+ }
82
+ function planeOffsets(camera, mode) {
83
+ if (mode === "fixed") return { background: ORIGIN, figure: ORIGIN, foreground: ORIGIN };
84
+ return {
85
+ background: planeShift(camera, mode === "pan" ? 1 : GAINS.background),
86
+ figure: planeShift(camera, mode === "pan" ? 1 : GAINS.figure),
87
+ foreground: planeShift(camera, mode === "pan" ? 1 : GAINS.foreground)
88
+ };
89
+ }
90
+ const SCENE_CAMERA_REPORT_MAX_BYTES = 8 * 1024 * 1024;
91
+ const PAN_CURVE_LENGTH = 8;
92
+ const SHA256 = /^[a-f0-9]{64}$/;
93
+ const floatBits = new DataView(new ArrayBuffer(4));
94
+ const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
95
+ function isReportBytes(value) {
96
+ return ArrayBuffer.isView(value) && Reflect.get(typedArrayPrototype, Symbol.toStringTag, value) === "Uint8Array";
97
+ }
98
+ function checkSceneCameraReportSize(byteLength, refuse) {
99
+ if (byteLength > SCENE_CAMERA_REPORT_MAX_BYTES) {
100
+ refuse(
101
+ "SCENE_CAMERA_REPORT_TOO_LARGE",
102
+ `observed ${byteLength} raw report bytes with a cap of ${SCENE_CAMERA_REPORT_MAX_BYTES} bytes`
103
+ );
104
+ }
105
+ }
106
+ function decodeSceneCameraReport(bytes, refuse) {
107
+ const byteLength = Reflect.get(typedArrayPrototype, "byteLength", bytes);
108
+ checkSceneCameraReportSize(byteLength, refuse);
109
+ try {
110
+ const buffer = Reflect.get(typedArrayPrototype, "buffer", bytes);
111
+ const byteOffset = Reflect.get(typedArrayPrototype, "byteOffset", bytes);
112
+ const view = new Uint8Array(buffer, byteOffset, byteLength);
113
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(view));
114
+ } catch (error) {
115
+ return refuse("SCENE_CAMERA_REPORT_INVALID", "the scene report is not valid UTF-8 JSON", error);
116
+ }
117
+ }
118
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
119
+ const finite = (value) => typeof value === "number" && Number.isFinite(value);
120
+ const durationValue = (value) => finite(value) && value >= 0;
121
+ const positive = (value) => finite(value) && value > 0;
122
+ const usableZoom = (zoom) => positive(zoom) && positive(1 / zoom);
123
+ const isDigest = (value) => typeof value === "string" && SHA256.test(value);
124
+ const matchesSample = (a, b) => a.pan[0] === b.pan[0] && a.pan[1] === b.pan[1] && a.zoom === b.zoom;
125
+ function readCameraHeader(report, refuse) {
126
+ if (isRecord(report) && report.spec === "spine-parts-scene-report/1") return null;
127
+ if (!isRecord(report) || report.spec !== "spine-parts-scene-report/2" || !isRecord(report.camera)) {
128
+ return refuse("SCENE_CAMERA_REPORT_INVALID", "expected a scene report /1 or a scene report /2 with a camera record");
129
+ }
130
+ const { canvas, camera } = report;
131
+ const { backdrop, fps, coverage, tracks, model_sha256: digest } = camera;
132
+ if (typeof backdrop !== "string" || !backdrop.length || fps !== 12 || !isRecord(tracks) || Object.keys(tracks).length === 0 || !isRecord(coverage) || coverage.status !== "PASS" || coverage.max_edge_overrun_px !== 0 || coverage.nonopaque_source_texels !== 0 || coverage.nonopaque_output_pixels !== 0 || !isRecord(canvas) || !positive(canvas.width) || !positive(canvas.height)) {
133
+ return refuse("SCENE_CAMERA_REPORT_INVALID", "expected a canvas and a keyed 12 fps camera with PASS coverage and zero overruns and alpha counts");
134
+ }
135
+ return { width: canvas.width, height: canvas.height, backdrop, fps, tracks, digest };
136
+ }
137
+ function requireDigest(digest, refuse) {
138
+ if (digest === void 0 || digest === null) {
139
+ return refuse("SCENE_CAMERA_MODEL_MISMATCH", "the scene camera report needs a model SHA-256");
140
+ }
141
+ if (!isDigest(digest)) return refuse("SCENE_CAMERA_REPORT_INVALID", "the model SHA-256 must be 64 lowercase hexadecimal digits");
142
+ return digest;
143
+ }
144
+ function sceneCameraModelDigest(report, refuse) {
145
+ const camera = readCameraHeader(report, refuse);
146
+ return camera === null ? null : requireDigest(camera.digest, refuse);
147
+ }
148
+ function finiteTuple(value, length) {
149
+ return Array.isArray(value) && value.length === length && [...value].every(finite);
150
+ }
151
+ function sceneCameraDriftEvidence(report, refuse) {
152
+ const camera = readCameraHeader(report, refuse);
153
+ if (!camera) return null;
154
+ const { backdrop, width, height, fps, tracks } = camera;
155
+ return {
156
+ backdrop,
157
+ failure(animation, pointer, sweep, backingPixel) {
158
+ const track = tracks[animation];
159
+ if (!isRecord(track) || !durationValue(track.duration) || !durationValue(track.compiled_duration) || !Array.isArray(track.frames)) return "missing sampled backdrop geometry";
160
+ const { duration, compiled_duration: compiled, frames } = track;
161
+ const ticks = Math.ceil(duration * fps);
162
+ const terminal = ticks > 0 && (ticks - 1) / fps >= duration ? ticks - 1 : ticks;
163
+ if (ticks >= 4294967295 || frames.length !== terminal + 1) {
164
+ return `incomplete sampled backdrop geometry at ${fps} fps through ${duration} s`;
165
+ }
166
+ for (const [i, row] of frames.entries()) {
167
+ const at = i === terminal ? duration : i / fps;
168
+ const label = `sample ${i} at ${at} authored s`;
169
+ if (!isRecord(row) || row.frame !== i || row.authored_time !== at || row.compiled_time !== (i === terminal ? compiled : at / duration * compiled) || !usableZoom(row.zoom) || !finiteTuple(row.view, 4) || !Array.isArray(row.backdrop_quad) || row.backdrop_quad.length !== 4 || ![...row.backdrop_quad].every((point) => finiteTuple(point, 2))) {
170
+ return `${label} has invalid backdrop evidence`;
171
+ }
172
+ const { zoom, view: [left, top, right, bottom], backdrop_quad: quad } = row;
173
+ const viewWidth = right - left, viewHeight = bottom - top;
174
+ const tolerance = 4 * Number.EPSILON * Math.max(1, Math.abs(left), Math.abs(top), Math.abs(right), Math.abs(bottom));
175
+ if (!positive(viewWidth) || !positive(viewHeight) || Math.abs(viewWidth - width / zoom) > tolerance || Math.abs(viewHeight - height / zoom) > tolerance) {
176
+ return `${label} has a view inconsistent with its output size and zoom`;
177
+ }
178
+ const px = pointer.x / zoom, py = pointer.y / zoom;
179
+ const sx = sweep.x / zoom, sy = sweep.y / zoom;
180
+ if (![px, py, sx, sy].every(finite)) return `${label} has a nonfinite scene excursion`;
181
+ const gx = backingPixel.x / zoom, gy = backingPixel.y / zoom;
182
+ if (!positive(gx) || !positive(gy)) return `${label} has an invalid backing-pixel edge guard`;
183
+ const edgeTolerance2 = Math.max(tolerance, 4 * Number.EPSILON * Math.max(...quad.flat().map(Math.abs)));
184
+ let winding = 0;
185
+ for (const [edge, [x, y]] of quad.entries()) {
186
+ const [nextX, nextY] = quad[(edge + 1) % 4];
187
+ const dx = nextX - x, dy = nextY - y;
188
+ const length = Math.hypot(dx, dy);
189
+ const nx = -dy / length, ny = dx / length;
190
+ const distance = ([a2, b2]) => nx * (a2 - x) + ny * (b2 - y);
191
+ const a = distance(quad[(edge + 2) % 4]), b = distance(quad[(edge + 3) % 4]);
192
+ if (edge === 0) winding = Math.sign(a);
193
+ const side = ["left", "top", "right", "bottom"][edge];
194
+ if (!positive(length) || !finite(a) || !finite(b) || !(a * winding > 0 && b * winding > 0)) {
195
+ return `${label} has an invalid convex backdrop quad at its ${side} edge`;
196
+ }
197
+ const margin = winding * distance([nx * winding >= 0 ? left : right, ny * winding >= 0 ? top : bottom]);
198
+ const excursion = Math.max(Math.abs(nx * px) + Math.abs(ny * py), Math.abs(nx * sx + ny * sy));
199
+ if (!finite(margin) || !finite(excursion)) return `${label} has nonfinite ${side} edge margin or excursion`;
200
+ const guard = Math.abs(nx) * gx + Math.abs(ny) * gy;
201
+ const requiredExcursion = excursion + guard;
202
+ if (!positive(guard) || !finite(requiredExcursion)) return `${label} has an invalid ${side} edge guard or guarded excursion`;
203
+ if (margin - requiredExcursion < -edgeTolerance2) {
204
+ return `${label}, ${side} edge margin ${margin} scene px, required excursion ${excursion} scene px, edge guard ${guard} scene px`;
205
+ }
206
+ }
207
+ }
208
+ return void 0;
209
+ }
210
+ };
211
+ }
212
+ function storedFloat32(value) {
213
+ const rounded = Math.fround(value);
214
+ if (rounded === 0 || !Number.isFinite(rounded)) return rounded === 0 ? 0 : rounded;
215
+ const magnitude = Math.abs(rounded);
216
+ const sign = rounded < 0 ? "-" : "";
217
+ floatBits.setFloat32(0, magnitude);
218
+ const word = floatBits.getUint32(0);
219
+ const exponent = word >>> 23;
220
+ const significand = BigInt(word & 8388607 | (exponent === 0 ? 0 : 8388608));
221
+ const doubledPower = (exponent === 0 ? -149 : exponent - 150) + 1;
222
+ for (let digits = 1; digits <= 9; digits++) {
223
+ const [mantissa, power] = magnitude.toExponential(digits - 1).split("e");
224
+ const nearest = BigInt(mantissa.replace(".", ""));
225
+ const scale = Number(power) - (digits - 1);
226
+ const candidates = [nearest - 1n, nearest, nearest + 1n].filter(
227
+ (candidate) => candidate > 0n && Math.fround(Number(`${candidate}e${scale}`)) === magnitude
228
+ );
229
+ if (candidates.length === 0) continue;
230
+ const chosen = candidates.reduce((a, b) => {
231
+ let midpoint = a + b;
232
+ let float = significand;
233
+ if (scale >= 0) midpoint *= 10n ** BigInt(scale);
234
+ else float *= 10n ** BigInt(-scale);
235
+ if (doubledPower >= 0) float <<= BigInt(doubledPower);
236
+ else midpoint <<= BigInt(-doubledPower);
237
+ return midpoint < float || midpoint === float && b % 2n === 0n ? b : a;
238
+ });
239
+ return Number(`${sign}${chosen}e${scale}`);
240
+ }
241
+ return rounded;
242
+ }
243
+ function storedTime(time) {
244
+ const named = storedFloat32(time);
245
+ const nearest = Math.fround(time);
246
+ if (named === time || nearest <= time || !Number.isFinite(nearest)) return named;
247
+ floatBits.setFloat32(0, nearest);
248
+ floatBits.setUint32(0, floatBits.getUint32(0) - 1);
249
+ return storedFloat32(floatBits.getFloat32(0));
250
+ }
251
+ function coreSampler(keys, duration, label, refuse) {
252
+ const times = keys.map((key) => storedTime(key.t));
253
+ for (const [i, key] of keys.entries()) {
254
+ if (!Number.isFinite(times[i]) || i > 0 && times[i] <= times[i - 1] || !key.pan.every((value) => Number.isFinite(Math.fround(value))) || !positive(Math.fround(1 / key.zoom))) {
255
+ refuse("SCENE_CAMERA_REPORT_INVALID", `${label} key ${i} cannot be stored in a float32 translation timeline`);
256
+ }
257
+ }
258
+ const name = "camera";
259
+ try {
260
+ const doc = readModel(JSON.stringify({
261
+ spec: CORE_DOCUMENT_SPEC,
262
+ referenceScale: 1,
263
+ stage: null,
264
+ bones: [{ name: "pan" }, { name: "span" }],
265
+ slots: [],
266
+ skins: [],
267
+ constraints: [],
268
+ events: [],
269
+ animations: [{
270
+ name,
271
+ duration,
272
+ slots: [],
273
+ constraints: { ik: [], transform: [], path: [], physics: [], slider: [] },
274
+ attachments: [],
275
+ drawOrder: [],
276
+ events: [],
277
+ bones: [
278
+ { name: "pan", timelines: [{ name: "translate", keys: keys.map((key, i) => ({
279
+ time: times[i],
280
+ x: storedFloat32(key.pan[0]),
281
+ y: storedFloat32(key.pan[1]),
282
+ curve: Array.isArray(key.curve) ? key.curve.slice(0, PAN_CURVE_LENGTH) : key.curve
283
+ })) }] },
284
+ { name: "span", timelines: [{ name: "translatex", keys: keys.map((key, i) => ({
285
+ time: times[i],
286
+ value: storedFloat32(1 / key.zoom),
287
+ curve: Array.isArray(key.curve) ? key.curve.slice(PAN_CURVE_LENGTH) : key.curve
288
+ })) }] }
289
+ ]
290
+ }],
291
+ editorOrder: { skins: [], animations: [name] },
292
+ images: [],
293
+ pageGrids: [],
294
+ droppedStates: [],
295
+ absentParts: [],
296
+ meshBones: [],
297
+ meshes: [],
298
+ physics: [],
299
+ deformTransforms: [],
300
+ trackDerivations: [],
301
+ rig: {},
302
+ pages: [],
303
+ spine: { sha256: "0".repeat(64) }
304
+ }), label);
305
+ return (time) => {
306
+ try {
307
+ const [pan, span] = poseRawAnimation(doc, name, time === 0 ? [] : [time]).at(-1).bones;
308
+ const zoom = 1 / span.worldX;
309
+ if (!finite(pan.worldX) || !finite(pan.worldY) || !usableZoom(zoom)) {
310
+ return refuse("SCENE_CAMERA_VIEW_INVALID", `${label} evaluates at ${time} s to nonfinite pan or unusable zoom`);
311
+ }
312
+ return { pan: [pan.worldX, pan.worldY], zoom };
313
+ } catch (error) {
314
+ if (!(error instanceof CoreInputError)) throw error;
315
+ return refuse("SCENE_CAMERA_VIEW_INVALID", `${label} cannot be evaluated at ${time} s`, error);
316
+ }
317
+ };
318
+ } catch (error) {
319
+ if (!(error instanceof CoreInputError)) throw error;
320
+ return refuse("SCENE_CAMERA_REPORT_INVALID", `${label} cannot be read as a Core timeline`, error);
321
+ }
322
+ }
323
+ function validViewport(view) {
324
+ return isRecord(view) && finite(view.x) && finite(view.y) && positive(view.width) && positive(view.height) && finite(view.x + view.width) && view.x + view.width > view.x && finite(view.y + view.height) && view.y + view.height > view.y;
325
+ }
326
+ function cameraView(stage, { pan, zoom }, label, refuse) {
327
+ const centerX = stage.x + stage.width / 2 + pan[0];
328
+ const centerY = stage.y + (stage.height - (stage.height / 2 + pan[1]));
329
+ const halfWidth = stage.width / zoom / 2;
330
+ const halfHeight = stage.height / zoom / 2;
331
+ const x = centerX - halfWidth;
332
+ const y = centerY - halfHeight;
333
+ const width = centerX + halfWidth - x;
334
+ const height = centerY + halfHeight - y;
335
+ const view = { x, y, width, height };
336
+ if (!usableZoom(zoom) || !validViewport(view) || !positive(width * zoom) || !positive(height * zoom)) {
337
+ refuse("SCENE_CAMERA_VIEW_INVALID", `${label} needs a finite, positive, noncollapsed camera view`);
338
+ }
339
+ return view;
340
+ }
341
+ function readTrack(raw, compiled, stage, label, refuse) {
342
+ if (!isRecord(raw) || !durationValue(raw.duration) || !durationValue(raw.compiled_duration) || typeof raw.loop !== "boolean" || !Array.isArray(raw.keys) || raw.keys.length === 0 || !Array.isArray(raw.frames)) {
343
+ return refuse("SCENE_CAMERA_REPORT_INVALID", `${label} needs keys, durations, a loop flag and a frames list`);
344
+ }
345
+ const { duration, loop } = raw;
346
+ if (raw.compiled_duration !== compiled || duration === 0 !== (compiled === 0)) {
347
+ refuse("SCENE_CAMERA_CLIP_MISMATCH", `${label} cannot map ${duration} authored s and ${raw.compiled_duration} reported compiled s to ${compiled} model s`);
348
+ }
349
+ const keys = [];
350
+ for (const [i, key] of raw.keys.entries()) {
351
+ const at = `${label} key ${i}`;
352
+ if (!isRecord(key) || Object.keys(key).some((field) => !["t", "pan", "zoom", "curve"].includes(field))) {
353
+ return refuse("SCENE_CAMERA_REPORT_INVALID", `${at} needs normalized t, pan, zoom and an optional outgoing curve`);
354
+ }
355
+ const { t, pan, zoom, curve } = key;
356
+ if (!finite(t) || (i === 0 ? t !== 0 : t <= keys[i - 1].t) || !Array.isArray(pan) || pan.length !== 2 || !finite(pan[0]) || !finite(pan[1]) || !usableZoom(zoom)) {
357
+ return refuse("SCENE_CAMERA_REPORT_INVALID", `${at} needs ordered finite seconds from zero, finite pan and positive zoom`);
358
+ }
359
+ if (curve !== void 0) {
360
+ const validCurve = curve === "stepped" || Array.isArray(curve) && curve.length === 12 && [...curve].every(
361
+ (value) => finite(value) && Number.isFinite(Math.fround(value)) && storedFloat32(value) === value
362
+ );
363
+ if (!validCurve || i === raw.keys.length - 1) {
364
+ return refuse("SCENE_CAMERA_REPORT_INVALID", `${at} needs a nonterminal outgoing curve (stepped or twelve float32 decimals)`);
365
+ }
366
+ }
367
+ const normalized = { t, pan: [pan[0], pan[1]], zoom, curve: Array.isArray(curve) ? [...curve] : curve };
368
+ cameraView(stage, normalized, at, refuse);
369
+ keys.push(normalized);
370
+ }
371
+ const first = keys[0], last = keys[keys.length - 1];
372
+ if (last.t !== duration || loop && !matchesSample(first, last)) {
373
+ refuse("SCENE_CAMERA_REPORT_INVALID", `${label} must end at its authored duration and close exactly when looped`);
374
+ }
375
+ const core = keys.some((key) => key.curve !== void 0) ? coreSampler(keys, duration, label, refuse) : void 0;
376
+ const start = core?.(0), end = core?.(Math.fround(storedTime(duration)));
377
+ if (start && end && loop && !matchesSample(start, end)) {
378
+ refuse("SCENE_CAMERA_REPORT_INVALID", `${label} must close exactly at the Core-evaluated loop endpoints`);
379
+ }
380
+ const easedStart = first.curve !== void 0;
381
+ const easedEnd = keys.at(-2)?.curve !== void 0;
382
+ const easedSeam = loop && (easedStart || easedEnd);
383
+ if (start && (easedSeam || easedStart)) cameraView(stage, start, label, refuse);
384
+ if (end && (easedSeam || easedEnd)) cameraView(stage, end, label, refuse);
385
+ return {
386
+ duration,
387
+ compiledDuration: compiled,
388
+ loop,
389
+ sample(time) {
390
+ if (time === 0 && (easedSeam || easedStart) && start) return start;
391
+ if (time === duration && (easedSeam || easedEnd) && end) return end;
392
+ let low = 0, high = keys.length - 1;
393
+ while (low < high) {
394
+ const mid = Math.ceil((low + high) / 2);
395
+ if (keys[mid].t <= time) low = mid;
396
+ else high = mid - 1;
397
+ }
398
+ const from = keys[low], to = keys[low + 1];
399
+ if (from.curve !== void 0 && core) return core(time);
400
+ if (time === from.t || to === void 0) return from;
401
+ const phase = (time - from.t) / (to.t - from.t);
402
+ const mix = (a, b) => a + (b - a) * phase;
403
+ return { pan: [mix(from.pan[0], to.pan[0]), mix(from.pan[1], to.pan[1])], zoom: 1 / mix(1 / from.zoom, 1 / to.zoom) };
404
+ }
405
+ };
406
+ }
407
+ function cameraTimes(track, clock, refuse) {
408
+ const { duration, compiledDuration, loop } = track;
409
+ if (isRecord(clock) && clock.endpoint === "terminal" && !("basis" in clock) && !("seconds" in clock)) {
410
+ return { authoredSeconds: duration, compiledSeconds: compiledDuration };
411
+ }
412
+ if (!isRecord(clock) || clock.endpoint !== void 0 && clock.endpoint !== "phase" || clock.basis !== "authored" && clock.basis !== "compiled" || !durationValue(clock.seconds)) {
413
+ return refuse("SCENE_CAMERA_CLOCK_INVALID", "expected terminal or finite nonnegative phase seconds on the authored or compiled clock");
414
+ }
415
+ const authored = clock.basis === "authored";
416
+ const limit = authored ? duration : compiledDuration;
417
+ const otherLimit = authored ? compiledDuration : duration;
418
+ const time = limit === 0 || clock.seconds === 0 ? 0 : loop ? clock.seconds % limit : Math.min(clock.seconds, limit);
419
+ const otherTime = time === limit ? otherLimit : time / limit * otherLimit;
420
+ return authored ? { authoredSeconds: time, compiledSeconds: otherTime } : { authoredSeconds: otherTime, compiledSeconds: time };
421
+ }
422
+ function bindSceneCameraReport(report, model, refuse) {
423
+ const document = isReportBytes(report) ? decodeSceneCameraReport(report, refuse) : report;
424
+ const camera = readCameraHeader(document, refuse);
425
+ if (camera === null) return null;
426
+ if (!validViewport(model?.stage)) return refuse("SCENE_CAMERA_VIEW_INVALID", "the model needs a finite, positive, noncollapsed stage");
427
+ if (model.sha256 !== requireDigest(camera.digest, refuse)) {
428
+ refuse("SCENE_CAMERA_MODEL_MISMATCH", "the scene camera SHA-256 does not match the consumed model");
429
+ }
430
+ const { x, y, width, height } = model.stage;
431
+ const stage = { x, y, width, height };
432
+ if (camera.width !== stage.width || camera.height !== stage.height) {
433
+ refuse("SCENE_CAMERA_MODEL_MISMATCH", "the report canvas dimensions must match the model stage");
434
+ }
435
+ const durations = /* @__PURE__ */ new Map();
436
+ if (!Array.isArray(model.animations)) refuse("SCENE_CAMERA_CLIP_MISMATCH", "the model needs an animation list");
437
+ for (const animation of model.animations) {
438
+ if (!isRecord(animation) || typeof animation.name !== "string" || !animation.name.length || durations.has(animation.name) || !durationValue(animation.duration)) {
439
+ refuse("SCENE_CAMERA_CLIP_MISMATCH", "the model needs unique animation names with finite nonnegative durations");
440
+ }
441
+ durations.set(animation.name, animation.duration);
442
+ }
443
+ const bound = /* @__PURE__ */ new Map();
444
+ for (const [animation, raw] of Object.entries(camera.tracks)) {
445
+ const label = `scene camera track ${JSON.stringify(animation)}`;
446
+ const duration = durations.get(animation);
447
+ if (duration === void 0) return refuse("SCENE_CAMERA_CLIP_MISMATCH", `${label} is absent from the model`);
448
+ bound.set(animation, readTrack(raw, duration, stage, label, refuse));
449
+ }
450
+ const output = Object.freeze({ width: stage.width, height: stage.height });
451
+ return Object.freeze({
452
+ sample(animation, clock) {
453
+ if (!durations.has(animation)) refuse("SCENE_CAMERA_CLIP_MISMATCH", `unknown model animation ${JSON.stringify(animation)}`);
454
+ const track = bound.get(animation);
455
+ if (!track) return null;
456
+ const times = cameraTimes(track, clock, refuse);
457
+ const { pan, zoom } = track.sample(times.authoredSeconds);
458
+ const viewWorld = cameraView(stage, { pan, zoom }, `scene camera track ${JSON.stringify(animation)} at ${times.authoredSeconds} s`, refuse);
459
+ return Object.freeze({
460
+ animation,
461
+ ...times,
462
+ pan: Object.freeze([pan[0], pan[1]]),
463
+ zoom,
464
+ viewWorld: Object.freeze(viewWorld),
465
+ output,
466
+ loop: track.loop
467
+ });
468
+ }
469
+ });
470
+ }
471
+ function sceneCameraTransform(frame, refuse) {
472
+ if (!frame || !validViewport(frame.viewWorld) || !usableZoom(frame.zoom) || !frame.output || !positive(frame.output.width) || !positive(frame.output.height) || !positive(frame.viewWorld.width * frame.zoom) || !positive(frame.viewWorld.height * frame.zoom)) {
473
+ return refuse("SCENE_CAMERA_VIEW_INVALID", "expected finite authored output dimensions and a positive, noncollapsed camera view");
474
+ }
475
+ const { viewWorld, zoom, output } = frame;
476
+ return { origin: { x: viewWorld.x, y: viewWorld.y + viewWorld.height }, zoom, width: output.width, height: output.height };
477
+ }
478
+ function projectSceneCamera(frame, refuse) {
479
+ const { origin, zoom, width, height } = sceneCameraTransform(frame, refuse);
480
+ return {
481
+ worldToOutput: ({ x, y }) => ({ x: (x - origin.x) * zoom, y: (origin.y - y) * zoom }),
482
+ outputToWorld: ({ x, y }) => ({ x: origin.x + x / zoom, y: origin.y - y / zoom }),
483
+ outputClip: { x: 0, y: 0, width, height }
484
+ };
485
+ }
486
+ class ComposedTakeError extends Error {
487
+ constructor(code, detail, cause) {
488
+ super(`${code}: ${detail}`, { cause });
489
+ this.code = code;
490
+ }
491
+ }
492
+ function refuseSceneCamera(code, detail, cause) {
493
+ throw new ComposedTakeError(code, detail, cause);
494
+ }
495
+ function bindSceneCamera(report, model) {
496
+ return bindSceneCameraReport(report, model, refuseSceneCamera);
497
+ }
498
+ function sceneCameraProjection(frame) {
499
+ return projectSceneCamera(frame, refuseSceneCamera);
500
+ }
501
+ const NEUTRAL = { x: 0, y: 0 };
502
+ const PLANES = ["background", "figure", "foreground"];
503
+ const DEFAULT_TRANSITION_MS = 120;
504
+ const BACKDROP_GAIN = -0.55;
505
+ const TURN_FULL_RANGE_AT_STAGE_EDGE = 1;
506
+ function turnCoordinate(axis, point) {
507
+ return axis === "pitch" ? point.y : point.x;
508
+ }
509
+ const ZERO_RANGE = { minX: 0, maxX: 0, minY: 0, maxY: 0 };
510
+ function checkMode(mode) {
511
+ if (mode !== "fixed" && mode !== "pan" && mode !== "parallax") {
512
+ throw new ComposedTakeError("COMPOSED_INVALID_CAMERA", `unknown camera mode ${String(mode)}`);
513
+ }
514
+ }
515
+ function bindSlots(assets, options) {
516
+ const { doc } = assets.document;
517
+ const skin = doc.skins.find((skin2) => skin2.name === "default");
518
+ const drawable = new Set(doc.slots.filter(({ name }) => {
519
+ const entries2 = Object.values(skin?.attachments[name] ?? {});
520
+ return entries2.some(({ kind }) => kind === "region" || kind === "mesh" || kind === "linkedmesh");
521
+ }).map((slot) => slot.name));
522
+ const named = options.planes;
523
+ if (named === void 0 === (options.slots === void 0)) {
524
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", "declare either slots or named planes");
525
+ }
526
+ if (named !== void 0 && (!named || typeof named !== "object" || Array.isArray(named))) {
527
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", "named planes must be a record keyed by plane ID");
528
+ }
529
+ const entries = named === void 0 ? PLANES.map((id) => [id, options.slots?.[id]]).filter(([id, slots]) => id !== "foreground" || slots !== void 0) : Object.entries(named).map(([id, plane]) => [id, plane?.slots]);
530
+ if (named !== void 0) {
531
+ const records = Object.values(named);
532
+ if (records.filter((record) => record?.role === "backdrop").length !== 1 || records.filter((record) => record?.role === "figure").length !== 1) {
533
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", "named planes need one backdrop and one figure");
534
+ }
535
+ }
536
+ const planes = /* @__PURE__ */ new Map();
537
+ for (const [plane, slots] of entries) {
538
+ const role = named?.[plane]?.role;
539
+ if (named && (!plane.trim() || role !== "backdrop" && role !== "overlay" && role !== "figure")) {
540
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", `${JSON.stringify(plane)} needs a valid plane ID and role`);
541
+ }
542
+ if (!Array.isArray(slots) || (named ? slots.length === 0 : plane !== "foreground" && slots.length === 0)) {
543
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", `${plane} needs an explicit slot list`);
544
+ }
545
+ if (named && role !== "figure" && slots.length !== 1) {
546
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", `${plane} must bind exactly one compiled plate slot`);
547
+ }
548
+ for (const slot of slots) {
549
+ if (!drawable.has(slot) || planes.has(slot)) {
550
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", `${plane} has a non-drawable or duplicate slot ${JSON.stringify(slot)}`);
551
+ }
552
+ planes.set(slot, plane);
553
+ }
554
+ }
555
+ const missing = [...drawable].filter((slot) => !planes.has(slot));
556
+ if (missing.length) {
557
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", `unbound drawable slots ${missing.join(", ")}`);
558
+ }
559
+ return planes;
560
+ }
561
+ function checkFrame(frame, planes, backdropPlane = "background", allowSharedClip = false) {
562
+ const seen = /* @__PURE__ */ new Set();
563
+ const clipPlanes = /* @__PURE__ */ new Map();
564
+ const backdrop = [];
565
+ for (const slot of frame.order) {
566
+ const plane = planes.get(slot.slot);
567
+ if (plane === void 0 || seen.has(slot.slot)) {
568
+ throw new ComposedTakeError("COMPOSED_SLOT_PARTITION", `unbound or repeated posed slot ${JSON.stringify(slot.slot)}`);
569
+ }
570
+ seen.add(slot.slot);
571
+ if (slot.clip && !allowSharedClip) {
572
+ const owner = clipPlanes.get(slot.clip);
573
+ if (owner !== void 0 && owner !== plane) {
574
+ throw new ComposedTakeError("COMPOSED_CROSS_PLANE_CLIP", `one clip covers ${owner} and ${plane} at ${JSON.stringify(slot.slot)}`);
575
+ }
576
+ clipPlanes.set(slot.clip, plane);
577
+ }
578
+ if (plane === backdropPlane) backdrop.push(slot);
579
+ }
580
+ return backdrop;
581
+ }
582
+ function trackError(id, detail) {
583
+ return new ComposedTakeError("COMPOSED_PLATE_TRACK", `plane ${JSON.stringify(id)} ${detail}`);
584
+ }
585
+ function namedPlanes(assets, options, animationName = options.animation) {
586
+ if (!options.planes) return void 0;
587
+ const read = assets.document;
588
+ const doc = underNoSkin(read.doc);
589
+ const skin = doc.skins.find((skin2) => skin2.name === "default");
590
+ const animation = doc.animations.find((animation2) => animation2.name === animationName);
591
+ const setup = poseRawSetup(doc);
592
+ const setupFrame = frameOf(frameSource(doc, read.parsed), setup);
593
+ const bones = new Map(doc.bones.map((bone) => [bone.name, bone]));
594
+ const gains = /* @__PURE__ */ new Map();
595
+ const plates = [];
596
+ const figureSlots = /* @__PURE__ */ new Set();
597
+ const drivers = /* @__PURE__ */ new Set();
598
+ function checkStable(id, slot, chain, driver, { name, timelines }) {
599
+ if (timelines.bones.some((row) => chain.has(row.name) && row.name !== driver && row.timelines.length) || timelines.slots.some((row) => row.name === slot && row.timelines.some((timeline) => timeline.kind === "attachment")) || timelines.attachments.some((row) => row.slot === slot && row.sequence)) {
600
+ throw trackError(id, `has non-translation motion or an unstable attachment in ${JSON.stringify(name)}`);
601
+ }
602
+ }
603
+ for (const [id, { role, slots, gain, baked }] of Object.entries(options.planes)) {
604
+ if (gain !== void 0 && !Number.isFinite(gain)) {
605
+ throw new ComposedTakeError("COMPOSED_INVALID_DISPLACEMENT", `plane ${JSON.stringify(id)} needs a finite gain`);
606
+ }
607
+ if (role === "figure") {
608
+ if (baked !== void 0 || gain !== void 0 && gain !== 0) {
609
+ throw trackError(id, "must stay at focal gain 0 without a baked camera track");
610
+ }
611
+ gains.set(id, 0);
612
+ for (const slot2 of slots) figureSlots.add(slot2);
613
+ continue;
614
+ }
615
+ const slot = doc.slots.find((slot2) => slot2.name === slots[0]);
616
+ const region = setupFrame.order.find((drawn) => drawn.slot === slot.name);
617
+ if (region?.kind !== "region") {
618
+ throw new ComposedTakeError("COMPOSED_BACKDROP_COVERAGE", `plane ${JSON.stringify(id)} has no rigid setup quad (all edges)`);
619
+ }
620
+ const plate = { id, role, setup: region };
621
+ plates.push(plate);
622
+ if (gain !== void 0 || role === "backdrop") gains.set(id, gain ?? BACKDROP_GAIN);
623
+ if (role === "overlay" && baked === void 0) continue;
624
+ const attachment = slot.setup === null ? void 0 : skin?.attachments[slot.name]?.[slot.setup];
625
+ if (attachment?.kind !== "region" || (attachment.sequenceCount ?? 1) !== 1) {
626
+ throw trackError(id, "needs one stable setup region");
627
+ }
628
+ const chain = /* @__PURE__ */ new Set();
629
+ for (let bone = bones.get(slot.bone); bone; bone = bone.parent === void 0 ? void 0 : bones.get(bone.parent)) {
630
+ chain.add(bone.name);
631
+ }
632
+ const driver = baked?.bone;
633
+ checkStable(id, slot.name, chain, driver, animation);
634
+ for (const { record } of doc.constraints) {
635
+ if (!record) continue;
636
+ if (record.kind === "slider") {
637
+ checkStable(id, slot.name, chain, void 0, { name: record.animation, timelines: record.timelines });
638
+ } else if (record.kind === "physics" ? chain.has(record.bone) : record.bones.some((bone) => chain.has(bone))) {
639
+ throw trackError(id, `has a moving or constrained plate ancestry (${JSON.stringify(record.name)})`);
640
+ }
641
+ }
642
+ if (baked === void 0) continue;
643
+ const parentName = bones.get(slot.bone)?.parent;
644
+ const parent = setup.bones.find((bone) => bone.name === parentName);
645
+ if (driver !== slot.bone || !parent?.active || parent.parent !== null || drivers.has(driver)) {
646
+ throw trackError(id, "needs an independent translate track on its compiled slot’s direct root-child bone");
647
+ }
648
+ drivers.add(driver);
649
+ const rows = animation.timelines.bones.filter((row) => row.name === driver);
650
+ const timelines = rows[0]?.timelines;
651
+ const keys = timelines?.[0]?.keys;
652
+ const duration = animation.timelines.duration;
653
+ const isCenter = (key) => key.values[0] === 0 && key.values[1] === 0;
654
+ if (rows.length !== 1 || timelines?.length !== 1 || timelines[0].kind !== "translate" || !keys || keys.length < 2 || keys[0].time !== 0 || keys[keys.length - 1].time !== duration || !isCenter(keys[0]) || !isCenter(keys[keys.length - 1]) || keys.some((key, i) => key.curve !== "linear" || !Number.isFinite(key.time) || key.values.length !== 2 || !key.values.every(Number.isFinite) || i > 0 && key.time <= keys[i - 1].time)) {
655
+ throw trackError(id, "needs a finite linear translate loop with ordered keys and setup-center endpoints");
656
+ }
657
+ const range = { ...ZERO_RANGE };
658
+ let amplitudeX = 0;
659
+ let horizontal = parent.c === 0 && parent.a !== 0;
660
+ for (const { values: [x, y] } of keys) {
661
+ horizontal &&= y === 0;
662
+ amplitudeX = Math.max(amplitudeX, Math.abs(x));
663
+ const dx = parent.a * x + parent.b * y;
664
+ const dy = -(parent.c * x + parent.d * y);
665
+ range.minX = Math.min(range.minX, dx);
666
+ range.maxX = Math.max(range.maxX, dx);
667
+ range.minY = Math.min(range.minY, dy);
668
+ range.maxY = Math.max(range.maxY, dy);
669
+ }
670
+ if (!Object.values(range).every(Number.isFinite)) throw trackError(id, "has a non-finite world translation envelope");
671
+ plate.baked = { range, amplitudeX, horizontalRoot: horizontal ? parent.name : void 0, keys };
672
+ }
673
+ const backdrop = plates.find((plate) => plate.role === "backdrop");
674
+ const backdropGain = gains.get(backdrop.id);
675
+ const reference = backdrop.baked;
676
+ if (options.autoSweep && plates.some((plate) => plate.baked)) {
677
+ throw trackError(backdrop.id, "cannot combine a camera-only autoSweep with baked plate motion");
678
+ }
679
+ for (const { id, baked } of plates) {
680
+ if (gains.has(id)) continue;
681
+ const comparable = baked && reference && reference.horizontalRoot !== void 0 && baked.horizontalRoot === reference.horizontalRoot && reference.amplitudeX > 0 && baked.amplitudeX > 0 && baked.keys.length === reference.keys.length && baked.keys.every((key, i) => key.time === reference.keys[i].time && Math.sign(key.values[0]) === Math.sign(reference.keys[i].values[0]));
682
+ const gain = comparable ? backdropGain * (baked.amplitudeX / reference.amplitudeX) : NaN;
683
+ if (!Number.isFinite(gain)) {
684
+ throw trackError(id, `needs an explicit gain for motion relative to backdrop plane ${JSON.stringify(backdrop.id)}`);
685
+ }
686
+ gains.set(id, gain);
687
+ }
688
+ return { plates, backdrop: backdrop.id, figureSlots, gains };
689
+ }
690
+ function transformFrame(frame, shiftFor, { origin = NEUTRAL, scale = { x: 1, y: 1 }, centered, clipInStockSpace = false } = {}) {
691
+ const clips = /* @__PURE__ */ new Map();
692
+ const native = origin.x === 0 && origin.y === 0 && scale.x === 1 && scale.y === 1;
693
+ return { order: frame.order.map((slot) => {
694
+ const shift = shiftFor(slot);
695
+ const setup = centered?.get(slot.slot);
696
+ if (native && shift.x === 0 && shift.y === 0 && !setup) {
697
+ return clipInStockSpace && slot.clip ? rememberComposedClip({ ...slot }, slot, shift, origin, scale) : slot;
698
+ }
699
+ const transform = (xy, delta = shift) => xy.map((value, i) => i % 2 === 0 ? (value + delta.x - origin.x) * scale.x : (value - delta.y - origin.y) * scale.y);
700
+ let clip = slot.clip;
701
+ if (clip) {
702
+ const variants = clips.get(clip) ?? [];
703
+ const existing = variants.find((entry) => entry.shift.x === shift.x && entry.shift.y === shift.y);
704
+ if (existing) clip = existing.clip;
705
+ else {
706
+ const source2 = clip;
707
+ clip = { ...source2, polygon: transform(source2.polygon) };
708
+ variants.push({ shift, clip });
709
+ clips.set(source2, variants);
710
+ }
711
+ }
712
+ const positioned = slot.kind === "mesh" ? { ...slot, clip, vertices: transform(slot.vertices) } : { ...slot, clip, corners: setup ? native ? setup.corners : transform(setup.corners, NEUTRAL) : transform(slot.corners) };
713
+ if (!clipInStockSpace || !slot.clip) return positioned;
714
+ const source = slot.kind === "region" && setup ? { ...slot, corners: setup.corners.map((value, i) => i % 2 === 0 ? value - shift.x : value + shift.y) } : slot;
715
+ return rememberComposedClip(positioned, source, shift, origin, scale);
716
+ }) };
717
+ }
718
+ function drawSceneCamera(renderer, pose, frame, backing, shiftFor = () => NEUTRAL) {
719
+ const { origin, zoom, width, height } = sceneCameraTransform(frame, refuseSceneCamera);
720
+ const pixels = backing === void 0 ? { width: Math.ceil(width), height: Math.ceil(height) } : backing;
721
+ const backingDimension = (value) => Number.isInteger(value) && value > 0 && value <= 4294967295;
722
+ if (!pixels || !backingDimension(pixels.width) || !backingDimension(pixels.height)) {
723
+ refuseSceneCamera("SCENE_CAMERA_VIEW_INVALID", "the backing needs positive integer canvas dimensions");
724
+ }
725
+ const scale = { x: zoom * (pixels.width / width), y: zoom * (pixels.height / height) };
726
+ if (!Object.values(scale).every((value) => Number.isFinite(value) && value > 0)) {
727
+ refuseSceneCamera("SCENE_CAMERA_VIEW_INVALID", "the view cannot be projected into this backing");
728
+ }
729
+ const projected = transformFrame(pose, shiftFor, { origin, scale, clipInStockSpace: true });
730
+ const { viewport, pixelRatio } = renderer;
731
+ try {
732
+ renderer.viewport = { x: 0, y: -pixels.height, width: pixels.width, height: pixels.height };
733
+ renderer.pixelRatio = 1;
734
+ renderer.render(projected);
735
+ } finally {
736
+ renderer.viewport = viewport;
737
+ renderer.pixelRatio = pixelRatio;
738
+ }
739
+ }
740
+ function renderSceneCameraFrame(renderer, pose, frame, backing) {
741
+ drawSceneCamera(renderer, pose, frame, backing);
742
+ }
743
+ const stageTop = (stage) => stage.y + stage.height;
744
+ const edgeTolerance = (a, b) => Math.max(Math.abs(a), Math.abs(b), 1) * 2 ** -23;
745
+ function requireStage(stage) {
746
+ if (!stage || ![stage.x, stage.y, stage.width, stage.height, stage.x + stage.width, stageTop(stage)].every(Number.isFinite) || stage.x + stage.width <= stage.x || stageTop(stage) <= stage.y) {
747
+ throw new ComposedTakeError("COMPOSED_STAGE_REQUIRED", "the compiled model needs a positive stage with finite coordinates");
748
+ }
749
+ return stage;
750
+ }
751
+ function backdropAlphaAudit(renderer) {
752
+ let lastNonOpaque;
753
+ let renderFailure;
754
+ return (frame, viewport, pixelRatio = 1) => {
755
+ renderer.viewport = viewport;
756
+ renderer.pixelRatio = pixelRatio;
757
+ try {
758
+ renderer.render(frame);
759
+ } catch (error) {
760
+ renderFailure = { error };
761
+ lastNonOpaque = void 0;
762
+ throw error;
763
+ }
764
+ if (renderer.framesReused && renderFailure) throw renderFailure.error;
765
+ renderFailure = void 0;
766
+ if (!renderer.framesReused || lastNonOpaque === void 0) {
767
+ lastNonOpaque = void 0;
768
+ const ctx = renderer.canvas.getContext("2d");
769
+ if (!ctx) throw new Error("Canvas 2D readback is unavailable");
770
+ const { data } = ctx.getImageData(0, 0, renderer.canvas.width, renderer.canvas.height);
771
+ let count = 0;
772
+ for (let i = 3; i < data.length; i += 4) count += Number(data[i] !== 255);
773
+ lastNonOpaque = count;
774
+ }
775
+ return lastNonOpaque;
776
+ };
777
+ }
778
+ function backdropGuard(audit, stage) {
779
+ return (order, layout, mode) => {
780
+ if (mode === "fixed") return;
781
+ const shift = planeOffsets(layout.excursion, mode).background;
782
+ const requested = { x: Math.abs(shift.x), y: Math.abs(shift.y) };
783
+ const x = requested.x * stage.width / layout.cssWidth;
784
+ const y = requested.y * stage.height / layout.cssHeight;
785
+ const stageRight = stage.x + stage.width;
786
+ const topOfStage = stageTop(stage);
787
+ const bounds = { left: stage.x - x, right: stageRight + x, top: topOfStage + y, bottom: stage.y - y };
788
+ let left = Infinity, right = -Infinity, top = -Infinity, bottom = Infinity;
789
+ for (const slot of order) {
790
+ const points = slot.kind === "region" ? slot.corners : slot.vertices;
791
+ for (let i = 0; i < points.length; i += 2) {
792
+ left = Math.min(left, points[i]);
793
+ right = Math.max(right, points[i]);
794
+ bottom = Math.min(bottom, points[i + 1]);
795
+ top = Math.max(top, points[i + 1]);
796
+ }
797
+ }
798
+ const fail = (detail) => {
799
+ const cssPixels = (value) => Number.isFinite(value) ? String(Number(value.toFixed(3))) : "unavailable";
800
+ const available = (edge, stageEdge, sign, cssPerUnit) => {
801
+ if (!Number.isFinite(edge)) return "unavailable";
802
+ const margin = (edge - stageEdge) * sign;
803
+ return cssPixels(Math.abs(margin) <= edgeTolerance(edge, stageEdge) ? 0 : margin * cssPerUnit);
804
+ };
805
+ const cssPerX = layout.cssWidth / stage.width;
806
+ const cssPerY = layout.cssHeight / stage.height;
807
+ const horizontal = `left=${available(left, stage.x, -1, cssPerX)}, right=${available(right, stageRight, 1, cssPerX)}`;
808
+ const vertical = `top=${available(top, topOfStage, 1, cssPerY)}, bottom=${available(bottom, stage.y, -1, cssPerY)}`;
809
+ return new ComposedTakeError(
810
+ "COMPOSED_BACKDROP_COVERAGE",
811
+ `${mode} at ${cssPixels(layout.cssWidth)} × ${cssPixels(layout.cssHeight)} CSS px needs an opaque backdrop (camera excursion ${cssPixels(layout.excursion.x)} × ${cssPixels(layout.excursion.y)} CSS px); requested shift per edge X=${cssPixels(requested.x)}, Y=${cssPixels(requested.y)} CSS px; available geometric overscan ${horizontal}, ${vertical} CSS px; ${detail}`
812
+ );
813
+ };
814
+ if (!Object.values(bounds).every(Number.isFinite)) throw fail("the requested envelope has non-finite world bounds");
815
+ const outside = (edge, expected, sign) => !Number.isFinite(edge) || (edge - expected) * sign > edgeTolerance(edge, expected);
816
+ const uncovered = [
817
+ outside(left, bounds.left, 1) && "left",
818
+ outside(right, bounds.right, -1) && "right",
819
+ outside(top, bounds.top, -1) && "top",
820
+ outside(bottom, bounds.bottom, 1) && "bottom"
821
+ ].filter(Boolean);
822
+ if (uncovered.length) throw fail(`uncovered geometric edges ${uncovered.join(", ")}`);
823
+ const width = Math.ceil(layout.width + 2 * x * layout.width / stage.width);
824
+ const height = Math.ceil(layout.height + 2 * y * layout.height / stage.height);
825
+ const envelope = transformFrame({ order }, () => NEUTRAL, {
826
+ origin: { x: bounds.left, y: bounds.top },
827
+ scale: { x: width / (bounds.right - bounds.left), y: height / (bounds.top - bounds.bottom) }
828
+ });
829
+ let lastNonOpaque;
830
+ try {
831
+ lastNonOpaque = audit(envelope, { x: 0, y: -height, width, height });
832
+ } catch (error) {
833
+ throw fail(`backdrop alpha cannot be read (${String(error)})`);
834
+ }
835
+ if (lastNonOpaque) throw fail(`${lastNonOpaque} envelope pixels have alpha below 255`);
836
+ };
837
+ }
838
+ function plateCoverageError(id, mode, detail) {
839
+ return new ComposedTakeError("COMPOSED_BACKDROP_COVERAGE", `plane ${JSON.stringify(id)} in ${mode}: ${detail}`);
840
+ }
841
+ function livePlates(frame, named, mode) {
842
+ const slots = new Map(frame.order.map((slot) => [slot.slot, slot]));
843
+ return named.plates.map((plate) => {
844
+ const { id, role, setup, baked } = plate;
845
+ const slot = slots.get(setup.slot);
846
+ if (slot?.kind !== "region") throw plateCoverageError(id, mode, "missing live rigid quad (all edges)");
847
+ if (!baked && role === "overlay") return { plate, slot, live: NEUTRAL };
848
+ const { corners } = slot;
849
+ const x = corners[0] - setup.corners[0];
850
+ const y = setup.corners[1] - corners[1];
851
+ const range = baked?.range ?? ZERO_RANGE;
852
+ const tolerance = Math.max(...corners.map((value, i) => edgeTolerance(value, setup.corners[i])));
853
+ if (slot.region !== setup.region || slot.page !== setup.page || corners.length !== 8 || !corners.every((value, i) => Math.abs(value - (setup.corners[i] + (i % 2 === 0 ? x : -y))) <= tolerance) || x < range.minX - tolerance || x > range.maxX + tolerance || y < range.minY - tolerance || y > range.maxY + tolerance) {
854
+ throw plateCoverageError(id, mode, "live quad is outside its stable translation contract (all edges)");
855
+ }
856
+ return { plate, slot, live: { x, y } };
857
+ });
858
+ }
859
+ function plateEnvelope(baked, pointer, sweep, mode) {
860
+ if (mode === "fixed") return baked;
861
+ if (mode === "pan") return {
862
+ minX: baked.minX - pointer.x,
863
+ maxX: baked.maxX + pointer.x,
864
+ minY: baked.minY - pointer.y,
865
+ maxY: baked.maxY + pointer.y
866
+ };
867
+ const x = Math.max(pointer.x, sweep.x);
868
+ const y = Math.max(pointer.y, sweep.y);
869
+ return {
870
+ minX: Math.min(baked.minX, -x),
871
+ maxX: Math.max(baked.maxX, x),
872
+ minY: Math.min(baked.minY, -y),
873
+ maxY: Math.max(baked.maxY, y)
874
+ };
875
+ }
876
+ function checkPlateEnvelopes(stage, layout, mode, excursion, plates, gains, sweep) {
877
+ const backingX = layout.width / stage.width;
878
+ const backingY = layout.height / stage.height;
879
+ const cssToBacking = { x: layout.width / layout.cssWidth, y: layout.height / layout.cssHeight };
880
+ for (const { plate: { id, setup, baked, role }, slot } of plates) {
881
+ const stable = baked || role === "backdrop";
882
+ const gain = Math.abs(mode === "pan" ? 1 : gains.get(id));
883
+ const range = baked?.range ?? ZERO_RANGE;
884
+ const requested = plateEnvelope(
885
+ {
886
+ minX: range.minX * backingX,
887
+ maxX: range.maxX * backingX,
888
+ minY: range.minY * backingY,
889
+ maxY: range.maxY * backingY
890
+ },
891
+ { x: gain * excursion.x * cssToBacking.x, y: gain * excursion.y * cssToBacking.y },
892
+ { x: gain * sweep.x * cssToBacking.x, y: gain * sweep.y * cssToBacking.y },
893
+ mode
894
+ );
895
+ const left = -requested.maxX;
896
+ const right = layout.width - requested.minX;
897
+ const top = -requested.maxY;
898
+ const bottom = layout.height - requested.minY;
899
+ const corners = stable ? setup.corners : slot.corners;
900
+ const xs = [0, 2, 4, 6].map((i) => (corners[i] - stage.x) * backingX);
901
+ const ys = [1, 3, 5, 7].map((i) => (stageTop(stage) - corners[i]) * backingY);
902
+ const bounds = (numbers) => `[${numbers.map((n) => Number(n.toFixed(4))).join(", ")}]`;
903
+ const fail = (detail) => plateCoverageError(id, mode, `${detail}; at ${layout.width} × ${layout.height} backing px, swept stage X=${bounds([left, right])}, Y=${bounds([top, bottom])}, quad X=${bounds([Math.min(...xs), Math.max(...xs)])}, Y=${bounds([Math.min(...ys), Math.max(...ys)])}`);
904
+ if (corners.length !== 8 || ![left, right, top, bottom, ...xs, ...ys].every((value) => Number.isFinite(Math.fround(value)))) {
905
+ throw fail("non-finite swept quad bounds (all edges)");
906
+ }
907
+ if (!xs.every((x) => [requested.minX, requested.maxX].every((shift) => Number.isFinite(Math.fround(x + shift)))) || !ys.every((y) => [requested.minY, requested.maxY].every((shift) => Number.isFinite(Math.fround(y + shift))))) {
908
+ throw fail("swept quad exceeds finite backing coordinates (all edges)");
909
+ }
910
+ const edgeNames = ["left", "top", "right", "bottom"];
911
+ const distances = xs.map((x, i) => {
912
+ const next = (i + 1) % 4;
913
+ const dx = xs[next] - x;
914
+ const dy = ys[next] - ys[i];
915
+ const length = Math.hypot(dx, dy);
916
+ return (px, py) => (dx * (py - ys[i]) - dy * (px - x)) / length;
917
+ });
918
+ const winding = Math.sign(distances[0](xs[2], ys[2]));
919
+ const invalid = distances.findIndex((distance, i) => [2, 3].some((step) => {
920
+ const corner = (i + step) % 4;
921
+ return !(distance(xs[corner], ys[corner]) * winding > 0);
922
+ }));
923
+ if (invalid !== -1) throw fail(`invalid quad at ${edgeNames[invalid]} edge`);
924
+ if (role === "overlay") continue;
925
+ const tolerance = Math.max(1, ...xs.map(Math.abs), ...ys.map(Math.abs), Math.abs(right), Math.abs(bottom)) * 2 ** -23;
926
+ const uncovered = edgeNames.filter((_edge, i) => [left, right].some((x) => [top, bottom].some((y) => distances[i](x, y) * winding < -tolerance)));
927
+ if (uncovered.length) throw fail(`uncovered geometric edges ${uncovered.join(", ")}`);
928
+ }
929
+ }
930
+ async function fetchSceneReport(url) {
931
+ if (typeof url !== "string" || !url.trim()) {
932
+ return refuseSceneCamera("SCENE_CAMERA_REPORT_INVALID", "expected a scene report URL");
933
+ }
934
+ try {
935
+ const response = await fetch(url);
936
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
937
+ if (!response.body) throw new Error("missing response body");
938
+ const reader = response.body.getReader();
939
+ let bytes = new Uint8Array(0);
940
+ let total = 0;
941
+ try {
942
+ for (; ; ) {
943
+ const { value, done } = await reader.read();
944
+ if (done) break;
945
+ const observed = total + value.byteLength;
946
+ checkSceneCameraReportSize(observed, refuseSceneCamera);
947
+ if (observed > bytes.length) {
948
+ const capacity = Math.min(SCENE_CAMERA_REPORT_MAX_BYTES, Math.max(observed, bytes.length * 2, 4096));
949
+ const grown = new Uint8Array(capacity);
950
+ grown.set(bytes.subarray(0, total));
951
+ bytes = grown;
952
+ }
953
+ bytes.set(value, total);
954
+ total = observed;
955
+ }
956
+ } catch (error) {
957
+ void reader.cancel().catch(() => {
958
+ });
959
+ throw error;
960
+ } finally {
961
+ reader.releaseLock();
962
+ }
963
+ return decodeSceneCameraReport(bytes.subarray(0, total), refuseSceneCamera);
964
+ } catch (error) {
965
+ if (error instanceof ComposedTakeError) throw error;
966
+ return refuseSceneCamera("SCENE_CAMERA_REPORT_INVALID", `could not read the scene report at ${url}`, error);
967
+ }
968
+ }
969
+ async function hashModelResponse(response) {
970
+ const subtle = globalThis.crypto?.subtle;
971
+ if (typeof subtle?.digest !== "function") {
972
+ return refuseSceneCamera(
973
+ "SCENE_CAMERA_MODEL_MISMATCH",
974
+ "could not compute SHA-256 for the exact model response bytes because Web Crypto subtle.digest is unavailable (browsers require a secure context)"
975
+ );
976
+ }
977
+ try {
978
+ const bytes = await response.clone().arrayBuffer();
979
+ const digest = await subtle.digest("SHA-256", bytes);
980
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
981
+ } catch (error) {
982
+ return refuseSceneCamera("SCENE_CAMERA_MODEL_MISMATCH", "could not compute SHA-256 for the exact model response bytes with Web Crypto", error);
983
+ }
984
+ }
985
+ function keyedPlaneGains(planes) {
986
+ if (!planes) return void 0;
987
+ const gains = /* @__PURE__ */ new Map();
988
+ for (const [id, { role, gain, baked }] of Object.entries(planes)) {
989
+ if (gain !== void 0 && !Number.isFinite(gain)) {
990
+ throw new ComposedTakeError("COMPOSED_INVALID_DISPLACEMENT", `plane ${JSON.stringify(id)} needs a finite gain`);
991
+ }
992
+ if (role === "figure" && (baked !== void 0 || gain !== void 0 && gain !== 0)) {
993
+ throw trackError(id, "must stay at focal gain 0 without a baked camera track");
994
+ }
995
+ gains.set(id, gain ?? (role === "backdrop" ? BACKDROP_GAIN : 0));
996
+ }
997
+ return gains;
998
+ }
999
+ async function mountComposedTake(root, options) {
1000
+ const initial = options.camera ?? "fixed";
1001
+ checkMode(initial);
1002
+ const { loop, sceneReportUrl } = options;
1003
+ if (loop !== true && (loop !== false || sceneReportUrl === void 0)) {
1004
+ throw new ComposedTakeError("COMPOSED_LOOP_REQUIRED", "declare the existing take as loop: true");
1005
+ }
1006
+ const override = options.maxDisplacement;
1007
+ const validLimit = (limit) => limit && Number.isFinite(limit.x) && limit.x >= 0 && Number.isFinite(limit.y) && limit.y >= 0;
1008
+ if (override !== void 0 && !validLimit(override)) {
1009
+ throw new ComposedTakeError("COMPOSED_INVALID_DISPLACEMENT", "x and y must both be finite nonnegative CSS pixel excursions");
1010
+ }
1011
+ const explicit = override && { ...override };
1012
+ const sweep = options.autoSweep;
1013
+ if (sweep !== void 0 && (!sweep || !Number.isFinite(sweep.periodSeconds) || sweep.periodSeconds <= 0 || !validLimit(sweep.maxDisplacement))) {
1014
+ throw new ComposedTakeError("COMPOSED_INVALID_DISPLACEMENT", "autoSweep needs a positive finite periodSeconds and finite nonnegative axis caps");
1015
+ }
1016
+ const sweepLimit = sweep ? { ...sweep.maxDisplacement } : NEUTRAL;
1017
+ const sweepPeriod = sweep?.periodSeconds;
1018
+ const transitionSeconds = (options.transitionMs === void 0 ? DEFAULT_TRANSITION_MS : options.transitionMs) / 1e3;
1019
+ if (!Number.isFinite(options.transitionMs ?? DEFAULT_TRANSITION_MS) || !(transitionSeconds > 0)) {
1020
+ throw new ComposedTakeError("COMPOSED_INVALID_DISPLACEMENT", "transitionMs must be positive and finite");
1021
+ }
1022
+ const report = sceneReportUrl === void 0 ? void 0 : await fetchSceneReport(sceneReportUrl);
1023
+ const digest = sceneReportUrl === void 0 ? null : sceneCameraModelDigest(report, refuseSceneCamera);
1024
+ if (digest === null && loop !== true) throw new ComposedTakeError("COMPOSED_LOOP_REQUIRED", "declare the existing take as loop: true");
1025
+ let sha256 = "";
1026
+ const assets = await loadModel({
1027
+ modelUrl: options.modelUrl,
1028
+ regions: "none",
1029
+ setsUrl: null,
1030
+ crossOrigin: "anonymous",
1031
+ ...digest === null ? {} : { fetch: async (input, init) => {
1032
+ const response = await fetch(input, init);
1033
+ if (response.ok) {
1034
+ sha256 = await hashModelResponse(response);
1035
+ if (sha256 !== digest) refuseSceneCamera("SCENE_CAMERA_MODEL_MISMATCH", "the scene camera SHA-256 does not match the consumed model");
1036
+ }
1037
+ return response;
1038
+ } }
1039
+ }).catch((error) => {
1040
+ if (error instanceof Error && /(?:problem\(s\): |; )(?:stage[.: ]|section "stage" is missing(?=; | — |$))/.test(error.message)) {
1041
+ if (digest !== null) refuseSceneCamera("SCENE_CAMERA_VIEW_INVALID", "the compiled model needs a valid stage", error);
1042
+ throw new ComposedTakeError("COMPOSED_STAGE_REQUIRED", "the compiled model needs a valid stage", error);
1043
+ }
1044
+ throw error;
1045
+ });
1046
+ const doc = root.ownerDocument;
1047
+ const surface = doc.createElement("div");
1048
+ let player;
1049
+ let audit;
1050
+ try {
1051
+ let cameraFor = function(animation, animationTime, loop2) {
1052
+ const view = bound?.sample(animation, { basis: "compiled", seconds: animationTime }) ?? null;
1053
+ if (view && view.loop !== loop2) {
1054
+ refuseSceneCamera("SCENE_CAMERA_CLIP_MISMATCH", `loop must match the authored camera track for ${JSON.stringify(animation)}`);
1055
+ }
1056
+ return view;
1057
+ }, planesFor = function(animation) {
1058
+ if (!namedInput) return void 0;
1059
+ let named = legacyPlanes.get(animation);
1060
+ if (!named) {
1061
+ named = namedPlanes(assets, options, animation);
1062
+ legacyPlanes.set(animation, named);
1063
+ }
1064
+ return named;
1065
+ }, syncTurn = function(next) {
1066
+ if (!dials.length) return;
1067
+ const weight = mode === "parallax" && next === mode ? handoff.weight : 0;
1068
+ const pointer = weight === 0 ? NEUTRAL : handoff.pointer;
1069
+ if (weight !== turnInput.weight || pointer.x !== turnInput.pointer.x || pointer.y !== turnInput.pointer.y) {
1070
+ turnInput = { weight, pointer };
1071
+ }
1072
+ }, createCoverageChecks = function() {
1073
+ const renderer2 = audit = new CanvasRenderer(doc.createElement("div"), assets.pageImages);
1074
+ renderer2.backend = backend;
1075
+ const auditBackdrop = backdropAlphaAudit(renderer2);
1076
+ return { renderer: renderer2, auditBackdrop, requireCoverage: backdropGuard(auditBackdrop, stage) };
1077
+ }, applyLegacyLayout = function() {
1078
+ const { native, width, height } = layout;
1079
+ renderer.viewport = native ? stage : { x: 0, y: -height, width, height };
1080
+ renderer.pixelRatio = native ? width / stage.width : 1;
1081
+ legacyLayoutPending = false;
1082
+ }, measure = function() {
1083
+ const box = surface.getBoundingClientRect();
1084
+ const cssWidth = box.width || stage.width;
1085
+ const cssHeight = box.height || stage.height;
1086
+ const dpr = window.devicePixelRatio;
1087
+ if (layout?.cssWidth === cssWidth && layout.cssHeight === cssHeight && layout.dpr === dpr) return;
1088
+ const width = Math.ceil(cssWidth * dpr);
1089
+ const height = Math.ceil(cssHeight * dpr);
1090
+ const pixelRatio = width / stage.width;
1091
+ const native = [stage.x, stage.y, stage.width, stage.height].every(Number.isInteger) && stage.width * pixelRatio === width && stage.height * pixelRatio === height;
1092
+ const excursion = explicit ?? cameraLimits(cssWidth, cssHeight);
1093
+ layout = { cssWidth, cssHeight, width, height, dpr, native, excursion };
1094
+ legacyLayoutPending = true;
1095
+ if (!bound) applyLegacyLayout();
1096
+ }, cameraExcursionFor = function(next) {
1097
+ const { excursion } = layout;
1098
+ return next === "parallax" && dials.length ? { x: excursion.x, y: 0 } : excursion;
1099
+ }, prepareFrame = function(frame, plates, next, excursion, named) {
1100
+ const worldX = stage.width / layout.cssWidth;
1101
+ const worldY = stage.height / layout.cssHeight;
1102
+ const centered = /* @__PURE__ */ new Map();
1103
+ const shifts = planeOffsets(cssTarget(camera, excursion), next);
1104
+ let frameOffsets = shifts;
1105
+ let namedShifts;
1106
+ if (named) {
1107
+ const liveByPlane = new Map(plates.map((plate) => [plate.plate.id, plate]));
1108
+ const changingMode = mode !== next;
1109
+ const weight = changingMode ? 0 : handoff.weight;
1110
+ const pointer = cssTarget(changingMode ? NEUTRAL : next === "pan" ? camera : handoff.pointer, excursion);
1111
+ const phase = sweepPeriod === void 0 ? 0 : Math.sin(2 * Math.PI * (poser.time % sweepPeriod / sweepPeriod));
1112
+ const automatic = { x: sweepLimit.x * phase, y: sweepLimit.y * phase };
1113
+ const liveOffsets = /* @__PURE__ */ new Map();
1114
+ namedShifts = /* @__PURE__ */ new Map();
1115
+ for (const [id, gain] of named.gains) {
1116
+ const state = liveByPlane.get(id);
1117
+ const live = state?.live ?? NEUTRAL;
1118
+ const translated = planeShift(pointer, next === "pan" ? 1 : gain);
1119
+ const baked = state?.plate.baked;
1120
+ let correction = NEUTRAL;
1121
+ let displayed = { x: live.x / worldX, y: live.y / worldY };
1122
+ if (next === "pan") {
1123
+ correction = translated;
1124
+ displayed = { x: displayed.x + correction.x, y: displayed.y + correction.y };
1125
+ } else if (next === "parallax") {
1126
+ const auto = baked ? displayed : planeShift(automatic, gain);
1127
+ displayed = {
1128
+ x: (1 - weight) * auto.x + weight * translated.x,
1129
+ y: (1 - weight) * auto.y + weight * translated.y
1130
+ };
1131
+ correction = baked ? { x: weight * (translated.x - auto.x), y: weight * (translated.y - auto.y) } : displayed;
1132
+ if (baked && weight === 1 && pointer.x === 0 && pointer.y === 0) centered.set(state.plate.setup.slot, state.plate.setup);
1133
+ }
1134
+ liveOffsets.set(id, displayed);
1135
+ namedShifts.set(id, correction);
1136
+ }
1137
+ frameOffsets = Object.fromEntries(liveOffsets);
1138
+ }
1139
+ const shiftFor = (slot) => {
1140
+ const { x, y } = namedShifts?.get(planes.get(slot.slot)) ?? shifts[planes.get(slot.slot)];
1141
+ return { x: x * stage.width / layout.cssWidth, y: y * stage.height / layout.cssHeight };
1142
+ };
1143
+ let positioned;
1144
+ if (!layout.native) {
1145
+ positioned = transformFrame(frame, shiftFor, {
1146
+ origin,
1147
+ scale: { x: layout.width / stage.width, y: layout.height / stage.height },
1148
+ centered,
1149
+ clipInStockSpace: true
1150
+ });
1151
+ } else if (!centered.size && (namedShifts ? [...namedShifts.values()] : Object.values(shifts)).every((shift) => shift.x === 0 && shift.y === 0)) {
1152
+ positioned = frame;
1153
+ if (frame.order.some((slot) => slot.clip)) {
1154
+ positioned = transformFrame(frame, () => NEUTRAL, { clipInStockSpace: true });
1155
+ const generation = Object.getOwnPropertyDescriptor(frame, "generation");
1156
+ if (generation) Object.defineProperty(positioned, "generation", generation);
1157
+ }
1158
+ } else {
1159
+ positioned = transformFrame(frame, shiftFor, { centered, clipInStockSpace: true });
1160
+ }
1161
+ return { frame: positioned, offsets: frameOffsets };
1162
+ }, checkBackdropAlpha = function(frame, { figureSlots, backdrop }, next, coverage, auditBackdrop) {
1163
+ const isFigure = (slot) => figureSlots.has(slot.slot);
1164
+ const figures = frame.order.filter(isFigure);
1165
+ const firstFigure = figures.length === figureSlots.size ? figures[0] : poser.slotIdentity().slots.find(isFigure);
1166
+ const order = frame.order.filter((slot) => slot.z < (firstFigure?.z ?? Infinity));
1167
+ coverage.backend = renderer.backend;
1168
+ coverage.clipping = renderer.clipping;
1169
+ coverage.meshSourceRect = renderer.meshSourceRect;
1170
+ let nonOpaque;
1171
+ try {
1172
+ nonOpaque = auditBackdrop({ order }, renderer.viewport, renderer.pixelRatio);
1173
+ } catch (error) {
1174
+ throw plateCoverageError(backdrop, next, `backdrop alpha cannot be read (${String(error)})`);
1175
+ }
1176
+ if (nonOpaque) {
1177
+ throw plateCoverageError(backdrop, next, `${nonOpaque} stage pixels have alpha below 255 at ${layout.width} × ${layout.height} backing px`);
1178
+ }
1179
+ }, currentFrame = function(next, named, keyed) {
1180
+ syncTurn(next);
1181
+ if (posedTurnInput !== turnInput) poser.repose();
1182
+ const frame = poser.posedFrame(null);
1183
+ return { frame, backdrop: checkFrame(frame, planes, named?.backdrop, keyed) };
1184
+ }, requireKeyedCoverage = function(view, next, excursion) {
1185
+ if (!driftEvidence || next === "fixed") return;
1186
+ const sweep2 = keyedGains && next === "parallax" ? sweepLimit : NEUTRAL;
1187
+ if (excursion.x === 0 && excursion.y === 0 && sweep2.x === 0 && sweep2.y === 0) return;
1188
+ const gain = next === "pan" ? 1 : keyedGains?.get(backdropPlane) ?? BACKDROP_GAIN;
1189
+ const sampledPlane = planes.get(driftEvidence.backdrop);
1190
+ if (gain === 0 && sampledPlane !== void 0 && keyedGains?.get(sampledPlane) === 0) return;
1191
+ const context = `take ${JSON.stringify(view.animation)}, sampled backdrop slot ${JSON.stringify(driftEvidence.backdrop)}, pointer excursion ±[${excursion.x}, ${excursion.y}] CSS px, sweep endpoint [${sweep2.x}, ${sweep2.y}] CSS px, backdrop gain ${gain}`;
1192
+ if (sampledPlane !== backdropPlane) {
1193
+ throw plateCoverageError(backdropPlane, next, `${context} needs that exact slot bound to the backdrop plane`);
1194
+ }
1195
+ const toOutput = ({ x, y }) => ({
1196
+ x: x === 0 ? 0 : x * (view.output.width / layout.cssWidth),
1197
+ y: y === 0 ? 0 : y * (view.output.height / layout.cssHeight)
1198
+ });
1199
+ const backingPixel = { x: view.output.width / layout.width, y: view.output.height / layout.height };
1200
+ const failure = driftEvidence.failure(
1201
+ view.animation,
1202
+ toOutput(planeShift(excursion, gain)),
1203
+ toOutput(planeShift(sweep2, gain)),
1204
+ backingPixel
1205
+ );
1206
+ if (failure) throw plateCoverageError(backdropPlane, next, `${context}; ${failure}`);
1207
+ }, drawKeyedFrame = function(frame, next, excursion, view) {
1208
+ let displayed = planeOffsets(cssTarget(camera, excursion), next);
1209
+ if (keyedGains) {
1210
+ const changingMode = mode !== next;
1211
+ const weight = changingMode ? 0 : handoff.weight;
1212
+ const pointer = cssTarget(changingMode ? NEUTRAL : next === "pan" ? camera : handoff.pointer, excursion);
1213
+ const phase = sweepPeriod === void 0 ? 0 : Math.sin(2 * Math.PI * (poser.time % sweepPeriod / sweepPeriod));
1214
+ const sweep2 = { x: sweepLimit.x * phase, y: sweepLimit.y * phase };
1215
+ const input = next === "pan" ? pointer : {
1216
+ x: (1 - weight) * sweep2.x + weight * pointer.x,
1217
+ y: (1 - weight) * sweep2.y + weight * pointer.y
1218
+ };
1219
+ displayed = Object.fromEntries([...keyedGains].map(([id, gain]) => [
1220
+ id,
1221
+ next === "fixed" ? NEUTRAL : planeShift(input, next === "pan" ? 1 : gain)
1222
+ ]));
1223
+ }
1224
+ const worldX = view.output.width / layout.cssWidth / view.zoom;
1225
+ const worldY = view.output.height / layout.cssHeight / view.zoom;
1226
+ drawSceneCamera(renderer, frame, view, layout, (slot) => {
1227
+ const { x, y } = displayed[planes.get(slot.slot)];
1228
+ return { x: x === 0 ? 0 : x * worldX, y: y === 0 ? 0 : y * worldY };
1229
+ });
1230
+ return displayed;
1231
+ }, drawMode = function(frame, backdrop, next, switching, view, named) {
1232
+ const excursion = cameraExcursionFor(next);
1233
+ let displayed;
1234
+ if (view) {
1235
+ keyedGains ??= keyedPlaneGains(options.planes);
1236
+ if (keyedAdmission?.animation !== view.animation || keyedAdmission.layout !== layout || keyedAdmission.mode !== next) {
1237
+ requireKeyedCoverage(view, next, excursion);
1238
+ keyedAdmission = { animation: view.animation, layout, mode: next };
1239
+ }
1240
+ displayed = drawKeyedFrame(frame, next, excursion, view);
1241
+ } else {
1242
+ keyedAdmission = void 0;
1243
+ if (legacyLayoutPending) applyLegacyLayout();
1244
+ const checks = coverageChecks ??= createCoverageChecks();
1245
+ const plates = named ? livePlates(frame, named, next) : [];
1246
+ if (named) checkPlateEnvelopes(stage, layout, next, excursion, plates, named.gains, sweepLimit);
1247
+ else checks.requireCoverage(backdrop, layout, next);
1248
+ const prepared = prepareFrame(frame, plates, next, excursion, named);
1249
+ if (named) checkBackdropAlpha(prepared.frame, named, next, checks.renderer, checks.auditBackdrop);
1250
+ renderer.render(prepared.frame);
1251
+ displayed = prepared.offsets;
1252
+ }
1253
+ if (namedInput && mode !== next) {
1254
+ camera = NEUTRAL;
1255
+ handoff.reset();
1256
+ if (next === "parallax" && hover !== void 0) handoff.enter();
1257
+ }
1258
+ mode = next;
1259
+ if (!namedInput && switching && mode === "fixed") camera = target = NEUTRAL;
1260
+ offsets = displayed;
1261
+ if (namedInput && mode === "parallax") handoff.painted();
1262
+ canvas.style.visibility = "";
1263
+ Object.assign(canvas.style, { width: "100%", height: "100%", transform: "none", pointerEvents: "auto" });
1264
+ }, select = function(next, switching, allowFallback) {
1265
+ const entry = bound && poser.entry();
1266
+ const view = entry?.animation ? cameraFor(entry.animation, entry.animationTime, entry.loop) : null;
1267
+ drawingKeyed = view !== null;
1268
+ const named = view ? void 0 : planesFor(entry?.animation ?? initialAnimation);
1269
+ const { frame, backdrop } = currentFrame(next, named, drawingKeyed);
1270
+ try {
1271
+ drawMode(frame, backdrop, next, switching, view, named);
1272
+ } catch (error) {
1273
+ if (!(error instanceof ComposedTakeError) || error.code !== "COMPOSED_BACKDROP_COVERAGE" || next === "fixed" || !named && !view && !allowFallback) throw error;
1274
+ try {
1275
+ const fixed = turnInput.weight === 0 ? { frame, backdrop } : currentFrame("fixed", named, drawingKeyed);
1276
+ drawMode(fixed.frame, fixed.backdrop, "fixed", true, view, named);
1277
+ } catch (fixedError) {
1278
+ canvas.style.visibility = "hidden";
1279
+ throw fixedError;
1280
+ }
1281
+ refusal = error;
1282
+ if (!allowFallback) throw error;
1283
+ }
1284
+ }, renderCurrent = function() {
1285
+ try {
1286
+ select(mode, false, true);
1287
+ } catch (error) {
1288
+ if (error instanceof ComposedTakeError) refusal = error;
1289
+ if (namedInput || drawingKeyed) canvas.style.visibility = "hidden";
1290
+ stopped = true;
1291
+ if (frameId !== void 0) window.cancelAnimationFrame(frameId);
1292
+ throw error;
1293
+ }
1294
+ }, setCamera = function(next) {
1295
+ if (disposed || stopped) return;
1296
+ try {
1297
+ checkMode(next);
1298
+ measure();
1299
+ select(next, true, false);
1300
+ refusal = null;
1301
+ } catch (error) {
1302
+ if (error instanceof ComposedTakeError) refusal = error;
1303
+ if ((namedInput || drawingKeyed) && next === "fixed") canvas.style.visibility = "hidden";
1304
+ throw error;
1305
+ }
1306
+ }, advanceCamera = function(elapsed) {
1307
+ if (!(elapsed > 0)) return;
1308
+ if (namedInput && mode === "parallax") handoff.advance(elapsed, target);
1309
+ else camera = easeCamera(camera, target, elapsed);
1310
+ }, syncCamera = function(now) {
1311
+ const next = Math.max(lastCameraAt, now);
1312
+ advanceCamera((next - lastCameraAt) / 1e3);
1313
+ lastCameraAt = next;
1314
+ }, advance = function(rigElapsed, cameraElapsed = rigElapsed) {
1315
+ if (disposed || stopped) return;
1316
+ advanceCamera(cameraElapsed);
1317
+ syncTurn(mode);
1318
+ poser.advance(rigElapsed);
1319
+ }, render = function() {
1320
+ if (disposed || stopped) return;
1321
+ measure();
1322
+ renderCurrent();
1323
+ }, leave = function() {
1324
+ if (hover === void 0 || stopped) return;
1325
+ if (autoStart) syncCamera(window.performance.now());
1326
+ hover = void 0;
1327
+ target = NEUTRAL;
1328
+ if (mode === "parallax") handoff.leave();
1329
+ };
1330
+ const bound = digest === null ? null : bindSceneCamera(report, { sha256, stage: assets.stage, animations: assets.animations });
1331
+ const driftEvidence = bound && sceneCameraDriftEvidence(report, refuseSceneCamera);
1332
+ const initialView = cameraFor(options.animation, 0, loop);
1333
+ if (!initialView && loop !== true) throw new ComposedTakeError("COMPOSED_LOOP_REQUIRED", "declare the existing take as loop: true");
1334
+ const stage = requireStage(assets.stage);
1335
+ const take = assets.animations.find((animation) => animation.name === options.animation);
1336
+ if (!take || !initialView && (!Number.isFinite(take.duration) || take.duration <= 0)) {
1337
+ throw new ComposedTakeError("COMPOSED_LOOP_REQUIRED", `no positive-duration animation named ${JSON.stringify(options.animation)}`);
1338
+ }
1339
+ const initialAnimation = take.name;
1340
+ const planes = bindSlots(assets, options);
1341
+ const namedInput = options.planes !== void 0;
1342
+ const backdropPlane = Object.entries(options.planes ?? {}).find(([, plane]) => plane.role === "backdrop")?.[0] ?? "background";
1343
+ const legacyPlanes = /* @__PURE__ */ new Map();
1344
+ const initialNamed = initialView ? void 0 : planesFor(initialAnimation);
1345
+ let keyedGains = initialView ? keyedPlaneGains(options.planes) : void 0;
1346
+ const dials = namedInput && options.pointerTurn !== false ? discoverTurnDials(assets.document.parsed, assets.animations) : [];
1347
+ const handoff = createCameraHandoff(transitionSeconds);
1348
+ let mode = initial;
1349
+ let turnInput = { weight: 0, pointer: NEUTRAL };
1350
+ let posedTurnInput = turnInput;
1351
+ let turnValues = [];
1352
+ const adjustTurn = (bones) => {
1353
+ const { weight, pointer } = turnInput;
1354
+ turnValues = dials.map((dial) => {
1355
+ const { axis, bone, channel, min, max } = dial;
1356
+ const locals = bones.bone(bone);
1357
+ const baked = locals[channel];
1358
+ const n = turnCoordinate(axis, pointer) / TURN_FULL_RANGE_AT_STAGE_EDGE;
1359
+ const limited = normalizedDial(n, dial);
1360
+ const value = weight === 0 ? baked : (1 - weight) * baked + weight * limited;
1361
+ if (value !== baked) locals[channel] = value;
1362
+ return { axis, min, max, baked, pointer: limited, value };
1363
+ });
1364
+ posedTurnInput = turnInput;
1365
+ };
1366
+ Object.assign(surface.style, {
1367
+ position: "relative",
1368
+ overflow: "hidden",
1369
+ width: "100%",
1370
+ height: "100%",
1371
+ aspectRatio: `${stage.width} / ${stage.height}`
1372
+ });
1373
+ root.appendChild(surface);
1374
+ const poser = player = new RigPlayer(surface, assets, { mode: "canvas", adjust: dials.length ? adjustTurn : null });
1375
+ const renderer = poser.renderer;
1376
+ const backend = options.backend ?? "webgl";
1377
+ renderer.backend = backend;
1378
+ let coverageChecks;
1379
+ if (!initialView) coverageChecks = createCoverageChecks();
1380
+ const canvas = renderer.canvas;
1381
+ poser.play(initialAnimation, { loop });
1382
+ let offsets = planeOffsets(NEUTRAL, "fixed");
1383
+ let camera = NEUTRAL;
1384
+ let target = NEUTRAL;
1385
+ let hover;
1386
+ let layout;
1387
+ let keyedAdmission;
1388
+ let legacyLayoutPending = true;
1389
+ let drawingKeyed = initialView !== null;
1390
+ let refusal = null;
1391
+ let stopped = false;
1392
+ let disposed = false;
1393
+ let frameId;
1394
+ const window = doc.defaultView;
1395
+ const origin = { x: stage.x, y: stageTop(stage) };
1396
+ const autoStart = options.autoStart !== false;
1397
+ let lastCameraAt = window.performance.now();
1398
+ const cssTarget = (point, excursion) => ({ x: point.x * excursion.x, y: point.y * excursion.y });
1399
+ measure();
1400
+ select(initial, true, initialNamed !== void 0 || initialView !== null);
1401
+ const boundaryEvent = (event) => event.target === root || event.bubbles;
1402
+ const aim = (event) => {
1403
+ if (!event.isPrimary || stopped) return;
1404
+ if (namedInput) {
1405
+ if (event.pointerType === "touch" || event.type === "pointerenter" && !boundaryEvent(event) || hover !== void 0 && hover !== event.pointerId) return;
1406
+ if (event.pointerType === "pen" && event.buttons !== 0) {
1407
+ leave();
1408
+ return;
1409
+ }
1410
+ }
1411
+ if (!Number.isFinite(event.clientX) || !Number.isFinite(event.clientY)) return;
1412
+ const box = surface.getBoundingClientRect();
1413
+ if (!(box.width > 0 && box.height > 0)) return;
1414
+ if (namedInput) {
1415
+ if (autoStart) syncCamera(window.performance.now());
1416
+ if (hover === void 0 && mode === "parallax") handoff.enter();
1417
+ hover = event.pointerId;
1418
+ }
1419
+ target = pointerTarget(event.clientX, event.clientY, box);
1420
+ };
1421
+ const recenter = (event) => {
1422
+ if (!event.isPrimary) return;
1423
+ if (!namedInput) {
1424
+ target = NEUTRAL;
1425
+ return;
1426
+ }
1427
+ if (event.pointerType !== "touch" && hover === event.pointerId && (event.type !== "pointerleave" || boundaryEvent(event))) leave();
1428
+ };
1429
+ const contact = (event) => {
1430
+ if (event.pointerType === "pen" && event.isPrimary && hover === event.pointerId) leave();
1431
+ };
1432
+ root.addEventListener("pointermove", aim, true);
1433
+ root.addEventListener("pointerleave", recenter, true);
1434
+ root.addEventListener("pointercancel", recenter, true);
1435
+ if (namedInput) {
1436
+ root.addEventListener("pointerenter", aim, true);
1437
+ root.addEventListener("pointerdown", contact, true);
1438
+ root.addEventListener("lostpointercapture", recenter, true);
1439
+ window.addEventListener("blur", leave);
1440
+ }
1441
+ const observer = new ResizeObserver(() => {
1442
+ try {
1443
+ render();
1444
+ } catch (error) {
1445
+ if (!(error instanceof ComposedTakeError)) throw error;
1446
+ }
1447
+ });
1448
+ observer.observe(surface);
1449
+ if (autoStart) {
1450
+ let last = window.performance.now();
1451
+ lastCameraAt = last;
1452
+ frameId = window.requestAnimationFrame(function tick(now) {
1453
+ if (disposed || stopped) return;
1454
+ const elapsed = Math.max(0, (now - last) / 1e3);
1455
+ last = now;
1456
+ if (namedInput) {
1457
+ syncCamera(now);
1458
+ advance(Math.min(elapsed, 1 / 15), 0);
1459
+ } else {
1460
+ advance(Math.min(elapsed, 1 / 15), elapsed);
1461
+ }
1462
+ if (namedInput || layout.dpr !== window.devicePixelRatio) measure();
1463
+ try {
1464
+ renderCurrent();
1465
+ } catch (error) {
1466
+ if (!(error instanceof ComposedTakeError)) throw error;
1467
+ }
1468
+ if (!stopped) frameId = window.requestAnimationFrame(tick);
1469
+ });
1470
+ }
1471
+ return {
1472
+ canvas,
1473
+ player: poser,
1474
+ get mode() {
1475
+ return mode;
1476
+ },
1477
+ get offsets() {
1478
+ return offsets;
1479
+ },
1480
+ get cameraExcursion() {
1481
+ return cameraExcursionFor(mode);
1482
+ },
1483
+ cameraExcursionFor,
1484
+ get cameraTarget() {
1485
+ return cssTarget(target, cameraExcursionFor(mode));
1486
+ },
1487
+ get turnReadouts() {
1488
+ return turnValues.map((reading) => {
1489
+ const n = turnCoordinate(reading.axis, target);
1490
+ const clamped = mode === "parallax" && hover !== void 0 && (Math.abs(n) >= TURN_FULL_RANGE_AT_STAGE_EDGE || n < 0 && reading.min === 0 || n > 0 && reading.max === 0);
1491
+ return { ...reading, clamped };
1492
+ });
1493
+ },
1494
+ get refusal() {
1495
+ return refusal;
1496
+ },
1497
+ setCamera,
1498
+ advance,
1499
+ render,
1500
+ dispose() {
1501
+ if (disposed) return;
1502
+ disposed = true;
1503
+ if (frameId !== void 0) window.cancelAnimationFrame(frameId);
1504
+ observer.disconnect();
1505
+ root.removeEventListener("pointermove", aim, true);
1506
+ root.removeEventListener("pointerleave", recenter, true);
1507
+ root.removeEventListener("pointercancel", recenter, true);
1508
+ if (namedInput) {
1509
+ root.removeEventListener("pointerenter", aim, true);
1510
+ root.removeEventListener("pointerdown", contact, true);
1511
+ root.removeEventListener("lostpointercapture", recenter, true);
1512
+ window.removeEventListener("blur", leave);
1513
+ }
1514
+ poser.dispose();
1515
+ audit?.dispose();
1516
+ surface.remove();
1517
+ assets.dispose();
1518
+ }
1519
+ };
1520
+ } catch (error) {
1521
+ player?.dispose();
1522
+ audit?.dispose();
1523
+ surface.remove();
1524
+ assets.dispose();
1525
+ throw error;
1526
+ }
1527
+ }
1528
+ export {
1529
+ ComposedTakeError,
1530
+ SCENE_CAMERA_REPORT_MAX_BYTES,
1531
+ bindSceneCamera,
1532
+ mountComposedTake,
1533
+ renderSceneCameraFrame,
1534
+ sceneCameraProjection
1535
+ };
1536
+ //# sourceMappingURL=composed-take.js.map