scal-runtime 1.2.3

Runtime for SCAL- easy animation system focused on code.
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
pub mod code;
mod math;
mod scroll;
pub mod terminal;
mod transform;

use std::any::Any;

use crate::types::Seconds;

use std::ops::Range;

use anyhow::{Context, Result};
use glam::{Vec2, Vec4Swizzles, vec3};
use log::debug;
use scal_core::{
    CodeAnimationStyle, CodeHighlightAction, Color, Ease, ScrollOffsetTarget, Sfx, SourceLoc,
    TerminalOutputAction, Time,
};
use uuid::Uuid;

use crate::anim_object::object_trait::DynAnimObj;
use crate::animator::Animator;

#[derive(Clone, Debug)]
pub enum AnimOperation {
    Instantiate(DynAnimObj, Option<SourceLoc>),
    TransformMovePos(Uuid, Vec2, Time, Ease, Option<SourceLoc>),
    TransformMoveToObj(Uuid, Uuid, Vec2, Time, Ease, Option<SourceLoc>),
    TransformRotate(Uuid, f32, Time, Ease, Option<SourceLoc>),
    TransformScale(Uuid, Vec2, Time, Ease, Option<SourceLoc>),
    CodeAddLines(
        Uuid,
        String,
        usize,
        Time,
        Ease,
        CodeAnimationStyle,
        Option<SourceLoc>,
    ),
    CodeModifyLine(
        Uuid,
        u32,
        String,
        Time,
        Ease,
        CodeAnimationStyle,
        Option<SourceLoc>,
    ),
    CodeRemoveLines(
        Uuid,
        Range<u32>,
        Time,
        Ease,
        CodeAnimationStyle,
        Option<SourceLoc>,
    ),
    CodeHighlight(Uuid, CodeHighlightAction, Option<SourceLoc>),
    TerminalTypeInput(
        Uuid,
        String,
        Option<String>,
        String,
        String,
        Time,
        Ease,
        Option<CodeAnimationStyle>,
        Option<SourceLoc>,
    ),
    TerminalOutput(
        Uuid,
        TerminalOutputAction,
        Time,
        Ease,
        Option<CodeAnimationStyle>,
        Option<SourceLoc>,
    ),
    ObjectColor(Uuid, Color, Time, Ease, Option<SourceLoc>),
    MathPartColor(Uuid, String, Color, Time, Ease, Option<SourceLoc>),
    MathHighlight(Uuid, Vec<String>, Color, f32, Time, Ease, Option<SourceLoc>),
    ScrollOffset(Uuid, ScrollOffsetTarget, Time, Ease, Option<SourceLoc>),
    All(Vec<Self>, Option<SourceLoc>),
    Sequence(Vec<Self>, Option<SourceLoc>),
    Wait(Time, Option<SourceLoc>),
    PlaySound(Sfx, Time, Option<SourceLoc>),
}

impl AnimOperation {
    pub fn location(&self) -> Option<&SourceLoc> {
        match self {
            AnimOperation::Instantiate(_, l)
            | AnimOperation::TransformMovePos(_, _, _, _, l)
            | AnimOperation::TransformMoveToObj(_, _, _, _, _, l)
            | AnimOperation::TransformRotate(_, _, _, _, l)
            | AnimOperation::TransformScale(_, _, _, _, l)
            | AnimOperation::CodeAddLines(_, _, _, _, _, _, l)
            | AnimOperation::CodeModifyLine(_, _, _, _, _, _, l)
            | AnimOperation::CodeRemoveLines(_, _, _, _, _, l)
            | AnimOperation::CodeHighlight(_, _, l)
            | AnimOperation::TerminalTypeInput(_, _, _, _, _, _, _, _, l)
            | AnimOperation::TerminalOutput(_, _, _, _, _, l)
            | AnimOperation::ObjectColor(_, _, _, _, l)
            | AnimOperation::MathPartColor(_, _, _, _, _, l)
            | AnimOperation::MathHighlight(_, _, _, _, _, _, l)
            | AnimOperation::ScrollOffset(_, _, _, _, l)
            | AnimOperation::All(_, l)
            | AnimOperation::Sequence(_, l)
            | AnimOperation::Wait(_, l)
            | AnimOperation::PlaySound(_, _, l) => l.as_ref(),
        }
    }
}

