๐Ÿ“ฆ aquaticcalf / samcan

๐Ÿ“„ animationtrack.ts ยท 227 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227import type { SceneNode } from "../scene/node"
import { Keyframe } from "./keyframe"

/**
 * Represents an animation track that animates a specific property of a SceneNode
 * Manages keyframes and evaluates interpolated values at given times
 */
export class AnimationTrack {
    private _target: SceneNode
    private _property: string
    private _keyframes: Keyframe[] = []

    constructor(target: SceneNode, property: string) {
        this._target = target
        this._property = property
    }

    /**
     * Get the target node being animated
     */
    get target(): SceneNode {
        return this._target
    }

    /**
     * Get the property path being animated (e.g., 'opacity', 'transform.position.x')
     */
    get property(): string {
        return this._property
    }

    /**
     * Get all keyframes in this track
     */
    get keyframes(): ReadonlyArray<Keyframe> {
        return this._keyframes
    }

    /**
     * Add a keyframe to this track
     * Keyframes are automatically sorted by time
     */
    addKeyframe(keyframe: Keyframe): void {
        this._keyframes.push(keyframe)
        // Sort keyframes by time
        this._keyframes.sort((a, b) => a.time - b.time)
    }

    /**
     * Remove a keyframe from this track
     */
    removeKeyframe(keyframe: Keyframe): boolean {
        const index = this._keyframes.indexOf(keyframe)
        if (index === -1) {
            return false
        }

        this._keyframes.splice(index, 1)
        return true
    }

    /**
     * Evaluate the track at a given time and apply the value to the target property
     * @param time The time in seconds to evaluate at
     */
    evaluate(time: number): unknown {
        if (this._keyframes.length === 0) {
            return undefined
        }

        // If time is before first keyframe, use first keyframe value
        if (time <= this._keyframes[0]!.time) {
            const value = this._keyframes[0]!.value
            this.applyValue(value)
            return value
        }

        // If time is after last keyframe, use last keyframe value
        const lastKeyframe = this._keyframes[this._keyframes.length - 1]!
        if (time >= lastKeyframe.time) {
            const value = lastKeyframe.value
            this.applyValue(value)
            return value
        }

        // Find the two keyframes to interpolate between
        let fromKeyframe: Keyframe | null = null
        let toKeyframe: Keyframe | null = null

        for (let i = 0; i < this._keyframes.length - 1; i++) {
            const current = this._keyframes[i]!
            const next = this._keyframes[i + 1]!

            if (time >= current.time && time <= next.time) {
                fromKeyframe = current
                toKeyframe = next
                break
            }
        }

        if (fromKeyframe === null || toKeyframe === null) {
            return undefined
        }

        // Calculate interpolation factor (0 to 1)
        const duration = toKeyframe.time - fromKeyframe.time
        let t = duration > 0 ? (time - fromKeyframe.time) / duration : 0

        // Apply easing function if present
        if (fromKeyframe.easing) {
            t = fromKeyframe.easing(t)
        }

        // Interpolate based on type
        let value: unknown
        switch (fromKeyframe.interpolation) {
            case "step":
                value = fromKeyframe.value
                break
            case "linear":
                value = this.interpolateLinear(
                    fromKeyframe.value,
                    toKeyframe.value,
                    t,
                )
                break
            case "cubic":
                value = this.interpolateCubic(
                    fromKeyframe.value,
                    toKeyframe.value,
                    t,
                )
                break
            case "bezier":
                value = this.interpolateBezier(
                    fromKeyframe.value,
                    toKeyframe.value,
                    t,
                )
                break
            default:
                value = fromKeyframe.value
        }

        this.applyValue(value)
        return value
    }

    /**
     * Linear interpolation between two values
     */
    private interpolateLinear(from: unknown, to: unknown, t: number): unknown {
        // Handle numbers
        if (typeof from === "number" && typeof to === "number") {
            return from + (to - from) * t
        }

        // For non-numeric types, use step interpolation
        return t < 0.5 ? from : to
    }

    /**
     * Cubic interpolation between two values (ease-in-out)
     */
    private interpolateCubic(from: unknown, to: unknown, t: number): unknown {
        // Handle numbers with cubic easing
        if (typeof from === "number" && typeof to === "number") {
            // Cubic ease-in-out: smooth acceleration and deceleration
            const easedT =
                t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2
            return from + (to - from) * easedT
        }

        // For non-numeric types, use step interpolation
        return t < 0.5 ? from : to
    }

    /**
     * Bezier interpolation between two values (smooth curve)
     */
    private interpolateBezier(from: unknown, to: unknown, t: number): unknown {
        // Handle numbers with bezier easing
        if (typeof from === "number" && typeof to === "number") {
            // Bezier curve approximation (0.42, 0, 0.58, 1)
            const easedT = t * t * (3 - 2 * t)
            return from + (to - from) * easedT
        }

        // For non-numeric types, use step interpolation
        return t < 0.5 ? from : to
    }

    /**
     * Apply a value to the target property
     */
    private applyValue(value: unknown): void {
        // Parse property path (e.g., 'opacity' or 'transform.position.x')
        const parts = this._property.split(".")

        // Navigate to the target object using Record type for type safety
        let target = this._target as unknown as Record<string, unknown>

        for (let i = 0; i < parts.length - 1; i++) {
            const part = parts[i]
            if (part && target[part] !== undefined) {
                target = target[part] as Record<string, unknown>
            } else {
                // Property path doesn't exist
                return
            }
        }

        // Set the final property
        const finalProp = parts[parts.length - 1]
        if (finalProp && target[finalProp] !== undefined) {
            target[finalProp] = value

            // Notify target of change
            if (this._property.startsWith("transform.")) {
                this._target.notifyTransformChanged()
            } else {
                this._target.markDirty()
            }
        }
    }
}