motlab.js 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/LICENSE +21 -0
  3. package/README.md +86 -2
  4. package/docs/stability.md +53 -0
  5. package/llms.txt +794 -0
  6. package/package.json +107 -6
  7. package/src/adapters/canvas.js +68 -0
  8. package/src/adapters/lottie.js +102 -0
  9. package/src/adapters/pixi.js +62 -0
  10. package/src/adapters/rapier.js +163 -0
  11. package/src/adapters/rive.js +316 -0
  12. package/src/adapters/three.js +81 -0
  13. package/src/addons/audio.js +422 -0
  14. package/src/addons/camera.js +319 -0
  15. package/src/addons/cel.js +498 -0
  16. package/src/addons/clone.js +299 -0
  17. package/src/addons/color.js +223 -0
  18. package/src/addons/deform.js +441 -0
  19. package/src/addons/dom.js +68 -0
  20. package/src/addons/edit.js +317 -0
  21. package/src/addons/fx.js +64 -0
  22. package/src/addons/game.js +106 -0
  23. package/src/addons/input.js +209 -0
  24. package/src/addons/machine.js +240 -0
  25. package/src/addons/media.js +581 -0
  26. package/src/addons/particles.js +179 -0
  27. package/src/addons/path.js +596 -0
  28. package/src/addons/physics.js +980 -0
  29. package/src/addons/player.js +170 -0
  30. package/src/addons/rig.js +851 -0
  31. package/src/addons/text.js +133 -0
  32. package/src/addons/trace.js +456 -0
  33. package/src/core/combinators.js +129 -0
  34. package/src/core/component.js +90 -0
  35. package/src/core/dmath.js +256 -0
  36. package/src/core/ease.js +136 -0
  37. package/src/core/guard.js +139 -0
  38. package/src/core/hash.js +74 -0
  39. package/src/core/markers.js +49 -0
  40. package/src/core/math.js +43 -0
  41. package/src/core/nodes.js +328 -0
  42. package/src/core/noise.js +340 -0
  43. package/src/core/path.js +295 -0
  44. package/src/core/rand.js +135 -0
  45. package/src/core/scene.js +678 -0
  46. package/src/core/simulate.js +289 -0
  47. package/src/core/spring.js +129 -0
  48. package/src/core/timeline.js +193 -0
  49. package/src/core/track.js +258 -0
  50. package/src/core/verify.js +208 -0
  51. package/src/core/version.js +2 -0
  52. package/src/index.js +19 -0
  53. package/src/renderer/canvas2d.js +950 -0
  54. package/src/renderer/pixels.js +57 -0
  55. package/src/renderer/svg.js +589 -0
  56. package/src/renderer/text-layout.js +80 -0
  57. package/src/renderer/webgl2.js +1331 -0
  58. package/types/adapters/canvas.d.ts +46 -0
  59. package/types/adapters/lottie.d.ts +45 -0
  60. package/types/adapters/pixi.d.ts +46 -0
  61. package/types/adapters/rapier.d.ts +116 -0
  62. package/types/adapters/rive.d.ts +62 -0
  63. package/types/adapters/three.d.ts +51 -0
  64. package/types/addons/audio.d.ts +124 -0
  65. package/types/addons/camera.d.ts +134 -0
  66. package/types/addons/cel.d.ts +215 -0
  67. package/types/addons/clone.d.ts +167 -0
  68. package/types/addons/color.d.ts +73 -0
  69. package/types/addons/deform.d.ts +112 -0
  70. package/types/addons/dom.d.ts +68 -0
  71. package/types/addons/edit.d.ts +293 -0
  72. package/types/addons/fx.d.ts +65 -0
  73. package/types/addons/game.d.ts +78 -0
  74. package/types/addons/input.d.ts +56 -0
  75. package/types/addons/machine.d.ts +111 -0
  76. package/types/addons/media.d.ts +117 -0
  77. package/types/addons/particles.d.ts +110 -0
  78. package/types/addons/path.d.ts +61 -0
  79. package/types/addons/physics.d.ts +265 -0
  80. package/types/addons/player.d.ts +48 -0
  81. package/types/addons/rig.d.ts +273 -0
  82. package/types/addons/text.d.ts +63 -0
  83. package/types/addons/trace.d.ts +110 -0
  84. package/types/core/combinators.d.ts +73 -0
  85. package/types/core/component.d.ts +50 -0
  86. package/types/core/dmath.d.ts +52 -0
  87. package/types/core/ease.d.ts +50 -0
  88. package/types/core/guard.d.ts +23 -0
  89. package/types/core/hash.d.ts +6 -0
  90. package/types/core/markers.d.ts +52 -0
  91. package/types/core/math.d.ts +38 -0
  92. package/types/core/nodes.d.ts +442 -0
  93. package/types/core/noise.d.ts +65 -0
  94. package/types/core/path.d.ts +82 -0
  95. package/types/core/rand.d.ts +47 -0
  96. package/types/core/scene.d.ts +189 -0
  97. package/types/core/simulate.d.ts +169 -0
  98. package/types/core/spring.d.ts +41 -0
  99. package/types/core/timeline.d.ts +86 -0
  100. package/types/core/track.d.ts +58 -0
  101. package/types/core/verify.d.ts +42 -0
  102. package/types/core/version.d.ts +2 -0
  103. package/types/index.d.ts +18 -0
  104. package/types/renderer/canvas2d.d.ts +184 -0
  105. package/types/renderer/pixels.d.ts +28 -0
  106. package/types/renderer/svg.d.ts +19 -0
  107. package/types/renderer/text-layout.d.ts +45 -0
  108. package/types/renderer/webgl2.d.ts +71 -0
