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
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
use crate::engine::ecs::ComponentId;
use crate::engine::ecs::EventSignal;
use crate::engine::ecs::RxWorld;
use crate::engine::ecs::World;
use crate::engine::ecs::component::CollisionComponent;
use crate::engine::ecs::system::System;
use crate::engine::ecs::system::TransformSystem;
use crate::engine::ecs::system::collision_geometry;
use crate::engine::ecs::system::collision_shape_resolver::resolve_collision_shape;
use crate::engine::graphics::VisualWorld;
use crate::engine::user_input::InputState;
use bvh::Point3;
use bvh::aabb::{AABB, Bounded};
use bvh::bounding_hierarchy::BHShape;
use bvh::bvh::{BVH, BVHNode};
use slotmap::Key;
use slotmap::{SlotMap, new_key_type};
use std::collections::{HashMap, HashSet};
use std::sync::mpsc;
use std::thread;

pub type CollisionShape = crate::engine::ecs::system::model::collision_types::CollisionShape;
pub type CollisionMode = crate::engine::ecs::system::model::collision_types::CollisionMode;

new_key_type! {
    pub struct StaticCollisionKey;
    pub struct KinematicCollisionKey;
    pub struct RiggedCollisionKey;
}

#[derive(Debug, Clone, Copy)]
pub enum CollisionHandle {
    Static(StaticCollisionKey),
    Kinematic(KinematicCollisionKey),
    Rigged(RiggedCollisionKey),
}

#[derive(Debug, Clone)]
pub enum CollisionMessage {
    // to worker
    Tick,
    AddObject {
        component: ComponentId,
        guid: uuid::Uuid,
        mode: CollisionMode,
        shape: CollisionShape,
        position_world: [f32; 3],
    },
    RemoveObject {
        component: ComponentId,
    },
    UpdateObject {
        component: ComponentId,
        guid: uuid::Uuid,
        mode: CollisionMode,
        shape: CollisionShape,
        position_world: [f32; 3],
    },
    Shutdown,

    // from worker
    CollisionDetected {
        a_component: ComponentId,
        a_guid: uuid::Uuid,
        a_mode: CollisionMode,
        b_component: ComponentId,
        b_guid: uuid::Uuid,
        b_mode: CollisionMode,
    },
}

/// Placeholder collision object record.
///
/// This will likely evolve into a more event-driven structure later (e.g. pairs,
/// contact manifolds, triggers).
#[derive(Debug, Clone)]
pub struct CollisionObject {
    pub component: ComponentId,
    pub guid: uuid::Uuid,
    pub mode: CollisionMode,
    pub shape: CollisionShape,

    /// Cached world-space position (translation).
    pub position_world: [f32; 3],
}

#[derive(Debug, Default)]
pub struct CollisionSystem {
    to_worker: Option<mpsc::Sender<CollisionMessage>>,
    from_worker: Option<mpsc::Receiver<CollisionMessage>>,
    worker: Option<thread::JoinHandle<()>>,

    known: HashSet<ComponentId>,