fn ensure_duration(d: Time, label: &str) -> Result<()> {
    anyhow::ensure!(d > 0.0, "{label} duration must be > 0, got {d}");
    Ok(())
}

pub fn resolve_op(op: AnimOperation) -> Result<Animation> {
    Ok(match op {
        AnimOperation::Instantiate(anim_obj, _loc) => {
            Animation::instant(Box::new(move |animator, _| {
                debug!("Instantiate uuid={}", anim_obj.uuid());
                animator.add_anim_object(anim_obj.clone())?;
                Ok(())
            }))
        }
        AnimOperation::TransformMovePos(uuid, pos, duration, curve, _loc) => {
            debug!("TransformMovePos uuid={uuid}");
            ensure_duration(duration, "TransformMovePos")?;
            transform::move_pos(uuid, pos, duration, curve)
        }
        AnimOperation::TransformMoveToObj(
            moving_uuid,
            target_uuid,
            offset,
            duration,
            curve,
            _loc,
        ) => {
            debug!("TransformMoveToObj moving={moving_uuid} target={target_uuid}");
            ensure_duration(duration, "TransformMoveToObj")?;
            Animation::new(
                duration,
                curve,
                Box::new(move |animator, storage| {
                    let target = animator.get_object_world_matrix(&target_uuid)?;
                    let pos = target.w_axis.xy() + offset;
                    let current = animator.get_object(&moving_uuid)?.transform().position;
                    storage.push(current.x);
                    storage.push(current.y);
                    storage.push(pos.x);
                    storage.push(pos.y);
                    Ok(())
                }),
                Some(Box::new(move |animator, t, storage| {
                    let obj = animator.get_object_mut(&moving_uuid)?;
                    let transform = obj.anim_data.transform_mut();
                    transform.position = vec3(
                        storage[0] + t * (storage[2] - storage[0]),
                        storage[1] + t * (storage[3] - storage[1]),
                        transform.position.z,
                    );
                    Ok(())
                })),
            )
        }
        AnimOperation::TransformRotate(uuid, target, duration, curve, _loc) => {
            debug!("TransformRotate uuid={uuid}");
            ensure_duration(duration, "TransformRotate")?;
            transform::rotate_to(uuid, target, duration, curve)
        }
        AnimOperation::TransformScale(uuid, target, duration, curve, _loc) => {
            debug!("TransformScale uuid={uuid}");
            ensure_duration(duration, "TransformScale")?;
            transform::scale_to(uuid, target, duration, curve)
        }
        AnimOperation::ObjectColor(uuid, target, duration, curve, _loc) => {
            debug!("ObjectColor uuid={uuid}");
            ensure_duration(duration, "ObjectColor")?;
            color_to(uuid, target, duration, curve)
        }
        AnimOperation::MathPartColor(uuid, part, target, duration, curve, _loc) => {
            debug!("MathPartColor uuid={uuid} part={part}");
            ensure_duration(duration, "MathPartColor")?;
            math::part_color_to(uuid, part, target, duration, curve)
        }
        AnimOperation::MathHighlight(uuid, parts, color, dim, duration, curve, _loc) => {
            debug!("MathHighlight uuid={uuid} parts={parts:?}");
            ensure_duration(duration, "MathHighlight")?;
            math::highlight_to(uuid, parts, color, dim, duration, curve)
        }
        AnimOperation::ScrollOffset(uuid, target, duration, curve, _loc) => {
            debug!("ScrollOffset uuid={uuid} target={target:?}");
            ensure_duration(duration, "ScrollOffset")?;
            scroll::scroll_offset_to(uuid, target, duration, curve)
        }

        AnimOperation::CodeAddLines(uuid, text, from_line, duration, curve, style, _loc) => {
            debug!("CodeAddLines uuid={uuid}");
            ensure_duration(duration, "CodeAddLines")?;
            code::add_lines(uuid, text, from_line, duration, curve, style)
        }
        AnimOperation::CodeModifyLine(uuid, line, new_text, duration, curve, style, _loc) => {
            debug!("CodeModifyLine uuid={uuid}");
            ensure_duration(duration, "CodeModifyLine")?;
            code::modify_line(uuid, line, new_text, duration, curve, style)
        }
        AnimOperation::CodeRemoveLines(uuid, lines, duration, curve, style, _loc) => {
            debug!("CodeRemoveLines uuid={uuid}");
            ensure_duration(duration, "CodeRemoveLines")?;
            code::remove_lines(uuid, lines, duration, curve, style)
        }
        AnimOperation::CodeHighlight(uuid, action, _loc) => {
            let (duration, curve) = action.duration_and_curve();
            ensure_duration(duration, "CodeHighlight")?;
            code::highlight_fade_in(uuid, action, duration, curve)
        }
        AnimOperation::TerminalTypeInput(
            uuid,
            command,
            display_override,
            captured_output,
            captured_prompt,
            duration,
            curve,
            style,
            _loc,
        ) => {
            debug!("TerminalTypeInput uuid={uuid}");
            ensure_duration(duration, "TerminalTypeInput")?;
            self::terminal::type_input(
                uuid,
                command,
                display_override,
                captured_output,
                captured_prompt,
                duration,
                curve,
                style,
            )
        }
        AnimOperation::TerminalOutput(uuid, action, duration, curve, style, _loc) => {
            debug!("TerminalOutput uuid={uuid} action={action:?}");
            match action {
                TerminalOutputAction::Pull(_)
                | TerminalOutputAction::PullAll
                | TerminalOutputAction::PullLine => {
                    ensure_duration(duration, "TerminalOutput")?;
                }
                _ => {}
            }
            self::terminal::output(uuid, action, duration, curve, style)
        }
        AnimOperation::All(anim_ops, _loc) => get_all_animation(anim_ops)?,
        AnimOperation::Sequence(anim_ops, _loc) => get_sequence_animation(anim_ops)?,
        // AnimOP::Current {
        //     uuid,
        //     closure,
        //     source_loc: _,
        // } => Animation::instant(Box::new(move |animator, _| {
        //     let mut snapshot = animator.get_object(&uuid)?.anim_data.clone();
        //     if let Ok(world) = animator.get_object_world_matrix(&uuid) {
        //         let (scale, rot, trans) = world.to_scale_rotation_translation();
        //         snapshot.transform_mut().world_uniform = Some(TransformUniform {
        //             scale: scale.truncate(),
        //             position: trans,
        //             rotation: rot.to_euler(glam::EulerRot::ZYX).0.to_degrees(),
        //         });
        //     }
        //     let anim_op = (closure.0)(snapshot);
        //     animator.animations_left.push(anim_op);
        //     Ok(())
        // })),
        AnimOperation::Wait(duration, _loc) => {
            ensure_duration(duration, "Wait")?;
            Animation::new(
                duration,
                Ease::Linear,
                Box::new(|_, _| Ok(())),
                Some(Box::new(|_, _, _| Ok(()))),
            )
        }
        AnimOperation::PlaySound(_, _, _) => Animation::instant(Box::new(|_, _| Ok(()))),
    })
}