@@ -0,0 +1,498 @@
1
+ // Cel animation as studios time it: exposure sheets, drawing swaps in slots, indexed palettes and Aseprite sprites.
2
+ // Onion skin and light table are ordinary nodes, so they render and verify like the rest of the scene.
3
+ import { at } from '../core/math.js'
4
+ import { step } from '../core/combinators.js'
5
+ import { group, image, rect, isNode } from '../core/nodes.js'
6
+
7
+ /** @typedef {import('../core/nodes.js').Node} Node */
8
+ /** @typedef {import('../core/nodes.js').Gradient} Gradient */
9
+ /** @typedef {import('../core/nodes.js').CommonProps & import('../core/nodes.js').LayerProps} GroupProps */
10
+
11
+ /**
12
+ * @template T
13
+ * @typedef {import('../core/math.js').Value<T>} Value
14
+ */
15
+
16
+ // Matches the nudge in step(), so a frame time such as 10 / 30 lands on the frame it names.
17
+ const FRAME_EPSILON = 1e-9
18
+ const HOLD = new Set(['.', '|'])
19
+ const BLANK = new Set(['-', 'x', '×'])
20
+ const CELL = /^([^:]+)(?::(\d+))?$/
21
+
22
+ /**
23
+ * One column's cells, one token per frame: a drawing name, '.' or '|' to hold the drawing before, '-', 'x' or '×' for
24
+ * an empty cel. 'name:3' (or '.:3', '-:3') stands for that token on 3 frames.
25
+ * @param {string} name
26
+ * @param {string | ReadonlyArray<string | number | null>} column
27
+ * @returns {(string | null)[]}
28
+ */
29
+ function parseColumn(name, column) {
30
+ const tokens = typeof column === 'string'
31
+ ? column.trim().split(/\s+/).filter(Boolean)
32
+ : Array.isArray(column) ? column.map(c => (c === null ? '-' : String(c))) : null
33
+ if (tokens === null) throw new TypeError(`xsheet: column "${name}" must be a string of cells or an array`)
34
+ /** @type {(string | null)[]} */
35
+ const cells = []
36
+ for (const token of tokens) {
37
+ const match = CELL.exec(token)
38
+ if (!match) throw new SyntaxError(`xsheet: column "${name}" has a bad cell "${token}"`)
39
+ const count = match[2] === undefined ? 1 : Number(match[2])
40
+ if (!(count >= 1)) throw new RangeError(`xsheet: column "${name}": "${token}" must last at least 1 frame`)
41
+ const cell = match[1]
42
+ let value
43
+ if (HOLD.has(cell)) {
44
+ if (cells.length === 0) throw new SyntaxError(`xsheet: column "${name}" starts with "${cell}", but there is no drawing yet to hold`)
45
+ value = cells[cells.length - 1]
46
+ } else value = BLANK.has(cell) ? null : cell
47
+ for (let k = 0; k < count; k++) cells.push(value)
48
+ }
49
+ if (cells.length === 0) throw new RangeError(`xsheet: column "${name}" has no cells`)
50
+ return cells
51
+ }
52
+
53
+ /**
54
+ * @typedef {object} Xsheet
55
+ * @property {number} rate Frames per second the cells are written at.
56
+ * @property {number} frames Length of the longest column.
57
+ * @property {number} duration frames / rate, in seconds.
58
+ * @property {readonly string[]} columns
59
+ * @property {(column: string, t: number) => string | null} cell The drawing a column shows at t, or null for an
60
+ * empty cel.
61
+ * @property {(column: string) => (t: number) => string | null} column The same as a Value, for slot's `show`.
62
+ * @property {(column: string) => number[]} keys Times where a column changes drawing, for exposure-aware onion skin.
63
+ */
64
+
65
+ /**
66
+ * An exposure sheet. Each column is one cel layer, written frame by frame at `rate` fps whatever fps the scene renders
67
+ * at, so '1 . 2 . 3 .' is a column on twos.
68
+ * @param {{ rate?: number, end?: 'hold' | 'loop' | 'blank',
69
+ * columns: Record<string, string | ReadonlyArray<string | number | null>> }} options
70
+ * After its last cell each column holds it (end 'hold', the default), starts over ('loop', so a 16 frame walk cycle
71
+ * repeats beside a longer blink column), or shows nothing ('blank'). Before frame 0 the first cell shows, except
72
+ * when looping.
73
+ * @returns {Xsheet}
74
+ */
75
+ export function xsheet({ rate = 24, end = 'hold', columns }) {
76
+ if (!(rate > 0) || rate === Infinity) throw new RangeError(`xsheet: rate must be a positive number of frames per second, got ${rate}`)
77
+ if (end !== 'hold' && end !== 'loop' && end !== 'blank') throw new RangeError(`xsheet: end must be 'hold', 'loop' or 'blank', got ${end}`)
78
+ if (columns === null || typeof columns !== 'object') throw new TypeError('xsheet: columns must be an object of column name to cells')
79
+ /** @type {Map<string, (string | null)[]>} */
80
+ const sheet = new Map()
81
+ for (const [name, column] of Object.entries(columns)) sheet.set(name, parseColumn(name, column))
82
+ if (sheet.size === 0) throw new RangeError('xsheet: give at least one column')
83
+ const frames = Math.max(...[...sheet.values()].map(cells => cells.length))
84
+
85
+ /** @param {string} column */
86
+ const cellsOf = column => {
87
+ const cells = sheet.get(column)
88
+ if (!cells) throw new RangeError(`xsheet: no column "${column}". The sheet has ${[...sheet.keys()].join(', ')}`)
89
+ return cells
90
+ }
91
+
92
+ /** @param {string} column @param {number} t */
93
+ const cell = (column, t) => {
94
+ const cells = cellsOf(column)
95
+ const length = cells.length
96
+ let frame = Math.floor(t * rate + FRAME_EPSILON)
97
+ if (end === 'loop') frame -= Math.floor(frame / length) * length
98
+ else if (frame < 0) frame = 0
99
+ else if (frame >= length) {
100
+ if (end === 'blank') return null
101
+ frame = length - 1
102
+ }
103
+ return cells[frame]
104
+ }
105
+
106
+ /** @type {Map<string, (t: number) => string | null>} */
107
+ const values = new Map()
108
+ return Object.freeze({
109
+ rate,
110
+ frames,
111
+ duration: frames / rate,
112
+ columns: Object.freeze([...sheet.keys()]),
113
+ cell,
114
+ /** @param {string} column */
115
+ column(column) {
116
+ cellsOf(column)
117
+ let value = values.get(column)
118
+ if (!value) values.set(column, (value = t => cell(column, t)))
119
+ return value
120
+ },
121
+ /** @param {string} column */
122
+ keys(column) {
123
+ const cells = cellsOf(column)
124
+ /** @type {number[]} */
125
+ const times = []
126
+ for (let i = 0; i < cells.length; i++) if (i === 0 || cells[i] !== cells[i - 1]) times.push(i / rate)
127
+ return times
128
+ },
129
+ })
130
+ }
131
+
132
+ /**
133
+ * A time remap for a group's `time` that holds each moment for n frames at `rate` fps: group({ time: on(2) }) animates
134
+ * its children on twos, while the group's own x, y and the rest still move on ones.
135
+ * @param {number} n
136
+ * @param {{ rate?: number }} [options] rate defaults to 24.
137
+ */
138
+ export const on = (n, { rate = 24 } = {}) => step(t => t, { rate, on: n })
139
+
140
+ /**
141
+ * @param {unknown} drawings
142
+ * @param {string} where
143
+ * @returns {Record<string, Node>}
144
+ */
145
+ function checkDrawings(drawings, where) {
146
+ if (drawings === null || typeof drawings !== 'object') throw new TypeError(`${where} must be an object of drawing name to node`)
147
+ for (const [name, node] of Object.entries(drawings)) {
148
+ if (!isNode(node)) throw new TypeError(`${where}: drawing "${name}" is not a node`)
149
+ }
150
+ return /** @type {Record<string, Node>} */ (drawings)
151
+ }
152
+
153
+ /**
154
+ * One place in a character that shows one drawing at a time, like a column in Harmony or a slot in Spine. Its
155
+ * transform stays put while the drawing swaps, so whatever moves the slot moves every drawing in it.
156
+ * @param {GroupProps & {
157
+ * show: Value<string | number | null | undefined>,
158
+ * drawings: Record<string, Node>,
159
+ * skins?: Record<string, Record<string, Node>>,
160
+ * skin?: Value<string>,
161
+ * }} props `show` names the drawing (null shows nothing), for example an xsheet column. A skin replaces some drawings
162
+ * by name, for costumes or variants; drawings it lacks come from `drawings`.
163
+ * @returns {Node}
164
+ */
165
+ export function slot({ show, drawings, skins = {}, skin, ...props }) {
166
+ checkDrawings(drawings, 'slot: drawings')
167
+ if (skins === null || typeof skins !== 'object') throw new TypeError('slot: skins must be an object of skin name to drawings')
168
+ for (const [name, set] of Object.entries(skins)) checkDrawings(set, `slot: skin "${name}"`)
169
+ if (skin !== undefined && typeof skin !== 'function' && !(skin in skins)) {
170
+ throw new RangeError(`slot: no skin "${skin}". It has ${Object.keys(skins).join(', ') || 'none'}`)
171
+ }
172
+ /** @type {Map<Node, readonly Node[]>} */
173
+ const single = new Map()
174
+ /** @type {readonly Node[]} */
175
+ const none = Object.freeze([])
176
+ return group(props, t => {
177
+ const name = at(show, t)
178
+ if (name === null || name === undefined) return none
179
+ const key = String(name)
180
+ const skinName = skin === undefined ? undefined : at(skin, t)
181
+ if (skinName !== undefined && !(skinName in skins)) {
182
+ throw new RangeError(`slot: no skin "${skinName}". It has ${Object.keys(skins).join(', ') || 'none'}`)
183
+ }
184
+ const node = (skinName === undefined ? undefined : skins[skinName][key]) ?? drawings[key]
185
+ if (!node) throw new RangeError(`slot: no drawing "${key}". It has ${Object.keys(drawings).join(', ')}`)
186
+ let list = single.get(node)
187
+ if (!list) single.set(node, (list = Object.freeze([node])))
188
+ return list
189
+ })
190
+ }
191
+
192
+ /**
193
+ * An indexed palette: shapes name a style instead of a colour, and the palette in use decides the colour, so a day
194
+ * and a night version of a shot differ only in `use`. Every set must name the same styles.
195
+ * @template {string} S
196
+ * @param {Record<string, Record<S, string | Gradient>>} sets
197
+ * @param {{ use: Value<string> }} options Which set to read; a function switches sets over time, as a hit flash does.
198
+ * @returns {((style: S) => Value<string | Gradient>) & { styles: readonly S[], sets: readonly string[] }}
199
+ */
200
+ export function palette(sets, { use }) {
201
+ if (sets === null || typeof sets !== 'object') throw new TypeError('palette: sets must be an object of set name to styles')
202
+ const names = Object.keys(sets)
203
+ if (names.length === 0) throw new RangeError('palette: give at least one set')
204
+ const styles = /** @type {S[]} */ (Object.keys(sets[names[0]]))
205
+ for (const name of names) {
206
+ const own = Object.keys(sets[name])
207
+ const missing = styles.filter(s => !own.includes(s))
208
+ const extra = own.filter(s => !(/** @type {string[]} */ (styles)).includes(s))
209
+ if (missing.length || extra.length) {
210
+ throw new RangeError(
211
+ `palette: set "${name}" must name the same styles as "${names[0]}"` +
212
+ (missing.length ? `; it lacks ${missing.join(', ')}` : '') + (extra.length ? `; it adds ${extra.join(', ')}` : ''),
213
+ )
214
+ }
215
+ }
216
+ /** @param {string} name */
217
+ const setOf = name => {
218
+ const set = sets[name]
219
+ if (!set) throw new RangeError(`palette: no set "${name}". It has ${names.join(', ')}`)
220
+ return set
221
+ }
222
+ if (typeof use !== 'function') setOf(use)
223
+
224
+ /** @param {S} style */
225
+ const colour = style => {
226
+ if (!styles.includes(style)) throw new RangeError(`palette: no style "${style}". It has ${styles.join(', ')}`)
227
+ if (typeof use !== 'function') return setOf(use)[style]
228
+ return /** @param {number} t */ t => setOf(use(t))[style]
229
+ }
230
+ return Object.assign(colour, { styles: Object.freeze(styles), sets: Object.freeze(names) })
231
+ }
232
+
233
+ /**
234
+ * One frame of a sprite sheet: where it sits in the image (x, y, w, h), where that trimmed box sits in the full frame
235
+ * (ox, oy), the full frame's size (sw, sh) and how long it shows in milliseconds.
236
+ * @typedef {{ x: number, y: number, w: number, h: number, ox: number, oy: number, sw: number, sh: number, ms: number,
237
+ * crop: readonly [number, number, number, number] }} SheetFrame
238
+ */
239
+
240
+ /**
241
+ * @typedef {object} Sheet
242
+ * @property {readonly SheetFrame[]} frames
243
+ * @property {readonly string[]} tags
244
+ * @property {readonly [number, number]} size The full frame's width and height.
245
+ * @property {number} duration Seconds to play every frame once.
246
+ * @property {boolean} smooth Whether sprites from this sheet smooth when scaled; Aseprite sheets are pixel art, so not.
247
+ * @property {(t: number, tag?: string) => number} frameAt The frame shown t seconds into a tag, or into all frames
248
+ * looping.
249
+ */
250
+
251
+ /**
252
+ * @typedef {object} Playback
253
+ * @property {Int32Array} list Frame indices in play order.
254
+ * @property {Float64Array} ends When each entry stops showing, in ms from the start.
255
+ * @property {boolean} loop
256
+ */
257
+
258
+ /**
259
+ * The frames a tag plays, by Aseprite's rules: pingpong shows each end once a round, and `repeat` (a count of passes,
260
+ * a pingpong pass being one way) plays that many then holds the last frame. Without `repeat` the tag loops.
261
+ * @param {{ from: number, to: number, direction?: string, repeat?: string | number }} tag
262
+ * @param {readonly SheetFrame[]} frames
263
+ * @returns {Playback}
264
+ */
265
+ function playback({ from, to, direction = 'forward', repeat }, frames) {
266
+ if (!(Number.isInteger(from) && Number.isInteger(to) && from >= 0 && to >= from && to < frames.length)) {
267
+ throw new RangeError(`sprite: a tag runs from frame ${from} to ${to}, outside the ${frames.length} frames`)
268
+ }
269
+ const up = []
270
+ const down = []
271
+ for (let i = from; i <= to; i++) up.push(i)
272
+ for (let i = to; i >= from; i--) down.push(i)
273
+ const passes = Number(repeat) > 0 ? Number(repeat) : 0
274
+ /** @type {number[]} */
275
+ let list
276
+ if (direction === 'forward' || direction === 'reverse') {
277
+ const one = direction === 'forward' ? up : down
278
+ list = passes ? Array.from({ length: passes }, () => one).flat() : one
279
+ } else if (direction === 'pingpong' || direction === 'pingpong_reverse') {
280
+ const [a, b] = direction === 'pingpong' ? [up, down] : [down, up]
281
+ if (!passes) list = up.length < 2 ? a : [...a, ...b.slice(1, -1)]
282
+ else {
283
+ list = [...a]
284
+ for (let p = 1; p < passes; p++) list.push(...(p % 2 ? b : a).slice(1))
285
+ }
286
+ } else throw new RangeError(`sprite: unknown tag direction "${direction}"`)
287
+ const ends = new Float64Array(list.length)
288
+ let total = 0
289
+ list.forEach((f, i) => (ends[i] = total += frames[f].ms))
290
+ return { list: Int32Array.from(list), ends, loop: passes === 0 }
291
+ }
292
+
293
+ /** @param {Playback} play @param {number} t */
294
+ function frameIn({ list, ends, loop }, t) {
295
+ const total = ends[ends.length - 1]
296
+ let ms = t * 1000 + 1e-6
297
+ if (loop) ms -= Math.floor(ms / total) * total
298
+ else if (ms >= total) return list[list.length - 1]
299
+ else if (ms < 0) ms = 0
300
+ let lo = 0
301
+ let hi = ends.length - 1
302
+ while (lo < hi) {
303
+ const mid = (lo + hi) >> 1
304
+ if (ends[mid] > ms) hi = mid
305
+ else lo = mid + 1
306
+ }
307
+ return list[lo]
308
+ }
309
+
310
+ /**
311
+ * @param {SheetFrame[]} frames
312
+ * @param {Record<string, { from: number, to: number, direction?: string, repeat?: string | number }>} tags
313
+ * @param {boolean} smooth
314
+ * @returns {Sheet}
315
+ */
316
+ function makeSheet(frames, tags, smooth) {
317
+ for (const f of frames) {
318
+ if (!(f.ms > 0)) throw new RangeError(`sprite: every frame must show for more than 0 ms, got ${f.ms}`)
319
+ f.crop = Object.freeze(/** @type {[number, number, number, number]} */ ([f.x, f.y, f.w, f.h]))
320
+ Object.freeze(f)
321
+ }
322
+ const all = playback({ from: 0, to: frames.length - 1 }, frames)
323
+ /** @type {Map<string, Playback>} */
324
+ const plays = new Map(Object.entries(tags).map(([name, tag]) => [name, playback(tag, frames)]))
325
+ return Object.freeze({
326
+ frames: Object.freeze(frames),
327
+ tags: Object.freeze([...plays.keys()]),
328
+ size: Object.freeze(/** @type {[number, number]} */ ([frames[0].sw, frames[0].sh])),
329
+ duration: frames.reduce((sum, f) => sum + f.ms, 0) / 1000,
330
+ smooth,
331
+ /** @param {number} t @param {string} [tag] */
332
+ frameAt(t, tag) {
333
+ if (tag === undefined) return frameIn(all, t)
334
+ const play = plays.get(tag)
335
+ if (!play) throw new RangeError(`sprite: no tag "${tag}". The sheet has ${[...plays.keys()].join(', ') || 'no tags'}`)
336
+ return frameIn(play, t)
337
+ },
338
+ })
339
+ }
340
+
341
+ /**
342
+ * Reads Aseprite's sprite sheet JSON (File > Export Sprite Sheet, with JSON data, as a hash or an array), with its
343
+ * frame durations, trimmed frames and tags. The image itself goes in the scene's assets.images.
344
+ * @param {any} json The parsed JSON.
345
+ * @returns {Sheet}
346
+ */
347
+ export function aseprite(json) {
348
+ const list = Array.isArray(json?.frames) ? json.frames : Object.values(json?.frames ?? {})
349
+ if (list.length === 0) throw new RangeError('aseprite: the JSON has no frames; export the sheet from Aseprite with JSON data')
350
+ /** @type {SheetFrame[]} */
351
+ const frames = list.map((/** @type {any} */ f, /** @type {number} */ i) => {
352
+ if (!f?.frame) throw new TypeError(`aseprite: frame ${i} has no "frame" box`)
353
+ const { x, y, w, h } = f.frame
354
+ return /** @type {SheetFrame} */ ({
355
+ x, y, w, h,
356
+ ox: f.spriteSourceSize?.x ?? 0,
357
+ oy: f.spriteSourceSize?.y ?? 0,
358
+ sw: f.sourceSize?.w ?? w,
359
+ sh: f.sourceSize?.h ?? h,
360
+ ms: f.duration ?? 100,
361
+ })
362
+ })
363
+ /** @type {Record<string, any>} */
364
+ const tags = {}
365
+ for (const tag of json.meta?.frameTags ?? []) tags[tag.name] = tag
366
+ return makeSheet(frames, tags, false)
367
+ }
368
+
369
+ /**
370
+ * A sheet of equal frames in rows, left to right and top to bottom.
371
+ * @param {{ count: number, columns?: number, size: [number, number], fps?: number,
372
+ * tags?: Record<string, { from: number, to: number, direction?: string, repeat?: number }>, smooth?: boolean }} options
373
+ * columns defaults to count (one row) and fps to 12; size is one frame's width and height in px.
374
+ * @returns {Sheet}
375
+ */
376
+ export function spriteSheet({ count, columns = count, size, fps = 12, tags = {}, smooth = true }) {
377
+ if (!(Number.isInteger(count) && count > 0)) throw new RangeError(`spriteSheet: count must be a whole number above 0, got ${count}`)
378
+ if (!(Number.isInteger(columns) && columns > 0)) throw new RangeError(`spriteSheet: columns must be a whole number above 0, got ${columns}`)
379
+ if (!Array.isArray(size) || !(size[0] > 0) || !(size[1] > 0)) throw new TypeError('spriteSheet: size must be [width, height] of one frame')
380
+ if (!(fps > 0)) throw new RangeError(`spriteSheet: fps must be above 0, got ${fps}`)
381
+ const [w, h] = size
382
+ const frames = Array.from({ length: count }, (_, i) => /** @type {SheetFrame} */ ({
383
+ x: (i % columns) * w, y: Math.floor(i / columns) * h, w, h, ox: 0, oy: 0, sw: w, sh: h, ms: 1000 / fps,
384
+ }))
385
+ return makeSheet(frames, tags, smooth)
386
+ }
387
+
388
+ /**
389
+ * Plays a sprite sheet: the frame at the node's local time, from a tag or all frames looping, or the frame you name.
390
+ * Its box is the full frame from (0, 0), so trimmed frames keep their place; set anchor to place the feet.
391
+ * @param {GroupProps & { sheet: Sheet, src: string, tag?: Value<string>, frame?: Value<number>, smooth?: boolean }} props
392
+ * src is the key of the sheet's image in the scene's assets.images.
393
+ * @returns {Node}
394
+ */
395
+ export function sprite({ sheet, src, tag, frame, smooth = sheet?.smooth, ...props }) {
396
+ if (!sheet || !Array.isArray(sheet.frames)) throw new TypeError('sprite: sheet must come from aseprite() or spriteSheet()')
397
+ if (typeof tag === 'string') sheet.frameAt(0, tag)
398
+ let lastT = NaN
399
+ let last = sheet.frames[0]
400
+ /** @param {number} t */
401
+ const current = t => {
402
+ if (t !== lastT) {
403
+ const index = frame === undefined ? sheet.frameAt(t, at(tag, t)) : at(frame, t)
404
+ const found = sheet.frames[index]
405
+ if (!found) throw new RangeError(`sprite: no frame ${index}; the sheet has ${sheet.frames.length}`)
406
+ last = found
407
+ lastT = t
408
+ }
409
+ return last
410
+ }
411
+ return group(props, [
412
+ image({
413
+ src,
414
+ crop: t => current(t).crop,
415
+ x: t => current(t).ox,
416
+ y: t => current(t).oy,
417
+ w: t => current(t).w,
418
+ h: t => current(t).h,
419
+ smooth,
420
+ }),
421
+ ])
422
+ }
423
+
424
+ const BIG = 1e5
425
+
426
+ /**
427
+ * The node at another time, faded and tinted: screen blending turns dark lines into the tint and leaves light fills
428
+ * pale, and the node's own alpha cuts the tint to its shape.
429
+ * @param {Node} node
430
+ * @param {(t: number) => number} time
431
+ * @param {Value<boolean>} visible
432
+ * @param {number} opacity
433
+ * @param {string | null} tint
434
+ */
435
+ function ghost(node, time, visible, opacity, tint) {
436
+ if (tint === null) return group({ time, visible, opacity }, [node])
437
+ return group({ time, visible, opacity, matte: { node } }, [
438
+ node,
439
+ rect({ x: -BIG, y: -BIG, w: 2 * BIG, h: 2 * BIG, fill: tint, blend: 'screen' }),
440
+ ])
441
+ }
442
+
443
+ /**
444
+ * Onion skin: the node plus faded, tinted copies of it from just before (red) and just after (green). With `keys`,
445
+ * such as an xsheet column's keys(), the copies are the neighbouring drawings rather than the neighbouring moments,
446
+ * so a drawing held on twos does not ghost itself.
447
+ * @param {Node} node
448
+ * @param {GroupProps & { before?: number, after?: number, step?: number, keys?: readonly number[], opacity?: number,
449
+ * colors?: [string | null, string | null] }} [options] before and after default to 1, step to 1/12 s and opacity to
450
+ * 0.4 for the nearest copy; each copy further out is fainter. A null colour shows that side untinted.
451
+ * @returns {Node}
452
+ */
453
+ export function onion(node, { before = 1, after = 1, step: every = 1 / 12, keys, opacity = 0.4, colors = ['#e5484d', '#30a46c'], ...props } = {}) {
454
+ if (!isNode(node)) throw new TypeError('onion: the first argument must be a node')
455
+ const sorted = keys === undefined ? null : Float64Array.from(keys).sort()
456
+ /** @param {number} t @param {number} j */
457
+ const keyTime = (t, j) => {
458
+ const list = /** @type {Float64Array} */ (sorted)
459
+ let lo = 0
460
+ let hi = list.length
461
+ while (lo < hi) {
462
+ const mid = (lo + hi) >> 1
463
+ if (list[mid] <= t + FRAME_EPSILON) lo = mid + 1
464
+ else hi = mid
465
+ }
466
+ const k = lo - 1 + j
467
+ return k >= 0 && k < list.length ? list[k] : NaN
468
+ }
469
+ /** @param {number} j */
470
+ const copy = j => ghost(
471
+ node,
472
+ sorted ? t => keyTime(t, j) : t => t + j * every,
473
+ sorted ? t => !Number.isNaN(keyTime(t, j)) : true,
474
+ opacity * 0.6 ** (Math.abs(j) - 1),
475
+ colors[j < 0 ? 0 : 1],
476
+ )
477
+ /** @type {Node[]} */
478
+ const ghosts = []
479
+ for (let j = before; j >= 1; j--) ghosts.push(copy(-j))
480
+ for (let j = 1; j <= after; j++) ghosts.push(copy(j))
481
+ // Returned from a function so the scene does not index the copies' ids a second time.
482
+ return group(props, [group({}, () => ghosts), node])
483
+ }
484
+
485
+ /**
486
+ * Light table: the node plus faded copies of it pinned at fixed times, such as the key drawings an inbetween sits
487
+ * between, whatever the current time is.
488
+ * @param {Node} node
489
+ * @param {GroupProps & { at: readonly number[], opacity?: number, color?: string | null }} options opacity defaults to
490
+ * 0.3 and color to blue; null shows the copies untinted.
491
+ * @returns {Node}
492
+ */
493
+ export function lightTable(node, { at: times, opacity = 0.3, color = '#3e63dd', ...props }) {
494
+ if (!isNode(node)) throw new TypeError('lightTable: the first argument must be a node')
495
+ if (!Array.isArray(times)) throw new TypeError('lightTable: at must be a list of times in seconds')
496
+ const ghosts = times.map(time => ghost(node, () => time, true, opacity, color))
497
+ return group(props, [group({}, () => ghosts), node])
498
+ }