    active_pairs: HashSet<(ComponentId, ComponentId)>,
    active_pair_deltas: HashMap<(ComponentId, ComponentId), [f32; 3]>,
}

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

    /// Snapshot of the currently-active overlap pairs (normalized ordering).
    ///
    /// Note: this is updated when `tick_with_rx` drains worker messages.
    pub fn active_pairs_snapshot(&self) -> Vec<(ComponentId, ComponentId)> {
        self.active_pairs.iter().copied().collect()
    }

    /// Snapshot of active overlap pairs with `delta = pos(b) - pos(a)` in world space.
    pub fn active_pairs_with_delta_snapshot(&self) -> Vec<(ComponentId, ComponentId, [f32; 3])> {
        self.active_pairs
            .iter()
            .copied()
            .map(|(a, b)| {
                let delta = self
                    .active_pair_deltas
                    .get(&(a, b))
                    .copied()
                    .unwrap_or([0.0, 0.0, 0.0]);
                (a, b, delta)
            })
            .collect()
    }

    pub fn register_collision(
        &mut self,
        world: &mut World,
        _visuals: &mut VisualWorld,
        component: ComponentId,
    ) {
        self.ensure_worker();
        self.upsert_component(world, component);
    }

    /// Update a collision object when its parent transform changes.
    ///
    /// Intended to be called by TransformSystem when `transform_component` has `component`
    /// as a direct child.
    pub fn update_from_transform(
        &mut self,
        world: &mut World,
        component: ComponentId,
        transform_component: ComponentId,
    ) {
        self.ensure_worker();

        let position_world = match world
            .get_component_by_id_as::<crate::engine::ecs::component::TransformComponent>(
                transform_component,
            )
            .map(|t| t.transform.matrix_world)
        {
            Some(m) => {
                let p = m[3];
                [p[0], p[1], p[2]]
            }
            None => TransformSystem::world_position(world, component).unwrap_or([0.0, 0.0, 0.0]),
        };

        self.upsert_component_with_position(world, component, position_world);
    }

    pub fn remove_collision(
        &mut self,
        _world: &mut World,
        _visuals: &mut VisualWorld,
        component: ComponentId,
    ) {
        self.ensure_worker();
        if let Some(tx) = self.to_worker.as_ref() {
            let _ = tx.send(CollisionMessage::RemoveObject { component });
        }
        self.known.remove(&component);
    }

    fn upsert_component(&mut self, world: &mut World, component: ComponentId) {
        let position_world =
            TransformSystem::world_position(world, component).unwrap_or([0.0, 0.0, 0.0]);
        self.upsert_component_with_position(world, component, position_world);
    }

    fn upsert_component_with_position(
        &mut self,
        world: &mut World,
        component: ComponentId,
        position_world: [f32; 3],
    ) {
        // Semantics: a CollisionComponent only has behavior when it is a direct child of a
        // TransformComponent. Otherwise, it should not participate in collision at all.
        let has_transform_parent = world
            .parent_of(component)
            .and_then(|p| {
                world
                    .get_component_by_id_as::<crate::engine::ecs::component::TransformComponent>(p)
                    .map(|_| p)
            })
            .is_some();

        if !has_transform_parent {
            if self.known.remove(&component) {
                if let Some(tx) = self.to_worker.as_ref() {
                    let _ = tx.send(CollisionMessage::RemoveObject { component });
                }
            }
            return;
        }

        let Some(collision_comp) = world.get_component_by_id_as::<CollisionComponent>(component)
        else {
            return;
        };

        let Some(tx) = self.to_worker.as_ref() else {
            return;
        };

        let guid = match world.get_component_record(component) {
            Some(node) => node.guid,
            None => return,
        };

        let mode = collision_comp.mode;

        let shape = resolve_collision_shape(world, component).unwrap_or_else(|| {
            crate::engine::ecs::system::model::collision_types::CollisionShape::CUBE()
        });

        let msg = if self.known.contains(&component) {
            CollisionMessage::UpdateObject {
                component,
                guid,
                mode,
                shape,
                position_world,
            }
        } else {
            CollisionMessage::AddObject {
                component,
                guid,
                mode,
                shape,
                position_world,
            }
        };

        let _ = tx.send(msg);
        self.known.insert(component);
    }

    fn ensure_worker(&mut self) {
        if self.to_worker.is_some() {
            return;
        }

        let (to_worker_tx, to_worker_rx) = mpsc::channel::<CollisionMessage>();
        let (from_worker_tx, from_worker_rx) = mpsc::channel::<CollisionMessage>();

        let handle = thread::Builder::new()
            .name("CollisionSystemWorker".to_string())
            .spawn(move || collision_worker_loop(to_worker_rx, from_worker_tx))
            .expect("failed to spawn CollisionSystemWorker thread");

        self.to_worker = Some(to_worker_tx);
        self.from_worker = Some(from_worker_rx);
        self.worker = Some(handle);
    }
}

