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
pub mod command_queue;
pub mod component;
pub mod rx;
pub mod system;
pub mod world_query_adapter;

#[cfg(test)]
mod world_graph_tests;

use crate::engine::graphics::{RenderAssets, VisualWorld};
use slotmap::{SlotMap, new_key_type};
use std::cell::RefCell;
use std::collections::HashMap;

new_key_type! {
    /// Global component identity (dense arena key).
    pub struct ComponentId;
}

// Re-export these so other modules can use `crate::engine::ecs::Transform`
// and `crate::engine::ecs::Renderable` consistently.
#[allow(unused_imports)]
pub use crate::engine::graphics::primitives::{Renderable, Transform, TransformMatrix};

pub use command_queue::CommandQueue;
pub use rx::{
    EventSignal, IntentSignal, IntentValue, PointerActivationSource, PoseApplyMode, RxWorld,
    Signal, SignalEmitter, SignalHandler, SignalKind, SignalWhen,
};
pub use system::{System, SystemWorld};
pub use world_query_adapter::WorldQueryAdapter;

/// Bundle of mutable engine state passed to component mutation APIs.
///
/// This exists to avoid threading `&mut World`, `&mut SystemWorld`, and `&mut VisualWorld`
/// through every component call.
pub struct WorldContext<'a> {
    pub world: &'a mut World,
    pub systems: &'a mut SystemWorld,
    pub visuals: &'a mut VisualWorld,
    pub render_assets: &'a mut RenderAssets,
}

impl<'a> WorldContext<'a> {
    pub fn new(
        world: &'a mut World,
        systems: &'a mut SystemWorld,
        visuals: &'a mut VisualWorld,
        render_assets: &'a mut RenderAssets,
    ) -> Self {
        Self {
            world,
            systems,
            visuals,
            render_assets,
        }
    }
}

/// World: owns all global components.
#[derive(Default)]
pub struct World {
    components: SlotMap<ComponentId, crate::engine::ecs::component::ComponentNode>,
    guid_index: HashMap<uuid::Uuid, ComponentId>,
    /// MMQ parser instance with per-instance AST cache. Behind a RefCell so
    /// `find_component(&self, ...)` can mutate the cache without forcing
    /// every caller to thread `&mut World`. Single-threaded — World lives
    /// on the main thread.
    mmq_parser: RefCell<mittens_query::mmq::MmqQuerySyntax>,
}

impl World {
    /// Fast GUID -> ComponentId lookup.
    pub fn component_id_by_guid(&self, guid: uuid::Uuid) -> Option<ComponentId> {
        self.guid_index.get(&guid).copied()
    }

    /// Replace the GUID of an already-inserted component, keeping its
    /// ComponentId stable. Used by spawn paths that restore an authored
    /// `guid = "..."` property after `create_component` has already minted
    /// a fresh GUID.
    ///
    /// Returns Err if the target id is missing, or if the new guid is
    /// already taken by another component (would silently overwrite the
    /// reverse index otherwise).
    pub fn set_component_guid(
        &mut self,
        id: ComponentId,
        new_guid: uuid::Uuid,
    ) -> Result<(), String> {
        let Some(node) = self.get_component_record(id) else {
            return Err(format!("set_component_guid: component {id:?} missing"));
        };
        let old_guid = node.guid;
        if old_guid == new_guid {
            return Ok(());
        }
        if let Some(&existing) = self.guid_index.get(&new_guid) {
            if existing != id {
                return Err(format!(
                    "set_component_guid: guid {new_guid} already in use by {existing:?}"
                ));
            }
        }
        self.guid_index.remove(&old_guid);
        self.guid_index.insert(new_guid, id);
        if let Some(node) = self.get_component_record_mut(id) {
            node.guid = new_guid;
        }
        Ok(())
    }

    /// Add a new component to the world (no parent) and return its id.
    ///
    /// Note: this currently does *not* call `Component::init`. That should happen via a
    /// higher-level API that has access to `SystemWorld` and `VisualWorld`.
    pub fn add_component<T: crate::engine::ecs::component::Component>(
        &mut self,
        c: T,
    ) -> ComponentId {
        // We set the id after insertion so components that cache their id can do so.
        let id = self.add_component_boxed(Box::new(c));
        if let Some(node) = self.get_component_record_mut(id) {
            node.component.set_id(id);
        }
        id
    }

    /// Register a new component in the world and return its id.
    ///
    /// This is intentionally a storage/identity operation only: it does *not* call
    /// `Component::init`.
    pub fn register<T: crate::engine::ecs::component::Component>(&mut self, c: T) -> ComponentId {
        self.add_component(c)
    }

