motlab.js 0.1.0 → 0.1.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/core/scene.js CHANGED
@@ -1,678 +1,678 @@
1
- import { at } from './math.js'
2
- import { path as newPath } from './path.js'
3
- import { COMMON, KIND_PROPS, STRIDE, EFFECTS, TRANSITIONS, isNode } from './nodes.js'
4
- import { Timeline, sealTimeline, snap } from './timeline.js'
5
- import { markers as makeMarkers } from './markers.js'
6
- import { guarded, context } from './guard.js'
7
-
8
- /** @typedef {import('./nodes.js').Node} Node */
9
- /** @typedef {import('./nodes.js').Gradient} Gradient */
10
- /** @typedef {import('./nodes.js').UnitStyle} UnitStyle */
11
- /** @typedef {import('./nodes.js').UnitFn} UnitFn */
12
- /** @typedef {import('./path.js').Path} Path */
13
- /** @typedef {import('./markers.js').Marker} Marker */
14
- /** @typedef {[number, number, number, number, number, number]} Matrix In setTransform(a, b, c, d, e, f) order. */
15
-
16
- /**
17
- * One thing to draw, with its transform already multiplied down from the root. A `layer` holds items that are
18
- * composited together first, for blend modes, mattes, isolation and motion blur. `blend` appears only when set. The
19
- * exact shape stays experimental until the first stable release.
20
- * @typedef {{ id: string, type: 'shape', matrix: Matrix, opacity: number, path: Path, fill?: string | Gradient,
21
- * stroke?: string | Gradient, strokeWidth?: number, lineCap?: string, lineJoin?: string, dash?: number[],
22
- * dashOffset?: number, blend?: string }
23
- * | { id: string, type: 'text', matrix: Matrix, opacity: number, text: string, font?: string, align?: string,
24
- * baseline?: string, fill?: string | Gradient, stroke?: string | Gradient, strokeWidth?: number, lineHeight?: number,
25
- * width?: number, units?: string[], offsets?: Required<Omit<UnitStyle, 'fill'>>[] & { fill?: string }[], blend?: string }
26
- * | { id: string, type: 'image', matrix: Matrix, opacity: number, src: string, w?: number, h?: number,
27
- * crop?: readonly [number, number, number, number], smooth?: false, blend?: string }
28
- * | { id: string, type: 'video', matrix: Matrix, opacity: number, src: string, time: number, w?: number, h?: number,
29
- * crop?: readonly [number, number, number, number], smooth?: false, blend?: string }
30
- * | { id: string, type: 'instances', matrix: Matrix, opacity: number, base: DisplayItem, data: Float32Array | Float64Array,
31
- * colors: string[], blend?: string }
32
- * | { id: string, type: 'draw', matrix: Matrix, opacity: number, t: number, draw: (ctx: any, t: number) => void,
33
- * blend?: string }
34
- * | { id: string, type: 'layer', opacity: number, blend?: string, items?: DisplayItem[], samples?: DisplayItem[][],
35
- * matte?: { mode: string, items: DisplayItem[] }, effects?: ResolvedEffect[], t?: number }
36
- * | { id: string, type: 'mesh', matrix: Matrix, opacity: number, src: string, points: ArrayLike<number>,
37
- * uvs: ArrayLike<number>, triangles: ArrayLike<number>, smooth?: false, blend?: string }
38
- * | { id: string, type: 'transition', opacity: number, progress: number, effect: string | { glsl: string },
39
- * params: Record<string, number | number[]>, from: DisplayItem[], to: DisplayItem[], box?: [number, number, number, number],
40
- * blend?: string }
41
- * } DisplayItem
42
- */
43
-
44
- /** An effect with every parameter filled in and read at the layer's time. @typedef {{ type: string } & Record<string, any>} ResolvedEffect */
45
-
46
- /**
47
- * @typedef {object} Assets
48
- * @property {{ family: string, src: string, weight?: string, style?: string }[]} [fonts]
49
- * @property {Record<string, string>} [images] Image URLs by the key an image node's `src` uses.
50
- * @property {Record<string, string>} [videos] MP4 URLs by the key a video node's `src` uses.
51
- * @property {Record<string, string>} [audio] Sound files by name, for players and exporters to play or mix in.
52
- */
53
-
54
- /**
55
- * @typedef {object} SceneSpec
56
- * @property {number} duration Seconds.
57
- * @property {[number, number]} size Logical width and height in px.
58
- * @property {Node} root
59
- * @property {string} [background] A CSS colour drawn under everything.
60
- * @property {Assets} [assets] Loaded by a renderer before the first frame.
61
- * @property {Marker[]} [markers]
62
- */
63
-
64
- /**
65
- * @typedef {object} Scene
66
- * @property {number} duration
67
- * @property {Readonly<[number, number]>} size
68
- * @property {Readonly<Assets>} assets
69
- * @property {ReturnType<typeof makeMarkers>} markers The scene's markers plus every timeline label.
70
- * @property {(fps: number) => number} frameCount
71
- * @property {(frame: number, fps: number) => number} frameTime
72
- * @property {(t: number, options?: { overrides?: Record<string, unknown> }) => DisplayItem[]} evaluate
73
- */
74
-
75
- /** @typedef {Map<string, Map<string, unknown>>} Overrides */
76
-
77
- /**
78
- * What one evaluation carries down the tree.
79
- * @typedef {object} State
80
- * @property {DisplayItem[]} out
81
- * @property {Overrides | null} overrides
82
- * @property {(font: string | undefined, id: string) => void} checkFont
83
- */
84
-
85
- /** @type {Matrix} */
86
- const IDENTITY = [1, 0, 0, 1, 0, 0]
87
- const DEG = Math.PI / 180
88
- const TAU = Math.PI * 2
89
- const BLENDS = [
90
- 'normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light',
91
- 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity', 'add',
92
- ]
93
- const SPLITS = ['grapheme', 'word', 'line']
94
- // Families every machine has some font for; anything else must be loaded from the scene's assets.
95
- const GENERIC = new Set([
96
- 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace',
97
- 'ui-rounded', 'emoji', 'math', 'fangsong',
98
- ])
99
- const FONT_SIZE = /(?:^|\s)(?:\d*\.?\d+(?:px|pt|pc|in|cm|mm|q|em|rem|ex|ch|%|vw|vh|vmin|vmax)|(?:xx?-|xxx-)?(?:small|large)|medium|larger|smaller)(?:\s*\/\s*\S+)?\s+(.+)$/i
100
-
101
- /**
102
- * Reads a prop at local time t, with an override taking the place of the node's own value.
103
- * @param {Readonly<Record<string, any>>} props
104
- * @param {Map<string, unknown> | undefined} override
105
- * @param {string} name
106
- * @param {number} t
107
- */
108
- function read(props, override, name, t) {
109
- const value = override !== undefined && override.has(name) ? override.get(name) : props[name]
110
- return value === undefined ? undefined : at(value, t)
111
- }
112
-
113
- /**
114
- * @param {Matrix} p
115
- * @param {Readonly<Record<string, any>>} props
116
- * @param {Map<string, unknown> | undefined} o
117
- * @param {number} t
118
- * @returns {Matrix}
119
- */
120
- function transform(p, props, o, t) {
121
- const x = read(props, o, 'x', t) ?? 0
122
- const y = read(props, o, 'y', t) ?? 0
123
- const rotation = read(props, o, 'rotation', t) ?? 0
124
- const scale = read(props, o, 'scale', t) ?? 1
125
- const skew = read(props, o, 'skew', t) ?? 0
126
- const anchor = read(props, o, 'anchor', t)
127
- if (x === 0 && y === 0 && rotation === 0 && scale === 1 && skew === 0 && anchor === undefined) return p
128
- const cos = rotation === 0 ? 1 : Math.cos(rotation * DEG)
129
- const sin = rotation === 0 ? 0 : Math.sin(rotation * DEG)
130
- const sx = typeof scale === 'number' ? scale : scale[0]
131
- const sy = typeof scale === 'number' ? scale : scale[1]
132
- // Rotation times skewX times scale: the second column picks up tan(skew) of the first.
133
- const k = skew === 0 ? 0 : Math.tan(skew * DEG)
134
- const a = cos * sx
135
- const b = sin * sx
136
- const c = (cos * k - sin) * sy
137
- const d = (sin * k + cos) * sy
138
- const ax = anchor ? anchor[0] : 0
139
- const ay = anchor ? anchor[1] : 0
140
- const e = x - (a * ax + c * ay)
141
- const f = y - (b * ax + d * ay)
142
- return [
143
- p[0] * a + p[2] * b,
144
- p[1] * a + p[3] * b,
145
- p[0] * c + p[2] * d,
146
- p[1] * c + p[3] * d,
147
- p[0] * e + p[2] * f + p[4],
148
- p[1] * e + p[3] * f + p[5],
149
- ]
150
- }
151
-
152
- // Rects and ellipses keep their last Path while their size stays the same, so a renderer can cache what it built.
153
- /** @type {WeakMap<Node, { key: string, path: Path }>} */
154
- const shapeCache = new WeakMap()
155
-
156
- /** @param {Node} node @param {string} key @param {() => Path} make */
157
- function cachedPath(node, key, make) {
158
- const hit = shapeCache.get(node)
159
- if (hit && hit.key === key) return hit.path
160
- const path = make()
161
- shapeCache.set(node, { key, path })
162
- return path
163
- }
164
-
165
- /** @type {Record<string, Intl.Segmenter>} */
166
- const segmenters = {}
167
- /** @type {WeakMap<Node, { text: string, split: string, units: string[] }>} */
168
- const unitCache = new WeakMap()
169
-
170
- /**
171
- * Cuts text into units that together give back the whole text. 'line' keeps each newline as its own unit.
172
- * @param {Node} node
173
- * @param {string} text
174
- * @param {string} split
175
- */
176
- function unitsOf(node, text, split) {
177
- const hit = unitCache.get(node)
178
- if (hit && hit.text === text && hit.split === split) return hit.units
179
- let units
180
- if (split === 'line') units = text.split(/(\n)/).filter(u => u !== '')
181
- else {
182
- const granularity = /** @type {'grapheme' | 'word'} */ (split)
183
- segmenters[granularity] ??= new Intl.Segmenter(undefined, { granularity })
184
- units = Array.from(segmenters[granularity].segment(text), s => s.segment)
185
- }
186
- unitCache.set(node, { text, split, units })
187
- return units
188
- }
189
-
190
- /**
191
- * Combines the styles of every perUnit function: positions and rotation add up, scale and opacity multiply, and the
192
- * last fill wins.
193
- * @param {UnitFn[]} fns
194
- * @param {number} i
195
- * @param {number} n
196
- * @param {number} t
197
- * @param {string} unit
198
- * @param {readonly string[]} units
199
- */
200
- function unitStyle(fns, i, n, t, unit, units) {
201
- let x = 0
202
- let y = 0
203
- let rotation = 0
204
- let scale = 1
205
- let opacity = 1
206
- /** @type {string | undefined} */
207
- let fill
208
- for (const fn of fns) {
209
- const s = fn(i, n, t, unit, units)
210
- if (!s) continue
211
- x += s.x ?? 0
212
- y += s.y ?? 0
213
- rotation += s.rotation ?? 0
214
- scale *= s.scale ?? 1
215
- opacity *= s.opacity ?? 1
216
- if (s.fill !== undefined) fill = s.fill
217
- }
218
- return { x, y, rotation, scale, opacity, fill }
219
- }
220
-
221
- /**
222
- * Collects ids and timeline labels from the parts of the tree that do not depend on time, and seals timelines.
223
- * @param {Node} node
224
- * @param {string} scope Prefix for ids inside component instances.
225
- * @param {Map<string, string>} ids Full id to node kind.
226
- * @param {Marker[]} labels
227
- * @param {number} offset Scene time where this subtree's time 0 falls.
228
- * @param {number} rate How fast this subtree's time runs against scene time.
229
- */
230
- function index(node, scope, ids, labels, offset, rate) {
231
- const id = node.props.id
232
- const full = id === undefined ? null : scope + id
233
- if (full !== null) {
234
- if (ids.has(full)) throw new Error(`scene: id "${full}" is used twice`)
235
- ids.set(full, node.kind)
236
- }
237
- if (node instanceof Timeline) {
238
- sealTimeline(node)
239
- for (const label of node.labels) labels.push({ at: snap(offset + label.at / rate), name: label.name, kind: 'label' })
240
- for (const item of node.items) index(item.node, scope, ids, labels, offset + item.at / rate, rate * item.speed)
241
- return
242
- }
243
- const inner = node.kind === 'instance' ? `${full}/` : scope
244
- if (node.props.matte?.node) index(node.props.matte.node, inner, ids, labels, offset, rate)
245
- if (Array.isArray(node.children)) for (const child of node.children) index(child, inner, ids, labels, offset, rate)
246
- }
247
-
248
- /**
249
- * @param {Record<string, unknown>} overrides
250
- * @param {Map<string, string>} ids
251
- * @returns {Overrides}
252
- */
253
- function parseOverrides(overrides, ids) {
254
- /** @type {Overrides} */
255
- const parsed = new Map()
256
- for (const [key, value] of Object.entries(overrides)) {
257
- const dot = key.indexOf('.')
258
- const id = key.slice(0, dot)
259
- const prop = key.slice(dot + 1)
260
- const kind = ids.get(id)
261
- if (dot < 1 || kind === undefined) throw new RangeError(`override "${key}": no node with id "${id}" in this scene`)
262
- const allowed = [...COMMON, ...KIND_PROPS[/** @type {keyof typeof KIND_PROPS} */ (kind)]]
263
- if (prop === 'id' || !allowed.includes(prop)) throw new RangeError(`override "${key}": a ${kind} has no prop "${prop}"`)
264
- const props = parsed.get(id) ?? new Map()
265
- props.set(prop, value)
266
- parsed.set(id, props)
267
- }
268
- return parsed
269
- }
270
-
271
- /**
272
- * The order to draw children in: by z, ties in code order. Null when no child sets z.
273
- * @param {ReadonlyArray<Node>} nodes
274
- * @param {(i: number) => number} timeOf
275
- * @param {string} scope
276
- * @param {Overrides | null} overrides
277
- */
278
- function drawOrder(nodes, timeOf, scope, overrides) {
279
- let any = false
280
- for (const node of nodes) {
281
- const id = node.props.id
282
- if (node.props.z !== undefined || (overrides && id !== undefined && overrides.get(scope + id)?.has('z'))) any = true
283
- }
284
- if (!any) return null
285
- const z = nodes.map((node, i) => {
286
- const id = node.props.id
287
- return read(node.props, overrides && id !== undefined ? overrides.get(scope + id) : undefined, 'z', timeOf(i)) ?? 0
288
- })
289
- return nodes.map((_, i) => i).sort((a, b) => z[a] - z[b] || a - b)
290
- }
291
-
292
- /**
293
- * Walks a group's children, or a timeline's items, into state.out.
294
- * @param {Node} node
295
- * @param {number} t
296
- * @param {Matrix} matrix
297
- * @param {number} opacity
298
- * @param {string} scope
299
- * @param {string} name
300
- * @param {State} state
301
- */
302
- function walkChildren(node, t, matrix, opacity, scope, name, state) {
303
- if (node instanceof Timeline) {
304
- const items = node.items
305
- const local = items.map(item => {
306
- const end = item.at + item.dur
307
- if (t >= item.at && t < end) return (t - item.at) * item.speed
308
- if (t < item.at) return item.hold === 'before' || item.hold === 'both' ? 0 : NaN
309
- return item.hold === 'after' || item.hold === 'both' ? item.dur * item.speed : NaN
310
- })
311
- const order = drawOrder(items.map(item => item.node), i => local[i], scope, state.overrides)
312
- for (let k = 0; k < items.length; k++) {
313
- const i = order ? order[k] : k
314
- if (!Number.isNaN(local[i])) walk(items[i].node, local[i], matrix, opacity, scope, `${name}/${i}`, state)
315
- }
316
- return
317
- }
318
- const children = typeof node.children === 'function' ? node.children(t) : (node.children ?? [])
319
- if (!Array.isArray(children) || !children.every(isNode)) throw new TypeError(`group "${name}": children(t) must return an array of nodes`)
320
- const order = drawOrder(children, () => t, scope, state.overrides)
321
- for (let k = 0; k < children.length; k++) {
322
- const i = order ? order[k] : k
323
- walk(children[i], t, matrix, opacity, scope, `${name}/${i}`, state)
324
- }
325
- }
326
-
327
- /**
328
- * Builds the display list for one node at its local time t.
329
- * @param {Node} node
330
- * @param {number} t
331
- * @param {Matrix} parent
332
- * @param {number} parentOpacity
333
- * @param {string} scope
334
- * @param {string} name Position-based name for nodes without an id, used in messages and as the item id.
335
- * @param {State} state
336
- */
337
- function walk(node, t, parent, parentOpacity, scope, name, state) {
338
- const props = node.props
339
- const full = props.id === undefined ? null : scope + props.id
340
- const id = full ?? name
341
- context.node = id
342
- context.t = t
343
- const o = full !== null && state.overrides ? state.overrides.get(full) : undefined
344
-
345
- if (read(props, o, 'visible', t) === false) return
346
- const opacity = parentOpacity * (read(props, o, 'opacity', t) ?? 1)
347
- if (opacity <= 0) return
348
- const blend = read(props, o, 'blend', t)
349
- if (blend !== undefined && !BLENDS.includes(blend)) throw new RangeError(`node "${id}": blend must be one of ${BLENDS.join(', ')}`)
350
- const out = state.out
351
-
352
- if (node.kind === 'group' || node.kind === 'instance' || node instanceof Timeline) {
353
- const inner = node.kind === 'instance' ? `${full}/` : scope
354
- const hasTime = props.time !== undefined || (o !== undefined && o.has('time'))
355
- /** @param {number} at Local time of this node. @param {DisplayItem[]} into @param {number} childOpacity */
356
- const children = (at, into, childOpacity) => {
357
- const matrix = transform(parent, props, o, at)
358
- const childT = hasTime ? read(props, o, 'time', at) : at
359
- walkChildren(node, childT, matrix, childOpacity, inner, name, { ...state, out: into })
360
- }
361
- const matte = o !== undefined && o.has('matte') ? /** @type {any} */ (o.get('matte')) : props.matte
362
- const blur = o !== undefined && o.has('motionBlur') ? /** @type {any} */ (o.get('motionBlur')) : props.motionBlur
363
- const effects = resolveEffects(read(props, o, 'effects', t), t, id)
364
- const layered = (blend !== undefined && blend !== 'normal') || matte || blur || effects || read(props, o, 'isolate', t) === true
365
- if (!layered) return children(t, out, opacity)
366
-
367
- /** @type {DisplayItem & { type: 'layer' }} */
368
- const layer = { id, type: 'layer', opacity }
369
- if (blend !== undefined && blend !== 'normal') layer.blend = blend
370
- if (blur) {
371
- const { samples = 8, shutter = 1 / 60 } = blur
372
- layer.samples = Array.from({ length: samples }, (_, k) => {
373
- /** @type {DisplayItem[]} */
374
- const list = []
375
- children(t + shutter * (k / (samples - 1) - 0.5), list, 1)
376
- return list
377
- })
378
- } else {
379
- layer.items = []
380
- children(t, layer.items, 1)
381
- }
382
- if (matte) {
383
- /** @type {DisplayItem[]} */
384
- const items = []
385
- const childT = hasTime ? read(props, o, 'time', t) : t
386
- walk(matte.node, childT, transform(parent, props, o, t), 1, inner, `${name}#matte`, { ...state, out: items })
387
- layer.matte = { mode: matte.mode ?? 'alpha', items }
388
- }
389
- if (effects) {
390
- layer.effects = effects
391
- layer.t = t
392
- }
393
- out.push(layer)
394
- return
395
- }
396
-
397
- if (node.kind === 'transition') {
398
- const progress = read(props, o, 'progress', t)
399
- if (!Number.isFinite(progress)) throw new TypeError(`transition "${id}": progress must be a number from 0 to 1`)
400
- const effect = read(props, o, 'effect', t) ?? 'fade'
401
- if (typeof effect === 'string' ? !TRANSITIONS.includes(effect) : typeof effect?.glsl !== 'string') {
402
- throw new RangeError(`transition "${id}": effect must be one of ${TRANSITIONS.join(', ')}, or { glsl }`)
403
- }
404
- const matrix = transform(parent, props, o, t)
405
- const box = read(props, o, 'box', t)
406
- /** @type {[number, number, number, number] | undefined} */
407
- let area
408
- if (box !== undefined) {
409
- if (!Array.isArray(box) || box.length !== 4 || !box.every(Number.isFinite) || !(box[2] > 0 && box[3] > 0)) {
410
- throw new TypeError(`transition "${id}": box must be [x, y, w, h] with w and h above 0`)
411
- }
412
- // The box's corners in scene px; renderers play the transition across the rectangle around them.
413
- const [bx, by, bw, bh] = box
414
- const corners = [[bx, by], [bx + bw, by], [bx, by + bh], [bx + bw, by + bh]]
415
- const xs = corners.map(([x, y]) => matrix[0] * x + matrix[2] * y + matrix[4])
416
- const ys = corners.map(([x, y]) => matrix[1] * x + matrix[3] * y + matrix[5])
417
- const x0 = Math.min(...xs)
418
- const y0 = Math.min(...ys)
419
- area = [x0, y0, Math.max(...xs) - x0, Math.max(...ys) - y0]
420
- if (!(area[2] > 0 && area[3] > 0)) return
421
- }
422
- const [first, second] = /** @type {Node[]} */ (node.children)
423
- /** @type {DisplayItem[]} */
424
- const from = []
425
- /** @type {DisplayItem[]} */
426
- const to = []
427
- walk(first, t, matrix, 1, scope, `${name}/0`, { ...state, out: from })
428
- walk(second, t, matrix, 1, scope, `${name}/1`, { ...state, out: to })
429
- /** @type {DisplayItem & { type: 'transition' }} */
430
- const item = { id, type: 'transition', opacity, progress: Math.min(1, Math.max(0, progress)), effect, params: read(props, o, 'params', t) ?? {}, from, to }
431
- if (area) item.box = area
432
- if (blend !== undefined && blend !== 'normal') item.blend = blend
433
- out.push(item)
434
- return
435
- }
436
-
437
- const matrix = transform(parent, props, o, t)
438
- /** @type {DisplayItem} */
439
- let item
440
- switch (node.kind) {
441
- case 'shape':
442
- case 'rect':
443
- case 'ellipse': {
444
- let path
445
- if (node.kind === 'shape') path = read(props, o, 'path', t)
446
- else {
447
- const w = read(props, o, 'w', t)
448
- const h = read(props, o, 'h', t)
449
- if (node.kind === 'rect') {
450
- const radius = read(props, o, 'radius', t) ?? 0
451
- path = cachedPath(node, `${w} ${h} ${radius}`, () =>
452
- radius === 0 ? newPath().rect(0, 0, w, h) : newPath().roundRect(0, 0, w, h, radius),
453
- )
454
- } else {
455
- path = cachedPath(node, `${w} ${h}`, () => newPath().ellipse(w / 2, h / 2, w / 2, h / 2, 0, 0, TAU))
456
- }
457
- }
458
- const fill = read(props, o, 'fill', t)
459
- const stroke = read(props, o, 'stroke', t)
460
- item = {
461
- id,
462
- type: 'shape',
463
- matrix,
464
- opacity,
465
- path,
466
- fill: fill === undefined && stroke === undefined ? '#000000' : fill,
467
- stroke,
468
- strokeWidth: read(props, o, 'strokeWidth', t),
469
- lineCap: read(props, o, 'lineCap', t),
470
- lineJoin: read(props, o, 'lineJoin', t),
471
- dash: read(props, o, 'dash', t),
472
- dashOffset: read(props, o, 'dashOffset', t),
473
- }
474
- break
475
- }
476
- case 'text': {
477
- const fill = read(props, o, 'fill', t)
478
- const stroke = read(props, o, 'stroke', t)
479
- const font = read(props, o, 'font', t)
480
- state.checkFont(font, id)
481
- const text = String(read(props, o, 'text', t))
482
- /** @type {DisplayItem & { type: 'text' }} */
483
- const textItem = {
484
- id,
485
- type: 'text',
486
- matrix,
487
- opacity,
488
- text,
489
- font,
490
- align: read(props, o, 'align', t),
491
- baseline: read(props, o, 'baseline', t),
492
- fill: fill === undefined && stroke === undefined ? '#000000' : fill,
493
- stroke,
494
- strokeWidth: read(props, o, 'strokeWidth', t),
495
- }
496
- const lineHeight = read(props, o, 'lineHeight', t)
497
- const width = read(props, o, 'width', t)
498
- if (lineHeight !== undefined) textItem.lineHeight = lineHeight
499
- if (width !== undefined) textItem.width = width
500
- const split = read(props, o, 'split', t)
501
- if (split !== undefined) {
502
- if (!SPLITS.includes(split)) throw new RangeError(`text "${id}": split must be 'grapheme', 'word' or 'line'`)
503
- const units = unitsOf(node, text, split)
504
- const perUnit = o !== undefined && o.has('perUnit') ? /** @type {UnitFn | UnitFn[] | undefined} */ (o.get('perUnit')) : props.perUnit
505
- const fns = perUnit === undefined ? [] : [perUnit].flat()
506
- textItem.units = units
507
- textItem.offsets = units.map((unit, i) => unitStyle(fns, i, units.length, t, unit, units))
508
- }
509
- item = textItem
510
- break
511
- }
512
- case 'image': {
513
- /** @type {DisplayItem & { type: 'image' }} */
514
- const image = { id, type: 'image', matrix, opacity, src: read(props, o, 'src', t), w: read(props, o, 'w', t), h: read(props, o, 'h', t) }
515
- const crop = read(props, o, 'crop', t)
516
- if (crop !== undefined) image.crop = crop
517
- if (read(props, o, 'smooth', t) === false) image.smooth = false
518
- item = image
519
- break
520
- }
521
- case 'mesh': {
522
- const points = read(props, o, 'points', t)
523
- const uvs = props.uvs
524
- const triangles = props.triangles
525
- if (!points || points.length !== uvs.length || points.length % 2 !== 0) {
526
- throw new TypeError(`mesh "${id}": points and uvs must be x, y pairs of the same length`)
527
- }
528
- if (triangles.length % 3 !== 0) throw new TypeError(`mesh "${id}": triangles must hold three vertex indices each`)
529
- /** @type {DisplayItem & { type: 'mesh' }} */
530
- const meshItem = { id, type: 'mesh', matrix, opacity, src: read(props, o, 'src', t), points, uvs, triangles }
531
- if (read(props, o, 'smooth', t) === false) meshItem.smooth = false
532
- item = meshItem
533
- break
534
- }
535
- case 'video': {
536
- const time = read(props, o, 'time', t)
537
- /** @type {DisplayItem & { type: 'video' }} */
538
- const frame = { id, type: 'video', matrix, opacity, src: read(props, o, 'src', t), time: time ?? t, w: read(props, o, 'w', t), h: read(props, o, 'h', t) }
539
- const crop = read(props, o, 'crop', t)
540
- if (crop !== undefined) frame.crop = crop
541
- if (read(props, o, 'smooth', t) === false) frame.smooth = false
542
- item = frame
543
- break
544
- }
545
- case 'instances': {
546
- /** @type {DisplayItem[]} */
547
- const based = []
548
- walk(props.base, t, IDENTITY, 1, scope, `${name}#base`, { ...state, out: based })
549
- const data = read(props, o, 'data', t)
550
- if (!(data instanceof Float32Array || data instanceof Float64Array) || data.length % STRIDE !== 0) {
551
- throw new TypeError(`instances "${id}": data must be a Float32Array or Float64Array with ${STRIDE} numbers per copy`)
552
- }
553
- if (based.length === 0) return
554
- if (based.length !== 1 || based[0].type === 'layer' || based[0].type === 'instances' || based[0].type === 'draw') {
555
- throw new TypeError(`instances "${id}": the base must draw exactly one shape, text or image`)
556
- }
557
- item = { id, type: 'instances', matrix, opacity, base: based[0], data, colors: read(props, o, 'colors', t) ?? [] }
558
- break
559
- }
560
- case 'draw':
561
- item = { id, type: 'draw', matrix, opacity, t, draw: props.draw }
562
- break
563
- default:
564
- throw new TypeError(`scene: unknown node kind "${node.kind}"`)
565
- }
566
- if (blend !== undefined && blend !== 'normal') item.blend = blend
567
- out.push(item)
568
- }
569
-
570
- /**
571
- * Effects with their defaults filled in and every parameter read at t, or null when there are none.
572
- * @param {ReadonlyArray<Record<string, any>> | undefined} effects @param {number} t @param {string} id
573
- * @returns {ResolvedEffect[] | null}
574
- */
575
- function resolveEffects(effects, t, id) {
576
- if (effects === undefined || effects === null || effects.length === 0) return null
577
- if (!Array.isArray(effects)) throw new TypeError(`node "${id}": effects must be a list, such as [glow(), grain()]`)
578
- return effects.map(effect => {
579
- const defaults = /** @type {Record<string, any> | undefined} */ (EFFECTS[/** @type {keyof typeof EFFECTS} */ (effect?.type)])
580
- if (!defaults) throw new RangeError(`node "${id}": unknown effect "${effect?.type}". Effects are ${Object.keys(EFFECTS).join(', ')}`)
581
- /** @type {ResolvedEffect} */
582
- const out = { type: effect.type }
583
- for (const key of Object.keys(effect)) {
584
- if (key !== 'type' && !(key in defaults)) throw new RangeError(`node "${id}": effect ${effect.type} has no "${key}". It takes ${Object.keys(defaults).join(', ')}`)
585
- }
586
- for (const [key, fallback] of Object.entries(defaults)) out[key] = at(effect[key] ?? fallback, t)
587
- return out
588
- })
589
- }
590
-
591
- /**
592
- * The families a CSS font string names, after its size.
593
- * @param {string} font
594
- */
595
- function familiesOf(font) {
596
- const match = FONT_SIZE.exec(font)
597
- if (!match) return []
598
- return match[1].split(',').map(f => f.trim().replace(/^["']|["']$/g, '').toLowerCase())
599
- }
600
-
601
- /**
602
- * A whole animation: a tree of nodes and how long it runs. `evaluate(t)` turns it into a display list for any time,
603
- * synchronously and without side effects, so frames can be computed in any order or in parallel.
604
- * @param {SceneSpec} spec
605
- * @returns {Scene}
606
- */
607
- export function scene({ duration, size, root, background, assets = {}, markers = [] }) {
608
- if (!(duration > 0) || duration === Infinity) throw new RangeError(`scene: duration must be a positive number of seconds, got ${duration}`)
609
- if (!Array.isArray(size) || size.length !== 2 || !(size[0] > 0) || !(size[1] > 0)) {
610
- throw new TypeError('scene: size must be [width, height] in px')
611
- }
612
- if (!isNode(root)) throw new TypeError('scene: root must be a node, such as group({}, [...])')
613
-
614
- /** @type {Map<string, string>} */
615
- const ids = new Map()
616
- /** @type {Marker[]} */
617
- const labels = []
618
- index(root, '', ids, labels, 0, 1)
619
-
620
- const declared = new Set((assets.fonts ?? []).map(f => f.family.toLowerCase()))
621
- /** @type {Map<string, string | null>} */
622
- const fontVerdicts = new Map()
623
- /** @param {string | undefined} font @param {string} id */
624
- const checkFont = (font, id) => {
625
- if (font === undefined) return
626
- let missing = fontVerdicts.get(font)
627
- if (missing === undefined) {
628
- missing = familiesOf(font).find(f => !GENERIC.has(f) && !declared.has(f)) ?? null
629
- fontVerdicts.set(font, missing)
630
- }
631
- if (missing !== null) {
632
- throw new RangeError(
633
- `text "${id}": font family "${missing}" is not in the scene's assets.fonts. Declare it there, or use a generic ` +
634
- 'family such as sans-serif, so every machine draws the same text.',
635
- )
636
- }
637
- }
638
-
639
- /** @type {WeakMap<object, Overrides>} */
640
- const parsed = new WeakMap()
641
- const backdrop = background === undefined ? null : newPath().rect(0, 0, size[0], size[1])
642
-
643
- return Object.freeze({
644
- duration,
645
- size: Object.freeze(/** @type {[number, number]} */ ([size[0], size[1]])),
646
- assets: Object.freeze({ ...assets }),
647
- markers: makeMarkers([...markers, ...labels]),
648
- /** @param {number} fps */
649
- frameCount: fps => Math.round(duration * fps),
650
- /** @param {number} frame @param {number} fps */
651
- frameTime: (frame, fps) => frame / fps,
652
- /**
653
- * @param {number} t
654
- * @param {{ overrides?: Record<string, unknown> }} [options] Values by 'id.prop', for tools that tweak a scene
655
- * without editing its code.
656
- */
657
- evaluate(t, { overrides } = {}) {
658
- if (!Number.isFinite(t)) throw new TypeError(`evaluate: t must be a finite number of seconds, got ${t}`)
659
- let o = null
660
- if (overrides) {
661
- // Cache only frozen override maps so tools can mutate a live overrides object in place.
662
- if (Object.isFrozen(overrides)) {
663
- o = parsed.get(overrides) ?? parseOverrides(overrides, ids)
664
- parsed.set(overrides, o)
665
- } else {
666
- o = parseOverrides(overrides, ids)
667
- }
668
- }
669
- /** @type {DisplayItem[]} */
670
- const out = []
671
- if (backdrop) out.push({ id: '#background', type: 'shape', matrix: IDENTITY, opacity: 1, path: backdrop, fill: background })
672
- return guarded(() => {
673
- walk(root, t, IDENTITY, 1, '', 'root', { out, overrides: o, checkFont })
674
- return out
675
- })
676
- },
677
- })
678
- }
1
+ import { at } from './math.js'
2
+ import { path as newPath } from './path.js'
3
+ import { COMMON, KIND_PROPS, STRIDE, EFFECTS, TRANSITIONS, isNode } from './nodes.js'
4
+ import { Timeline, sealTimeline, snap } from './timeline.js'
5
+ import { markers as makeMarkers } from './markers.js'
6
+ import { guarded, context } from './guard.js'
7
+
8
+ /** @typedef {import('./nodes.js').Node} Node */
9
+ /** @typedef {import('./nodes.js').Gradient} Gradient */
10
+ /** @typedef {import('./nodes.js').UnitStyle} UnitStyle */
11
+ /** @typedef {import('./nodes.js').UnitFn} UnitFn */
12
+ /** @typedef {import('./path.js').Path} Path */
13
+ /** @typedef {import('./markers.js').Marker} Marker */
14
+ /** @typedef {[number, number, number, number, number, number]} Matrix In setTransform(a, b, c, d, e, f) order. */
15
+
16
+ /**
17
+ * One thing to draw, with its transform already multiplied down from the root. A `layer` holds items that are
18
+ * composited together first, for blend modes, mattes, isolation and motion blur. `blend` appears only when set. The
19
+ * exact shape stays experimental until the first stable release.
20
+ * @typedef {{ id: string, type: 'shape', matrix: Matrix, opacity: number, path: Path, fill?: string | Gradient,
21
+ * stroke?: string | Gradient, strokeWidth?: number, lineCap?: string, lineJoin?: string, dash?: number[],
22
+ * dashOffset?: number, blend?: string }
23
+ * | { id: string, type: 'text', matrix: Matrix, opacity: number, text: string, font?: string, align?: string,
24
+ * baseline?: string, fill?: string | Gradient, stroke?: string | Gradient, strokeWidth?: number, lineHeight?: number,
25
+ * width?: number, units?: string[], offsets?: Required<Omit<UnitStyle, 'fill'>>[] & { fill?: string }[], blend?: string }
26
+ * | { id: string, type: 'image', matrix: Matrix, opacity: number, src: string, w?: number, h?: number,
27
+ * crop?: readonly [number, number, number, number], smooth?: false, blend?: string }
28
+ * | { id: string, type: 'video', matrix: Matrix, opacity: number, src: string, time: number, w?: number, h?: number,
29
+ * crop?: readonly [number, number, number, number], smooth?: false, blend?: string }
30
+ * | { id: string, type: 'instances', matrix: Matrix, opacity: number, base: DisplayItem, data: Float32Array | Float64Array,
31
+ * colors: string[], blend?: string }
32
+ * | { id: string, type: 'draw', matrix: Matrix, opacity: number, t: number, draw: (ctx: any, t: number) => void,
33
+ * blend?: string }
34
+ * | { id: string, type: 'layer', opacity: number, blend?: string, items?: DisplayItem[], samples?: DisplayItem[][],
35
+ * matte?: { mode: string, items: DisplayItem[] }, effects?: ResolvedEffect[], t?: number }
36
+ * | { id: string, type: 'mesh', matrix: Matrix, opacity: number, src: string, points: ArrayLike<number>,
37
+ * uvs: ArrayLike<number>, triangles: ArrayLike<number>, smooth?: false, blend?: string }
38
+ * | { id: string, type: 'transition', opacity: number, progress: number, effect: string | { glsl: string },
39
+ * params: Record<string, number | number[]>, from: DisplayItem[], to: DisplayItem[], box?: [number, number, number, number],
40
+ * blend?: string }
41
+ * } DisplayItem
42
+ */
43
+
44
+ /** An effect with every parameter filled in and read at the layer's time. @typedef {{ type: string } & Record<string, any>} ResolvedEffect */
45
+
46
+ /**
47
+ * @typedef {object} Assets
48
+ * @property {{ family: string, src: string, weight?: string, style?: string }[]} [fonts]
49
+ * @property {Record<string, string>} [images] Image URLs by the key an image node's `src` uses.
50
+ * @property {Record<string, string>} [videos] MP4 URLs by the key a video node's `src` uses.
51
+ * @property {Record<string, string>} [audio] Sound files by name, for players and exporters to play or mix in.
52
+ */
53
+
54
+ /**
55
+ * @typedef {object} SceneSpec
56
+ * @property {number} duration Seconds.
57
+ * @property {[number, number]} size Logical width and height in px.
58
+ * @property {Node} root
59
+ * @property {string} [background] A CSS colour drawn under everything.
60
+ * @property {Assets} [assets] Loaded by a renderer before the first frame.
61
+ * @property {Marker[]} [markers]
62
+ */
63
+
64
+ /**
65
+ * @typedef {object} Scene
66
+ * @property {number} duration
67
+ * @property {Readonly<[number, number]>} size
68
+ * @property {Readonly<Assets>} assets
69
+ * @property {ReturnType<typeof makeMarkers>} markers The scene's markers plus every timeline label.
70
+ * @property {(fps: number) => number} frameCount
71
+ * @property {(frame: number, fps: number) => number} frameTime
72
+ * @property {(t: number, options?: { overrides?: Record<string, unknown> }) => DisplayItem[]} evaluate
73
+ */
74
+
75
+ /** @typedef {Map<string, Map<string, unknown>>} Overrides */
76
+
77
+ /**
78
+ * What one evaluation carries down the tree.
79
+ * @typedef {object} State
80
+ * @property {DisplayItem[]} out
81
+ * @property {Overrides | null} overrides
82
+ * @property {(font: string | undefined, id: string) => void} checkFont
83
+ */
84
+
85
+ /** @type {Matrix} */
86
+ const IDENTITY = [1, 0, 0, 1, 0, 0]
87
+ const DEG = Math.PI / 180
88
+ const TAU = Math.PI * 2
89
+ const BLENDS = [
90
+ 'normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light',
91
+ 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity', 'add',
92
+ ]
93
+ const SPLITS = ['grapheme', 'word', 'line']
94
+ // Families every machine has some font for; anything else must be loaded from the scene's assets.
95
+ const GENERIC = new Set([
96
+ 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace',
97
+ 'ui-rounded', 'emoji', 'math', 'fangsong',
98
+ ])
99
+ const FONT_SIZE = /(?:^|\s)(?:\d*\.?\d+(?:px|pt|pc|in|cm|mm|q|em|rem|ex|ch|%|vw|vh|vmin|vmax)|(?:xx?-|xxx-)?(?:small|large)|medium|larger|smaller)(?:\s*\/\s*\S+)?\s+(.+)$/i
100
+
101
+ /**
102
+ * Reads a prop at local time t, with an override taking the place of the node's own value.
103
+ * @param {Readonly<Record<string, any>>} props
104
+ * @param {Map<string, unknown> | undefined} override
105
+ * @param {string} name
106
+ * @param {number} t
107
+ */
108
+ function read(props, override, name, t) {
109
+ const value = override !== undefined && override.has(name) ? override.get(name) : props[name]
110
+ return value === undefined ? undefined : at(value, t)
111
+ }
112
+
113
+ /**
114
+ * @param {Matrix} p
115
+ * @param {Readonly<Record<string, any>>} props
116
+ * @param {Map<string, unknown> | undefined} o
117
+ * @param {number} t
118
+ * @returns {Matrix}
119
+ */
120
+ function transform(p, props, o, t) {
121
+ const x = read(props, o, 'x', t) ?? 0
122
+ const y = read(props, o, 'y', t) ?? 0
123
+ const rotation = read(props, o, 'rotation', t) ?? 0
124
+ const scale = read(props, o, 'scale', t) ?? 1
125
+ const skew = read(props, o, 'skew', t) ?? 0
126
+ const anchor = read(props, o, 'anchor', t)
127
+ if (x === 0 && y === 0 && rotation === 0 && scale === 1 && skew === 0 && anchor === undefined) return p
128
+ const cos = rotation === 0 ? 1 : Math.cos(rotation * DEG)
129
+ const sin = rotation === 0 ? 0 : Math.sin(rotation * DEG)
130
+ const sx = typeof scale === 'number' ? scale : scale[0]
131
+ const sy = typeof scale === 'number' ? scale : scale[1]
132
+ // Rotation times skewX times scale: the second column picks up tan(skew) of the first.
133
+ const k = skew === 0 ? 0 : Math.tan(skew * DEG)
134
+ const a = cos * sx
135
+ const b = sin * sx
136
+ const c = (cos * k - sin) * sy
137
+ const d = (sin * k + cos) * sy
138
+ const ax = anchor ? anchor[0] : 0
139
+ const ay = anchor ? anchor[1] : 0
140
+ const e = x - (a * ax + c * ay)
141
+ const f = y - (b * ax + d * ay)
142
+ return [
143
+ p[0] * a + p[2] * b,
144
+ p[1] * a + p[3] * b,
145
+ p[0] * c + p[2] * d,
146
+ p[1] * c + p[3] * d,
147
+ p[0] * e + p[2] * f + p[4],
148
+ p[1] * e + p[3] * f + p[5],
149
+ ]
150
+ }
151
+
152
+ // Rects and ellipses keep their last Path while their size stays the same, so a renderer can cache what it built.
153
+ /** @type {WeakMap<Node, { key: string, path: Path }>} */
154
+ const shapeCache = new WeakMap()
155
+
156
+ /** @param {Node} node @param {string} key @param {() => Path} make */
157
+ function cachedPath(node, key, make) {
158
+ const hit = shapeCache.get(node)
159
+ if (hit && hit.key === key) return hit.path
160
+ const path = make()
161
+ shapeCache.set(node, { key, path })
162
+ return path
163
+ }
164
+
165
+ /** @type {Record<string, Intl.Segmenter>} */
166
+ const segmenters = {}
167
+ /** @type {WeakMap<Node, { text: string, split: string, units: string[] }>} */
168
+ const unitCache = new WeakMap()
169
+
170
+ /**
171
+ * Cuts text into units that together give back the whole text. 'line' keeps each newline as its own unit.
172
+ * @param {Node} node
173
+ * @param {string} text
174
+ * @param {string} split
175
+ */
176
+ function unitsOf(node, text, split) {
177
+ const hit = unitCache.get(node)
178
+ if (hit && hit.text === text && hit.split === split) return hit.units
179
+ let units
180
+ if (split === 'line') units = text.split(/(\n)/).filter(u => u !== '')
181
+ else {
182
+ const granularity = /** @type {'grapheme' | 'word'} */ (split)
183
+ segmenters[granularity] ??= new Intl.Segmenter(undefined, { granularity })
184
+ units = Array.from(segmenters[granularity].segment(text), s => s.segment)
185
+ }
186
+ unitCache.set(node, { text, split, units })
187
+ return units
188
+ }
189
+
190
+ /**
191
+ * Combines the styles of every perUnit function: positions and rotation add up, scale and opacity multiply, and the
192
+ * last fill wins.
193
+ * @param {UnitFn[]} fns
194
+ * @param {number} i
195
+ * @param {number} n
196
+ * @param {number} t
197
+ * @param {string} unit
198
+ * @param {readonly string[]} units
199
+ */
200
+ function unitStyle(fns, i, n, t, unit, units) {
201
+ let x = 0
202
+ let y = 0
203
+ let rotation = 0
204
+ let scale = 1
205
+ let opacity = 1
206
+ /** @type {string | undefined} */
207
+ let fill
208
+ for (const fn of fns) {
209
+ const s = fn(i, n, t, unit, units)
210
+ if (!s) continue
211
+ x += s.x ?? 0
212
+ y += s.y ?? 0
213
+ rotation += s.rotation ?? 0
214
+ scale *= s.scale ?? 1
215
+ opacity *= s.opacity ?? 1
216
+ if (s.fill !== undefined) fill = s.fill
217
+ }
218
+ return { x, y, rotation, scale, opacity, fill }
219
+ }
220
+
221
+ /**
222
+ * Collects ids and timeline labels from the parts of the tree that do not depend on time, and seals timelines.
223
+ * @param {Node} node
224
+ * @param {string} scope Prefix for ids inside component instances.
225
+ * @param {Map<string, string>} ids Full id to node kind.
226
+ * @param {Marker[]} labels
227
+ * @param {number} offset Scene time where this subtree's time 0 falls.
228
+ * @param {number} rate How fast this subtree's time runs against scene time.
229
+ */
230
+ function index(node, scope, ids, labels, offset, rate) {
231
+ const id = node.props.id
232
+ const full = id === undefined ? null : scope + id
233
+ if (full !== null) {
234
+ if (ids.has(full)) throw new Error(`scene: id "${full}" is used twice`)
235
+ ids.set(full, node.kind)
236
+ }
237
+ if (node instanceof Timeline) {
238
+ sealTimeline(node)
239
+ for (const label of node.labels) labels.push({ at: snap(offset + label.at / rate), name: label.name, kind: 'label' })
240
+ for (const item of node.items) index(item.node, scope, ids, labels, offset + item.at / rate, rate * item.speed)
241
+ return
242
+ }
243
+ const inner = node.kind === 'instance' ? `${full}/` : scope
244
+ if (node.props.matte?.node) index(node.props.matte.node, inner, ids, labels, offset, rate)
245
+ if (Array.isArray(node.children)) for (const child of node.children) index(child, inner, ids, labels, offset, rate)
246
+ }
247
+
248
+ /**
249
+ * @param {Record<string, unknown>} overrides
250
+ * @param {Map<string, string>} ids
251
+ * @returns {Overrides}
252
+ */
253
+ function parseOverrides(overrides, ids) {
254
+ /** @type {Overrides} */
255
+ const parsed = new Map()
256
+ for (const [key, value] of Object.entries(overrides)) {
257
+ const dot = key.indexOf('.')
258
+ const id = key.slice(0, dot)
259
+ const prop = key.slice(dot + 1)
260
+ const kind = ids.get(id)
261
+ if (dot < 1 || kind === undefined) throw new RangeError(`override "${key}": no node with id "${id}" in this scene`)
262
+ const allowed = [...COMMON, ...KIND_PROPS[/** @type {keyof typeof KIND_PROPS} */ (kind)]]
263
+ if (prop === 'id' || !allowed.includes(prop)) throw new RangeError(`override "${key}": a ${kind} has no prop "${prop}"`)
264
+ const props = parsed.get(id) ?? new Map()
265
+ props.set(prop, value)
266
+ parsed.set(id, props)
267
+ }
268
+ return parsed
269
+ }
270
+
271
+ /**
272
+ * The order to draw children in: by z, ties in code order. Null when no child sets z.
273
+ * @param {ReadonlyArray<Node>} nodes
274
+ * @param {(i: number) => number} timeOf
275
+ * @param {string} scope
276
+ * @param {Overrides | null} overrides
277
+ */
278
+ function drawOrder(nodes, timeOf, scope, overrides) {
279
+ let any = false
280
+ for (const node of nodes) {
281
+ const id = node.props.id
282
+ if (node.props.z !== undefined || (overrides && id !== undefined && overrides.get(scope + id)?.has('z'))) any = true
283
+ }
284
+ if (!any) return null
285
+ const z = nodes.map((node, i) => {
286
+ const id = node.props.id
287
+ return read(node.props, overrides && id !== undefined ? overrides.get(scope + id) : undefined, 'z', timeOf(i)) ?? 0
288
+ })
289
+ return nodes.map((_, i) => i).sort((a, b) => z[a] - z[b] || a - b)
290
+ }
291
+
292
+ /**
293
+ * Walks a group's children, or a timeline's items, into state.out.
294
+ * @param {Node} node
295
+ * @param {number} t
296
+ * @param {Matrix} matrix
297
+ * @param {number} opacity
298
+ * @param {string} scope
299
+ * @param {string} name
300
+ * @param {State} state
301
+ */
302
+ function walkChildren(node, t, matrix, opacity, scope, name, state) {
303
+ if (node instanceof Timeline) {
304
+ const items = node.items
305
+ const local = items.map(item => {
306
+ const end = item.at + item.dur
307
+ if (t >= item.at && t < end) return (t - item.at) * item.speed
308
+ if (t < item.at) return item.hold === 'before' || item.hold === 'both' ? 0 : NaN
309
+ return item.hold === 'after' || item.hold === 'both' ? item.dur * item.speed : NaN
310
+ })
311
+ const order = drawOrder(items.map(item => item.node), i => local[i], scope, state.overrides)
312
+ for (let k = 0; k < items.length; k++) {
313
+ const i = order ? order[k] : k
314
+ if (!Number.isNaN(local[i])) walk(items[i].node, local[i], matrix, opacity, scope, `${name}/${i}`, state)
315
+ }
316
+ return
317
+ }
318
+ const children = typeof node.children === 'function' ? node.children(t) : (node.children ?? [])
319
+ if (!Array.isArray(children) || !children.every(isNode)) throw new TypeError(`group "${name}": children(t) must return an array of nodes`)
320
+ const order = drawOrder(children, () => t, scope, state.overrides)
321
+ for (let k = 0; k < children.length; k++) {
322
+ const i = order ? order[k] : k
323
+ walk(children[i], t, matrix, opacity, scope, `${name}/${i}`, state)
324
+ }
325
+ }
326
+
327
+ /**
328
+ * Builds the display list for one node at its local time t.
329
+ * @param {Node} node
330
+ * @param {number} t
331
+ * @param {Matrix} parent
332
+ * @param {number} parentOpacity
333
+ * @param {string} scope
334
+ * @param {string} name Position-based name for nodes without an id, used in messages and as the item id.
335
+ * @param {State} state
336
+ */
337
+ function walk(node, t, parent, parentOpacity, scope, name, state) {
338
+ const props = node.props
339
+ const full = props.id === undefined ? null : scope + props.id
340
+ const id = full ?? name
341
+ context.node = id
342
+ context.t = t
343
+ const o = full !== null && state.overrides ? state.overrides.get(full) : undefined
344
+
345
+ if (read(props, o, 'visible', t) === false) return
346
+ const opacity = parentOpacity * (read(props, o, 'opacity', t) ?? 1)
347
+ if (opacity <= 0) return
348
+ const blend = read(props, o, 'blend', t)
349
+ if (blend !== undefined && !BLENDS.includes(blend)) throw new RangeError(`node "${id}": blend must be one of ${BLENDS.join(', ')}`)
350
+ const out = state.out
351
+
352
+ if (node.kind === 'group' || node.kind === 'instance' || node instanceof Timeline) {
353
+ const inner = node.kind === 'instance' ? `${full}/` : scope
354
+ const hasTime = props.time !== undefined || (o !== undefined && o.has('time'))
355
+ /** @param {number} at Local time of this node. @param {DisplayItem[]} into @param {number} childOpacity */
356
+ const children = (at, into, childOpacity) => {
357
+ const matrix = transform(parent, props, o, at)
358
+ const childT = hasTime ? read(props, o, 'time', at) : at
359
+ walkChildren(node, childT, matrix, childOpacity, inner, name, { ...state, out: into })
360
+ }
361
+ const matte = o !== undefined && o.has('matte') ? /** @type {any} */ (o.get('matte')) : props.matte
362
+ const blur = o !== undefined && o.has('motionBlur') ? /** @type {any} */ (o.get('motionBlur')) : props.motionBlur
363
+ const effects = resolveEffects(read(props, o, 'effects', t), t, id)
364
+ const layered = (blend !== undefined && blend !== 'normal') || matte || blur || effects || read(props, o, 'isolate', t) === true
365
+ if (!layered) return children(t, out, opacity)
366
+
367
+ /** @type {DisplayItem & { type: 'layer' }} */
368
+ const layer = { id, type: 'layer', opacity }
369
+ if (blend !== undefined && blend !== 'normal') layer.blend = blend
370
+ if (blur) {
371
+ const { samples = 8, shutter = 1 / 60 } = blur
372
+ layer.samples = Array.from({ length: samples }, (_, k) => {
373
+ /** @type {DisplayItem[]} */
374
+ const list = []
375
+ children(t + shutter * (k / (samples - 1) - 0.5), list, 1)
376
+ return list
377
+ })
378
+ } else {
379
+ layer.items = []
380
+ children(t, layer.items, 1)
381
+ }
382
+ if (matte) {
383
+ /** @type {DisplayItem[]} */
384
+ const items = []
385
+ const childT = hasTime ? read(props, o, 'time', t) : t
386
+ walk(matte.node, childT, transform(parent, props, o, t), 1, inner, `${name}#matte`, { ...state, out: items })
387
+ layer.matte = { mode: matte.mode ?? 'alpha', items }
388
+ }
389
+ if (effects) {
390
+ layer.effects = effects
391
+ layer.t = t
392
+ }
393
+ out.push(layer)
394
+ return
395
+ }
396
+
397
+ if (node.kind === 'transition') {
398
+ const progress = read(props, o, 'progress', t)
399
+ if (!Number.isFinite(progress)) throw new TypeError(`transition "${id}": progress must be a number from 0 to 1`)
400
+ const effect = read(props, o, 'effect', t) ?? 'fade'
401
+ if (typeof effect === 'string' ? !TRANSITIONS.includes(effect) : typeof effect?.glsl !== 'string') {
402
+ throw new RangeError(`transition "${id}": effect must be one of ${TRANSITIONS.join(', ')}, or { glsl }`)
403
+ }
404
+ const matrix = transform(parent, props, o, t)
405
+ const box = read(props, o, 'box', t)
406
+ /** @type {[number, number, number, number] | undefined} */
407
+ let area
408
+ if (box !== undefined) {
409
+ if (!Array.isArray(box) || box.length !== 4 || !box.every(Number.isFinite) || !(box[2] > 0 && box[3] > 0)) {
410
+ throw new TypeError(`transition "${id}": box must be [x, y, w, h] with w and h above 0`)
411
+ }
412
+ // The box's corners in scene px; renderers play the transition across the rectangle around them.
413
+ const [bx, by, bw, bh] = box
414
+ const corners = [[bx, by], [bx + bw, by], [bx, by + bh], [bx + bw, by + bh]]
415
+ const xs = corners.map(([x, y]) => matrix[0] * x + matrix[2] * y + matrix[4])
416
+ const ys = corners.map(([x, y]) => matrix[1] * x + matrix[3] * y + matrix[5])
417
+ const x0 = Math.min(...xs)
418
+ const y0 = Math.min(...ys)
419
+ area = [x0, y0, Math.max(...xs) - x0, Math.max(...ys) - y0]
420
+ if (!(area[2] > 0 && area[3] > 0)) return
421
+ }
422
+ const [first, second] = /** @type {Node[]} */ (node.children)
423
+ /** @type {DisplayItem[]} */
424
+ const from = []
425
+ /** @type {DisplayItem[]} */
426
+ const to = []
427
+ walk(first, t, matrix, 1, scope, `${name}/0`, { ...state, out: from })
428
+ walk(second, t, matrix, 1, scope, `${name}/1`, { ...state, out: to })
429
+ /** @type {DisplayItem & { type: 'transition' }} */
430
+ const item = { id, type: 'transition', opacity, progress: Math.min(1, Math.max(0, progress)), effect, params: read(props, o, 'params', t) ?? {}, from, to }
431
+ if (area) item.box = area
432
+ if (blend !== undefined && blend !== 'normal') item.blend = blend
433
+ out.push(item)
434
+ return
435
+ }
436
+
437
+ const matrix = transform(parent, props, o, t)
438
+ /** @type {DisplayItem} */
439
+ let item
440
+ switch (node.kind) {
441
+ case 'shape':
442
+ case 'rect':
443
+ case 'ellipse': {
444
+ let path
445
+ if (node.kind === 'shape') path = read(props, o, 'path', t)
446
+ else {
447
+ const w = read(props, o, 'w', t)
448
+ const h = read(props, o, 'h', t)
449
+ if (node.kind === 'rect') {
450
+ const radius = read(props, o, 'radius', t) ?? 0
451
+ path = cachedPath(node, `${w} ${h} ${radius}`, () =>
452
+ radius === 0 ? newPath().rect(0, 0, w, h) : newPath().roundRect(0, 0, w, h, radius),
453
+ )
454
+ } else {
455
+ path = cachedPath(node, `${w} ${h}`, () => newPath().ellipse(w / 2, h / 2, w / 2, h / 2, 0, 0, TAU))
456
+ }
457
+ }
458
+ const fill = read(props, o, 'fill', t)
459
+ const stroke = read(props, o, 'stroke', t)
460
+ item = {
461
+ id,
462
+ type: 'shape',
463
+ matrix,
464
+ opacity,
465
+ path,
466
+ fill: fill === undefined && stroke === undefined ? '#000000' : fill,
467
+ stroke,
468
+ strokeWidth: read(props, o, 'strokeWidth', t),
469
+ lineCap: read(props, o, 'lineCap', t),
470
+ lineJoin: read(props, o, 'lineJoin', t),
471
+ dash: read(props, o, 'dash', t),
472
+ dashOffset: read(props, o, 'dashOffset', t),
473
+ }
474
+ break
475
+ }
476
+ case 'text': {
477
+ const fill = read(props, o, 'fill', t)
478
+ const stroke = read(props, o, 'stroke', t)
479
+ const font = read(props, o, 'font', t)
480
+ state.checkFont(font, id)
481
+ const text = String(read(props, o, 'text', t))
482
+ /** @type {DisplayItem & { type: 'text' }} */
483
+ const textItem = {
484
+ id,
485
+ type: 'text',
486
+ matrix,
487
+ opacity,
488
+ text,
489
+ font,
490
+ align: read(props, o, 'align', t),
491
+ baseline: read(props, o, 'baseline', t),
492
+ fill: fill === undefined && stroke === undefined ? '#000000' : fill,
493
+ stroke,
494
+ strokeWidth: read(props, o, 'strokeWidth', t),
495
+ }
496
+ const lineHeight = read(props, o, 'lineHeight', t)
497
+ const width = read(props, o, 'width', t)
498
+ if (lineHeight !== undefined) textItem.lineHeight = lineHeight
499
+ if (width !== undefined) textItem.width = width
500
+ const split = read(props, o, 'split', t)
501
+ if (split !== undefined) {
502
+ if (!SPLITS.includes(split)) throw new RangeError(`text "${id}": split must be 'grapheme', 'word' or 'line'`)
503
+ const units = unitsOf(node, text, split)
504
+ const perUnit = o !== undefined && o.has('perUnit') ? /** @type {UnitFn | UnitFn[] | undefined} */ (o.get('perUnit')) : props.perUnit
505
+ const fns = perUnit === undefined ? [] : [perUnit].flat()
506
+ textItem.units = units
507
+ textItem.offsets = units.map((unit, i) => unitStyle(fns, i, units.length, t, unit, units))
508
+ }
509
+ item = textItem
510
+ break
511
+ }
512
+ case 'image': {
513
+ /** @type {DisplayItem & { type: 'image' }} */
514
+ const image = { id, type: 'image', matrix, opacity, src: read(props, o, 'src', t), w: read(props, o, 'w', t), h: read(props, o, 'h', t) }
515
+ const crop = read(props, o, 'crop', t)
516
+ if (crop !== undefined) image.crop = crop
517
+ if (read(props, o, 'smooth', t) === false) image.smooth = false
518
+ item = image
519
+ break
520
+ }
521
+ case 'mesh': {
522
+ const points = read(props, o, 'points', t)
523
+ const uvs = props.uvs
524
+ const triangles = props.triangles
525
+ if (!points || points.length !== uvs.length || points.length % 2 !== 0) {
526
+ throw new TypeError(`mesh "${id}": points and uvs must be x, y pairs of the same length`)
527
+ }
528
+ if (triangles.length % 3 !== 0) throw new TypeError(`mesh "${id}": triangles must hold three vertex indices each`)
529
+ /** @type {DisplayItem & { type: 'mesh' }} */
530
+ const meshItem = { id, type: 'mesh', matrix, opacity, src: read(props, o, 'src', t), points, uvs, triangles }
531
+ if (read(props, o, 'smooth', t) === false) meshItem.smooth = false
532
+ item = meshItem
533
+ break
534
+ }
535
+ case 'video': {
536
+ const time = read(props, o, 'time', t)
537
+ /** @type {DisplayItem & { type: 'video' }} */
538
+ const frame = { id, type: 'video', matrix, opacity, src: read(props, o, 'src', t), time: time ?? t, w: read(props, o, 'w', t), h: read(props, o, 'h', t) }
539
+ const crop = read(props, o, 'crop', t)
540
+ if (crop !== undefined) frame.crop = crop
541
+ if (read(props, o, 'smooth', t) === false) frame.smooth = false
542
+ item = frame
543
+ break
544
+ }
545
+ case 'instances': {
546
+ /** @type {DisplayItem[]} */
547
+ const based = []
548
+ walk(props.base, t, IDENTITY, 1, scope, `${name}#base`, { ...state, out: based })
549
+ const data = read(props, o, 'data', t)
550
+ if (!(data instanceof Float32Array || data instanceof Float64Array) || data.length % STRIDE !== 0) {
551
+ throw new TypeError(`instances "${id}": data must be a Float32Array or Float64Array with ${STRIDE} numbers per copy`)
552
+ }
553
+ if (based.length === 0) return
554
+ if (based.length !== 1 || based[0].type === 'layer' || based[0].type === 'instances' || based[0].type === 'draw') {
555
+ throw new TypeError(`instances "${id}": the base must draw exactly one shape, text or image`)
556
+ }
557
+ item = { id, type: 'instances', matrix, opacity, base: based[0], data, colors: read(props, o, 'colors', t) ?? [] }
558
+ break
559
+ }
560
+ case 'draw':
561
+ item = { id, type: 'draw', matrix, opacity, t, draw: props.draw }
562
+ break
563
+ default:
564
+ throw new TypeError(`scene: unknown node kind "${node.kind}"`)
565
+ }
566
+ if (blend !== undefined && blend !== 'normal') item.blend = blend
567
+ out.push(item)
568
+ }
569
+
570
+ /**
571
+ * Effects with their defaults filled in and every parameter read at t, or null when there are none.
572
+ * @param {ReadonlyArray<Record<string, any>> | undefined} effects @param {number} t @param {string} id
573
+ * @returns {ResolvedEffect[] | null}
574
+ */
575
+ function resolveEffects(effects, t, id) {
576
+ if (effects === undefined || effects === null || effects.length === 0) return null
577
+ if (!Array.isArray(effects)) throw new TypeError(`node "${id}": effects must be a list, such as [glow(), grain()]`)
578
+ return effects.map(effect => {
579
+ const defaults = /** @type {Record<string, any> | undefined} */ (EFFECTS[/** @type {keyof typeof EFFECTS} */ (effect?.type)])
580
+ if (!defaults) throw new RangeError(`node "${id}": unknown effect "${effect?.type}". Effects are ${Object.keys(EFFECTS).join(', ')}`)
581
+ /** @type {ResolvedEffect} */
582
+ const out = { type: effect.type }
583
+ for (const key of Object.keys(effect)) {
584
+ if (key !== 'type' && !(key in defaults)) throw new RangeError(`node "${id}": effect ${effect.type} has no "${key}". It takes ${Object.keys(defaults).join(', ')}`)
585
+ }
586
+ for (const [key, fallback] of Object.entries(defaults)) out[key] = at(effect[key] ?? fallback, t)
587
+ return out
588
+ })
589
+ }
590
+
591
+ /**
592
+ * The families a CSS font string names, after its size.
593
+ * @param {string} font
594
+ */
595
+ function familiesOf(font) {
596
+ const match = FONT_SIZE.exec(font)
597
+ if (!match) return []
598
+ return match[1].split(',').map(f => f.trim().replace(/^["']|["']$/g, '').toLowerCase())
599
+ }
600
+
601
+ /**
602
+ * A whole animation: a tree of nodes and how long it runs. `evaluate(t)` turns it into a display list for any time,
603
+ * synchronously and without side effects, so frames can be computed in any order or in parallel.
604
+ * @param {SceneSpec} spec
605
+ * @returns {Scene}
606
+ */
607
+ export function scene({ duration, size, root, background, assets = {}, markers = [] }) {
608
+ if (!(duration > 0) || duration === Infinity) throw new RangeError(`scene: duration must be a positive number of seconds, got ${duration}`)
609
+ if (!Array.isArray(size) || size.length !== 2 || !(size[0] > 0) || !(size[1] > 0)) {
610
+ throw new TypeError('scene: size must be [width, height] in px')
611
+ }
612
+ if (!isNode(root)) throw new TypeError('scene: root must be a node, such as group({}, [...])')
613
+
614
+ /** @type {Map<string, string>} */
615
+ const ids = new Map()
616
+ /** @type {Marker[]} */
617
+ const labels = []
618
+ index(root, '', ids, labels, 0, 1)
619
+
620
+ const declared = new Set((assets.fonts ?? []).map(f => f.family.toLowerCase()))
621
+ /** @type {Map<string, string | null>} */
622
+ const fontVerdicts = new Map()
623
+ /** @param {string | undefined} font @param {string} id */
624
+ const checkFont = (font, id) => {
625
+ if (font === undefined) return
626
+ let missing = fontVerdicts.get(font)
627
+ if (missing === undefined) {
628
+ missing = familiesOf(font).find(f => !GENERIC.has(f) && !declared.has(f)) ?? null
629
+ fontVerdicts.set(font, missing)
630
+ }
631
+ if (missing !== null) {
632
+ throw new RangeError(
633
+ `text "${id}": font family "${missing}" is not in the scene's assets.fonts. Declare it there, or use a generic ` +
634
+ 'family such as sans-serif, so every machine draws the same text.',
635
+ )
636
+ }
637
+ }
638
+
639
+ /** @type {WeakMap<object, Overrides>} */
640
+ const parsed = new WeakMap()
641
+ const backdrop = background === undefined ? null : newPath().rect(0, 0, size[0], size[1])
642
+
643
+ return Object.freeze({
644
+ duration,
645
+ size: Object.freeze(/** @type {[number, number]} */ ([size[0], size[1]])),
646
+ assets: Object.freeze({ ...assets }),
647
+ markers: makeMarkers([...markers, ...labels]),
648
+ /** @param {number} fps */
649
+ frameCount: fps => Math.round(duration * fps),
650
+ /** @param {number} frame @param {number} fps */
651
+ frameTime: (frame, fps) => frame / fps,
652
+ /**
653
+ * @param {number} t
654
+ * @param {{ overrides?: Record<string, unknown> }} [options] Values by 'id.prop', for tools that tweak a scene
655
+ * without editing its code.
656
+ */
657
+ evaluate(t, { overrides } = {}) {
658
+ if (!Number.isFinite(t)) throw new TypeError(`evaluate: t must be a finite number of seconds, got ${t}`)
659
+ let o = null
660
+ if (overrides) {
661
+ // Cache only frozen override maps so tools can mutate a live overrides object in place.
662
+ if (Object.isFrozen(overrides)) {
663
+ o = parsed.get(overrides) ?? parseOverrides(overrides, ids)
664
+ parsed.set(overrides, o)
665
+ } else {
666
+ o = parseOverrides(overrides, ids)
667
+ }
668
+ }
669
+ /** @type {DisplayItem[]} */
670
+ const out = []
671
+ if (backdrop) out.push({ id: '#background', type: 'shape', matrix: IDENTITY, opacity: 1, path: backdrop, fill: background })
672
+ return guarded(() => {
673
+ walk(root, t, IDENTITY, 1, '', 'root', { out, overrides: o, checkFont })
674
+ return out
675
+ })
676
+ },
677
+ })
678
+ }