Skip to main content

mraphics_core/geometry/
mesh.rs

1use crate::{Geometry, InstanceUpdater, Material, MraphicsID, RenderInstance};
2use std::marker::PhantomData;
3
4pub trait MeshLike: InstanceUpdater {
5    /// Returns the unique identifier of this mesh.
6    fn identifier(&self) -> MraphicsID;
7
8    /// Builds a [`RenderInstance`] using this mesh's data.
9    fn build_instance(&self) -> RenderInstance;
10
11    /// Updates self before updating the render instance, optional.
12    fn update(&mut self) {}
13}
14
15#[derive(Clone)]
16pub struct MeshHandle<M: MeshLike> {
17    id: MraphicsID,
18
19    _marker: PhantomData<M>,
20}
21
22impl<M: MeshLike> MeshHandle<M> {
23    pub fn new(id: MraphicsID) -> Self {
24        Self {
25            id,
26            _marker: PhantomData,
27        }
28    }
29
30    pub fn identifier(&self) -> MraphicsID {
31        self.id
32    }
33}
34
35pub struct Mesh<G: Geometry, M: Material> {
36    identifier: MraphicsID,
37
38    pub geometry: G,
39    pub material: M,
40}
41
42impl<G: Geometry, M: Material> Mesh<G, M> {
43    pub fn new(geometry: G, material: M) -> Self {
44        Self {
45            identifier: MraphicsID::acquire(),
46            geometry,
47            material,
48        }
49    }
50}
51
52impl<G: Geometry, M: Material> InstanceUpdater for Mesh<G, M> {
53    fn update_instance(&self, instance: &mut RenderInstance) {
54        self.geometry.update_view(&mut instance.geometry);
55        self.material.update_view(&mut instance.material);
56    }
57}
58
59impl<G: Geometry, M: Material> MeshLike for Mesh<G, M> {
60    fn identifier(&self) -> MraphicsID {
61        self.identifier
62    }
63
64    fn build_instance(&self) -> RenderInstance {
65        let mut instance = RenderInstance::new(self.identifier, &self.material);
66
67        self.geometry.init_view(&mut instance.geometry);
68
69        instance
70    }
71
72    fn update(&mut self) {
73        self.geometry.update();
74    }
75}