impl Drop for CollisionSystem {
    fn drop(&mut self) {
        if let Some(tx) = self.to_worker.take() {
            let _ = tx.send(CollisionMessage::Shutdown);
        }
        if let Some(h) = self.worker.take() {
            let _ = h.join();
        }
    }
}

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

impl CollisionSystem {
    pub fn tick_with_rx(
        &mut self,
        world: &mut World,
        _visuals: &mut VisualWorld,
        _input: &InputState,
        _dt_sec: f32,
        rx: &mut RxWorld,
    ) {
        self.ensure_worker();

        let Some(tx) = self.to_worker.as_ref() else {
            return;
        };

        // Drain worker -> current overlap set.
        let mut current_pairs: HashSet<(ComponentId, ComponentId)> = HashSet::new();
        let mut current_deltas: HashMap<(ComponentId, ComponentId), [f32; 3]> = HashMap::new();
        if let Some(from_worker) = self.from_worker.as_ref() {
            while let Ok(msg) = from_worker.try_recv() {
                let CollisionMessage::CollisionDetected {
                    a_component,
                    a_guid: _,
                    a_mode: _,
                    b_component,
                    b_guid: _,
                    b_mode: _,
                } = msg
                else {
                    continue;
                };

                // Normalize ordering so (a,b) and (b,a) map to the same pair.
                let a_key = a_component.data().as_ffi();
                let b_key = b_component.data().as_ffi();
                let (lo, hi) = if a_key <= b_key {
                    (a_component, b_component)
                } else {
                    (b_component, a_component)
                };
                if lo != hi {
                    if current_pairs.insert((lo, hi)) {
                        let a_pos =
                            TransformSystem::world_position(world, lo).unwrap_or([0.0, 0.0, 0.0]);
                        let b_pos =
                            TransformSystem::world_position(world, hi).unwrap_or([0.0, 0.0, 0.0]);
                        current_deltas.insert(
                            (lo, hi),
                            [
                                b_pos[0] - a_pos[0],
                                b_pos[1] - a_pos[1],
                                b_pos[2] - a_pos[2],
                            ],
                        );
                    }
                }
            }
        }

        // Emit started/ended based on set diffs.
        for &(a, b) in current_pairs.difference(&self.active_pairs) {
            let delta = current_deltas
                .get(&(a, b))
                .copied()
                .unwrap_or([0.0, 0.0, 0.0]);
            rx.push_event(a, EventSignal::CollisionStarted { a, b, delta });
            rx.push_event(b, EventSignal::CollisionStarted { a, b, delta });
        }

        for &(a, b) in self.active_pairs.difference(&current_pairs) {
            let delta = self
                .active_pair_deltas
                .get(&(a, b))
                .copied()
                .unwrap_or([0.0, 0.0, 0.0]);
            rx.push_event(a, EventSignal::CollisionEnded { a, b, delta });
            rx.push_event(b, EventSignal::CollisionEnded { a, b, delta });
        }

        self.active_pairs = current_pairs;
        self.active_pair_deltas = current_deltas;

        let _ = tx.send(CollisionMessage::Tick);
    }
}

#[derive(Debug, Clone)]
struct StoredObject {
    component: ComponentId,
    guid: uuid::Uuid,
    mode: CollisionMode,
    shape: CollisionShape,
    position_world: [f32; 3],
}

struct WorkerState {
    static_objects: SlotMap<StaticCollisionKey, StoredObject>,
    kinematic_objects: SlotMap<KinematicCollisionKey, StoredObject>,
    rigged_objects: SlotMap<RiggedCollisionKey, StoredObject>,

    by_component: HashMap<ComponentId, CollisionHandle>,
}

impl Default for WorkerState {
    fn default() -> Self {
        Self {
            static_objects: SlotMap::with_key(),
            kinematic_objects: SlotMap::with_key(),
            rigged_objects: SlotMap::with_key(),
            by_component: HashMap::new(),
        }
    }
}

