mraphics_core/
scene.rs

1use crate::{RenderInstance, Renderable};
2use std::collections::HashMap;
3
4pub struct Scene {
5    pub instances: Vec<RenderInstance>,
6    instance_map: HashMap<usize, usize>,
7}
8
9impl Scene {
10    pub fn new() -> Self {
11        Self {
12            instances: Vec::new(),
13            instance_map: HashMap::new(),
14        }
15    }
16
17    pub fn add_renderable<R: Renderable>(&mut self, renderable: &R) {
18        self.instances.push(renderable.build_instance());
19        self.instance_map
20            .insert(renderable.identifier(), self.instances.len() - 1);
21    }
22
23    pub fn remove_renderable(&mut self, identifier: &usize) -> Option<RenderInstance> {
24        let remove_index = *self.instance_map.get(identifier)?;
25        let swap_index = self.instances.len() - 1;
26
27        for index in self.instance_map.values_mut() {
28            if *index == swap_index {
29                *index = remove_index;
30            }
31        }
32
33        Some(self.instances.swap_remove(remove_index))
34    }
35
36    pub fn acquire_instance(&self, identifier: usize) -> Option<&RenderInstance> {
37        let index = self.instance_map.get(&identifier)?;
38        self.instances.get(*index)
39    }
40
41    pub fn acquire_instance_unchecked(&self, identifier: usize) -> &RenderInstance {
42        &self.instances[*self.instance_map.get(&identifier).unwrap()]
43    }
44
45    pub fn acquire_instance_mut(&mut self, identifier: usize) -> Option<&mut RenderInstance> {
46        let index = self.instance_map.get(&identifier)?;
47        self.instances.get_mut(*index)
48    }
49
50    pub fn acquire_instance_mut_unchecked(&mut self, identifier: usize) -> &mut RenderInstance {
51        &mut self.instances[*self.instance_map.get(&identifier).unwrap()]
52    }
53}