    /// Whether this component has had `Component::init` invoked.
    pub fn is_initialized(&self, c: ComponentId) -> bool {
        self.get_component_record(c)
            .map(|n| n.initialized)
            .unwrap_or(false)
    }

    /// Add a new component to the world (no parent). Returns its global id.
    pub fn add_component_boxed(
        &mut self,
        c: Box<dyn crate::engine::ecs::component::Component>,
    ) -> ComponentId {
        let node = crate::engine::ecs::component::ComponentNode::new(c);
        let guid = node.guid;
        let id = self.components.insert(node);
        let _old = self.guid_index.insert(guid, id);
        if let Some(node) = self.get_component_record_mut(id) {
            node.component.set_id(id);
        }
        id
    }

    /// Add a new boxed component with an explicit stored name.
    pub fn add_component_boxed_named(
        &mut self,
        name: impl Into<String>,
        c: Box<dyn crate::engine::ecs::component::Component>,
    ) -> ComponentId {
        let node = crate::engine::ecs::component::ComponentNode::new_named(name, c);
        let guid = node.guid;
        let id = self.components.insert(node);
        let _old = self.guid_index.insert(guid, id);
        if let Some(node) = self.get_component_record_mut(id) {
            node.component.set_id(id);
        }
        id
    }

    /// Add a new boxed component with a restored GUID and explicit stored name.
    ///
    /// This is intended for deserialization.
    pub fn add_component_boxed_with_guid_named(
        &mut self,
        guid: uuid::Uuid,
        name: impl Into<String>,
        c: Box<dyn crate::engine::ecs::component::Component>,
    ) -> ComponentId {
        if self.guid_index.contains_key(&guid) {
            panic!("duplicate component guid inserted into World: {}", guid);
        }

        let node = crate::engine::ecs::component::ComponentNode::new_with_guid_named(guid, name, c);
        let guid = node.guid;
        let id = self.components.insert(node);
        self.guid_index.insert(guid, id);
        if let Some(node) = self.get_component_record_mut(id) {
            node.component.set_id(id);
        }
        id
    }

    /// Temporary alias during migration.
    pub fn spawn_component_boxed(
        &mut self,
        c: Box<dyn crate::engine::ecs::component::Component>,
    ) -> ComponentId {
        self.add_component_boxed(c)
    }

    pub fn get_component_record(
        &self,
        id: ComponentId,
    ) -> Option<&crate::engine::ecs::component::ComponentNode> {
        self.components.get(id)
    }

    /// Alias for `get_component_record`.
    pub fn get_component_node(
        &self,
        id: ComponentId,
    ) -> Option<&crate::engine::ecs::component::ComponentNode> {
        self.get_component_record(id)
    }

    pub fn get_component_record_mut(
        &mut self,
        id: ComponentId,
    ) -> Option<&mut crate::engine::ecs::component::ComponentNode> {
        self.components.get_mut(id)
    }

    /// Returns the engine type identifier for this component (e.g. `"transform"`).
    pub fn component_name(&self, id: ComponentId) -> Option<&str> {
        self.get_component_record(id)
            .map(|node| node.component_type.as_str())
    }

    /// Returns the user-assigned label for this component (empty string if unset).
    pub fn component_label(&self, id: ComponentId) -> Option<&str> {
        self.get_component_record(id).map(|node| node.name.as_str())
    }

    // --- Topology helpers (component-graph) ---
    pub fn parent_of(&self, c: ComponentId) -> Option<ComponentId> {
        self.get_component_record(c)?.parent
    }

