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/nodes.js CHANGED
@@ -1,328 +1,328 @@
1
- /** @typedef {import('./path.js').Path} Path */
2
-
3
- /**
4
- * @template T
5
- * @typedef {import('./math.js').Value<T>} Value
6
- */
7
-
8
- /**
9
- * Properties every node takes. Each may be a constant or a function of the node's local time.
10
- * @typedef {object} CommonProps
11
- * @property {string} [id] Stable name, unique in a scene; letters, digits, - and _ only.
12
- * @property {Value<number>} [x] Position in px, relative to the parent.
13
- * @property {Value<number>} [y]
14
- * @property {Value<number>} [rotation] Degrees, clockwise.
15
- * @property {Value<number | [number, number]>} [scale]
16
- * @property {Value<number>} [skew] Degrees, shearing x along y like CSS skewX, applied between rotation and scale.
17
- * @property {Value<[number, number]>} [anchor] The point, in px from the node's origin, that x and y place and that
18
- * rotation and scale turn around.
19
- * @property {Value<number>} [opacity] 0..1, multiplied into every child.
20
- * @property {Value<boolean>} [visible] false skips the node and its children.
21
- * @property {Value<number>} [z] Draw order within the parent: higher is in front; ties keep code order.
22
- * @property {Value<BlendMode>} [blend] How the node mixes with what is under it. On a group it blends the group as
23
- * one layer.
24
- */
25
-
26
- /**
27
- * @typedef {'normal' | 'multiply' | 'screen' | 'overlay' | 'darken' | 'lighten' | 'color-dodge' | 'color-burn'
28
- * | 'hard-light' | 'soft-light' | 'difference' | 'exclusion' | 'hue' | 'saturation' | 'color' | 'luminosity'
29
- * | 'add'} BlendMode
30
- */
31
-
32
- /**
33
- * A gradient fill or stroke, in the node's own coordinates. The color addon builds these with perceptual colour steps.
34
- * @typedef {{ type: 'linear', x0: number, y0: number, x1: number, y1: number, stops: [number, string][] }
35
- * | { type: 'radial', x0: number, y0: number, r0: number, x1: number, y1: number, r1: number, stops: [number, string][] }
36
- * } Gradient
37
- */
38
-
39
- /**
40
- * Props only groups and component instances take.
41
- * @typedef {object} LayerProps
42
- * @property {{ node: Node, mode?: 'alpha' | 'alpha-inverted' | 'luma' | 'luma-inverted' }} [matte] Shows the group only
43
- * where `node` is drawn (alpha) or bright (luma). The matte node uses the group's coordinates and time and is not
44
- * drawn itself.
45
- * @property {Value<boolean>} [isolate] Composites the children as one layer, so opacity and blend apply to the whole.
46
- * @property {Value<number>} [time] Remaps time for the children: they see time(t) instead of t, as a precomp does.
47
- * @property {{ samples?: number, shutter?: number }} [motionBlur] Averages `samples` (default 8) moments across
48
- * `shutter` seconds (default 1/60) centred on t, including the group's own motion.
49
- * @property {Value<ReadonlyArray<Effect>>} [effects] Image effects applied to the group as one layer, in order, such
50
- * as those the fx addon builds.
51
- */
52
-
53
- /**
54
- * An image effect on a layer. Each parameter may be a Value; missing ones take the defaults in EFFECTS.
55
- * @typedef {{ type: keyof typeof EFFECTS } & Record<string, any>} Effect
56
- */
57
-
58
- /**
59
- * Effect types and their parameters' defaults. Sizes are scene px. blur softens; glow adds a blurred copy of what is
60
- * brighter than `threshold`; diffusion is the soft bloom of anime photography (satsuei); grain adds film noise;
61
- * para lays a gradient over the layer with a blend mode, inside its shape; vignette darkens toward the edges.
62
- */
63
- export const EFFECTS = Object.freeze({
64
- blur: Object.freeze({ radius: 4 }),
65
- glow: Object.freeze({ radius: 12, strength: 1, threshold: 0.6 }),
66
- diffusion: Object.freeze({ radius: 16, strength: 0.5 }),
67
- grain: Object.freeze({ amount: 0.08, size: 1.5, seed: 0 }),
68
- para: Object.freeze({ from: 'rgba(255, 255, 255, 0.5)', to: 'rgba(255, 255, 255, 0)', angle: 90, blend: 'screen', opacity: 1 }),
69
- vignette: Object.freeze({ strength: 0.4, radius: 0.7 }),
70
- })
71
-
72
- /** Built-in transitions; a transition can also run GLSL written for gl-transitions. */
73
- export const TRANSITIONS = Object.freeze(['fade', 'wipe', 'slide', 'circle', 'zoom', 'dissolve'])
74
-
75
- /**
76
- * Offsets for one unit (grapheme, word or line) of a split text, relative to where the text layout puts it.
77
- * @typedef {object} UnitStyle
78
- * @property {number} [x]
79
- * @property {number} [y]
80
- * @property {number} [rotation] Degrees around the unit's centre on the baseline.
81
- * @property {number} [scale]
82
- * @property {number} [opacity] Multiplied into the text's opacity.
83
- * @property {string} [fill]
84
- */
85
-
86
- /**
87
- * Gives unit i of n its style at time t. `units` is every unit, for functions that skip spaces or look at neighbours.
88
- * @typedef {(i: number, n: number, t: number, unit: string, units: readonly string[]) => UnitStyle | null | undefined} UnitFn
89
- */
90
-
91
- /**
92
- * @typedef {object} ShapeStyle
93
- * @property {Value<string | Gradient>} [fill] A CSS colour or a gradient. Black when neither fill nor stroke is given,
94
- * as in SVG.
95
- * @property {Value<string | Gradient>} [stroke]
96
- * @property {Value<number>} [strokeWidth]
97
- * @property {Value<'butt' | 'round' | 'square'>} [lineCap]
98
- * @property {Value<'miter' | 'round' | 'bevel'>} [lineJoin]
99
- * @property {Value<number[]>} [dash]
100
- * @property {Value<number>} [dashOffset]
101
- */
102
-
103
- /** @typedef {CommonProps & ShapeStyle & { path: Value<Path> }} ShapeProps */
104
- /** @typedef {CommonProps & ShapeStyle & { w: Value<number>, h: Value<number>, radius?: Value<number | number[]> }} RectProps */
105
- /** @typedef {CommonProps & ShapeStyle & { w: Value<number>, h: Value<number> }} EllipseProps */
106
- /**
107
- * @typedef {CommonProps & {
108
- * text: Value<string>, font?: Value<string>, align?: Value<'left' | 'right' | 'center' | 'start' | 'end'>,
109
- * baseline?: Value<'top' | 'hanging' | 'middle' | 'alphabetic' | 'ideographic' | 'bottom'>,
110
- * fill?: Value<string | Gradient>, stroke?: Value<string | Gradient>, strokeWidth?: Value<number>,
111
- * lineHeight?: Value<number>, width?: Value<number>,
112
- * split?: Value<'grapheme' | 'word' | 'line'>, perUnit?: UnitFn | UnitFn[]
113
- * }} TextProps
114
- * lineHeight is in px (default 1.2 times the font size); width wraps lines at spaces. split cuts the text into units
115
- * and perUnit gives each unit its offsets at time t.
116
- */
117
- /**
118
- * @typedef {CommonProps & { src: Value<string>, w?: Value<number>, h?: Value<number>,
119
- * crop?: Value<readonly [number, number, number, number]>, smooth?: Value<boolean> }} ImageProps
120
- * crop is [x, y, w, h] of the source image to draw, for sprite sheets; w and h default to the crop's size. smooth: false
121
- * keeps pixel art sharp when scaled.
122
- */
123
-
124
- /**
125
- * @typedef {CommonProps & { src: Value<string>, time?: Value<number>, w?: Value<number>, h?: Value<number>,
126
- * crop?: Value<readonly [number, number, number, number]>, smooth?: Value<boolean> }} VideoProps
127
- * src names a key of the scene's assets.videos; time is the moment of the footage to show, in its own seconds, and
128
- * defaults to the node's local time.
129
- */
130
-
131
- /**
132
- * Numbers per copy in an instances node's data: x, y, rotation in degrees, scale x, scale y, opacity, and an index
133
- * into `colors` (-1 keeps the base's own fill).
134
- */
135
- export const STRIDE = 7
136
-
137
- /**
138
- * @typedef {CommonProps & { base: Node, data: Value<Float32Array | Float64Array>, colors?: string[] }} InstancesProps
139
- * base is drawn once per copy. data must be a new array on every call, never one reused between frames.
140
- */
141
- /** @typedef {CommonProps & { draw: (ctx: any, t: number) => void }} DrawProps */
142
-
143
- /**
144
- * @typedef {object} Node
145
- * @property {string} kind
146
- * @property {Readonly<Record<string, any>>} props
147
- * @property {ReadonlyArray<Node> | ((t: number) => ReadonlyArray<Node>)} [children]
148
- */
149
-
150
- export const COMMON = ['id', 'x', 'y', 'rotation', 'scale', 'skew', 'anchor', 'opacity', 'visible', 'z', 'blend']
151
- const STYLE = ['fill', 'stroke', 'strokeWidth', 'lineCap', 'lineJoin', 'dash', 'dashOffset']
152
- const LAYER = ['matte', 'isolate', 'time', 'motionBlur', 'effects']
153
-
154
- /** Properties each kind of node accepts besides COMMON. */
155
- export const KIND_PROPS = Object.freeze({
156
- group: LAYER,
157
- timeline: [],
158
- instance: LAYER,
159
- shape: ['path', ...STYLE],
160
- rect: ['w', 'h', 'radius', ...STYLE],
161
- ellipse: ['w', 'h', ...STYLE],
162
- text: ['text', 'font', 'align', 'baseline', 'fill', 'stroke', 'strokeWidth', 'lineHeight', 'width', 'split', 'perUnit'],
163
- image: ['src', 'w', 'h', 'crop', 'smooth'],
164
- video: ['src', 'time', 'w', 'h', 'crop', 'smooth'],
165
- mesh: ['src', 'points', 'uvs', 'triangles', 'smooth'],
166
- transition: ['progress', 'effect', 'params', 'box'],
167
- draw: ['draw'],
168
- instances: ['base', 'data', 'colors'],
169
- })
170
-
171
- /** @type {Record<string, string[]>} */
172
- const REQUIRED = {
173
- shape: ['path'], rect: ['w', 'h'], ellipse: ['w', 'h'], text: ['text'], image: ['src'], video: ['src'], mesh: ['src', 'points', 'uvs', 'triangles'], transition: ['progress'], draw: ['draw'], instances: ['base', 'data'],
174
- }
175
- const INSTANCE_BASES = ['shape', 'rect', 'ellipse', 'text', 'image']
176
-
177
- export const ID_PATTERN = /^[A-Za-z0-9_-]+$/
178
-
179
- /**
180
- * Checks a node's props and returns them frozen.
181
- * @param {keyof typeof KIND_PROPS} kind
182
- * @param {Record<string, any>} props
183
- */
184
- export function checkProps(kind, props) {
185
- if (props === null || typeof props !== 'object') throw new TypeError(`${kind}: props must be an object`)
186
- const allowed = /** @type {readonly string[]} */ (KIND_PROPS[kind])
187
- for (const name of Object.keys(props)) {
188
- if (!COMMON.includes(name) && !allowed.includes(name)) {
189
- throw new TypeError(`${kind}: unknown prop "${name}". It takes ${[...COMMON, ...allowed].join(', ')}`)
190
- }
191
- }
192
- for (const name of REQUIRED[kind] ?? []) {
193
- if (props[name] === undefined) throw new TypeError(`${kind}: "${name}" is required`)
194
- }
195
- if (props.id !== undefined && (typeof props.id !== 'string' || !ID_PATTERN.test(props.id))) {
196
- throw new TypeError(`${kind}: id "${props.id}" may only use letters, digits, - and _`)
197
- }
198
- if (kind === 'draw' && typeof props.draw !== 'function') throw new TypeError('draw: "draw" must be a function (ctx, t) => void')
199
- const { matte, motionBlur, perUnit } = props
200
- if (matte !== undefined) {
201
- if (!matte || !isNode(matte.node)) throw new TypeError(`${kind}: matte must be { node, mode }, with a node to cut by`)
202
- if (!MATTE_MODES.includes(matte.mode ?? 'alpha')) {
203
- throw new RangeError(`${kind}: matte mode must be ${MATTE_MODES.join(', ')}, got ${matte.mode}`)
204
- }
205
- }
206
- if (motionBlur !== undefined) {
207
- const { samples = 8, shutter = 1 / 60 } = motionBlur ?? {}
208
- if (!Number.isInteger(samples) || samples < 2) throw new RangeError(`${kind}: motionBlur samples must be a whole number of 2 or more`)
209
- if (!(shutter >= 0)) throw new RangeError(`${kind}: motionBlur shutter must be 0 or more seconds`)
210
- }
211
- if (kind === 'instances' && !(isNode(props.base) && INSTANCE_BASES.includes(props.base.kind))) {
212
- throw new TypeError(`instances: base must be a ${INSTANCE_BASES.join(', ')} node`)
213
- }
214
- if (perUnit !== undefined && ![perUnit].flat().every(f => typeof f === 'function')) {
215
- throw new TypeError(`${kind}: perUnit must be a function (i, n, t, unit) => style, or a list of them`)
216
- }
217
- return Object.freeze({ ...props })
218
- }
219
-
220
- const MATTE_MODES = ['alpha', 'alpha-inverted', 'luma', 'luma-inverted']
221
-
222
- /** @param {unknown} value */
223
- export const isNode = value =>
224
- value !== null && typeof value === 'object' && typeof (/** @type {any} */ (value).kind) === 'string' && 'props' in value
225
-
226
- /**
227
- * @param {ReadonlyArray<Node> | ((t: number) => ReadonlyArray<Node>)} children
228
- * @param {string} owner
229
- */
230
- function checkChildren(children, owner) {
231
- if (typeof children === 'function') return children
232
- if (!Array.isArray(children)) throw new TypeError(`${owner}: children must be an array of nodes or a function of t`)
233
- children.forEach((child, i) => {
234
- if (!isNode(child)) throw new TypeError(`${owner}: child ${i} is not a node`)
235
- })
236
- return Object.freeze([...children])
237
- }
238
-
239
- /**
240
- * Holds other nodes and moves, turns, scales or fades them together. Children may also be a function of time that
241
- * returns nodes, for structure that changes; it must be pure like every other Value.
242
- * @param {CommonProps & LayerProps} [props]
243
- * @param {ReadonlyArray<Node> | ((t: number) => ReadonlyArray<Node>)} [children]
244
- * @returns {Node}
245
- */
246
- export function group(props = {}, children = []) {
247
- return Object.freeze({ kind: 'group', props: checkProps('group', props), children: checkChildren(children, 'group') })
248
- }
249
-
250
- /** @param {ShapeProps} props @returns {Node} */
251
- export const shape = props => Object.freeze({ kind: 'shape', props: checkProps('shape', props) })
252
-
253
- /** A rectangle from (0, 0) to (w, h), with an optional corner radius. @param {RectProps} props @returns {Node} */
254
- export const rect = props => Object.freeze({ kind: 'rect', props: checkProps('rect', props) })
255
-
256
- /** An ellipse filling the box from (0, 0) to (w, h). @param {EllipseProps} props @returns {Node} */
257
- export const ellipse = props => Object.freeze({ kind: 'ellipse', props: checkProps('ellipse', props) })
258
-
259
- /** @param {TextProps} props @returns {Node} */
260
- export const text = props => Object.freeze({ kind: 'text', props: checkProps('text', props) })
261
-
262
- /** `src` names a key of the scene's `assets.images`. @param {ImageProps} props @returns {Node} */
263
- export const image = props => Object.freeze({ kind: 'image', props: checkProps('image', props) })
264
-
265
- /**
266
- * @typedef {CommonProps & { src: Value<string>, points: Value<ArrayLike<number>>, uvs: ArrayLike<number>,
267
- * triangles: ArrayLike<number>, smooth?: Value<boolean> }} MeshProps
268
- * points are the vertices as x, y pairs in node space, uvs the matching places in the image in px, and triangles
269
- * three vertex indices each. Moving the points bends the image, as an ArtMesh in Live2D or a mesh in Spine does.
270
- */
271
-
272
- /**
273
- * An image drawn through a triangle mesh whose points can move, for rigs made from cut-out pictures.
274
- * @param {MeshProps} props
275
- * @returns {Node}
276
- */
277
- export const mesh = props => Object.freeze({ kind: 'mesh', props: checkProps('mesh', props) })
278
-
279
- /**
280
- * @typedef {CommonProps & { progress: Value<number>, effect?: Value<string | { glsl: string }>,
281
- * params?: Value<Record<string, number | number[]>>, box?: Value<readonly [number, number, number, number]> }} TransitionProps
282
- * progress runs 0 (all `from`) to 1 (all `to`). effect is one of TRANSITIONS, default 'fade', or GLSL written for
283
- * gl-transitions (a `vec4 transition(vec2 uv)` using getFromColor, getToColor, progress and ratio), which only the
284
- * WebGL2 renderer runs; params sets the effect's own uniforms or options. Without `box` the transition plays across
285
- * the whole frame, as a cut between shots does; box (x, y, w, h in node space) plays it across that area instead,
286
- * such as a phone screen, and draws nothing outside it.
287
- */
288
-
289
- /**
290
- * Two nodes mixed by a transition, such as a wipe from one shot to the next.
291
- * @param {TransitionProps} props
292
- * @param {[Node, Node]} children from, then to.
293
- * @returns {Node}
294
- */
295
- export function transition(props, children) {
296
- if (!Array.isArray(children) || children.length !== 2 || !children.every(isNode)) {
297
- throw new TypeError('transition: give two nodes, [from, to]')
298
- }
299
- const effect = props.effect
300
- if (typeof effect === 'string' && !TRANSITIONS.includes(effect)) {
301
- throw new RangeError(`transition: effect must be one of ${TRANSITIONS.join(', ')}, or { glsl }`)
302
- }
303
- return Object.freeze({ kind: 'transition', props: checkProps('transition', props), children: Object.freeze([...children]) })
304
- }
305
-
306
- /**
307
- * A frame of footage from the scene's `assets.videos`, chosen by `time`. Renderers decode frames ahead of drawing,
308
- * so the exact frame for every time is shown.
309
- * @param {VideoProps} props
310
- * @returns {Node}
311
- */
312
- export const video = props => Object.freeze({ kind: 'video', props: checkProps('video', props) })
313
-
314
- /**
315
- * Many copies of one base node in a single display item, for cloners and particles: each copy is STRIDE numbers in
316
- * `data`. Drawing hundreds of copies this way costs one item instead of hundreds of nodes.
317
- * @param {InstancesProps} props
318
- * @returns {Node}
319
- */
320
- export const instances = props => Object.freeze({ kind: 'instances', props: checkProps('instances', props) })
321
-
322
- /**
323
- * Free drawing with the canvas API. `ctx` already carries the node's transform and opacity, and the function must
324
- * draw the same thing every time it gets the same t.
325
- * @param {DrawProps} props
326
- * @returns {Node}
327
- */
328
- export const draw = props => Object.freeze({ kind: 'draw', props: checkProps('draw', props) })
1
+ /** @typedef {import('./path.js').Path} Path */
2
+
3
+ /**
4
+ * @template T
5
+ * @typedef {import('./math.js').Value<T>} Value
6
+ */
7
+
8
+ /**
9
+ * Properties every node takes. Each may be a constant or a function of the node's local time.
10
+ * @typedef {object} CommonProps
11
+ * @property {string} [id] Stable name, unique in a scene; letters, digits, - and _ only.
12
+ * @property {Value<number>} [x] Position in px, relative to the parent.
13
+ * @property {Value<number>} [y]
14
+ * @property {Value<number>} [rotation] Degrees, clockwise.
15
+ * @property {Value<number | [number, number]>} [scale]
16
+ * @property {Value<number>} [skew] Degrees, shearing x along y like CSS skewX, applied between rotation and scale.
17
+ * @property {Value<[number, number]>} [anchor] The point, in px from the node's origin, that x and y place and that
18
+ * rotation and scale turn around.
19
+ * @property {Value<number>} [opacity] 0..1, multiplied into every child.
20
+ * @property {Value<boolean>} [visible] false skips the node and its children.
21
+ * @property {Value<number>} [z] Draw order within the parent: higher is in front; ties keep code order.
22
+ * @property {Value<BlendMode>} [blend] How the node mixes with what is under it. On a group it blends the group as
23
+ * one layer.
24
+ */
25
+
26
+ /**
27
+ * @typedef {'normal' | 'multiply' | 'screen' | 'overlay' | 'darken' | 'lighten' | 'color-dodge' | 'color-burn'
28
+ * | 'hard-light' | 'soft-light' | 'difference' | 'exclusion' | 'hue' | 'saturation' | 'color' | 'luminosity'
29
+ * | 'add'} BlendMode
30
+ */
31
+
32
+ /**
33
+ * A gradient fill or stroke, in the node's own coordinates. The color addon builds these with perceptual colour steps.
34
+ * @typedef {{ type: 'linear', x0: number, y0: number, x1: number, y1: number, stops: [number, string][] }
35
+ * | { type: 'radial', x0: number, y0: number, r0: number, x1: number, y1: number, r1: number, stops: [number, string][] }
36
+ * } Gradient
37
+ */
38
+
39
+ /**
40
+ * Props only groups and component instances take.
41
+ * @typedef {object} LayerProps
42
+ * @property {{ node: Node, mode?: 'alpha' | 'alpha-inverted' | 'luma' | 'luma-inverted' }} [matte] Shows the group only
43
+ * where `node` is drawn (alpha) or bright (luma). The matte node uses the group's coordinates and time and is not
44
+ * drawn itself.
45
+ * @property {Value<boolean>} [isolate] Composites the children as one layer, so opacity and blend apply to the whole.
46
+ * @property {Value<number>} [time] Remaps time for the children: they see time(t) instead of t, as a precomp does.
47
+ * @property {{ samples?: number, shutter?: number }} [motionBlur] Averages `samples` (default 8) moments across
48
+ * `shutter` seconds (default 1/60) centred on t, including the group's own motion.
49
+ * @property {Value<ReadonlyArray<Effect>>} [effects] Image effects applied to the group as one layer, in order, such
50
+ * as those the fx addon builds.
51
+ */
52
+
53
+ /**
54
+ * An image effect on a layer. Each parameter may be a Value; missing ones take the defaults in EFFECTS.
55
+ * @typedef {{ type: keyof typeof EFFECTS } & Record<string, any>} Effect
56
+ */
57
+
58
+ /**
59
+ * Effect types and their parameters' defaults. Sizes are scene px. blur softens; glow adds a blurred copy of what is
60
+ * brighter than `threshold`; diffusion is the soft bloom of anime photography (satsuei); grain adds film noise;
61
+ * para lays a gradient over the layer with a blend mode, inside its shape; vignette darkens toward the edges.
62
+ */
63
+ export const EFFECTS = Object.freeze({
64
+ blur: Object.freeze({ radius: 4 }),
65
+ glow: Object.freeze({ radius: 12, strength: 1, threshold: 0.6 }),
66
+ diffusion: Object.freeze({ radius: 16, strength: 0.5 }),
67
+ grain: Object.freeze({ amount: 0.08, size: 1.5, seed: 0 }),
68
+ para: Object.freeze({ from: 'rgba(255, 255, 255, 0.5)', to: 'rgba(255, 255, 255, 0)', angle: 90, blend: 'screen', opacity: 1 }),
69
+ vignette: Object.freeze({ strength: 0.4, radius: 0.7 }),
70
+ })
71
+
72
+ /** Built-in transitions; a transition can also run GLSL written for gl-transitions. */
73
+ export const TRANSITIONS = Object.freeze(['fade', 'wipe', 'slide', 'circle', 'zoom', 'dissolve'])
74
+
75
+ /**
76
+ * Offsets for one unit (grapheme, word or line) of a split text, relative to where the text layout puts it.
77
+ * @typedef {object} UnitStyle
78
+ * @property {number} [x]
79
+ * @property {number} [y]
80
+ * @property {number} [rotation] Degrees around the unit's centre on the baseline.
81
+ * @property {number} [scale]
82
+ * @property {number} [opacity] Multiplied into the text's opacity.
83
+ * @property {string} [fill]
84
+ */
85
+
86
+ /**
87
+ * Gives unit i of n its style at time t. `units` is every unit, for functions that skip spaces or look at neighbours.
88
+ * @typedef {(i: number, n: number, t: number, unit: string, units: readonly string[]) => UnitStyle | null | undefined} UnitFn
89
+ */
90
+
91
+ /**
92
+ * @typedef {object} ShapeStyle
93
+ * @property {Value<string | Gradient>} [fill] A CSS colour or a gradient. Black when neither fill nor stroke is given,
94
+ * as in SVG.
95
+ * @property {Value<string | Gradient>} [stroke]
96
+ * @property {Value<number>} [strokeWidth]
97
+ * @property {Value<'butt' | 'round' | 'square'>} [lineCap]
98
+ * @property {Value<'miter' | 'round' | 'bevel'>} [lineJoin]
99
+ * @property {Value<number[]>} [dash]
100
+ * @property {Value<number>} [dashOffset]
101
+ */
102
+
103
+ /** @typedef {CommonProps & ShapeStyle & { path: Value<Path> }} ShapeProps */
104
+ /** @typedef {CommonProps & ShapeStyle & { w: Value<number>, h: Value<number>, radius?: Value<number | number[]> }} RectProps */
105
+ /** @typedef {CommonProps & ShapeStyle & { w: Value<number>, h: Value<number> }} EllipseProps */
106
+ /**
107
+ * @typedef {CommonProps & {
108
+ * text: Value<string>, font?: Value<string>, align?: Value<'left' | 'right' | 'center' | 'start' | 'end'>,
109
+ * baseline?: Value<'top' | 'hanging' | 'middle' | 'alphabetic' | 'ideographic' | 'bottom'>,
110
+ * fill?: Value<string | Gradient>, stroke?: Value<string | Gradient>, strokeWidth?: Value<number>,
111
+ * lineHeight?: Value<number>, width?: Value<number>,
112
+ * split?: Value<'grapheme' | 'word' | 'line'>, perUnit?: UnitFn | UnitFn[]
113
+ * }} TextProps
114
+ * lineHeight is in px (default 1.2 times the font size); width wraps lines at spaces. split cuts the text into units
115
+ * and perUnit gives each unit its offsets at time t.
116
+ */
117
+ /**
118
+ * @typedef {CommonProps & { src: Value<string>, w?: Value<number>, h?: Value<number>,
119
+ * crop?: Value<readonly [number, number, number, number]>, smooth?: Value<boolean> }} ImageProps
120
+ * crop is [x, y, w, h] of the source image to draw, for sprite sheets; w and h default to the crop's size. smooth: false
121
+ * keeps pixel art sharp when scaled.
122
+ */
123
+
124
+ /**
125
+ * @typedef {CommonProps & { src: Value<string>, time?: Value<number>, w?: Value<number>, h?: Value<number>,
126
+ * crop?: Value<readonly [number, number, number, number]>, smooth?: Value<boolean> }} VideoProps
127
+ * src names a key of the scene's assets.videos; time is the moment of the footage to show, in its own seconds, and
128
+ * defaults to the node's local time.
129
+ */
130
+
131
+ /**
132
+ * Numbers per copy in an instances node's data: x, y, rotation in degrees, scale x, scale y, opacity, and an index
133
+ * into `colors` (-1 keeps the base's own fill).
134
+ */
135
+ export const STRIDE = 7
136
+
137
+ /**
138
+ * @typedef {CommonProps & { base: Node, data: Value<Float32Array | Float64Array>, colors?: string[] }} InstancesProps
139
+ * base is drawn once per copy. data must be a new array on every call, never one reused between frames.
140
+ */
141
+ /** @typedef {CommonProps & { draw: (ctx: any, t: number) => void }} DrawProps */
142
+
143
+ /**
144
+ * @typedef {object} Node
145
+ * @property {string} kind
146
+ * @property {Readonly<Record<string, any>>} props
147
+ * @property {ReadonlyArray<Node> | ((t: number) => ReadonlyArray<Node>)} [children]
148
+ */
149
+
150
+ export const COMMON = ['id', 'x', 'y', 'rotation', 'scale', 'skew', 'anchor', 'opacity', 'visible', 'z', 'blend']
151
+ const STYLE = ['fill', 'stroke', 'strokeWidth', 'lineCap', 'lineJoin', 'dash', 'dashOffset']
152
+ const LAYER = ['matte', 'isolate', 'time', 'motionBlur', 'effects']
153
+
154
+ /** Properties each kind of node accepts besides COMMON. */
155
+ export const KIND_PROPS = Object.freeze({
156
+ group: LAYER,
157
+ timeline: [],
158
+ instance: LAYER,
159
+ shape: ['path', ...STYLE],
160
+ rect: ['w', 'h', 'radius', ...STYLE],
161
+ ellipse: ['w', 'h', ...STYLE],
162
+ text: ['text', 'font', 'align', 'baseline', 'fill', 'stroke', 'strokeWidth', 'lineHeight', 'width', 'split', 'perUnit'],
163
+ image: ['src', 'w', 'h', 'crop', 'smooth'],
164
+ video: ['src', 'time', 'w', 'h', 'crop', 'smooth'],
165
+ mesh: ['src', 'points', 'uvs', 'triangles', 'smooth'],
166
+ transition: ['progress', 'effect', 'params', 'box'],
167
+ draw: ['draw'],
168
+ instances: ['base', 'data', 'colors'],
169
+ })
170
+
171
+ /** @type {Record<string, string[]>} */
172
+ const REQUIRED = {
173
+ shape: ['path'], rect: ['w', 'h'], ellipse: ['w', 'h'], text: ['text'], image: ['src'], video: ['src'], mesh: ['src', 'points', 'uvs', 'triangles'], transition: ['progress'], draw: ['draw'], instances: ['base', 'data'],
174
+ }
175
+ const INSTANCE_BASES = ['shape', 'rect', 'ellipse', 'text', 'image']
176
+
177
+ export const ID_PATTERN = /^[A-Za-z0-9_-]+$/
178
+
179
+ /**
180
+ * Checks a node's props and returns them frozen.
181
+ * @param {keyof typeof KIND_PROPS} kind
182
+ * @param {Record<string, any>} props
183
+ */
184
+ export function checkProps(kind, props) {
185
+ if (props === null || typeof props !== 'object') throw new TypeError(`${kind}: props must be an object`)
186
+ const allowed = /** @type {readonly string[]} */ (KIND_PROPS[kind])
187
+ for (const name of Object.keys(props)) {
188
+ if (!COMMON.includes(name) && !allowed.includes(name)) {
189
+ throw new TypeError(`${kind}: unknown prop "${name}". It takes ${[...COMMON, ...allowed].join(', ')}`)
190
+ }
191
+ }
192
+ for (const name of REQUIRED[kind] ?? []) {
193
+ if (props[name] === undefined) throw new TypeError(`${kind}: "${name}" is required`)
194
+ }
195
+ if (props.id !== undefined && (typeof props.id !== 'string' || !ID_PATTERN.test(props.id))) {
196
+ throw new TypeError(`${kind}: id "${props.id}" may only use letters, digits, - and _`)
197
+ }
198
+ if (kind === 'draw' && typeof props.draw !== 'function') throw new TypeError('draw: "draw" must be a function (ctx, t) => void')
199
+ const { matte, motionBlur, perUnit } = props
200
+ if (matte !== undefined) {
201
+ if (!matte || !isNode(matte.node)) throw new TypeError(`${kind}: matte must be { node, mode }, with a node to cut by`)
202
+ if (!MATTE_MODES.includes(matte.mode ?? 'alpha')) {
203
+ throw new RangeError(`${kind}: matte mode must be ${MATTE_MODES.join(', ')}, got ${matte.mode}`)
204
+ }
205
+ }
206
+ if (motionBlur !== undefined) {
207
+ const { samples = 8, shutter = 1 / 60 } = motionBlur ?? {}
208
+ if (!Number.isInteger(samples) || samples < 2) throw new RangeError(`${kind}: motionBlur samples must be a whole number of 2 or more`)
209
+ if (!(shutter >= 0)) throw new RangeError(`${kind}: motionBlur shutter must be 0 or more seconds`)
210
+ }
211
+ if (kind === 'instances' && !(isNode(props.base) && INSTANCE_BASES.includes(props.base.kind))) {
212
+ throw new TypeError(`instances: base must be a ${INSTANCE_BASES.join(', ')} node`)
213
+ }
214
+ if (perUnit !== undefined && ![perUnit].flat().every(f => typeof f === 'function')) {
215
+ throw new TypeError(`${kind}: perUnit must be a function (i, n, t, unit) => style, or a list of them`)
216
+ }
217
+ return Object.freeze({ ...props })
218
+ }
219
+
220
+ const MATTE_MODES = ['alpha', 'alpha-inverted', 'luma', 'luma-inverted']
221
+
222
+ /** @param {unknown} value */
223
+ export const isNode = value =>
224
+ value !== null && typeof value === 'object' && typeof (/** @type {any} */ (value).kind) === 'string' && 'props' in value
225
+
226
+ /**
227
+ * @param {ReadonlyArray<Node> | ((t: number) => ReadonlyArray<Node>)} children
228
+ * @param {string} owner
229
+ */
230
+ function checkChildren(children, owner) {
231
+ if (typeof children === 'function') return children
232
+ if (!Array.isArray(children)) throw new TypeError(`${owner}: children must be an array of nodes or a function of t`)
233
+ children.forEach((child, i) => {
234
+ if (!isNode(child)) throw new TypeError(`${owner}: child ${i} is not a node`)
235
+ })
236
+ return Object.freeze([...children])
237
+ }
238
+
239
+ /**
240
+ * Holds other nodes and moves, turns, scales or fades them together. Children may also be a function of time that
241
+ * returns nodes, for structure that changes; it must be pure like every other Value.
242
+ * @param {CommonProps & LayerProps} [props]
243
+ * @param {ReadonlyArray<Node> | ((t: number) => ReadonlyArray<Node>)} [children]
244
+ * @returns {Node}
245
+ */
246
+ export function group(props = {}, children = []) {
247
+ return Object.freeze({ kind: 'group', props: checkProps('group', props), children: checkChildren(children, 'group') })
248
+ }
249
+
250
+ /** @param {ShapeProps} props @returns {Node} */
251
+ export const shape = props => Object.freeze({ kind: 'shape', props: checkProps('shape', props) })
252
+
253
+ /** A rectangle from (0, 0) to (w, h), with an optional corner radius. @param {RectProps} props @returns {Node} */
254
+ export const rect = props => Object.freeze({ kind: 'rect', props: checkProps('rect', props) })
255
+
256
+ /** An ellipse filling the box from (0, 0) to (w, h). @param {EllipseProps} props @returns {Node} */
257
+ export const ellipse = props => Object.freeze({ kind: 'ellipse', props: checkProps('ellipse', props) })
258
+
259
+ /** @param {TextProps} props @returns {Node} */
260
+ export const text = props => Object.freeze({ kind: 'text', props: checkProps('text', props) })
261
+
262
+ /** `src` names a key of the scene's `assets.images`. @param {ImageProps} props @returns {Node} */
263
+ export const image = props => Object.freeze({ kind: 'image', props: checkProps('image', props) })
264
+
265
+ /**
266
+ * @typedef {CommonProps & { src: Value<string>, points: Value<ArrayLike<number>>, uvs: ArrayLike<number>,
267
+ * triangles: ArrayLike<number>, smooth?: Value<boolean> }} MeshProps
268
+ * points are the vertices as x, y pairs in node space, uvs the matching places in the image in px, and triangles
269
+ * three vertex indices each. Moving the points bends the image, as an ArtMesh in Live2D or a mesh in Spine does.
270
+ */
271
+
272
+ /**
273
+ * An image drawn through a triangle mesh whose points can move, for rigs made from cut-out pictures.
274
+ * @param {MeshProps} props
275
+ * @returns {Node}
276
+ */
277
+ export const mesh = props => Object.freeze({ kind: 'mesh', props: checkProps('mesh', props) })
278
+
279
+ /**
280
+ * @typedef {CommonProps & { progress: Value<number>, effect?: Value<string | { glsl: string }>,
281
+ * params?: Value<Record<string, number | number[]>>, box?: Value<readonly [number, number, number, number]> }} TransitionProps
282
+ * progress runs 0 (all `from`) to 1 (all `to`). effect is one of TRANSITIONS, default 'fade', or GLSL written for
283
+ * gl-transitions (a `vec4 transition(vec2 uv)` using getFromColor, getToColor, progress and ratio), which only the
284
+ * WebGL2 renderer runs; params sets the effect's own uniforms or options. Without `box` the transition plays across
285
+ * the whole frame, as a cut between shots does; box (x, y, w, h in node space) plays it across that area instead,
286
+ * such as a phone screen, and draws nothing outside it.
287
+ */
288
+
289
+ /**
290
+ * Two nodes mixed by a transition, such as a wipe from one shot to the next.
291
+ * @param {TransitionProps} props
292
+ * @param {[Node, Node]} children from, then to.
293
+ * @returns {Node}
294
+ */
295
+ export function transition(props, children) {
296
+ if (!Array.isArray(children) || children.length !== 2 || !children.every(isNode)) {
297
+ throw new TypeError('transition: give two nodes, [from, to]')
298
+ }
299
+ const effect = props.effect
300
+ if (typeof effect === 'string' && !TRANSITIONS.includes(effect)) {
301
+ throw new RangeError(`transition: effect must be one of ${TRANSITIONS.join(', ')}, or { glsl }`)
302
+ }
303
+ return Object.freeze({ kind: 'transition', props: checkProps('transition', props), children: Object.freeze([...children]) })
304
+ }
305
+
306
+ /**
307
+ * A frame of footage from the scene's `assets.videos`, chosen by `time`. Renderers decode frames ahead of drawing,
308
+ * so the exact frame for every time is shown.
309
+ * @param {VideoProps} props
310
+ * @returns {Node}
311
+ */
312
+ export const video = props => Object.freeze({ kind: 'video', props: checkProps('video', props) })
313
+
314
+ /**
315
+ * Many copies of one base node in a single display item, for cloners and particles: each copy is STRIDE numbers in
316
+ * `data`. Drawing hundreds of copies this way costs one item instead of hundreds of nodes.
317
+ * @param {InstancesProps} props
318
+ * @returns {Node}
319
+ */
320
+ export const instances = props => Object.freeze({ kind: 'instances', props: checkProps('instances', props) })
321
+
322
+ /**
323
+ * Free drawing with the canvas API. `ctx` already carries the node's transform and opacity, and the function must
324
+ * draw the same thing every time it gets the same t.
325
+ * @param {DrawProps} props
326
+ * @returns {Node}
327
+ */
328
+ export const draw = props => Object.freeze({ kind: 'draw', props: checkProps('draw', props) })