mittens-engine 0.7.0

A Vulkan and OpenXR scene engine with ECS, reactive signals, and Meow Meow scripting
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
use std::collections::{BTreeMap, BTreeSet};

use crate::engine::ecs::component::{AnimationComponent, AnimationState, KeyframeComponent};
use crate::engine::ecs::system::System;
use crate::engine::ecs::system::animation_keyframe_evaluator::AnimationKeyframeEvaluator;
use crate::engine::ecs::system::animation_scheduler::AnimationScheduler;
use crate::engine::ecs::{ComponentId, RxWorld, World};
use crate::engine::graphics::VisualWorld;
use crate::engine::user_input::InputState;

#[derive(Debug, Default)]
struct AnimationRuntime {
    keyframes: Vec<ComponentId>,
    fired_keyframes: BTreeSet<ComponentId>,
    /// For audio lookahead scheduling, track the last loop-cycle index each keyframe was
    /// scheduled for.
    audio_scheduled_cycle_by_keyframe: BTreeMap<ComponentId, u64>,
    /// Loop cycle index for audio scheduling. Increments whenever a looping animation wraps.
    audio_cycle: u64,
    start_beat: f64,
    pending_state: Option<AnimationState>,
}

#[derive(Debug, Default)]
pub struct AnimationSystem {
    /// Runtime state keyed by `AnimationComponent` id.
    ///
    /// BTree* gives deterministic iteration order (nice for debugging/logs).
    animations: BTreeMap<ComponentId, AnimationRuntime>,
    last_beat: f64,

    scheduler: AnimationScheduler,
    keyframe_evaluator: AnimationKeyframeEvaluator,
}

impl AnimationSystem {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn register_animation(&mut self, world: &mut World, component: ComponentId) {
        if world
            .get_component_by_id_as::<AnimationComponent>(component)
            .is_none()
        {
            return;
        }

        self.animations
            .entry(component)
            .or_insert_with(AnimationRuntime::default);
    }

    pub fn set_animation_state(&mut self, animation: ComponentId, state: AnimationState) {
        self.animations
            .entry(animation)
            .or_insert_with(AnimationRuntime::default)
            .pending_state = Some(state);
    }

    pub fn register_keyframe(&mut self, world: &mut World, component: ComponentId) {
        if world
            .get_component_by_id_as::<KeyframeComponent>(component)
            .is_none()
        {
            return;
        }

        // Find ancestor AnimationComponent.
        let mut cursor = world.parent_of(component);
        while let Some(node) = cursor {
            if world
                .get_component_by_id_as::<AnimationComponent>(node)
                .is_some()
            {
                let runtime = self
                    .animations
                    .entry(node)
                    .or_insert_with(AnimationRuntime::default);
                let list = &mut runtime.keyframes;

                if !list.contains(&component) {
                    list.push(component);
                }

                // Keep deterministic order by beat.
                list.sort_by(|a, b| {
                    let ba = world
                        .get_component_by_id_as::<KeyframeComponent>(*a)
                        .map(|k| k.beat)
                        .unwrap_or(0.0);
                    let bb = world
                        .get_component_by_id_as::<KeyframeComponent>(*b)
                        .map(|k| k.beat)
                        .unwrap_or(0.0);
                    ba.partial_cmp(&bb).unwrap_or(std::cmp::Ordering::Equal)
                });
                return;
            }
            cursor = world.parent_of(node);
        }
    }

