maple_engine 0.3.0

Engine implementation of maple engine
Documentation
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
use std::{
    any::TypeId,
    collections::{HashMap, VecDeque},
    marker::PhantomData,
    ops::{Deref, DerefMut},
    sync::Arc,
};

use parking_lot::{ArcRwLockReadGuard, ArcRwLockWriteGuard, RawRwLock, RwLock};

use crate::{
    GameContext, Node,
    asset::{Asset, AssetHandle, AssetLibrary, AssetState},
    platform::SendSync,
    prelude::{EventCtx, EventLabel, EventReceiver, Ready, node_transform::WorldTransform},
};

#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
pub struct NodeId(u64);

impl Default for NodeId {
    fn default() -> Self {
        Self::new()
    }
}

impl NodeId {
    pub fn new() -> Self {
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(1);
        NodeId(COUNTER.fetch_add(1, Ordering::Relaxed))
    }
}

pub struct SceneNode {
    _id: NodeId,
    name: String,
    children: Vec<NodeId>,
    parent: Option<NodeId>,
    type_id: TypeId,
}

type NodeStorage = Arc<RwLock<Box<dyn Node>>>;

/// Typed Handle to a node in the scene
///
/// Allows access to a node in the scene without locks. This doesnt store the Node and is
/// cheap to copy. The actual node can be accessed via '.read()' and '.write()'.
///
/// lifetime is tied to the scene
pub struct NodeHandle<'a, T: Node> {
    id: NodeId,
    scene: &'a Scene,
    _ty: PhantomData<T>,
}

/// RAII guard for immutible access to a node.
pub struct NodeReadGuard<T: Node> {
    guard: ArcRwLockReadGuard<RawRwLock, Box<dyn Node>>,
    _ty: PhantomData<T>,
}

/// RAII guard for mutible access to a node.
pub struct NodeWriteGuard<T: Node> {
    guard: ArcRwLockWriteGuard<RawRwLock, Box<dyn Node>>,
    _ty: PhantomData<T>,
}

impl<T: Node> Deref for NodeReadGuard<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        self.guard.as_any().downcast_ref::<T>().unwrap()
    }
}

impl<T: Node> Deref for NodeWriteGuard<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        self.guard.as_any().downcast_ref::<T>().unwrap()
    }
}

impl<T: Node> DerefMut for NodeWriteGuard<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.guard.as_any_mut().downcast_mut::<T>().unwrap()
    }
}

impl<'a, T: Node> NodeHandle<'a, T> {
    /// returns the id of this node
    pub fn id(&self) -> NodeId {
        self.id
    }

    /// returns the name of the node
    pub fn name(&self) -> Option<String> {
        self.scene.node_name(self.id)
    }

    /// returns the children of this node
    pub fn children(&self) -> Vec<NodeId> {
        self.scene.children(self.id)
    }

    /// add a node as a child of this node
    pub fn spawn_child<C: Node>(&self, name: impl Into<String>, node: C) -> NodeHandle<'a, C> {
        self.scene.spawn_as_child(name, node, self.id)
    }

    /// merge a different node as a child of this node
    pub fn merge_scene(&self, other: Scene) -> Vec<NodeId> {
        self.scene.merge_as_child(other, self.id)
    }

    /// merge a scene asset into the scene
    pub fn merge_asset<A: SceneAsset>(&self, handle: AssetHandle<A>) {
        self.scene.merge_asset_as_child(handle, self.id);
    }

    /// add an event to the node
    pub fn on<E: EventLabel>(
        &self,
        handler: impl FnMut(EventCtx<E, T>) + Send + Sync + 'static,
    ) -> &Self {
        self.scene.on(self.id(), handler);
        self
    }

    /// provides immutible access to this node.
    ///
    /// Multiple reader can access the same node at the same time but blocks if a writer holds the
    /// lock.
    pub fn read(&self) -> NodeReadGuard<T> {
        let node_lock = {
            let nodes = self.scene.nodes.read();
            Arc::clone(nodes.get(&self.id).expect("Node not found"))
        };

        // Use read_arc instead of read - it takes ownership semantics of the Arc
        let guard = RwLock::read_arc(&node_lock);
        NodeReadGuard {
            guard,
            _ty: PhantomData,
        }
    }

    /// provides mutible access to this node.
    ///
    /// Only one writer can access a node at a time.
    /// Blocks if any readers or writers hold a lock.
    pub fn write(&self) -> NodeWriteGuard<T> {
        let node_lock = {
            let nodes = self.scene.nodes.read();
            Arc::clone(nodes.get(&self.id).expect("Node not found"))
        };

        let guard = RwLock::write_arc(&node_lock);

        NodeWriteGuard {
            guard,
            _ty: PhantomData,
        }
    }
}