pub fn play(sfx: Sfx, video_delay: Time) -> AnimOperation {
    AnimOperation::PlaySound(sfx, video_delay, None)
}
pub fn sequence(ops: Vec<AnimOperation>) -> AnimOperation {
    AnimOperation::Sequence(ops, None)
}
pub fn all(ops: Vec<AnimOperation>) -> AnimOperation {
    AnimOperation::All(ops, None)
}
pub fn get_sequence_animation(ops: Vec<AnimOperation>) -> Result<Animation> {
    let mut child_durations: Vec<f32> = Vec::with_capacity(ops.len());
    let mut total_dur = 0_f32;
    for op in &ops {
        let anim: Animation = resolve_op(op.to_owned())?;
        let d = if anim.update.is_some() {
            anim.total_duration
        } else {
            0.0
        };
        child_durations.push(d);
        total_dur += d;
    }

    let start = Box::new({
        let loc_ops = ops.to_owned();
        move |animator: &mut Animator, store: &mut Vec<f32>| {
            store.clear();
            for (child_idx, op) in loc_ops.to_owned().into_iter().enumerate() {
                let op_debug = format!("{op:?}");

                let anim: Animation = resolve_op(op.to_owned())?;
                let mut data = vec![];
                (*anim.start)(animator, &mut data).with_context(|| {
                    format!("child[{child_idx}] start failed for op {op_debug}")
                })?;
                store.push(data.len() as f32);
                store.append(&mut data);
            }
            Ok(())
        }
    });

    let update: Option<UpdateAnimationFunction> = if total_dur > 0. {
        let ops_clone = ops.to_owned();
        let durations = child_durations;
        Some(Box::new(
            move |animator: &mut Animator, t: f32, store: &mut Vec<f32>| {
                let abs_time = t * total_dur;
                let mut cumulative = 0_f32;
                let mut store_index = 0;

                for (i, op) in ops_clone.iter().enumerate() {
                    let op_debug = format!("{op:?}");

                    let anim: Animation = resolve_op(op.to_owned())
                        .with_context(|| format!("failed to convert child[{i}] op {op_debug}"))?;
                    let to_read = store[store_index] as usize;
                    let child_duration = durations[i];

                    if child_duration > 0.
                        && abs_time >= cumulative
                        && abs_time < cumulative + child_duration
                    {
                        let local_t = (abs_time - cumulative) / child_duration;
                        let mut temp_store =
                            store[store_index + 1..store_index + 1 + to_read].to_vec();
                        if let Some(update) = anim.update {
                            (*update)(animator, anim.curve.apply(local_t), &mut temp_store)
                                .with_context(|| {
                                    format!("child[{i}] update failed for op {op_debug}")
                                })?;
                        }
                        store[store_index + 1..store_index + 1 + to_read]
                            .copy_from_slice(&temp_store);
                        break;
                    }

                    cumulative += child_duration;
                    store_index += to_read + 1;
                }

                Ok(())
            },
        ))
    } else {
        None
    };

    Ok(Animation::new(total_dur, Ease::Linear, start, update))
}
pub fn get_all_animation(ops: Vec<AnimOperation>) -> Result<Animation> {
    let mut dur = 0_f32;
    for operation in &ops {
        let anim: Animation = resolve_op(operation.to_owned())?;
        if anim.update.is_some() {
            dur = dur.max(anim.total_duration);
        }
    }
    let start = Box::new({
        let loc_ops = ops.to_owned();
        move |animator: &mut Animator, store: &mut Vec<f32>| {
            store.clear();
            for (child_idx, op) in loc_ops.to_owned().into_iter().enumerate() {
                let op_debug = format!("{op:?}");
                let anim: Animation = resolve_op(op.to_owned())?;
                let mut data = vec![];
                (*anim.start)(animator, &mut data).with_context(|| {
                    format!("child[{child_idx}] start failed for op {op_debug}")
                })?;
                store.push(data.len() as f32);
                store.append(&mut data);
            }
            Ok(())
        }
    });
    let update = if dur != 0. {
        let t: Option<UpdateAnimationFunction> = Some(Box::new(
            move |animator: &mut Animator, t: f32, store: &mut Vec<f32>| {
                let mut updated_store = vec![];
                let mut store_index = 0;
                for (child_idx, op) in ops.to_owned().into_iter().enumerate() {
                    let op_debug = format!("{op:?}");

                    let anim: Animation = resolve_op(op.to_owned()).with_context(|| {
                        format!("failed to convert child[{child_idx}] op {op_debug}")
                    })?;
                    let to_read = store[store_index] as usize;
                    // +1 to skip the to_read;
                    let mut temp_store = store[store_index + 1..store_index + 1 + to_read].to_vec();
                    if let Some(update) = anim.update {
                        (*update)(animator, anim.curve.apply(t), &mut temp_store).with_context(
                            || format!("child[{child_idx}] update failed for op {op_debug}"),
                        )?;
                    }
                    store_index += to_read + 1;
                    updated_store.push(temp_store.len() as f32);
                    updated_store.append(&mut temp_store);
                }
                *store = updated_store;
                Ok(())
            },
        ));
        t
    } else {
        None
    };

    Ok(Animation::new(dur, Ease::Linear, start, update))
}

