Skip to main content

wde_gltf/
lib.rs

1//! GLTF Loader for WaterDropEngine
2//!
3//! This crate provides functionality to load and parse glTF files, converting them into assets that can be used within the WaterDropEngine. It supports loading meshes, materials, and textures defined in glTF files and integrates them with the engine's rendering system.
4//!
5//! # Example
6//! To load a glTF model, you can use the [`GltfLoader`](crate::GltfLoader) in your `setup` system as follows:
7//! ```rust
8//! let gltf_asset = asset_server.load("models/model.gltf");
9//! GltfLoader::spawn(&mut gltf_spawn_queue, gltf_asset);
10//! ```
11//! Note that the `gltf_asset` handle will be enqueued for spawning once it is loaded. The actual spawning of the model into the world will happen automatically in the background, and you can check for its presence using the asset handle.
12//! The rendering of the loaded model is then managed by the [`wde_pbr`](wde_pbr) crate, which handles the materials and shaders for the meshes.
13use std::{collections::HashMap, sync::Arc};
14
15use serde::{Deserialize, Serialize};
16use wde_logger::prelude::*;
17
18use bevy::{
19    asset::{AssetLoader, LoadContext, io::Reader},
20    prelude::*
21};
22use wde_animation::prelude::*;
23use wde_pbr::prelude::*;
24use wde_renderer::prelude::*;
25
26#[doc(hidden)]
27pub mod prelude {
28    pub use crate::GltfAsset;
29    pub use crate::GltfError;
30    pub use crate::GltfLight;
31    pub use crate::GltfLightKind;
32    pub use crate::GltfLoader;
33    pub use crate::GltfLoaderSettings;
34    pub use crate::GltfSpawnQueue;
35    pub use crate::MeshGeometry;
36    pub use crate::ModelCondition;
37}
38
39mod accessor;
40mod error;
41mod loader;
42mod material;
43mod model;
44mod parser;
45
46pub use error::GltfError;
47pub use model::{GltfBone, GltfLight, GltfLightKind, ModelCondition};
48
49pub struct GltfPlugin;
50impl Plugin for GltfPlugin {
51    fn build(&self, app: &mut App) {
52        app.init_asset::<GltfAsset>()
53            .init_asset_loader::<GltfAssetLoader>()
54            .init_resource::<GltfSpawnQueue>()
55            .add_systems(Update, process_gltf_spawn_queue);
56    }
57}
58
59/// Queue of glTF assets to spawn once they are loaded.
60#[derive(Resource, Default)]
61pub struct GltfSpawnQueue {
62    pending: Vec<(Entity, Handle<GltfAsset>)>
63}
64
65/// Representation of a 3D GLTF model asset.
66/// This will spawn the model and return the parent entity ID.
67/// See the [crate] documentation for usage examples.
68#[derive(Asset, TypePath, Clone)]
69pub struct GltfAsset {
70    path: String,
71
72    /// The list of parsed glTF models.
73    /// Each model is represented by a mesh and its associated material.
74    pub models: Vec<(Handle<Mesh>, Handle<PbrMaterial>)>,
75    /// Connection condition of each entry of [`Self::models`] (`None` = always shown).
76    pub conditions: Vec<Option<ModelCondition>>,
77    /// Triangles of each entry of [`Self::models`], kept on the CPU (e.g. for navigation): the
78    /// meshes themselves leave the main world once uploaded to the GPU.
79    pub geometry: Vec<Arc<MeshGeometry>>,
80    /// The englobing bounding box of the entire model, computed from the bounding boxes of all meshes.
81    pub bbox: MeshBbox,
82    /// Named properties (e.g. spawn points) extracted from meshes whose name starts with `%P%`.
83    /// These meshes are not added to [`Self::models`]; only their name, position and scale are kept here.
84    pub properties: HashMap<String, (Vec3, Vec3)>,
85    /// Bones of a rigged model (nodes named `%B%<bone>`), parents first.
86    pub bones: Vec<GltfBone>,
87    /// Bone each entry of [`Self::models`] moves with (its vertices are then relative to the bone).
88    pub model_bones: Vec<Option<usize>>,
89    /// Animation clips of the bones, by name.
90    pub animations: HashMap<String, Handle<AnimationClip>>,
91    /// Lights of the model, spawned with it (see [`Self::spawn_lights`]).
92    pub lights: Vec<GltfLight>
93}
94
95impl GltfAsset {
96    pub fn animation(&self, name: &str) -> Option<&Handle<AnimationClip>> {
97        self.animations.get(name)
98    }
99
100    /// Spawns the lights of the model under `parent`, following its transform.
101    pub fn spawn_lights(&self, commands: &mut Commands, parent: Entity) {
102        for light in &self.lights {
103            let color = wde_renderer::prelude::WdeColor::LinearRgba(
104                light.color.x,
105                light.color.y,
106                light.color.z,
107                1.0
108            );
109            let mut entity = commands.spawn((
110                Name::new(format!("Light {}", light.name)),
111                light.transform,
112                ChildOf(parent)
113            ));
114            match light.kind {
115                GltfLightKind::Point => entity.insert(PointLight {
116                    position: Vec3::ZERO,
117                    color,
118                    intensity: light.intensity,
119                    range: light.range
120                }),
121                GltfLightKind::Spot {
122                    inner_cone,
123                    outer_cone
124                } => entity.insert(SpotLight {
125                    position: Vec3::ZERO,
126                    direction: Vec3::NEG_Z,
127                    color,
128                    intensity: light.intensity,
129                    range: light.range,
130                    inner_cone,
131                    outer_cone
132                })
133            };
134        }
135    }
136
137    /// Models whose connection condition holds, `connected` telling whether an anchor is connected.
138    pub fn models_where(
139        &self,
140        connected: impl Fn(&str) -> bool
141    ) -> impl Iterator<Item = &(Handle<Mesh>, Handle<PbrMaterial>)> {
142        self.models
143            .iter()
144            .zip(self.conditions.iter())
145            .filter(move |(_, condition): &(_, &Option<ModelCondition>)| {
146                condition
147                    .as_ref()
148                    .is_none_or(|c| connected(&c.anchor) == c.connected)
149            })
150            .map(|(model, _)| model)
151    }
152}
153
154/// Triangles of a mesh, in model space (or bone space for meshes moving with a bone).
155#[derive(Debug, Default)]
156pub struct MeshGeometry {
157    pub positions: Vec<Vec3>,
158    pub indices: Vec<u32>
159}
160
161/// Options for loading a glTF model.
162#[derive(Serialize, Deserialize)]
163#[serde(default)]
164pub struct GltfLoaderSettings {
165    /// The optional stencil value to set the stencil buffer to when rendering the model. By default, no stencil value is set.
166    pub stencil_value: Option<u32>,
167    /// Levels of detail generated for each mesh, none if `None`.
168    pub lods: Option<MeshLodSettings>
169}
170impl Default for GltfLoaderSettings {
171    fn default() -> Self {
172        Self {
173            stencil_value: None,
174            lods: Some(MeshLodSettings::default())
175        }
176    }
177}
178
179#[derive(Default, TypePath)]
180pub(crate) struct GltfAssetLoader;
181impl AssetLoader for GltfAssetLoader {
182    type Asset = GltfAsset;
183    type Settings = GltfLoaderSettings;
184    type Error = GltfError;
185
186    async fn load(
187        &self,
188        reader: &mut dyn Reader,
189        settings: &Self::Settings,
190        load_context: &mut LoadContext<'_>
191    ) -> Result<Self::Asset, Self::Error> {
192        let path = load_context.path().clone();
193        debug!("Loading glTF file {}.", &path);
194
195        // Parse the glTF file
196        let mut bytes = Vec::new();
197        reader.read_to_end(&mut bytes).await?;
198        let model = parser::parse_gltf(bytes, &path.to_string())?;
199
200        // Form and load the model into the Bevy world
201        let (raw_materials, raw_meshes, bounding_boxes) = loader::form_models(&model)?;
202
203        // Construct materials
204        let materials_handles: Vec<Handle<PbrMaterial>> = raw_materials
205            .iter()
206            .map(|material| material.to_pbr(load_context))
207            .collect();
208
209        // Model space transform of each bone in its rest pose
210        let mut bone_matrices: Vec<Mat4> = Vec::with_capacity(model.bones.len());
211        for bone in &model.bones {
212            let local = Mat4::from_scale_rotation_translation(
213                bone.rest.scale,
214                bone.rest.rotation,
215                bone.rest.translation
216            );
217            bone_matrices.push(match bone.parent {
218                Some(parent) => bone_matrices[parent] * local,
219                None => local
220            });
221        }
222
223        // Add meshes to the asset server
224        let mut models = Vec::new();
225        let mut conditions = Vec::new();
226        let mut geometry = Vec::new();
227        let mut model_bones = Vec::new();
228        let mut bbox_min = Vec3::splat(f32::INFINITY);
229        let mut bbox_max = Vec3::splat(f32::NEG_INFINITY);
230        for (i, (indices_data, vertices, material_id, condition, bone)) in
231            raw_meshes.iter().enumerate()
232        {
233            let label = format!("gltf_mesh_{}", i);
234            let (bb_min, bb_max) = bounding_boxes[i];
235            let mut mesh_asset = Mesh {
236                label: label.clone(),
237                vertices: vertices.clone(),
238                indices: indices_data.clone(),
239                lods: Vec::new(),
240                bbox: MeshBbox {
241                    min: bb_min,
242                    max: bb_max
243                },
244                use_ssbo: true
245            };
246            if let Some(lods) = &settings.lods {
247                mesh_asset.generate_lods(lods);
248            }
249
250            models.push((
251                load_context.add_labeled_asset(label.clone(), mesh_asset),
252                materials_handles[*material_id].clone()
253            ));
254            conditions.push(condition.clone());
255            geometry.push(Arc::new(MeshGeometry {
256                positions: vertices.iter().map(|v| Vec3::from(v.position)).collect(),
257                indices: match indices_data.is_empty() {
258                    true => (0..vertices.len() as u32).collect(),
259                    false => indices_data.clone()
260                }
261            }));
262            model_bones.push(*bone);
263
264            // Update the overall bounding box of the model, with bone meshes in their rest pose
265            let corners = match bone {
266                Some(bone) => (0..8)
267                    .map(|c| {
268                        let corner = Vec3::select(
269                            bevy::math::BVec3::new(c & 1 != 0, c & 2 != 0, c & 4 != 0),
270                            bb_max,
271                            bb_min
272                        );
273                        bone_matrices[*bone].transform_point3(corner)
274                    })
275                    .collect(),
276                None => vec![bb_min, bb_max]
277            };
278            for corner in corners {
279                bbox_min = bbox_min.min(corner);
280                bbox_max = bbox_max.max(corner);
281            }
282        }
283
284        let animations = model
285            .animations
286            .into_iter()
287            .map(|clip| {
288                let name = clip.name.clone();
289                let handle = load_context.add_labeled_asset(format!("animation_{name}"), clip);
290                (name, handle)
291            })
292            .collect();
293
294        Ok(GltfAsset {
295            path: path.to_string(),
296            models,
297            conditions,
298            geometry,
299            bbox: MeshBbox {
300                min: bbox_min,
301                max: bbox_max
302            },
303            properties: model.properties,
304            bones: model.bones,
305            model_bones,
306            animations,
307            lights: model.lights
308        })
309    }
310
311    fn extensions(&self) -> &[&str] {
312        &["gltf", "glb"]
313    }
314}
315
316/// Manager to load glTF models into the Bevy world.
317/// See the [crate] documentation for usage examples.
318pub struct GltfLoader;
319impl GltfLoader {
320    /// Enqueue a glTF asset handle to be spawned automatically when loaded.
321    pub fn spawn(queue: &mut GltfSpawnQueue, gltf_asset: Handle<GltfAsset>, parent: Entity) {
322        queue.pending.push((parent, gltf_asset));
323    }
324
325    /// Try to spawn the loaded glTF model into the Bevy world.
326    /// Returns `None` if the asset handle is not loaded yet.
327    pub fn try_spawn(
328        commands: &mut Commands,
329        gltf_asset: &Handle<GltfAsset>,
330        gltf_assets: &Assets<GltfAsset>,
331        parent: Entity
332    ) -> Option<()> {
333        let gltf_asset = gltf_assets.get(gltf_asset)?;
334
335        // Bones, animated by the `AnimationPlayer` of an ancestor
336        let mut bones: Vec<Entity> = Vec::with_capacity(gltf_asset.bones.len());
337        for bone in &gltf_asset.bones {
338            let bone_entity = commands
339                .spawn((
340                    Name::new(format!("Bone {}", bone.name)),
341                    bone.rest,
342                    AnimationBone {
343                        name: bone.name.clone(),
344                        rest: bone.rest
345                    },
346                    ChildOf(bone.parent.map_or(parent, |p| bones[p]))
347                ))
348                .id();
349            bones.push(bone_entity);
350        }
351
352        for (i, (mesh_handle, material_handle)) in gltf_asset.models.iter().enumerate() {
353            let mesh_parent = gltf_asset.model_bones[i].map_or(parent, |bone| bones[bone]);
354            commands.spawn((
355                Name::new(format!(
356                    "Mesh Entity {} for GLTF Model {}",
357                    i, gltf_asset.path
358                )),
359                Transform::default(),
360                Mesh3d(mesh_handle.clone()),
361                PbrMaterial3d(material_handle.clone()),
362                ChildOf(mesh_parent)
363            ));
364        }
365        gltf_asset.spawn_lights(commands, parent);
366        Some(())
367    }
368}
369
370fn process_gltf_spawn_queue(
371    mut commands: Commands,
372    mut queue: ResMut<GltfSpawnQueue>,
373    gltf_assets: Res<Assets<GltfAsset>>
374) {
375    let mut i = 0;
376    while i < queue.pending.len() {
377        let (parent, gltf_asset) = &queue.pending[i];
378        if GltfLoader::try_spawn(&mut commands, gltf_asset, &gltf_assets, *parent).is_some() {
379            queue.pending.swap_remove(i);
380        } else {
381            i += 1;
382        }
383    }
384}