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
use crate::renderer::*;
pub use three_d_asset::Model as CpuModel;

///
/// Part of a [Model] consisting of a [Mesh], some type of [material] and a set of possible animations.
///
pub struct ModelPart<M: Material> {
    gm: Gm<Mesh, M>,
    animations: Vec<KeyFrameAnimation>,
}

impl<M: Material> ModelPart<M> {
    ///
    /// Returns a list of unique names for the animations for this model part. Use these names as input to [Self::choose_animation].
    ///
    pub fn animations(&self) -> Vec<Option<String>> {
        self.animations
            .iter()
            .map(|animation| animation.name.clone())
            .collect()
    }

    ///
    /// Specifies the animation to use when [Geometry::animate] is called. Use the [Self::animations] method to get a list of possible animations.
    ///
    pub fn choose_animation(&mut self, animation_name: Option<&str>) {
        if let Some(animation) = self
            .animations
            .iter()
            .find(|a| animation_name == a.name.as_deref())
            .cloned()
        {
            self.set_animation(move |time| animation.transformation(time));
        }
    }
}

use std::ops::Deref;
impl<M: Material> Deref for ModelPart<M> {
    type Target = Gm<Mesh, M>;
    fn deref(&self) -> &Self::Target {
        &self.gm
    }
}

impl<M: Material> std::ops::DerefMut for ModelPart<M> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.gm
    }
}

impl<M: Material> Geometry for ModelPart<M> {
    impl_geometry_body!(deref);

    fn animate(&mut self, time: f32) {
        self.gm.animate(time)
    }
}

impl<M: Material> Object for ModelPart<M> {
    impl_object_body!(deref);
}

impl<'a, M: Material> IntoIterator for &'a ModelPart<M> {
    type Item = &'a dyn Object;
    type IntoIter = std::iter::Once<&'a dyn Object>;

    fn into_iter(self) -> Self::IntoIter {
        self.gm.into_iter()
    }
}

///
/// A 3D model consisting of a set of [Gm]s with [Mesh]es as the geometries and a [material] type specified by the generic parameter.
///
pub struct Model<M: Material>(Vec<ModelPart<M>>);

impl<'a, M: Material> IntoIterator for &'a Model<M> {
    type Item = &'a dyn Object;
    type IntoIter = std::vec::IntoIter<&'a dyn Object>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
            .map(|m| m as &dyn Object)
            .collect::<Vec<_>>()
            .into_iter()
    }
}

impl<M: Material + FromCpuMaterial + Clone + Default> Model<M> {
    ///
    /// Constructs a [Model] from a [CpuModel], ie. constructs a list of [Gm]s with a [Mesh] as geometry (constructed from the [CpuMesh]es in the [CpuModel]) and
    /// a [material] type specified by the generic parameter which implement [FromCpuMaterial] (constructed from the [CpuMaterial]s in the [CpuModel]).
    ///
    pub fn new(context: &Context, cpu_model: &CpuModel) -> Result<Self, RendererError> {
        let materials = cpu_model
            .materials
            .iter()
            .map(|m| M::from_cpu_material(context, m))
            .collect::<Vec<_>>();
        let mut gms = Vec::new();
        for primitive in cpu_model.geometries.iter() {
            if let CpuGeometry::Triangles(geometry) = &primitive.geometry {
                let material = if let Some(material_index) = primitive.material_index {
                    materials
                        .get(material_index)
                        .ok_or_else(|| {
                            RendererError::MissingMaterial(
                                material_index.to_string(),
                                primitive.name.clone(),
                            )
                        })?
                        .clone()
                } else {
                    M::default()
                };
                let mut gm = Gm {
                    geometry: Mesh::new(context, geometry),
                    material,
                };
                gm.set_transformation(primitive.transformation);
                gms.push(ModelPart {
                    gm,
                    animations: primitive.animations.clone(),
                });
            }
        }
        let mut model = Self(gms);
        if let Some(animation_name) = model.animations().first().cloned() {
            model.choose_animation(animation_name.as_deref());
        }
        Ok(model)
    }

    ///
    /// Returns a list of unique names for the animations in this model. Use these names as input to [Self::choose_animation].
    ///
    pub fn animations(&self) -> Vec<Option<String>> {
        let mut set = std::collections::HashSet::new();
        for model_part in self.0.iter() {
            set.extend(model_part.animations());
        }
        set.into_iter().collect()
    }

    ///
    /// Specifies the animation to use when [Geometry::animate] is called. Use the [Self::animations] method to get a list of possible animations.
    ///
    pub fn choose_animation(&mut self, animation_name: Option<&str>) {
        for part in self.0.iter_mut() {
            part.choose_animation(animation_name);
        }
    }

    ///
    /// For updating the animation. The time parameter should be some continious time, for example the time since start.
    ///
    pub fn animate(&mut self, time: f32) {
        self.iter_mut().for_each(|m| m.animate(time));
    }
}

impl<M: Material> std::ops::Deref for Model<M> {
    type Target = Vec<ModelPart<M>>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<M: Material> std::ops::DerefMut for Model<M> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}