type PendingAssetEntry = (Box<dyn PendingSceneAsset>, Option<NodeId>);

/// A hierarchical scene graph for storing and organizing nodes.
///
/// the scene manages the Scene Tree which stores Nodes in a Tree structure meaning Nodes can have
/// children. Nodes are stored internally using a RWLock to allow mutibility because of this borrow
/// checking is runtime managed and calling .write on the same node twice at once will panic.
///
/// # Example
/// ```ignore
/// let scene = Scene::new();
/// let camera = scene.add("main_camera", Camera3D::default());
/// let player = Scene.add("player", Player::default());
/// player.add_child("tool", Tool::new());
/// ```
///
///
pub struct Scene {
    nodes: RwLock<HashMap<NodeId, NodeStorage>>,

    heirarchy: RwLock<HashMap<NodeId, SceneNode>>,

    events: RwLock<HashMap<NodeId, EventReceiver>>,

    /// ready event queue since nodes added after engine ready wouldnt run ready otherwise and we
    /// dont have context on add
    ready_queue: RwLock<VecDeque<NodeId>>,

    pending_assets: RwLock<Vec<PendingAssetEntry>>,
}

impl Default for Scene {
    fn default() -> Self {
        Self::new()
    }
}

impl<'a> Scene {
    pub fn new() -> Self {
        Self {
            nodes: RwLock::new(HashMap::new()),
            heirarchy: RwLock::new(HashMap::new()),
            events: RwLock::new(HashMap::new()),
            ready_queue: RwLock::new(VecDeque::new()),
            pending_assets: RwLock::new(Vec::new()),
        }
    }

    /// Adds a node to the root of the scene with no parents.
    pub fn spawn<T: Node>(&'a self, name: impl Into<String>, node: T) -> NodeHandle<'a, T> {
        self.spawn_with_parent(name, node, None)
    }

    /// Adds a node to the scene with a parent
    pub fn spawn_as_child<T: Node>(
        &'a self,
        name: impl Into<String>,
        node: T,
        parent: NodeId,
    ) -> NodeHandle<'a, T> {
        self.spawn_with_parent(name, node, Some(parent))
    }

    /// add an event to a node
    pub fn on<E: EventLabel, N: Node>(
        &self,
        node: NodeId,
        handler: impl FnMut(EventCtx<E, N>) + SendSync + 'static,
    ) {
        self.events
            .write()
            .entry(node)
            .or_default()
            .on::<E, N, _>(handler);
    }

    fn spawn_with_parent<T: Node>(
        &'a self,
        name: impl Into<String>,
        node: T,
        parent: Option<NodeId>,
    ) -> NodeHandle<'a, T> {
        let id = NodeId::new();

        let scene_node = SceneNode {
            _id: id,
            name: name.into(),
            children: Vec::new(),
            parent,
            type_id: TypeId::of::<T>(),
        };

        {
            let mut hierarchy = self.heirarchy.write();
            if let Some(parent_id) = parent
                && let Some(parent_node) = hierarchy.get_mut(&parent_id)
            {
                parent_node.children.push(id);
            }
            hierarchy.insert(id, scene_node);
        }

        {
            let mut nodes = self.nodes.write();
            nodes.insert(id, Arc::new(RwLock::new(Box::new(node))));
        }

        {
            let mut ready_queue = self.ready_queue.write();
            ready_queue.push_back(id);
        }

        NodeHandle {
            id,
            scene: self,
            _ty: PhantomData,
        }
    }

    /// merge a different scene into this one preserving the hierarchy.
    pub fn merge(&self, other: impl Into<Scene>) -> Vec<NodeId> {
        self.merge_as_child_of(other.into(), None)
    }

    /// merge a different scene as a child of a specified node
    pub fn merge_as_child(&self, other: impl Into<Scene>, parent: NodeId) -> Vec<NodeId> {
        self.merge_as_child_of(other.into(), Some(parent))
    }

    /// merge a scene without blocking the load
    pub fn merge_asset<T: Asset + SceneAsset>(&self, handle: AssetHandle<T>) {
        let pending = TypedPendingAsset { handle };
        self.pending_assets.write().push((Box::new(pending), None));
    }

    /// merge a scene assent as a child of a node
    pub fn merge_asset_as_child<T: Asset + SceneAsset>(
        &self,
        handle: AssetHandle<T>,
        parent: NodeId,
    ) {
        let pending = TypedPendingAsset { handle };
        self.pending_assets
            .write()
            .push((Box::new(pending), Some(parent)));
    }

    fn merge_as_child_of(&self, other: Scene, parent: Option<NodeId>) -> Vec<NodeId> {
        let mut other_hierarchy = other.heirarchy.write();
        let mut other_nodes = other.nodes.write();
        let mut other_events = other.events.write();

        let root_ids: Vec<NodeId> = other_hierarchy
            .iter()
            .filter(|(_, node)| node.parent.is_none())
            .map(|(id, _)| *id)
            .collect();

        {
            let mut self_heirarchy = self.heirarchy.write();
            let mut self_nodes = self.nodes.write();
            let mut self_events = self.events.write();

            for (id, mut scene_node) in other_hierarchy.drain() {
                if scene_node.parent.is_none() {
                    scene_node.parent = parent;
                }
                self_heirarchy.insert(id, scene_node);
            }

            for (id, node_data) in other_nodes.drain() {
                self_nodes.insert(id, node_data);
            }

            for (id, events) in other_events.drain() {
                self_events.insert(id, events);
            }

            self.ready_queue
                .write()
                .append(&mut other.ready_queue.write());

            self.pending_assets
                .write()
                .append(&mut other.pending_assets.write());

            if let Some(parent_id) = parent
                && let Some(parent_node) = self_heirarchy.get_mut(&parent_id)
            {
                parent_node.children.extend(&root_ids);
            }
        }

        root_ids
    }

    /// get handle to a node via an id
    pub fn get<T: Node>(&'a self, id: NodeId) -> Option<NodeHandle<'a, T>> {
        let hierarchy = self.heirarchy.read();
        let scene_node = hierarchy.get(&id)?;

        if scene_node.type_id != TypeId::of::<T>() {
            return None;
        }

        Some(NodeHandle {
            id,
            scene: self,
            _ty: PhantomData,
        })
    }

    /// get a node by name
    pub fn get_by_name<T: Node>(&'a self, name: &str) -> Option<NodeHandle<'a, T>> {
        let hierarchy = self.heirarchy.read();
        let type_id = TypeId::of::<T>();

        for (id, scene_node) in hierarchy.iter() {
            if scene_node.name == name && scene_node.type_id == type_id {
                return Some(NodeHandle {
                    id: *id,
                    scene: self,
                    _ty: PhantomData,
                });
            }
        }
        None
    }

    /// get the parent of the node
    pub fn parent(&self, id: NodeId) -> Option<NodeId> {
        self.heirarchy.read().get(&id).and_then(|n| n.parent)
    }

    /// get the children of the node
    pub fn children(&self, id: NodeId) -> Vec<NodeId> {
        self.heirarchy
            .read()
            .get(&id)
            .map(|n| n.children.clone())
            .unwrap_or_default()
    }

    /// get the name of a node
    pub fn node_name(&self, id: NodeId) -> Option<String> {
        self.heirarchy.read().get(&id).map(|n| n.name.clone())
    }

    /// collects all nodes of a specific type
    pub fn collect<T: Node>(&'a self) -> Vec<NodeHandle<'a, T>> {
        let heirarchy = self.heirarchy.read();
        let type_id = TypeId::of::<T>();

        heirarchy
            .iter()
            .filter(|(_, node)| node.type_id == type_id)
            .map(|(id, _)| NodeHandle {
                id: *id,
                scene: self,
                _ty: PhantomData,
            })
            .collect()
    }

    /// get all the root node ids
    pub fn root_ids(&self) -> Vec<NodeId> {
        let hierarchy = self.heirarchy.read();
        hierarchy
            .iter()
            .filter(|(_, node)| node.parent.is_none())
            .map(|(id, _)| *id)
            .collect()
    }

    /// emit an event to the scene (this will also update world space transforms)
    pub fn emit<E: EventLabel>(&self, event: &E, ctx: &GameContext) {
        for root_id in self.root_ids() {
            self.emit_recursive(root_id, event, ctx);
        }
    }

    fn emit_recursive<E: EventLabel>(&self, id: NodeId, event: &E, ctx: &GameContext) {
        // if an event receiver exist trigger the event to it
        if let Some(events) = self.events.read().get(&id) {
            events.trigger(event, self, id, ctx);
        }

        let children = self.children(id);
        for child_id in children {
            self.emit_recursive(child_id, event, ctx);
        }
    }

    /// goes through every node and updates the world position recursively
    ///
    /// this is done once per frame after update
    pub fn sync_world_transform(&self) {
        for id in self.root_ids() {
            self.sync_world_transform_recursive(id, WorldTransform::default());
        }
    }

    fn sync_world_transform_recursive(&self, id: NodeId, parent_world: WorldTransform) {
        let node_lock = {
            let nodes = self.nodes.read();
            nodes.get(&id).map(Arc::clone)
        };

        let Some(node_lock) = node_lock else {
            return;
        };

        let mut node = node_lock.write();

        node.get_transform().get_world_space(parent_world);
        let current_world = *node.get_transform().world_space();

        drop(node);

        let children = self.children(id);
        for child in children {
            self.sync_world_transform_recursive(child, current_world);
        }
    }

    pub(crate) fn pop_ready_queue(&self, ctx: &GameContext) {
        while let Some(id) = self.ready_queue.write().pop_front() {
            self.emit_to(id, &Ready, ctx);
        }
    }

    /// emit an event to a single node
    pub fn emit_to<E: EventLabel>(&self, id: NodeId, event: &E, ctx: &GameContext) {
        // if an event receiver exist trigger the event to it
        if let Some(events) = self.events.read().get(&id) {
            events.trigger(event, self, id, ctx);
        }
    }

    /// run a callback on each node of a specific type
    pub fn for_each<T: Node>(&self, f: &mut impl FnMut(&mut T)) {
        let type_id = TypeId::of::<T>();

        let node_locks: Vec<NodeStorage> = {
            let hierarchy = self.heirarchy.read();
            let nodes = self.nodes.read();

            hierarchy
                .iter()
                .filter(|(_, node)| node.type_id == type_id)
                .filter_map(|(id, _)| nodes.get(id).map(Arc::clone))
                .collect()
        };

        for node_lock in node_locks {
            let mut node = node_lock.write();
            if let Some(concrete) = node.as_any_mut().downcast_mut::<T>() {
                f(concrete);
            }
        }
    }

    /// run a callback for each node of a specific type
    pub fn for_each_ref<T: Node>(&self, f: &mut impl FnMut(&T)) {
        let type_id = TypeId::of::<T>();

        let node_locks: Vec<NodeStorage> = {
            let hierarchy = self.heirarchy.read();
            let nodes = self.nodes.read();

            hierarchy
                .iter()
                .filter(|(_, node)| node.type_id == type_id)
                .filter_map(|(id, _)| nodes.get(id).map(Arc::clone))
                .collect()
        };

        for node_lock in node_locks {
            let node = node_lock.read();
            if let Some(concrete) = node.as_any().downcast_ref::<T>() {
                f(concrete);
            }
        }
    }

    /// run a callback on each node of a specific type and get the NodeId
    pub fn for_each_with_id<T: Node>(&self, f: &mut impl FnMut(NodeId, &mut T)) {
        let type_id = TypeId::of::<T>();

        let node_data: Vec<(NodeId, NodeStorage)> = {
            let hierarchy = self.heirarchy.read();
            let nodes = self.nodes.read();

            hierarchy
                .iter()
                .filter(|(_, node)| node.type_id == type_id)
                .filter_map(|(id, _)| nodes.get(id).map(|n| (*id, Arc::clone(n))))
                .collect()
        };

        for (id, node_lock) in node_data {
            let mut node = node_lock.write();
            if let Some(concrete) = node.as_any_mut().downcast_mut::<T>() {
                f(id, concrete);
            }
        }
    }

    /// polls pending assets and adds them if ready
    pub fn poll_async(&mut self, assets: &AssetLibrary) {
        let mut loaded_indices = Vec::new();

        {
            let pending = self.pending_assets.read();
            if pending.is_empty() {
                return;
            }

            log::trace!("Polling {} scene assets", pending.len());

            // Check which assets are done
            for (i, (asset, parent)) in pending.iter().enumerate() {
                if asset.poll_and_load(assets, self, *parent) {
                    loaded_indices.push(i);
                }
            }
        }

        // Remove loaded assets (iterate in reverse to maintain indices)
        if !loaded_indices.is_empty() {
            let mut pending = self.pending_assets.write();
            for &i in loaded_indices.iter().rev() {
                log::info!("merging loaded scene into scene");
                pending.swap_remove(i);
            }
        }
    }
}

trait PendingSceneAsset: Send + Sync {
    /// Poll this asset and load it into the scene if ready                                                                                                                                                                                                                     
    /// Returns true if done (loaded or errored), false if still loading                                                                                                                                                                                                        
    fn poll_and_load(&self, assets: &AssetLibrary, scene: &Scene, parent: Option<NodeId>) -> bool;
}

// Concrete implementation that wraps a typed handle
struct TypedPendingAsset<T: Asset + SceneAsset> {
    handle: AssetHandle<T>,
}

impl<T: Asset + SceneAsset> PendingSceneAsset for TypedPendingAsset<T> {
    fn poll_and_load(&self, assets: &AssetLibrary, scene: &Scene, parent: Option<NodeId>) -> bool {
        match assets.get(&self.handle) {
            AssetState::Loaded(asset) => {
                asset.load(scene, parent);
                true // Done - remove from pending                                                                                                                                                                                                                              
            }
            AssetState::Error(e) => {
                log::error!("Failed to load scene asset: {:?}", e);
                true // Done with error - remove from pending                                                                                                                                                                                                                   
            }
            AssetState::Loading => false, // Still loading - keep in pending
        }
    }
}
pub trait SceneAsset: Asset {
    fn load(&self, scene: &Scene, parent: Option<NodeId>);
}

pub trait IntoScene {
    fn into(self, assets: &AssetLibrary) -> Scene;
}

impl IntoScene for Scene {
    fn into(self, _assets: &AssetLibrary) -> Scene {
        self
    }
}

pub trait SceneBuilder {
    fn build(&mut self, assets: &AssetLibrary) -> Scene;
}

impl<T: SceneBuilder> IntoScene for T {
    fn into(mut self, assets: &AssetLibrary) -> Scene {
        self.build(assets)
    }
}

// TODO make instanceable scene
// type InstanceableNodeStorage = Arc<RwLock<Box<dyn Instanceable>>>;
//
// pub struct InstancableScene {
//     nodes: RwLock<HashMap<NodeId, InstanceableNodeStorage>>,
//
//     heirarchy: RwLock<HashMap<NodeId, SceneNode>>,
//
//     events: RwLock<HashMap<NodeId, EventReceiver>>,
//
//     /// ready event queue since nodes added after engine ready wouldnt run ready otherwise and we
//     /// dont have context on add
//     ready_queue: RwLock<VecDeque<NodeId>>,
//
//     pending_assets: RwLock<Vec<(Box<dyn PendingSceneAsset>, Option<NodeId>)>>,
// }
//
// impl Default for InstancableScene {
//     fn default() -> Self {
//         Self::new()
//     }
// }
//
// impl<'a> InstancableScene {
//     pub fn new() -> Self {
//         Self {
//             nodes: RwLock::new(HashMap::new()),
//             heirarchy: RwLock::new(HashMap::new()),
//             events: RwLock::new(HashMap::new()),
//             ready_queue: RwLock::new(VecDeque::new()),
//             pending_assets: RwLock::new(Vec::new()),
//         }
//     }
// }