Skip to main content

euv_core/game/engine3d/scene_graph/
impl.rs

1use super::*;
2
3/// Default metadata for `BlenderExtrasTags3D`.
4impl Default for BlenderExtrasTags3D {
5    /// Creates default Blender tags with shadows enabled and no collider or buoyancy.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default `BlenderExtrasTags3D`.
10    fn default() -> Self {
11        Self {
12            collider: SceneColliderShape3D::None,
13            buoyancy_density: 0.0,
14            is_trigger: false,
15            cast_shadows: true,
16            custom_json: None,
17        }
18    }
19}
20
21/// Default single-root registry for `CollectionRegistry3D`.
22impl Default for CollectionRegistry3D {
23    /// Creates a registry initialized with the default Blender root collection at bit `0`.
24    ///
25    /// # Returns
26    ///
27    /// - `Self` - Initialized `CollectionRegistry3D`.
28    fn default() -> Self {
29        Self {
30            entries: vec![CollectionEntry3D {
31                name: SCENE_DEFAULT_COLLECTION_NAME.to_string(),
32                bit_index: 0,
33                visible_viewport: true,
34                visible_render: true,
35            }],
36            active_mask: 1,
37        }
38    }
39}
40
41/// Collection registration and visibility mask management for `CollectionRegistry3D`.
42impl CollectionRegistry3D {
43    /// Registers or looks up a Blender collection by `name` and returns its 64-bit mask.
44    ///
45    /// # Arguments
46    ///
47    /// - `&Self` - Mutable collection registry.
48    /// - `&str` - Blender collection name.
49    ///
50    /// # Returns
51    ///
52    /// - `u64` - Single-bit collection mask (`1 << bit_index`), or bit `0` if full.
53    pub fn register_collection(&mut self, name: &str) -> u64 {
54        for entry in self.get_entries().iter() {
55            if entry.get_name() == name {
56                return 1u64 << u32::from(entry.get_bit_index());
57            }
58        }
59        let next_idx: usize = self.get_entries().len();
60        if next_idx >= SCENE_GRAPH_MAX_COLLECTIONS {
61            return 1u64;
62        }
63        let bit_index: u8 = next_idx as u8;
64        let bit_mask: u64 = 1u64 << u32::from(bit_index);
65        self.get_mut_entries().push(CollectionEntry3D {
66            name: name.to_string(),
67            bit_index,
68            visible_viewport: true,
69            visible_render: true,
70        });
71        let updated_mask: u64 = self.get_active_mask() | bit_mask;
72        self.set_active_mask(updated_mask);
73        bit_mask
74    }
75
76    /// Sets viewport visibility for the collection matching `name` and refreshes `active_mask`.
77    ///
78    /// # Arguments
79    ///
80    /// - `&Self` - Mutable collection registry.
81    /// - `&str` - Target collection name.
82    /// - `bool` - Whether the collection is visible in viewport.
83    ///
84    /// # Returns
85    ///
86    /// - `bool` - `true` if a matching collection was updated.
87    pub fn set_collection_visible(&mut self, name: &str, visible: bool) -> bool {
88        let mut found_bit: Option<u8> = None;
89        for entry in self.get_mut_entries().iter_mut() {
90            if entry.get_name() == name {
91                entry.set_visible_viewport(visible);
92                found_bit = Some(entry.get_bit_index());
93                break;
94            }
95        }
96        if let Some(bit_index) = found_bit {
97            let bit_mask: u64 = 1u64 << u32::from(bit_index);
98            let next_mask: u64 = if visible {
99                self.get_active_mask() | bit_mask
100            } else {
101                self.get_active_mask() & !bit_mask
102            };
103            self.set_active_mask(next_mask);
104            true
105        } else {
106            false
107        }
108    }
109
110    /// Returns `true` when any collection bit in `node_mask` is currently visible.
111    ///
112    /// # Arguments
113    ///
114    /// - `&Self` - Collection registry reference.
115    /// - `u64` - Node collection membership bitmask.
116    ///
117    /// # Returns
118    ///
119    /// - `bool` - `true` when at least one assigned collection is active.
120    #[must_use]
121    pub fn is_mask_visible(&self, node_mask: u64) -> bool {
122        (node_mask & self.get_active_mask()) != 0
123    }
124}
125
126/// Construction and local matrix helpers for `SceneNode3D`.
127impl SceneNode3D {
128    /// Creates an identity `SceneNode3D` with `name` and optional `parent`.
129    ///
130    /// # Arguments
131    ///
132    /// - `&str` - Node label.
133    /// - `Option<u32>` - Optional parent node index.
134    ///
135    /// # Returns
136    ///
137    /// - `Self` - Constructed identity scene node.
138    #[must_use]
139    pub fn from_name(name: &str, parent: Option<u32>) -> Self {
140        Self {
141            name: name.to_string(),
142            parent,
143            depth: 0,
144            local_translation: Vec3::zero(),
145            local_rotation: Quat::identity(),
146            local_scale: Vec3::splat(1.0),
147            world_matrix: Mat4::identity(),
148            prev_world_matrix: Mat4::identity(),
149            collection_mask: 1,
150            visible: true,
151            mesh_id: None,
152            skin_id: None,
153            camera_id: None,
154            light_id: None,
155            morph_weight_offset: 0,
156            morph_weight_count: 0,
157            extras: BlenderExtrasTags3D::default(),
158        }
159    }
160
161    /// Computes this node's local TRS matrix `T * R * S`.
162    ///
163    /// # Arguments
164    ///
165    /// - `&Self` - Scene node reference.
166    ///
167    /// # Returns
168    ///
169    /// - `Mat4` - Local transformation matrix.
170    #[must_use]
171    pub fn local_matrix(&self) -> Mat4 {
172        Mat4::from_trs_quat(
173            self.get_local_translation(),
174            self.get_local_rotation(),
175            self.get_local_scale(),
176        )
177    }
178}
179
180/// Default empty hierarchy for `SceneGraph3D`.
181impl Default for SceneGraph3D {
182    /// Creates an empty `SceneGraph3D` with a default `CollectionRegistry3D`.
183    ///
184    /// # Returns
185    ///
186    /// - `Self` - Empty scene graph.
187    fn default() -> Self {
188        Self {
189            nodes: Vec::new(),
190            topo_order: Vec::new(),
191            dirty_words: Vec::new(),
192            morph_weights: Vec::new(),
193            collections: CollectionRegistry3D::default(),
194            topology_dirty: false,
195            revision: 0,
196        }
197    }
198}
199
200/// Hierarchy insertion, dirty bitset management, and zero-allocation propagation for `SceneGraph3D`.
201impl SceneGraph3D {
202    /// Appends `node` to the graph, marks it dirty, and returns its assigned node index.
203    ///
204    /// # Arguments
205    ///
206    /// - `&Self` - Mutable scene graph.
207    /// - `SceneNode3D` - Node descriptor to insert.
208    ///
209    /// # Returns
210    ///
211    /// - `u32` - Assigned node index inside `nodes`.
212    pub fn add_node(&mut self, node: SceneNode3D) -> u32 {
213        let node_id: u32 = self.get_nodes().len() as u32;
214        self.get_mut_nodes().push(node);
215        let needed_words: usize = self.get_nodes().len().div_ceil(64);
216        if self.get_dirty_words().len() < needed_words {
217            self.get_mut_dirty_words().resize(needed_words, 0);
218        }
219        self.mark_dirty(node_id);
220        self.set_topology_dirty(true);
221        node_id
222    }
223
224    /// Appends initial shape-key morph weights for `node_id` and records their slice range.
225    ///
226    /// # Arguments
227    ///
228    /// - `&Self` - Mutable scene graph.
229    /// - `u32` - Target node index.
230    /// - `&[f32]` - Initial morph target weights.
231    pub fn attach_morph_weights(&mut self, node_id: u32, weights: &[f32]) {
232        if weights.is_empty() {
233            return;
234        }
235        let offset: u32 = self.get_morph_weights().len() as u32;
236        let count: u16 = weights.len().min(usize::from(u16::MAX)) as u16;
237        self.get_mut_morph_weights()
238            .extend_from_slice(&weights[..usize::from(count)]);
239        if let Some(node) = self.get_mut_nodes().get_mut(node_id as usize) {
240            node.set_morph_weight_offset(offset);
241            node.set_morph_weight_count(count);
242        }
243    }
244
245    /// Updates a node's local TRS transform and marks its subtree dirty without allocating.
246    ///
247    /// # Arguments
248    ///
249    /// - `&Self` - Mutable scene graph.
250    /// - `u32` - Target node index.
251    /// - `Vec3` - Local translation.
252    /// - `Quat` - Local rotation quaternion.
253    /// - `Vec3` - Local non-uniform scale.
254    pub fn set_local_trs(&mut self, node_id: u32, translation: Vec3, rotation: Quat, scale: Vec3) {
255        if let Some(node) = self.get_mut_nodes().get_mut(node_id as usize) {
256            node.set_local_translation(translation);
257            node.set_local_rotation(rotation.normalize());
258            node.set_local_scale(scale);
259            self.mark_dirty(node_id);
260        }
261    }
262
263    /// Decomposes a local 4x4 matrix into TRS and applies it to `node_id`.
264    ///
265    /// # Arguments
266    ///
267    /// - `&Self` - Mutable scene graph.
268    /// - `u32` - Target node index.
269    /// - `Mat4` - Local 4x4 transformation matrix.
270    pub fn set_local_matrix(&mut self, node_id: u32, matrix: Mat4) {
271        let (translation, rotation, scale): (Vec3, Quat, Vec3) = matrix.decompose_trs();
272        self.set_local_trs(node_id, translation, rotation, scale);
273    }
274
275    /// Sets the dirty bit for `node_id` in O(1) with zero heap allocations.
276    ///
277    /// # Arguments
278    ///
279    /// - `&Self` - Mutable scene graph.
280    /// - `u32` - Target node index.
281    pub fn mark_dirty(&mut self, node_id: u32) {
282        let idx: usize = node_id as usize;
283        let word_idx: usize = idx >> 6;
284        let bit_mask: u64 = 1u64 << (idx & 63);
285        if let Some(word) = self.get_mut_dirty_words().get_mut(word_idx) {
286            *word |= bit_mask;
287        }
288    }
289
290    /// Returns `true` when `node_id` is currently marked dirty.
291    ///
292    /// # Arguments
293    ///
294    /// - `&Self` - Scene graph reference.
295    /// - `u32` - Node index.
296    ///
297    /// # Returns
298    ///
299    /// - `bool` - Whether the node's world matrix requires recomputation.
300    #[must_use]
301    pub fn is_dirty(&self, node_id: u32) -> bool {
302        let idx: usize = node_id as usize;
303        let word_idx: usize = idx >> 6;
304        let bit_mask: u64 = 1u64 << (idx & 63);
305        self.get_dirty_words()
306            .get(word_idx)
307            .is_some_and(|word: &u64| (*word & bit_mask) != 0)
308    }
309
310    /// Returns the borrowed slice of morph target weights owned by `node_id`.
311    ///
312    /// # Arguments
313    ///
314    /// - `&Self` - Scene graph reference.
315    /// - `u32` - Target node index.
316    ///
317    /// # Returns
318    ///
319    /// - `&[f32]` - Morph weights slice (empty when unattached).
320    #[must_use]
321    pub fn morph_weights_for_node(&self, node_id: u32) -> &[f32] {
322        let Some(node) = self.get_nodes().get(node_id as usize) else {
323            return &[];
324        };
325        let start: usize = node.get_morph_weight_offset() as usize;
326        let end: usize = start.saturating_add(usize::from(node.get_morph_weight_count()));
327        if end <= self.get_morph_weights().len() {
328            &self.get_morph_weights()[start..end]
329        } else {
330            &[]
331        }
332    }
333
334    /// Overwrites morph weights for `node_id` in place with zero heap allocations.
335    ///
336    /// # Arguments
337    ///
338    /// - `&Self` - Mutable scene graph.
339    /// - `u32` - Target node index.
340    /// - `&[f32]` - New morph target weights.
341    pub fn update_morph_weights(&mut self, node_id: u32, weights: &[f32]) {
342        let Some((start, count)) =
343            self.get_nodes()
344                .get(node_id as usize)
345                .map(|node: &SceneNode3D| {
346                    (
347                        node.get_morph_weight_offset() as usize,
348                        usize::from(node.get_morph_weight_count()),
349                    )
350                })
351        else {
352            return;
353        };
354        let copy_len: usize = count.min(weights.len());
355        let dst_all: &mut Vec<f32> = self.get_mut_morph_weights();
356        if start + copy_len <= dst_all.len() {
357            dst_all[start..(start + copy_len)].copy_from_slice(&weights[..copy_len]);
358        }
359    }
360
361    /// Rebuilds the depth-sorted topological traversal list when nodes were inserted or reparented.
362    ///
363    /// # Arguments
364    ///
365    /// - `&Self` - Mutable scene graph.
366    pub fn ensure_topology_order(&mut self) {
367        if !self.get_topology_dirty() {
368            return;
369        }
370        let (order, depths): (Vec<u32>, Vec<u16>) = compute_scene_topo_order(self.get_nodes());
371        for (idx, &depth) in depths.iter().enumerate() {
372            if let Some(node) = self.get_mut_nodes().get_mut(idx) {
373                node.set_depth(depth);
374            }
375        }
376        self.set_topo_order(order);
377        self.set_topology_dirty(false);
378    }
379
380    /// Propagates dirty local transforms down the hierarchy in topological order with zero steady-state allocations.
381    ///
382    /// # Arguments
383    ///
384    /// - `&Self` - Mutable scene graph.
385    ///
386    /// # Returns
387    ///
388    /// - `usize` - Number of node world matrices recomputed during this pass.
389    pub fn propagate_world_matrices(&mut self) -> usize {
390        self.ensure_topology_order();
391        let Self {
392            nodes,
393            topo_order,
394            dirty_words,
395            revision,
396            ..
397        } = self;
398        let mut updated: usize = 0;
399        for &node_id in topo_order.iter() {
400            let idx: usize = node_id as usize;
401            let parent_opt: Option<u32> = nodes[idx].try_get_parent();
402            let self_word: usize = idx >> 6;
403            let self_mask: u64 = 1u64 << (idx & 63);
404            let mut needs_update: bool = (dirty_words[self_word] & self_mask) != 0;
405            if !needs_update && let Some(parent_id) = parent_opt {
406                let p_idx: usize = parent_id as usize;
407                if p_idx < nodes.len() {
408                    let p_word: usize = p_idx >> 6;
409                    let p_mask: u64 = 1u64 << (p_idx & 63);
410                    if (dirty_words[p_word] & p_mask) != 0 {
411                        dirty_words[self_word] |= self_mask;
412                        needs_update = true;
413                    }
414                }
415            }
416            if !needs_update {
417                continue;
418            }
419            let local_mat: Mat4 = nodes[idx].local_matrix();
420            let world_mat: Mat4 = match parent_opt {
421                Some(parent_id) if (parent_id as usize) < nodes.len() => {
422                    nodes[parent_id as usize].get_world_matrix().mul(local_mat)
423                }
424                _ => local_mat,
425            };
426            let prev: Mat4 = nodes[idx].get_world_matrix();
427            nodes[idx].set_prev_world_matrix(prev);
428            nodes[idx].set_world_matrix(world_mat);
429            updated += 1;
430        }
431        if updated > 0 {
432            dirty_words.fill(0);
433            *revision = revision.saturating_add(1);
434        }
435        updated
436    }
437
438    /// Returns `true` when `node_id` and its entire ancestor chain are visible and pass collection masks.
439    ///
440    /// # Arguments
441    ///
442    /// - `&Self` - Scene graph reference.
443    /// - `u32` - Target node index.
444    ///
445    /// # Returns
446    ///
447    /// - `bool` - Effective scene visibility.
448    #[must_use]
449    pub fn is_node_effectively_visible(&self, node_id: u32) -> bool {
450        let nodes: &[SceneNode3D] = self.get_nodes().as_slice();
451        let collections: &CollectionRegistry3D = self.get_collections();
452        let mut cursor: Option<u32> = Some(node_id);
453        let mut guard: usize = 0;
454        while let Some(idx) = cursor {
455            let Some(node) = nodes.get(idx as usize) else {
456                return false;
457            };
458            if !node.get_visible() || !collections.is_mask_visible(node.get_collection_mask()) {
459                return false;
460            }
461            cursor = node.try_get_parent();
462            guard += 1;
463            if guard > nodes.len() {
464                break;
465            }
466        }
467        true
468    }
469}