    pub fn tick_with_beat(&mut self, world: &mut World, beat_now: f64, bpm: f64, rx: &mut RxWorld) {
        // If time jumps backwards, reset fired state.
        if beat_now + 1e-9 < self.last_beat {
            for runtime in self.animations.values_mut() {
                runtime.fired_keyframes.clear();
                runtime.audio_scheduled_cycle_by_keyframe.clear();
                runtime.audio_cycle = 0;
            }
        }

        // Apply any requested state changes.
        // Setting Playing/Looping is treated as a restart.
        for (&anim, runtime) in self.animations.iter_mut() {
            let Some(state) = runtime.pending_state.take() else {
                continue;
            };

            let Some(anim_comp) = world.get_component_by_id_as_mut::<AnimationComponent>(anim)
            else {
                continue;
            };

            anim_comp.state = state;
            runtime.start_beat = beat_now;
            runtime.fired_keyframes.clear();
            runtime.audio_scheduled_cycle_by_keyframe.clear();
            runtime.audio_cycle = 0;
        }

        // Drive animations.
        for (&anim, runtime) in self.animations.iter_mut() {
            let (state, length_override) =
                match world.get_component_by_id_as::<AnimationComponent>(anim) {
                    Some(c) => (c.state, c.length_beats),
                    None => continue,
                };

            if state == AnimationState::Paused {
                continue;
            }

            if runtime.keyframes.is_empty() {
                continue;
            }

            // Compute beat range for this animation.
            let Some((min_beat, max_beat)) = runtime
                .keyframes
                .iter()
                .filter_map(|&kf_id| {
                    world
                        .get_component_by_id_as::<KeyframeComponent>(kf_id)
                        .map(|kf| kf.beat)
                })
                .fold(None, |acc: Option<(f64, f64)>, beat| match acc {
                    None => Some((beat, beat)),
                    Some((min_b, max_b)) => Some((min_b.min(beat), max_b.max(beat))),
                })
            else {
                continue;
            };

            // Use per-animation local beat time so animations can restart/loop.
            let mut local_beat = (beat_now - runtime.start_beat).max(0.0);
            let span = (max_beat - min_beat).max(0.0);
            // Explicit `Animation.length(n)` wins. Otherwise default:
            // snap to the next whole beat after the last keyframe so
            // common musical loops stay stable even with off-beat
            // keyframes (e.g. max_beat=31.5 → 32.0, not 32.5).
            let loop_len = match length_override {
                Some(n) if n.is_finite() && n > 0.0 => n,
                _ if span < 1e-6 => 1.0,
                _ => span.floor() + 1.0,
            };

            if state == AnimationState::Looping {
                // Wrap local beat into [0, loop_len).
                // When we wrap, clear fired set so keyframes can fire again.
                if local_beat + 1e-9 >= loop_len {
                    let wraps = (local_beat / loop_len).floor();
                    if wraps >= 1.0 {
                        local_beat -= wraps * loop_len;
                        runtime.start_beat = beat_now - local_beat;
                        runtime.fired_keyframes.clear();

                        // Audio scheduling de-dupe is tracked by loop cycle index, so we do
                        // NOT clear it on wrap (lookahead may already have scheduled keyframes
                        // for the next cycle). We just advance the cycle counter.
                        runtime.audio_cycle = runtime.audio_cycle.saturating_add(wraps as u64);
                    }
                }
            }

            // Audio lookahead scheduling phase.
            //
            // Key detail: scheduled audio actions take a beat *offset* relative to the
            // beat context passed into keyframe evaluation. For lookahead, we want that
            // context to be the keyframe's intended beat time (global), not "now".
            let audio_due = self.scheduler.audio_due_keyframes(
                world,
                anim,
                &runtime.keyframes,
                &runtime.audio_scheduled_cycle_by_keyframe,
                runtime.audio_cycle,
                min_beat,
                local_beat,
                bpm,
                loop_len,
            );

            if !audio_due.is_empty() {
                for (kf_id, kf_local_beat, kf_cycle) in audio_due {
                    let cycle_offset = kf_cycle.saturating_sub(runtime.audio_cycle) as f64;
                    let kf_global_beat =
                        runtime.start_beat + cycle_offset * loop_len + kf_local_beat;

                    self.keyframe_evaluator.evaluate_audio_due_keyframe(
                        world,
                        rx,
                        kf_id,
                        kf_global_beat,
                    );

                    runtime
                        .audio_scheduled_cycle_by_keyframe
                        .insert(kf_id, kf_cycle);
                }
            }

            let due_keyframes = self.scheduler.visual_due_keyframes(
                world,
                &runtime.keyframes,
                &runtime.fired_keyframes,
                min_beat,
                local_beat,
            );

            for kf_id in due_keyframes {
                let Some(kf) = world.get_component_by_id_as::<KeyframeComponent>(kf_id) else {
                    continue;
                };
                let kf_local_beat = kf.beat - min_beat;

                if kf_local_beat <= local_beat + 1e-9 {
                    let already_scheduled = runtime
                        .audio_scheduled_cycle_by_keyframe
                        .get(&kf_id)
                        .copied()
                        == Some(runtime.audio_cycle);
                    self.keyframe_evaluator.evaluate_visual_due_keyframe(
                        world,
                        rx,
                        kf_id,
                        beat_now,
                        already_scheduled,
                    );

                    runtime.fired_keyframes.insert(kf_id);
                }
            }

            // Completion: a one-shot animation becomes paused once it has passed its end.
            if state == AnimationState::Playing {
                let done = local_beat + 1e-9 >= loop_len;
                if done {
                    if let Some(anim_comp) =
                        world.get_component_by_id_as_mut::<AnimationComponent>(anim)
                    {
                        anim_comp.state = AnimationState::Paused;
                    }
                }
            }
        }

        self.last_beat = beat_now;
    }
}

