lecodes-sdk 1.1.0 → 1.2.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.
@@ -1,175 +1,175 @@
1
- // `Timeline` (docs/timeline-plan.md §2.4): choreography over the keyframe core. Tracks on any
2
- // number of targets (UI elements, 3D / 2D nodes, lights, cameras) at absolute positions, JS calls
3
- // at times, labels, holds — one clock, one handle. Also the `animateTo` / `animateFrom` bag
4
- // builder every target class delegates to (`tweenBag`).
5
-
6
- import { TweenAnimation, type Animation } from "./Animation"
7
- import { makeValueTrack, type AnimateOptions, type AnimateValue } from "./animateValue"
8
- import { CLOCK_GAME, CLOCK_UI, bagProps, iterationsOf, makeTrack, type Track, type TweenMeta, type TweenSpec, type TweenTarget } from "./spec"
9
-
10
- /** Vector-valued props: an array value is ONE keyframe unless it is an array of vectors. */
11
- const VECTOR_PROPS = new Set(["position", "scale", "quaternion", "eulerAngles", "color"])
12
-
13
- const clockOf = (clock: TweenMeta["clock"], fallback: number): number =>
14
- clock === "game" ? CLOCK_GAME : clock === "ui" ? CLOCK_UI : fallback
15
-
16
- /** @internal Build the tracks of one options bag on one target. `fromCurrent` = animateTo shape. */
17
- export const bagTracks = (target: TweenTarget, bag: Record<string, unknown>, atMs: number, fromCurrent: boolean): Track[] => {
18
- const meta = bag as TweenMeta
19
- const tracks: Track[] = []
20
- for (const [prop, value] of bagProps(bag)) {
21
- const track = makeTrack(target, prop, value, meta, atMs, fromCurrent, VECTOR_PROPS.has(prop))
22
- if (track) tracks.push(track)
23
- }
24
- return tracks
25
- }
26
-
27
- /** @internal The `animateTo` / `animateFrom` implementation: one bag → one animation, played now. */
28
- export const tweenBag = (target: TweenTarget, bag: Record<string, unknown>, fromCurrent: boolean): Animation => {
29
- const meta = bag as TweenMeta
30
- const tracks = bagTracks(target, bag, 0, fromCurrent)
31
- let durationMs = 0
32
- for (const t of tracks) durationMs = Math.max(durationMs, t.atMs + t.durMs)
33
- const spec: TweenSpec = {
34
- clock: clockOf(meta.clock, target._tweenClock),
35
- durationMs, delayMs: 0,
36
- iterations: iterationsOf(meta.loop),
37
- pingPong: meta.loopMode !== "restart",
38
- rate: 1, tracks, calls: [],
39
- }
40
- return new TweenAnimation(spec).play()
41
- }
42
-
43
- export type TimelineOptions = {
44
- /** `'ui'` (default) = wall time; `'game'` follows `Time.scale` and pauses with the game. */
45
- clock?: "ui" | "game",
46
- /** Repeat the whole timeline: `true` = forever, a number = cycles. */
47
- loop?: boolean | number,
48
- loopMode?: "restart" | "ping-pong",
49
- /** Wait before the first play, ms. */
50
- delay?: number,
51
- }
52
-
53
- /** Where a track goes: ms, a label, or `[label, offsetMs]`. Default = the current end (sequencing). */
54
- export type TimelinePosition = number | string | [string, number]
55
-
56
- export type TimelineAddOptions = {
57
- at?: TimelinePosition,
58
- /** With several targets: each starts this many ms after the previous one. */
59
- stagger?: number,
60
- }
61
-
62
- /** A choreography: tracks on many targets at absolute times, JS calls, labels and holds, driven by
63
- * one clock. Build it once, `play()` on every entrance — `play()` restarts from t = 0 and the pose
64
- * at any time is fully defined by the tracks (the first keyframe of a track holds before it
65
- * starts, the last one after it ends). */
66
- export class TimelineImpl extends TweenAnimation {
67
- private _labels = new Map<string, number>()
68
- private _end = 0
69
-
70
- constructor(options: TimelineOptions = {}) {
71
- super({
72
- clock: clockOf(options.clock, CLOCK_UI),
73
- durationMs: 0,
74
- delayMs: options.delay ?? 0,
75
- iterations: iterationsOf(options.loop),
76
- pingPong: options.loopMode !== "restart",
77
- rate: 1, tracks: [], calls: [],
78
- })
79
- }
80
-
81
- private _at(at: TimelinePosition | undefined): number {
82
- if (at === undefined) return this._end
83
- if (typeof at === "number") return at
84
- const name = Array.isArray(at) ? at[0] : at
85
- const offset = Array.isArray(at) ? at[1] : 0
86
- const base = this._labels.get(name)
87
- if (base === undefined) throw new Error(`Timeline: unknown label "${name}"`)
88
- return base + offset
89
- }
90
-
91
- private _grow(endMs: number): void {
92
- if (endMs > this._end) this._end = endMs
93
- this._spec.durationMs = this._end
94
- }
95
-
96
- /** Animate `props` on one target or several (staggered), like `animateTo` — arrays are keyframes,
97
- * `duration` / `easing` / `times` / `commit` apply. The bag's `delay` shifts the track after `at`. */
98
- add(target: TweenTarget | TweenTarget[], props: Record<string, unknown> & TweenMeta, options: TimelineAddOptions = {}): this {
99
- const at = this._at(options.at)
100
- const targets = Array.isArray(target) ? target : [target]
101
- const stagger = options.stagger ?? 0
102
- targets.forEach((t, i) => {
103
- const tracks = bagTracks(t, props, at + i * stagger, true)
104
- for (const tr of tracks) { this._spec.tracks.push(tr); this._grow(tr.atMs + tr.durMs) }
105
- })
106
- return this
107
- }
108
-
109
- /** Like `add` with the `animateFrom` shape: the target's own state is the implicit last keyframe. */
110
- addFrom(target: TweenTarget | TweenTarget[], props: Record<string, unknown> & TweenMeta, options: TimelineAddOptions = {}): this {
111
- const at = this._at(options.at)
112
- const targets = Array.isArray(target) ? target : [target]
113
- const stagger = options.stagger ?? 0
114
- targets.forEach((t, i) => {
115
- const tracks = bagTracks(t, props, at + i * stagger, false)
116
- for (const tr of tracks) { this._spec.tracks.push(tr); this._grow(tr.atMs + tr.durMs) }
117
- })
118
- return this
119
- }
120
-
121
- /** A free-value track (see the `animate()` global): the host evaluates it and calls `onUpdate`
122
- * every frame with the value. */
123
- animate<T extends AnimateValue>(options: AnimateOptions<T>, at?: TimelinePosition): this {
124
- const { track, deliver, slot } = makeValueTrack(options, this._at(at))
125
- this._values.set(slot, deliver)
126
- this._spec.tracks.push(track)
127
- this._grow(track.atMs + track.durMs)
128
- return this
129
- }
130
-
131
- /** Call `fn` when playback crosses `at` (forward or backward), in time order, always before
132
- * finish, never from a previous run. */
133
- call(at: TimelinePosition, fn: () => void): this {
134
- const t = this._at(at)
135
- this._spec.calls.push(t)
136
- this._calls.push(fn)
137
- this._grow(t)
138
- return this
139
- }
140
-
141
- /** Name a time — for `at`, `seek` and callers (`tl.labels.landed`). Default = the current end. */
142
- label(name: string, at?: TimelinePosition): this {
143
- this._labels.set(name, this._at(at))
144
- return this
145
- }
146
-
147
- /** Named times, ms. */
148
- get labels(): Record<string, number> {
149
- const o: Record<string, number> = {}
150
- for (const [k, v] of this._labels) o[k] = v
151
- return o
152
- }
153
-
154
- /** Extend the timeline with stillness after its current end. */
155
- hold(ms: number): this {
156
- this._grow(this._end + Math.max(0, ms))
157
- return this
158
- }
159
-
160
- /** The current end, ms (tracks, calls and holds). */
161
- get end(): number { return this._end }
162
-
163
- /** `seek` also accepts a label. */
164
- override seek(at: number | string): this {
165
- return super.seek(typeof at === "string" ? this._at(at) : at)
166
- }
167
- }
168
-
169
- /** The timeline handle type (see {@link TimelineImpl} for the members). */
170
- export type Timeline = TimelineImpl
171
-
172
- /** Create a timeline — `Timeline()` / `Timeline({ clock: 'game', loop: true })`. */
173
- export function Timeline(options?: TimelineOptions): Timeline {
174
- return new TimelineImpl(options)
175
- }
1
+ // `Timeline` (docs/timeline-plan.md §2.4): choreography over the keyframe core. Tracks on any
2
+ // number of targets (UI elements, 3D / 2D nodes, lights, cameras) at absolute positions, JS calls
3
+ // at times, labels, holds — one clock, one handle. Also the `animateTo` / `animateFrom` bag
4
+ // builder every target class delegates to (`tweenBag`).
5
+
6
+ import { TweenAnimation, type Animation } from "./Animation"
7
+ import { makeValueTrack, type AnimateOptions, type AnimateValue } from "./animateValue"
8
+ import { CLOCK_GAME, CLOCK_UI, bagProps, iterationsOf, makeTrack, type Track, type TweenMeta, type TweenSpec, type TweenTarget } from "./spec"
9
+
10
+ /** Vector-valued props: an array value is ONE keyframe unless it is an array of vectors. */
11
+ const VECTOR_PROPS = new Set(["position", "scale", "quaternion", "eulerAngles", "color"])
12
+
13
+ const clockOf = (clock: TweenMeta["clock"], fallback: number): number =>
14
+ clock === "game" ? CLOCK_GAME : clock === "ui" ? CLOCK_UI : fallback
15
+
16
+ /** @internal Build the tracks of one options bag on one target. `fromCurrent` = animateTo shape. */
17
+ export const bagTracks = (target: TweenTarget, bag: Record<string, unknown>, atMs: number, fromCurrent: boolean): Track[] => {
18
+ const meta = bag as TweenMeta
19
+ const tracks: Track[] = []
20
+ for (const [prop, value] of bagProps(bag)) {
21
+ const track = makeTrack(target, prop, value, meta, atMs, fromCurrent, VECTOR_PROPS.has(prop))
22
+ if (track) tracks.push(track)
23
+ }
24
+ return tracks
25
+ }
26
+
27
+ /** @internal The `animateTo` / `animateFrom` implementation: one bag → one animation, played now. */
28
+ export const tweenBag = (target: TweenTarget, bag: Record<string, unknown>, fromCurrent: boolean): Animation => {
29
+ const meta = bag as TweenMeta
30
+ const tracks = bagTracks(target, bag, 0, fromCurrent)
31
+ let durationMs = 0
32
+ for (const t of tracks) durationMs = Math.max(durationMs, t.atMs + t.durMs)
33
+ const spec: TweenSpec = {
34
+ clock: clockOf(meta.clock, target._tweenClock),
35
+ durationMs, delayMs: 0,
36
+ iterations: iterationsOf(meta.loop),
37
+ pingPong: meta.loopMode !== "restart",
38
+ rate: 1, tracks, calls: [],
39
+ }
40
+ return new TweenAnimation(spec).play()
41
+ }
42
+
43
+ export type TimelineOptions = {
44
+ /** `'ui'` (default) = wall time; `'game'` follows `Time.scale` and pauses with the game. */
45
+ clock?: "ui" | "game",
46
+ /** Repeat the whole timeline: `true` = forever, a number = cycles. */
47
+ loop?: boolean | number,
48
+ loopMode?: "restart" | "ping-pong",
49
+ /** Wait before the first play, ms. */
50
+ delay?: number,
51
+ }
52
+
53
+ /** Where a track goes: ms, a label, or `[label, offsetMs]`. Default = the current end (sequencing). */
54
+ export type TimelinePosition = number | string | [string, number]
55
+
56
+ export type TimelineAddOptions = {
57
+ at?: TimelinePosition,
58
+ /** With several targets: each starts this many ms after the previous one. */
59
+ stagger?: number,
60
+ }
61
+
62
+ /** A choreography: tracks on many targets at absolute times, JS calls, labels and holds, driven by
63
+ * one clock. Build it once, `play()` on every entrance — `play()` restarts from t = 0 and the pose
64
+ * at any time is fully defined by the tracks (the first keyframe of a track holds before it
65
+ * starts, the last one after it ends). */
66
+ export class TimelineImpl extends TweenAnimation {
67
+ private _labels = new Map<string, number>()
68
+ private _end = 0
69
+
70
+ constructor(options: TimelineOptions = {}) {
71
+ super({
72
+ clock: clockOf(options.clock, CLOCK_UI),
73
+ durationMs: 0,
74
+ delayMs: options.delay ?? 0,
75
+ iterations: iterationsOf(options.loop),
76
+ pingPong: options.loopMode !== "restart",
77
+ rate: 1, tracks: [], calls: [],
78
+ })
79
+ }
80
+
81
+ private _at(at: TimelinePosition | undefined): number {
82
+ if (at === undefined) return this._end
83
+ if (typeof at === "number") return at
84
+ const name = Array.isArray(at) ? at[0] : at
85
+ const offset = Array.isArray(at) ? at[1] : 0
86
+ const base = this._labels.get(name)
87
+ if (base === undefined) throw new Error(`Timeline: unknown label "${name}"`)
88
+ return base + offset
89
+ }
90
+
91
+ private _grow(endMs: number): void {
92
+ if (endMs > this._end) this._end = endMs
93
+ this._spec.durationMs = this._end
94
+ }
95
+
96
+ /** Animate `props` on one target or several (staggered), like `animateTo` — arrays are keyframes,
97
+ * `duration` / `easing` / `times` / `commit` apply. The bag's `delay` shifts the track after `at`. */
98
+ add(target: TweenTarget | TweenTarget[], props: Record<string, unknown> & TweenMeta, options: TimelineAddOptions = {}): this {
99
+ const at = this._at(options.at)
100
+ const targets = Array.isArray(target) ? target : [target]
101
+ const stagger = options.stagger ?? 0
102
+ targets.forEach((t, i) => {
103
+ const tracks = bagTracks(t, props, at + i * stagger, true)
104
+ for (const tr of tracks) { this._spec.tracks.push(tr); this._grow(tr.atMs + tr.durMs) }
105
+ })
106
+ return this
107
+ }
108
+
109
+ /** Like `add` with the `animateFrom` shape: the target's own state is the implicit last keyframe. */
110
+ addFrom(target: TweenTarget | TweenTarget[], props: Record<string, unknown> & TweenMeta, options: TimelineAddOptions = {}): this {
111
+ const at = this._at(options.at)
112
+ const targets = Array.isArray(target) ? target : [target]
113
+ const stagger = options.stagger ?? 0
114
+ targets.forEach((t, i) => {
115
+ const tracks = bagTracks(t, props, at + i * stagger, false)
116
+ for (const tr of tracks) { this._spec.tracks.push(tr); this._grow(tr.atMs + tr.durMs) }
117
+ })
118
+ return this
119
+ }
120
+
121
+ /** A free-value track (see the `animate()` global): the host evaluates it and calls `onUpdate`
122
+ * every frame with the value. */
123
+ animate<T extends AnimateValue>(options: AnimateOptions<T>, at?: TimelinePosition): this {
124
+ const { track, deliver, slot } = makeValueTrack(options, this._at(at))
125
+ this._values.set(slot, deliver)
126
+ this._spec.tracks.push(track)
127
+ this._grow(track.atMs + track.durMs)
128
+ return this
129
+ }
130
+
131
+ /** Call `fn` when playback crosses `at` (forward or backward), in time order, always before
132
+ * finish, never from a previous run. */
133
+ call(at: TimelinePosition, fn: () => void): this {
134
+ const t = this._at(at)
135
+ this._spec.calls.push(t)
136
+ this._calls.push(fn)
137
+ this._grow(t)
138
+ return this
139
+ }
140
+
141
+ /** Name a time — for `at`, `seek` and callers (`tl.labels.landed`). Default = the current end. */
142
+ label(name: string, at?: TimelinePosition): this {
143
+ this._labels.set(name, this._at(at))
144
+ return this
145
+ }
146
+
147
+ /** Named times, ms. */
148
+ get labels(): Record<string, number> {
149
+ const o: Record<string, number> = {}
150
+ for (const [k, v] of this._labels) o[k] = v
151
+ return o
152
+ }
153
+
154
+ /** Extend the timeline with stillness after its current end. */
155
+ hold(ms: number): this {
156
+ this._grow(this._end + Math.max(0, ms))
157
+ return this
158
+ }
159
+
160
+ /** The current end, ms (tracks, calls and holds). */
161
+ get end(): number { return this._end }
162
+
163
+ /** `seek` also accepts a label. */
164
+ override seek(at: number | string): this {
165
+ return super.seek(typeof at === "string" ? this._at(at) : at)
166
+ }
167
+ }
168
+
169
+ /** The timeline handle type (see {@link TimelineImpl} for the members). */
170
+ export type Timeline = TimelineImpl
171
+
172
+ /** Create a timeline — `Timeline()` / `Timeline({ clock: 'game', loop: true })`. */
173
+ export function Timeline(options?: TimelineOptions): Timeline {
174
+ return new TimelineImpl(options)
175
+ }
@@ -1,100 +1,100 @@
1
- // `animate()` — "animate a VALUE, I apply it" (docs/timeline-plan.md): the free-value tween for
2
- // anything without a native writer (a material parameter, a volume, a number the Canvas draws).
3
- // Since 2026-09-14 it runs on the keyframe core like everything else: a VALUE-domain track the host
4
- // evaluates natively and hands back to JS once per frame, the same easing vocabulary, keyframes,
5
- // loops and clocks, and the same `Animation` handle. `Timeline.animate` puts one into a timeline.
6
-
7
- import { TweenAnimation, type Animation } from "./Animation"
8
- import { Mat4 } from "../../math/mat4"
9
- import type { Vec2Like, Vec3Like } from "../../math/vec"
10
- import type { QuatLike } from "../../math/quat"
11
- import type { Mat4Like } from "../../math/mat4"
12
- import type { ColorInput } from "../../core/color"
13
- import {
14
- CLOCK_GAME, CLOCK_UI, DOM_VALUE, KIND_FLOAT, KIND_MAT4, DEFAULT_DURATION_MS, easingFor, iterationsOf, lanesOf, valueValue,
15
- type Keyframe, type Track, type TweenChannel, type TweenMeta, type TweenSpec, type TweenTarget,
16
- } from "./spec"
17
-
18
- /** What `animate()` tweens: a number, a color (string / packed / rgb(a) array — delivered as rgba
19
- * 0..1), a 2 / 3-vector, a quaternion (slerp), or a 4x4 matrix (position / rotation / scale). */
20
- export type AnimateValue = number | string | Vec2Like | Vec3Like | QuatLike | Mat4Like | ColorInput
21
-
22
- /** `onUpdate` receives a number for a number; every other kind arrives as the SAME `Float32Array`
23
- * every frame (overwritten in place — copy it if you keep it). A matrix is the 16 floats. */
24
- export type AnimateOut<T> = T extends number ? number : Float32Array
25
-
26
- export type AnimateOptions<T extends AnimateValue> = Omit<TweenMeta, "commit" | "layer"> & {
27
- /** Start value (required unless `values` is given). */
28
- from?: T,
29
- /** End value. */
30
- to?: T,
31
- /** Keyframes instead of from/to (offsets via `times`). */
32
- values?: T[],
33
- onUpdate(value: AnimateOut<T>): void,
34
- /** After the last frame of a run that reached its end (not on cancel). */
35
- onComplete?(): void,
36
- }
37
-
38
- /** @internal Deliverers turn the host's lanes into the `onUpdate` argument without allocating. */
39
- const deliverer = (kind: number, lanes: number, onUpdate: (v: any) => void): ((l: Float32Array) => void) => {
40
- if (kind === KIND_FLOAT) return (l) => onUpdate(l[0])
41
- if (kind === KIND_MAT4) {
42
- const out = new Float32Array(16)
43
- return (l) => {
44
- const m = Mat4.compose([l[0]!, l[1]!, l[2]!], [l[3]!, l[4]!, l[5]!, l[6]!], [l[7]!, l[8]!, l[9]!]).m
45
- for (let i = 0; i < 16; i++) out[i] = m[i]!
46
- onUpdate(out)
47
- }
48
- }
49
- const out = new Float32Array(lanes)
50
- return (l) => { for (let i = 0; i < lanes; i++) out[i] = l[i]!; onUpdate(out) }
51
- }
52
-
53
- /** VALUE slots are unique per world: the host addresses a value track by (animation, slot), and the
54
- * evaluator must never see two animations naming the same slot (a channel is owned by the newest
55
- * animation that names it — values have no shared state to own). */
56
- let nextSlot = 0
57
-
58
- /** @internal Build a VALUE track from animate options. Returns the track, its deliverer and its slot. */
59
- export const makeValueTrack = (o: AnimateOptions<any>, atMs: number): { track: Track, deliver: (l: Float32Array) => void, slot: number } => {
60
- const slot = ++nextSlot
61
- const raw: unknown[] = o.values ?? (o.from !== undefined && o.to !== undefined ? [o.from, o.to] : [])
62
- if (raw.length < 1) throw new Error("animate: give `from` + `to`, or `values`")
63
- const norm = raw.map((v) => valueValue(v))
64
- if (norm.some((n) => n === null)) throw new Error("animate: a value is not a number, color, vector, quaternion or matrix")
65
- const kind = norm[0]!.kind
66
- if (norm.some((n) => n!.kind !== kind)) throw new Error("animate: every value must be the same kind")
67
- const lanes = lanesOf(kind)
68
- const easing = easingFor(o.easing, "value")
69
- const keys: Keyframe[] = norm.map((n, i) => ({
70
- t: o.times && o.times.length === norm.length ? o.times[i]! : norm.length === 1 ? 1 : i / (norm.length - 1),
71
- easing,
72
- value: { lanes: (n as { lanes: number[] }).lanes },
73
- raw: raw[i],
74
- }))
75
- const channel: TweenChannel = { domain: DOM_VALUE, id: () => slot, value: valueValue }
76
- const target: TweenTarget = { _tweenClock: CLOCK_UI, _tweenChannel: () => channel }
77
- const track: Track = {
78
- target, prop: "value", channel, kind, lanes,
79
- atMs: atMs + (o.delay ?? 0), durMs: Math.max(0, o.duration ?? DEFAULT_DURATION_MS),
80
- commit: false, keys,
81
- }
82
- return { track, deliver: deliverer(kind, lanes, o.onUpdate), slot }
83
- }
84
-
85
- /** Tween a free value and apply it yourself in `onUpdate` — the primitive for anything without a
86
- * native channel (material params, volumes, numbers a Canvas draws). Same easing / keyframes /
87
- * `loop` / `clock` as `animateTo`; returns the {@link Animation} handle. Default clock: `'ui'`. */
88
- export const animate = <T extends AnimateValue>(options: AnimateOptions<T>): Animation => {
89
- const { track, deliver, slot } = makeValueTrack(options, 0)
90
- const spec: TweenSpec = {
91
- clock: options.clock === "game" ? CLOCK_GAME : CLOCK_UI,
92
- durationMs: track.atMs + track.durMs, delayMs: 0,
93
- iterations: iterationsOf(options.loop), pingPong: options.loopMode !== "restart",
94
- rate: 1, tracks: [track], calls: [],
95
- }
96
- const a = new TweenAnimation(spec)
97
- a._values.set(slot, deliver)
98
- if (options.onComplete) a.onFinish((done) => { if (done) options.onComplete!() })
99
- return a.play()
100
- }
1
+ // `animate()` — "animate a VALUE, I apply it" (docs/timeline-plan.md): the free-value tween for
2
+ // anything without a native writer (a material parameter, a volume, a number the Canvas draws).
3
+ // Since 2026-09-14 it runs on the keyframe core like everything else: a VALUE-domain track the host
4
+ // evaluates natively and hands back to JS once per frame, the same easing vocabulary, keyframes,
5
+ // loops and clocks, and the same `Animation` handle. `Timeline.animate` puts one into a timeline.
6
+
7
+ import { TweenAnimation, type Animation } from "./Animation"
8
+ import { Mat4 } from "../../math/mat4"
9
+ import type { Vec2Like, Vec3Like } from "../../math/vec"
10
+ import type { QuatLike } from "../../math/quat"
11
+ import type { Mat4Like } from "../../math/mat4"
12
+ import type { ColorInput } from "../../core/color"
13
+ import {
14
+ CLOCK_GAME, CLOCK_UI, DOM_VALUE, KIND_FLOAT, KIND_MAT4, DEFAULT_DURATION_MS, easingFor, iterationsOf, lanesOf, valueValue,
15
+ type Keyframe, type Track, type TweenChannel, type TweenMeta, type TweenSpec, type TweenTarget,
16
+ } from "./spec"
17
+
18
+ /** What `animate()` tweens: a number, a color (string / packed / rgb(a) array — delivered as rgba
19
+ * 0..1), a 2 / 3-vector, a quaternion (slerp), or a 4x4 matrix (position / rotation / scale). */
20
+ export type AnimateValue = number | string | Vec2Like | Vec3Like | QuatLike | Mat4Like | ColorInput
21
+
22
+ /** `onUpdate` receives a number for a number; every other kind arrives as the SAME `Float32Array`
23
+ * every frame (overwritten in place — copy it if you keep it). A matrix is the 16 floats. */
24
+ export type AnimateOut<T> = T extends number ? number : Float32Array
25
+
26
+ export type AnimateOptions<T extends AnimateValue> = Omit<TweenMeta, "commit" | "layer"> & {
27
+ /** Start value (required unless `values` is given). */
28
+ from?: T,
29
+ /** End value. */
30
+ to?: T,
31
+ /** Keyframes instead of from/to (offsets via `times`). */
32
+ values?: T[],
33
+ onUpdate(value: AnimateOut<T>): void,
34
+ /** After the last frame of a run that reached its end (not on cancel). */
35
+ onComplete?(): void,
36
+ }
37
+
38
+ /** @internal Deliverers turn the host's lanes into the `onUpdate` argument without allocating. */
39
+ const deliverer = (kind: number, lanes: number, onUpdate: (v: any) => void): ((l: Float32Array) => void) => {
40
+ if (kind === KIND_FLOAT) return (l) => onUpdate(l[0])
41
+ if (kind === KIND_MAT4) {
42
+ const out = new Float32Array(16)
43
+ return (l) => {
44
+ const m = Mat4.compose([l[0]!, l[1]!, l[2]!], [l[3]!, l[4]!, l[5]!, l[6]!], [l[7]!, l[8]!, l[9]!]).m
45
+ for (let i = 0; i < 16; i++) out[i] = m[i]!
46
+ onUpdate(out)
47
+ }
48
+ }
49
+ const out = new Float32Array(lanes)
50
+ return (l) => { for (let i = 0; i < lanes; i++) out[i] = l[i]!; onUpdate(out) }
51
+ }
52
+
53
+ /** VALUE slots are unique per world: the host addresses a value track by (animation, slot), and the
54
+ * evaluator must never see two animations naming the same slot (a channel is owned by the newest
55
+ * animation that names it — values have no shared state to own). */
56
+ let nextSlot = 0
57
+
58
+ /** @internal Build a VALUE track from animate options. Returns the track, its deliverer and its slot. */
59
+ export const makeValueTrack = (o: AnimateOptions<any>, atMs: number): { track: Track, deliver: (l: Float32Array) => void, slot: number } => {
60
+ const slot = ++nextSlot
61
+ const raw: unknown[] = o.values ?? (o.from !== undefined && o.to !== undefined ? [o.from, o.to] : [])
62
+ if (raw.length < 1) throw new Error("animate: give `from` + `to`, or `values`")
63
+ const norm = raw.map((v) => valueValue(v))
64
+ if (norm.some((n) => n === null)) throw new Error("animate: a value is not a number, color, vector, quaternion or matrix")
65
+ const kind = norm[0]!.kind
66
+ if (norm.some((n) => n!.kind !== kind)) throw new Error("animate: every value must be the same kind")
67
+ const lanes = lanesOf(kind)
68
+ const easing = easingFor(o.easing, "value")
69
+ const keys: Keyframe[] = norm.map((n, i) => ({
70
+ t: o.times && o.times.length === norm.length ? o.times[i]! : norm.length === 1 ? 1 : i / (norm.length - 1),
71
+ easing,
72
+ value: { lanes: (n as { lanes: number[] }).lanes },
73
+ raw: raw[i],
74
+ }))
75
+ const channel: TweenChannel = { domain: DOM_VALUE, id: () => slot, value: valueValue }
76
+ const target: TweenTarget = { _tweenClock: CLOCK_UI, _tweenChannel: () => channel }
77
+ const track: Track = {
78
+ target, prop: "value", channel, kind, lanes,
79
+ atMs: atMs + (o.delay ?? 0), durMs: Math.max(0, o.duration ?? DEFAULT_DURATION_MS),
80
+ commit: false, keys,
81
+ }
82
+ return { track, deliver: deliverer(kind, lanes, o.onUpdate), slot }
83
+ }
84
+
85
+ /** Tween a free value and apply it yourself in `onUpdate` — the primitive for anything without a
86
+ * native channel (material params, volumes, numbers a Canvas draws). Same easing / keyframes /
87
+ * `loop` / `clock` as `animateTo`; returns the {@link Animation} handle. Default clock: `'ui'`. */
88
+ export const animate = <T extends AnimateValue>(options: AnimateOptions<T>): Animation => {
89
+ const { track, deliver, slot } = makeValueTrack(options, 0)
90
+ const spec: TweenSpec = {
91
+ clock: options.clock === "game" ? CLOCK_GAME : CLOCK_UI,
92
+ durationMs: track.atMs + track.durMs, delayMs: 0,
93
+ iterations: iterationsOf(options.loop), pingPong: options.loopMode !== "restart",
94
+ rate: 1, tracks: [track], calls: [],
95
+ }
96
+ const a = new TweenAnimation(spec)
97
+ a._values.set(slot, deliver)
98
+ if (options.onComplete) a.onFinish((done) => { if (done) options.onComplete!() })
99
+ return a.play()
100
+ }