fn collision_worker_loop(rx: mpsc::Receiver<CollisionMessage>, tx: mpsc::Sender<CollisionMessage>) {
    let mut state = WorkerState::default();
    while let Ok(msg) = rx.recv() {
        match msg {
            CollisionMessage::Shutdown => break,
            CollisionMessage::AddObject {
                component,
                guid,
                mode,
                shape,
                position_world,
            } => {
                worker_upsert(&mut state, component, guid, mode, shape, position_world);
            }
            CollisionMessage::UpdateObject {
                component,
                guid,
                mode,
                shape,
                position_world,
            } => {
                worker_upsert(&mut state, component, guid, mode, shape, position_world);
            }
            CollisionMessage::RemoveObject { component } => {
                worker_remove(&mut state, component);
            }
            CollisionMessage::Tick => {
                worker_tick(&state, &tx);
            }
            CollisionMessage::CollisionDetected { .. } => {
                // main->worker never sends this
            }
        }
    }
}

fn worker_remove(state: &mut WorkerState, component: ComponentId) {
    let Some(handle) = state.by_component.remove(&component) else {
        return;
    };

    match handle {
        CollisionHandle::Static(k) => {
            let _ = state.static_objects.remove(k);
        }
        CollisionHandle::Kinematic(k) => {
            let _ = state.kinematic_objects.remove(k);
        }
        CollisionHandle::Rigged(k) => {
            let _ = state.rigged_objects.remove(k);
        }
    }
}

fn worker_upsert(
    state: &mut WorkerState,
    component: ComponentId,
    guid: uuid::Uuid,
    mode: CollisionMode,
    shape: CollisionShape,
    position_world: [f32; 3],
) {
    // If mode changed, remove from old store.
    if let Some(existing) = state.by_component.get(&component).copied() {
        let existing_mode = match existing {
            CollisionHandle::Static(_) => CollisionMode::Static,
            CollisionHandle::Kinematic(_) => CollisionMode::Kinematic,
            CollisionHandle::Rigged(_) => CollisionMode::Rigged,
        };
        if existing_mode != mode {
            worker_remove(state, component);
        }
    }

    let obj = StoredObject {
        component,
        guid,
        mode,
        shape,
        position_world,
    };

    match state.by_component.get(&component).copied() {
        Some(CollisionHandle::Static(k)) => {
            if let Some(stored) = state.static_objects.get_mut(k) {
                *stored = obj;
            }
        }
        Some(CollisionHandle::Kinematic(k)) => {
            if let Some(stored) = state.kinematic_objects.get_mut(k) {
                *stored = obj;
            }
        }
        Some(CollisionHandle::Rigged(k)) => {
            if let Some(stored) = state.rigged_objects.get_mut(k) {
                *stored = obj;
            }
        }
        None => {
            let handle = match mode {
                CollisionMode::Static => {
                    let k = state.static_objects.insert(obj);
                    CollisionHandle::Static(k)
                }
                CollisionMode::Kinematic => {
                    let k = state.kinematic_objects.insert(obj);
                    CollisionHandle::Kinematic(k)
                }
                CollisionMode::Rigged => {
                    let k = state.rigged_objects.insert(obj);
                    CollisionHandle::Rigged(k)
                }
            };
            state.by_component.insert(component, handle);
        }
    }
}