impl System for AnimationSystem {
    fn tick(
        &mut self,
        _world: &mut World,
        _visuals: &mut VisualWorld,
        _input: &InputState,
        _dt_sec: f32,
    ) {
        // Driven via `tick_with_beat` from SystemWorld.
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::ecs::IntentValue;
    use crate::engine::ecs::component::{AudioOscillatorComponent, TransformComponent};
    use crate::scripting::ast::{
        BinOpKind, BlockStatement, CallExpression, Expression, Ident, Statement,
    };
    use crate::scripting::object::{RuntimeClosure, Value};
    use crate::scripting::world_evaluator::{RuntimeClosureExecMode, eval_runtime_closure};
    use std::collections::HashMap;
    use std::sync::Arc;

    #[test]
    fn keyframe_callback_dispatches_live_component_intent_when_due() {
        let mut world = World::default();
        let animation =
            world.add_component(AnimationComponent::new().with_state(AnimationState::Playing));
        let target = world.add_component(TransformComponent::new());
        let callback = RuntimeClosure {
            body: BlockStatement {
                statements: vec![Statement::Expression(Expression::Call(CallExpression {
                    callee: Box::new(Expression::BinaryOp {
                        op: BinOpKind::Dot,
                        lhs: Box::new(Expression::Identifier(Ident("cube_t".to_string()))),
                        rhs: Box::new(Expression::Identifier(Ident(
                            "update_transform".to_string(),
                        ))),
                    }),
                    args: vec![
                        Expression::Array(vec![
                            Expression::Number(1.0),
                            Expression::Number(2.0),
                            Expression::Number(3.0),
                        ]),
                        Expression::Array(vec![
                            Expression::Number(0.0),
                            Expression::Number(0.5),
                            Expression::Number(0.0),
                        ]),
                        Expression::Array(vec![
                            Expression::Number(2.0),
                            Expression::Number(2.0),
                            Expression::Number(2.0),
                        ]),
                    ],
                }))],
            },
            captured_env: Arc::new(HashMap::from([(
                "cube_t".to_string(),
                Value::ComponentObject {
                    id: target,
                    component_type: "Transform".to_string(),
                },
            )])),
            heap: crate::scripting::object::HeapHandle::new(),
            analysis: None,
        };
        let keyframe = world.add_component(KeyframeComponent::new_with_callback(0.0, callback));
        world.add_child(animation, keyframe).unwrap();

        let mut system = AnimationSystem::new();
        system.register_animation(&mut world, animation);
        system.register_keyframe(&mut world, keyframe);

        let mut rx = RxWorld::default();
        system.tick_with_beat(&mut world, 0.0, 60.0, &mut rx);

        let intents = rx.drain_ready_intents();
        assert!(intents.iter().any(|signal| {
            matches!(
                signal.intent.as_ref().map(|intent| &intent.value),
                Some(IntentValue::UpdateTransform {
                    component_id,
                    translation,
                    scale,
                    ..
                }) if component_id == &target
                    && *translation == [1.0, 2.0, 3.0]
                    && *scale == [2.0, 2.0, 2.0]
            )
        }));
    }

    #[test]
    fn keyframe_callback_emissive_set_intensity_emits_intensity_intent() {
        let mut world = World::default();
        let animation =
            world.add_component(AnimationComponent::new().with_state(AnimationState::Playing));
        let target = world.add_component(crate::engine::ecs::component::EmissiveComponent::off());
        let callback = RuntimeClosure {
            body: BlockStatement {
                statements: vec![Statement::Expression(Expression::Call(CallExpression {
                    callee: Box::new(Expression::BinaryOp {
                        op: BinOpKind::Dot,
                        lhs: Box::new(Expression::Identifier(Ident("glow".to_string()))),
                        rhs: Box::new(Expression::Identifier(Ident("set_intensity".to_string()))),
                    }),
                    args: vec![Expression::Number(2.5)],
                }))],
            },
            captured_env: Arc::new(HashMap::from([(
                "glow".to_string(),
                Value::ComponentObject {
                    id: target,
                    component_type: "EM".to_string(),
                },
            )])),
            heap: crate::scripting::object::HeapHandle::new(),
            analysis: None,
        };
        let keyframe = world.add_component(KeyframeComponent::new_with_callback(0.0, callback));
        world.add_child(animation, keyframe).unwrap();

        let mut system = AnimationSystem::new();
        system.register_animation(&mut world, animation);
        system.register_keyframe(&mut world, keyframe);

        let mut rx = RxWorld::default();
        system.tick_with_beat(&mut world, 0.0, 60.0, &mut rx);

        let intents = rx.drain_ready_intents();
        assert!(intents.iter().any(|signal| {
            matches!(
                signal.intent.as_ref().map(|intent| &intent.value),
                Some(IntentValue::SetEmissiveIntensity {
                    component_id,
                    intensity,
                }) if component_id == &target && (*intensity - 2.5).abs() < 1.0e-6
            )
        }));

        let emissive = world
            .get_component_by_id_as::<crate::engine::ecs::component::EmissiveComponent>(target)
            .expect("target emissive exists");
        assert!((emissive.intensity - 2.5).abs() < 1.0e-6);
    }

    #[test]
    fn runtime_closure_audio_only_filters_visual_and_rewrites_beat_context() {
        let mut world = World::default();
        let glow = world.add_component(crate::engine::ecs::component::EmissiveComponent::off());
        let lead = world.add_component(AudioOscillatorComponent::default());

        let callback = RuntimeClosure {
            body: BlockStatement {
                statements: vec![
                    Statement::Expression(Expression::Call(CallExpression {
                        callee: Box::new(Expression::BinaryOp {
                            op: BinOpKind::Dot,
                            lhs: Box::new(Expression::Identifier(Ident("glow".to_string()))),
                            rhs: Box::new(Expression::Identifier(Ident(
                                "set_intensity".to_string(),
                            ))),
                        }),
                        args: vec![Expression::Number(2.5)],
                    })),
                    Statement::Expression(Expression::Call(CallExpression {
                        callee: Box::new(Expression::BinaryOp {
                            op: BinOpKind::Dot,
                            lhs: Box::new(Expression::Identifier(Ident("MusicNote".to_string()))),
                            rhs: Box::new(Expression::Identifier(Ident("e".to_string()))),
                        }),
                        args: vec![
                            Expression::Number(4.0),
                            Expression::Number(0.25),
                            Expression::Identifier(Ident("lead".to_string())),
                        ],
                    })),
                ],
            },
            captured_env: Arc::new(HashMap::from([
                (
                    "glow".to_string(),
                    Value::ComponentObject {
                        id: glow,
                        component_type: "EM".to_string(),
                    },
                ),
                (
                    "lead".to_string(),
                    Value::ComponentObject {
                        id: lead,
                        component_type: "AudioOscillator".to_string(),
                    },
                ),
            ])),
            heap: crate::scripting::object::HeapHandle::new(),
            analysis: None,
        };

        let mut rx = RxWorld::default();
        eval_runtime_closure(
            &callback,
            None,
            Some(&mut world),
            Some(&mut rx),
            None,
            RuntimeClosureExecMode::KeyframeAudioOnly { beat_context: 12.5 },
        )
        .expect("audio-only runtime closure eval succeeds");

        let intents = rx.drain_ready_intents();
        assert_eq!(intents.len(), 1);
        assert!(intents.iter().any(|signal| {
            matches!(
                signal.intent.as_ref().map(|intent| &intent.value),
                Some(IntentValue::AudioSchedulePlay {
                    component_id,
                    beat_context,
                    ..
                }) if component_id == &lead && *beat_context == Some(12.5)
            )
        }));
    }

    #[test]
    fn runtime_closure_visual_only_filters_audio() {
        let mut world = World::default();
        let glow = world.add_component(crate::engine::ecs::component::EmissiveComponent::off());
        let lead = world.add_component(AudioOscillatorComponent::default());

        let callback = RuntimeClosure {
            body: BlockStatement {
                statements: vec![
                    Statement::Expression(Expression::Call(CallExpression {
                        callee: Box::new(Expression::BinaryOp {
                            op: BinOpKind::Dot,
                            lhs: Box::new(Expression::Identifier(Ident("MusicNote".to_string()))),
                            rhs: Box::new(Expression::Identifier(Ident("e".to_string()))),
                        }),
                        args: vec![
                            Expression::Number(4.0),
                            Expression::Number(0.25),
                            Expression::Identifier(Ident("lead".to_string())),
                        ],
                    })),
                    Statement::Expression(Expression::Call(CallExpression {
                        callee: Box::new(Expression::BinaryOp {
                            op: BinOpKind::Dot,
                            lhs: Box::new(Expression::Identifier(Ident("glow".to_string()))),
                            rhs: Box::new(Expression::Identifier(Ident(
                                "set_intensity".to_string(),
                            ))),
                        }),
                        args: vec![Expression::Number(2.5)],
                    })),
                ],
            },
            captured_env: Arc::new(HashMap::from([
                (
                    "glow".to_string(),
                    Value::ComponentObject {
                        id: glow,
                        component_type: "EM".to_string(),
                    },
                ),
                (
                    "lead".to_string(),
                    Value::ComponentObject {
                        id: lead,
                        component_type: "AudioOscillator".to_string(),
                    },
                ),
            ])),
            heap: crate::scripting::object::HeapHandle::new(),
            analysis: None,
        };

        let mut rx = RxWorld::default();
        eval_runtime_closure(
            &callback,
            None,
            Some(&mut world),
            Some(&mut rx),
            None,
            RuntimeClosureExecMode::KeyframeVisualOnly,
        )
        .expect("visual-only runtime closure eval succeeds");

        let intents = rx.drain_ready_intents();
        assert_eq!(intents.len(), 1);
        assert!(intents.iter().any(|signal| {
            matches!(
                signal.intent.as_ref().map(|intent| &intent.value),
                Some(IntentValue::SetEmissiveIntensity {
                    component_id,
                    intensity,
                }) if component_id == &glow && (*intensity - 2.5).abs() < 1.0e-6
            )
        }));
    }
}