    /// Iterator over all component IDs in the world.
    pub fn all_components(&self) -> impl Iterator<Item = ComponentId> + '_ {
        self.components.keys()
    }

    pub fn component_count(&self) -> usize {
        self.components.len()
    }

    pub fn children_of(&self, c: ComponentId) -> &[ComponentId] {
        static EMPTY: [ComponentId; 0] = [];
        self.get_component_record(c)
            .map(|n| n.children.as_slice())
            .unwrap_or(&EMPTY)
    }

    // --- Typed component access ---
    pub fn get_component_by_id_as<T: 'static>(&self, c: ComponentId) -> Option<&T> {
        let node = self.get_component_record(c)?;
        node.component.as_any().downcast_ref::<T>()
    }

    pub fn get_component_by_id_as_mut<T: 'static>(&mut self, c: ComponentId) -> Option<&mut T> {
        let node = self.get_component_record_mut(c)?;
        node.component.as_any_mut().downcast_mut::<T>()
    }

    /// Find the first component under `root` matching `selector`.
    ///
    /// `selector` is parsed as MMQ — `#name`, `Type`, `Type#name`, `[name='...']`, etc.
    /// See `crates/mittens-query/src/mmq/parser.rs`.
    pub fn find_component(&self, root: ComponentId, selector: &str) -> Option<ComponentId> {
        let matches = self.run_query(root, selector);
        matches.into_iter().next()
    }

    /// Find all components under `root` matching `selector` (DFS pre-order).
    pub fn find_all_components(&self, root: ComponentId, selector: &str) -> Vec<ComponentId> {
        self.run_query(root, selector)
    }

    /// Roots searched by a live scripting query scoped to `component`.
    ///
    /// Imported glTF nodes are physically attached beneath the asset's transform anchor rather
    /// than the `GLTFComponent` itself. Include the top-level imported nodes recorded in runtime
    /// metadata so `gltf.query(...)` still has the expected asset-instance scope.
    pub fn scripting_query_roots(&self, component: ComponentId) -> Vec<ComponentId> {
        let Some(gltf) =
            self.get_component_by_id_as::<crate::engine::ecs::component::GLTFComponent>(component)
        else {
            return vec![component];
        };

        let spawned: std::collections::HashSet<_> =
            gltf.spawned_node_transforms.iter().copied().collect();
        let mut roots = vec![component];
        roots.extend(gltf.spawned_node_transforms.iter().copied().filter(|node| {
            self.parent_of(*node)
                .is_none_or(|parent| !spawned.contains(&parent))
        }));
        roots
    }

    pub fn component_matches_selector(&self, component: ComponentId, selector: &str) -> bool {
        self.run_query(component, selector).first().copied() == Some(component)
    }

    pub fn world_roots(&self) -> Vec<ComponentId> {
        self.all_components()
            .filter(|&cid| self.parent_of(cid).is_none())
            .collect()
    }

    fn run_query(&self, root: ComponentId, selector: &str) -> Vec<ComponentId> {
        use crate::engine::ecs::world_query_adapter::WorldQueryAdapter;
        use mittens_query::QueryEvaluator;
        use mittens_query::QuerySyntax;

        if self.get_component_record(root).is_none() {
            return Vec::new();
        }
        let Ok(ast) = self.mmq_parser.borrow_mut().parse(selector) else {
            return Vec::new();
        };
        let adapter = WorldQueryAdapter::new(self);
        QueryEvaluator::evaluate(&adapter, root, &ast)
    }

    pub fn get_parent_as<T: 'static>(&self, c: ComponentId) -> Option<(ComponentId, &T)> {
        let parent = self.parent_of(c)?;
        let typed = self.get_component_by_id_as::<T>(parent)?;
        Some((parent, typed))
    }

    pub fn get_parent_as_mut<T: 'static>(
        &mut self,
        c: ComponentId,
    ) -> Option<(ComponentId, &mut T)> {
        let parent = self.parent_of(c)?;
        // Avoid borrowing self twice by doing the downcast via the node.
        let node = self.get_component_record_mut(parent)?;
        let typed = node.component.as_any_mut().downcast_mut::<T>()?;
        Some((parent, typed))
    }

    // --- Graph mutation ---
    fn is_ancestor_of(&self, maybe_ancestor: ComponentId, mut node: ComponentId) -> bool {
        while let Some(p) = self.parent_of(node) {
            if p == maybe_ancestor {
                return true;
            }
            node = p;
        }
        false
    }

    /// Attach `child` under `parent`.
    ///
    /// This is a lower-level graph mutation API.
    ///
    /// It updates only the parent/child links in the world graph. It does not
    /// emit `ParentChanged`, does not refresh topology-dependent systems, and
    /// does not route through runtime helpers like routers/scroll ownership.
    ///
    /// Prefer `IntentValue::Attach` or `Universe::attach(...)` when attaching a
    /// subtree into an already-live parent and you expect normal runtime side
    /// effects.
    ///
    /// `add_child(...)` is appropriate for offline subtree assembly before init,
    /// tests, and internal structural building where the caller intentionally
    /// manages any needed follow-up work.
    ///
    /// Safety rules:
    /// - Both ids must exist.
    /// - `child` is detached from its current parent first.
    /// - Cycles are rejected.
    pub fn add_child(
        &mut self,
        parent: ComponentId,
        child: ComponentId,
    ) -> Result<(), &'static str> {
        if self.get_component_record(parent).is_none() {
            return Err("parent does not exist");
        }
        if self.get_component_record(child).is_none() {
            return Err("child does not exist");
        }
        if parent == child {
            return Err("cannot parent component to itself");
        }
        if self.is_ancestor_of(child, parent) {
            return Err("cycle detected");
        }

        self.detach_from_parent(child);

        // Set child's parent.
        {
            let child_node = self
                .get_component_record_mut(child)
                .ok_or("child missing")?;
            child_node.parent = Some(parent);
        }
        // Push into parent's children list.
        {
            let parent_node = self
                .get_component_record_mut(parent)
                .ok_or("parent missing")?;
            if !parent_node.children.contains(&child) {
                parent_node.children.push(child);
            }
        }

        Ok(())
    }

    /// Change a component's parent.
    ///
    /// Equivalent to `detach_from_parent(child)` when `new_parent` is None.
    pub fn set_parent(
        &mut self,
        child: ComponentId,
        new_parent: Option<ComponentId>,
    ) -> Result<(), &'static str> {
        match new_parent {
            None => {
                self.detach_from_parent(child);
                Ok(())
            }
            Some(parent) => self.add_child(parent, child),
        }
    }

    /// Detach `child` from its current parent.
    ///
    /// This does *not* delete anything.
    pub fn detach_from_parent(&mut self, child: ComponentId) {
        let Some(old_parent) = self.parent_of(child) else {
            return;
        };

        // Clear child's parent.
        if let Some(node) = self.get_component_record_mut(child) {
            node.parent = None;
        }

        // Remove from old parent's children list.
        if let Some(parent_node) = self.get_component_record_mut(old_parent) {
            parent_node.children.retain(|&c| c != child);
        }
    }

    /// Remove a component from the world.
    ///
    /// This is a *leaf-only* removal: it fails if the component still has children.
    /// Use `remove_component_subtree` when you want to delete a whole branch.
    pub fn remove_component_leaf(&mut self, c: ComponentId) -> Result<(), &'static str> {
        let guid = {
            let Some(node) = self.get_component_record(c) else {
                return Err("component does not exist");
            };
            if !node.children.is_empty() {
                return Err(
                    "component has children; use remove_component_subtree or detach children first",
                );
            }
            node.guid
        };

        self.guid_index.remove(&guid);

        self.detach_from_parent(c);
        self.components.remove(c);
        Ok(())
    }

    /// Remove a component and all its descendants.
    pub fn remove_component_subtree(&mut self, root: ComponentId) -> Result<(), &'static str> {
        if self.get_component_record(root).is_none() {
            return Err("component does not exist");
        }

        // Detach root first so parent doesn't retain dead child.
        self.detach_from_parent(root);

        // Post-order delete: collect subtree ids, then delete leaves upward.
        let mut stack = vec![root];
        let mut order: Vec<ComponentId> = Vec::new();
        while let Some(c) = stack.pop() {
            order.push(c);
            let children: Vec<ComponentId> = self.children_of(c).to_vec();
            for ch in children {
                stack.push(ch);
            }
        }

        // Delete in reverse (children first).
        for c in order.into_iter().rev() {
            let guid = self.get_component_record(c).map(|n| n.guid);
            if let Some(guid) = guid {
                self.guid_index.remove(&guid);
            }
            // Clear parent/children links if node still exists.
            if let Some(node) = self.get_component_record_mut(c) {
                node.parent = None;
                node.children.clear();
            }
            self.components.remove(c);
        }

        Ok(())
    }

    /// Initialize a component tree starting from the given root component.
    ///
    /// This recursively initializes the root component and all its descendants by calling
    /// `Component::init` on each component in the tree.
    pub fn init_component_tree(
        &mut self,
        root: ComponentId,
        emit: &mut dyn crate::engine::ecs::SignalEmitter,
    ) {
        use std::collections::HashSet;

        // Iterative traversal prevents stack overflows on large init expansions.
        let mut stack: Vec<ComponentId> = vec![root];
        let mut visited: HashSet<ComponentId> = HashSet::new();

        // Log only a small number of cycle detections to avoid spam.
        let mut cycle_logs_left: usize = 8;

        while let Some(node_id) = stack.pop() {
            if !visited.insert(node_id) {
                if cycle_logs_left > 0 {
                    cycle_logs_left -= 1;
                    println!(
                        "[World::init_component_tree] cycle/revisit detected at component={:?}",
                        node_id
                    );
                }
                continue;
            }

            // Initialize the component (idempotent).
            if let Some(node) = self.get_component_record_mut(node_id) {
                if !node.initialized {
                    node.component.init(emit, node_id);
                    node.initialized = true;
                }
            }

            // Push children (reverse so first child is processed first in LIFO order).
            let children: Vec<ComponentId> = self.children_of(node_id).to_vec();
            for child in children.into_iter().rev() {
                stack.push(child);
            }
        }
    }
}