fn worker_tick(state: &WorkerState, tx: &mpsc::Sender<CollisionMessage>) {
    let mut all: Vec<&StoredObject> = Vec::new();
    all.extend(state.static_objects.values());
    all.extend(state.kinematic_objects.values());
    all.extend(state.rigged_objects.values());

    if all.len() < 2 {
        return;
    }

    // Broadphase: build a BVH over world-space AABBs for the collision objects.
    // This reduces the candidate set for narrowphase `intersects()`.
    let mut shapes: Vec<CollisionAabbShape> = all
        .iter()
        .enumerate()
        .filter_map(|(index, obj)| {
            let (min, max) = world_aabb_for_collision_object(obj);
            Some(CollisionAabbShape::new(index, min, max))
        })
        .collect();

    // If any shapes failed to produce AABBs, fall back to brute force.
    if shapes.len() != all.len() {
        for i in 0..all.len() {
            for j in (i + 1)..all.len() {
                let a = all[i];
                let b = all[j];

                if a.mode == CollisionMode::Static && b.mode == CollisionMode::Static {
                    continue;
                }

                if intersects(a, b) {
                    let _ = tx.send(CollisionMessage::CollisionDetected {
                        a_component: a.component,
                        a_guid: a.guid,
                        a_mode: a.mode,
                        b_component: b.component,
                        b_guid: b.guid,
                        b_mode: b.mode,
                    });
                }
            }
        }
        return;
    }

    let bvh = BVH::build(&mut shapes);

    // Only query from non-static objects.
    // Static-static collisions are ignored, and static objects don't need to initiate queries.
    for i in 0..all.len() {
        let a = all[i];
        if a.mode == CollisionMode::Static {
            continue;
        }

        let query = shapes[i].aabb;
        let candidates = bvh_query_aabb_indices(&bvh, &shapes, &query);

        for j in candidates {
            if j == i || j >= all.len() {
                continue;
            }

            let b = all[j];

            // Avoid double-reporting dynamic-dynamic pairs, but always test dynamic-static.
            if b.mode != CollisionMode::Static && j <= i {
                continue;
            }

            if intersects(a, b) {
                let _ = tx.send(CollisionMessage::CollisionDetected {
                    a_component: a.component,
                    a_guid: a.guid,
                    a_mode: a.mode,
                    b_component: b.component,
                    b_guid: b.guid,
                    b_mode: b.mode,
                });
            }
        }
    }
}

#[derive(Debug, Clone)]
struct CollisionAabbShape {
    index: usize,
    aabb: AABB,
    node_index: usize,
}

impl CollisionAabbShape {
    fn new(index: usize, min: [f32; 3], max: [f32; 3]) -> Self {
        Self {
            index,
            aabb: AABB::with_bounds(
                Point3::new(min[0], min[1], min[2]),
                Point3::new(max[0], max[1], max[2]),
            ),
            node_index: 0,
        }
    }
}

impl Bounded for CollisionAabbShape {
    fn aabb(&self) -> AABB {
        self.aabb
    }
}

impl BHShape for CollisionAabbShape {
    fn set_bh_node_index(&mut self, index: usize) {
        self.node_index = index;
    }

    fn bh_node_index(&self) -> usize {
        self.node_index
    }
}

fn bvh_query_aabb_indices(bvh: &BVH, shapes: &[CollisionAabbShape], query: &AABB) -> Vec<usize> {
    if bvh.nodes.is_empty() {
        return Vec::new();
    }

    let mut out = Vec::new();
    let mut stack = vec![0usize];
    while let Some(node_index) = stack.pop() {
        match bvh.nodes[node_index] {
            BVHNode::Node {
                child_l_index,
                child_l_aabb,
                child_r_index,
                child_r_aabb,
                ..
            } => {
                if aabb_overlap_bvh(query, &child_l_aabb) {
                    stack.push(child_l_index);
                }
                if aabb_overlap_bvh(query, &child_r_aabb) {
                    stack.push(child_r_index);
                }
            }
            BVHNode::Leaf { shape_index, .. } => {
                if let Some(s) = shapes.get(shape_index) {
                    if aabb_overlap_bvh(query, &s.aabb) {
                        out.push(s.index);
                    }
                }
            }
        }
    }

    out
}

fn aabb_overlap_bvh(a: &AABB, b: &AABB) -> bool {
    !(a.max.x < b.min.x
        || a.min.x > b.max.x
        || a.max.y < b.min.y
        || a.min.y > b.max.y
        || a.max.z < b.min.z
        || a.min.z > b.max.z)
}

fn world_aabb_for_collision_object(obj: &StoredObject) -> ([f32; 3], [f32; 3]) {
    collision_geometry::world_aabb(obj.position_world, obj.shape)
}

fn intersects(a: &StoredObject, b: &StoredObject) -> bool {
    collision_geometry::intersects(a.position_world, a.shape, b.position_world, b.shape)
}