fn set_object_color(obj: &mut dyn Any, color: Color) {
    if let Some(rect) = obj.downcast_mut::<crate::anim_object::primitive_shapes::Rectangle>() {
        rect.color = color;
    } else if let Some(circle) = obj.downcast_mut::<crate::anim_object::primitive_shapes::Circle>()
    {
        circle.color = color;
    } else if let Some(poly) = obj.downcast_mut::<crate::anim_object::primitive_shapes::Polygon>() {
        poly.color = color;
    } else if let Some(text) = obj.downcast_mut::<crate::anim_object::text::Text>() {
        text.color = color;
    } else if let Some(image) = obj.downcast_mut::<crate::anim_object::image::Image>() {
        image.color = color;
    } else if let Some(math) = obj.downcast_mut::<crate::anim_object::math::Math>() {
        math.color = color;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::anim_object::Transform;
    use crate::anim_object::object_trait::DynAnimObj;
    use crate::anim_object::primitive_shapes::Rectangle;
    use crate::anim_object::render::{ObjectRenderData, PipelineKind};
    use crate::animator::{Animator, Object};
    use glam::{Mat4, Vec2, Vec3};
    use scal_core::{Camera, Color};
    use uuid::Uuid;

    fn make_rect_obj(uuid: Uuid, parent: Option<Uuid>) -> Object {
        Object {
            anim_data: DynAnimObj(Box::new(Rectangle {
                size: Vec2::new(10.0, 10.0),
                corner_radius: 0.0,
                color: Color::WHITE,
                transform: Transform {
                    uuid,
                    parent,
                    position: Vec3::ZERO,
                    rotation: 0.0,
                    scale: Vec2::ONE,
                    layout_container: None,
                    world_uniform: None,
                    clip_rect: None,
                },
            })),
            render_data: ObjectRenderData {
                world_matrix_cache: Mat4::ZERO,
                vertices_base_index: 0,
                vertices: vec![],
                indices_base_index: 0,
                indices_count: 0,
                pipeline: PipelineKind::Shape,
                object_bind_groups: vec![],
            },
        }
    }

    fn make_animator_with_rect(uuid: Uuid) -> Animator {
        let camera = Camera::new(Vec2::new(100.0, 100.0), Vec2::ZERO, 1.0);
        let mut animator =
            Animator::new(vec![AnimOperation::Wait(0.001, None)], 60, camera, 1.0).unwrap();
        animator.objects.push(make_rect_obj(uuid, None));
        animator.objects_lookup.insert(uuid, 0);
        animator
    }

    #[test]
    fn parallel_applies_child_ease() {
        let uuid = Uuid::new_v4();
        let mut animator = make_animator_with_rect(uuid);
        let op = AnimOperation::All(
            vec![AnimOperation::TransformMovePos(
                uuid,
                Vec2::new(100.0, 0.0),
                1.0,
                Ease::OutCubic,
                None,
            )],
            None,
        );
        let anim = resolve_op(op).unwrap();
        let mut store = vec![];
        (anim.start)(&mut animator, &mut store).unwrap();
        (anim.update.unwrap())(&mut animator, 0.5, &mut store).unwrap();

        let pos = animator.get_object(&uuid).unwrap().transform().position;
        let expected = Ease::OutCubic.apply(0.5) * 100.0;
        assert!(
            (pos.x - expected).abs() < 0.01,
            "expected x={expected}, got {}",
            pos.x
        );
    }

    #[test]
    fn sequence_applies_child_ease() {
        let uuid = Uuid::new_v4();
        let mut animator = make_animator_with_rect(uuid);
        let op = AnimOperation::Sequence(
            vec![AnimOperation::TransformMovePos(
                uuid,
                Vec2::new(100.0, 0.0),
                1.0,
                Ease::OutCubic,
                None,
            )],
            None,
        );
        let anim = resolve_op(op).unwrap();
        let mut store = vec![];
        (anim.start)(&mut animator, &mut store).unwrap();
        (anim.update.unwrap())(&mut animator, 0.5, &mut store).unwrap();

        let pos = animator.get_object(&uuid).unwrap().transform().position;
        let expected = Ease::OutCubic.apply(0.5) * 100.0;
        assert!(
            (pos.x - expected).abs() < 0.01,
            "expected x={expected}, got {}",
            pos.x
        );
    }
}

fn get_object_color(obj: &dyn Any) -> Option<Color> {
    if let Some(rect) = obj.downcast_ref::<crate::anim_object::primitive_shapes::Rectangle>() {
        Some(rect.color)
    } else if let Some(circle) = obj.downcast_ref::<crate::anim_object::primitive_shapes::Circle>()
    {
        Some(circle.color)
    } else if let Some(poly) = obj.downcast_ref::<crate::anim_object::primitive_shapes::Polygon>() {
        Some(poly.color)
    } else if let Some(text) = obj.downcast_ref::<crate::anim_object::text::Text>() {
        Some(text.color)
    } else if let Some(image) = obj.downcast_ref::<crate::anim_object::image::Image>() {
        Some(image.color)
    } else if let Some(math) = obj.downcast_ref::<crate::anim_object::math::Math>() {
        Some(math.color)
    } else {
        None
    }
}

fn color_to(uuid: Uuid, target: Color, duration: Seconds, curve: Ease) -> Animation {
    Animation::new(
        duration,
        curve,
        Box::new(move |animator, storage| {
            let obj = animator.get_object(&uuid)?;
            if let Some(initial) = get_object_color(obj.anim_data.as_any()) {
                storage.push(initial.r);
                storage.push(initial.g);
                storage.push(initial.b);
                storage.push(initial.a);
            }
            Ok(())
        }),
        Some(Box::new(move |animator, t, storage| {
            if storage.len() < 4 {
                return Ok(());
            }
            let r = storage[0] + t * (target.r - storage[0]);
            let g = storage[1] + t * (target.g - storage[1]);
            let b = storage[2] + t * (target.b - storage[2]);
            let a = storage[3] + t * (target.a - storage[3]);
            let obj = animator.get_object_mut(&uuid)?;
            set_object_color(obj.anim_data.as_any_mut(), Color::new(r, g, b, a));
            // Vertex colors are baked into the mesh, so it has to be rebuilt to show the change.
            animator.regenerate_object_mesh(&uuid)?;
            Ok(())
        })),
    )
}

type StartAnimationFunction = Box<dyn Fn(&mut Animator, &mut Vec<f32>) -> Result<()>>;
/// Animator + percentage of the animation
type UpdateAnimationFunction = Box<dyn Fn(&mut Animator, f32, &mut Vec<f32>) -> Result<()>>;

pub struct Animation {
    pub total_duration: f32,
    pub curve: Ease,
    pub start: StartAnimationFunction,
    pub update: Option<UpdateAnimationFunction>,
    pub location: Option<SourceLoc>,
}
impl Animation {
    #[track_caller]
    pub fn new(
        total_duration: f32,
        curve: Ease,
        start: StartAnimationFunction,
        update: Option<UpdateAnimationFunction>,
    ) -> Self {
        let loc = std::panic::Location::caller();
        Animation {
            total_duration,
            curve,
            start,
            update,
            location: Some(SourceLoc {
                file: loc.file().to_string(),
                line: loc.line(),
            }),
        }
    }
    #[track_caller]
    pub fn instant(start: StartAnimationFunction) -> Self {
        let loc = std::panic::Location::caller();
        Animation {
            total_duration: 0.0,
            curve: Ease::Linear,
            start,
            update: None,
            location: Some(SourceLoc {
                file: loc.file().to_string(),
                line: loc.line(),
            }),
        }
    }
}