bevy_mesh/
morph.rs

1use super::Mesh;
2use bevy_asset::{Handle, RenderAssetUsages};
3use bevy_ecs::prelude::*;
4use bevy_image::Image;
5use bevy_math::Vec3;
6use bevy_reflect::prelude::*;
7use bytemuck::{Pod, Zeroable};
8use thiserror::Error;
9use wgpu_types::{Extent3d, TextureDimension, TextureFormat};
10
11const MAX_TEXTURE_WIDTH: u32 = 2048;
12// NOTE: "component" refers to the element count of math objects,
13// Vec3 has 3 components, Mat2 has 4 components.
14const MAX_COMPONENTS: u32 = MAX_TEXTURE_WIDTH * MAX_TEXTURE_WIDTH;
15
16/// Max target count available for [morph targets](MorphWeights).
17pub const MAX_MORPH_WEIGHTS: usize = 64;
18
19#[derive(Error, Clone, Debug)]
20pub enum MorphBuildError {
21    #[error(
22        "Too many vertexĂ—components in morph target, max is {MAX_COMPONENTS}, \
23        got {vertex_count}Ă—{component_count} = {}",
24        *vertex_count * *component_count as usize
25    )]
26    TooManyAttributes {
27        vertex_count: usize,
28        component_count: u32,
29    },
30    #[error(
31        "Bevy only supports up to {} morph targets (individual poses), tried to \
32        create a model with {target_count} morph targets",
33        MAX_MORPH_WEIGHTS
34    )]
35    TooManyTargets { target_count: usize },
36}
37
38/// An image formatted for use with [`MorphWeights`] for rendering the morph target.
39#[derive(Debug)]
40pub struct MorphTargetImage(pub Image);
41
42impl MorphTargetImage {
43    /// Generate textures for each morph target.
44    ///
45    /// This accepts an "iterator of [`MorphAttributes`] iterators". Each item iterated in the top level
46    /// iterator corresponds "the attributes of a specific morph target".
47    ///
48    /// Each pixel of the texture is a component of morph target animated
49    /// attributes. So a set of 9 pixels is this morph's displacement for
50    /// position, normal and tangents of a single vertex (each taking 3 pixels).
51    pub fn new(
52        targets: impl ExactSizeIterator<Item = impl Iterator<Item = MorphAttributes>>,
53        vertex_count: usize,
54        asset_usage: RenderAssetUsages,
55    ) -> Result<Self, MorphBuildError> {
56        let max = MAX_TEXTURE_WIDTH;
57        let target_count = targets.len();
58        if target_count > MAX_MORPH_WEIGHTS {
59            return Err(MorphBuildError::TooManyTargets { target_count });
60        }
61        let component_count = (vertex_count * MorphAttributes::COMPONENT_COUNT) as u32;
62        let Some((Rect(width, height), padding)) = lowest_2d(component_count, max) else {
63            return Err(MorphBuildError::TooManyAttributes {
64                vertex_count,
65                component_count,
66            });
67        };
68        let data = targets
69            .flat_map(|mut attributes| {
70                let layer_byte_count = (padding + component_count) as usize * size_of::<f32>();
71                let mut buffer = Vec::with_capacity(layer_byte_count);
72                for _ in 0..vertex_count {
73                    let Some(to_add) = attributes.next() else {
74                        break;
75                    };
76                    buffer.extend_from_slice(bytemuck::bytes_of(&to_add));
77                }
78                // Pad each layer so that they fit width * height
79                buffer.extend(core::iter::repeat_n(0, padding as usize * size_of::<f32>()));
80                debug_assert_eq!(buffer.len(), layer_byte_count);
81                buffer
82            })
83            .collect();
84        let extents = Extent3d {
85            width,
86            height,
87            depth_or_array_layers: target_count as u32,
88        };
89        let image = Image::new(
90            extents,
91            TextureDimension::D3,
92            data,
93            TextureFormat::R32Float,
94            asset_usage,
95        );
96        Ok(MorphTargetImage(image))
97    }
98}
99
100/// Controls the [morph targets] for all child `Mesh3d` entities. In most cases, [`MorphWeights`] should be considered
101/// the "source of truth" when writing morph targets for meshes. However you can choose to write child [`MeshMorphWeights`]
102/// if your situation requires more granularity. Just note that if you set [`MorphWeights`], it will overwrite child
103/// [`MeshMorphWeights`] values.
104///
105/// This exists because Bevy's [`Mesh`] corresponds to a _single_ surface / material, whereas morph targets
106/// as defined in the GLTF spec exist on "multi-primitive meshes" (where each primitive is its own surface with its own material).
107/// Therefore in Bevy [`MorphWeights`] an a parent entity are the "canonical weights" from a GLTF perspective, which then
108/// synchronized to child `Mesh3d` / [`MeshMorphWeights`] (which correspond to "primitives" / "surfaces" from a GLTF perspective).
109///
110/// Add this to the parent of one or more [`Entities`](`Entity`) with a `Mesh3d` with a [`MeshMorphWeights`].
111///
112/// [morph targets]: https://en.wikipedia.org/wiki/Morph_target_animation
113#[derive(Reflect, Default, Debug, Clone, Component)]
114#[reflect(Debug, Component, Default, Clone)]
115pub struct MorphWeights {
116    weights: Vec<f32>,
117    /// The first mesh primitive assigned to these weights
118    first_mesh: Option<Handle<Mesh>>,
119}
120impl MorphWeights {
121    pub fn new(
122        weights: Vec<f32>,
123        first_mesh: Option<Handle<Mesh>>,
124    ) -> Result<Self, MorphBuildError> {
125        if weights.len() > MAX_MORPH_WEIGHTS {
126            let target_count = weights.len();
127            return Err(MorphBuildError::TooManyTargets { target_count });
128        }
129        Ok(MorphWeights {
130            weights,
131            first_mesh,
132        })
133    }
134    /// The first child `Mesh3d` primitive controlled by these weights.
135    /// This can be used to look up metadata information such as [`Mesh::morph_target_names`].
136    pub fn first_mesh(&self) -> Option<&Handle<Mesh>> {
137        self.first_mesh.as_ref()
138    }
139    pub fn weights(&self) -> &[f32] {
140        &self.weights
141    }
142    pub fn weights_mut(&mut self) -> &mut [f32] {
143        &mut self.weights
144    }
145}
146
147/// Control a specific [`Mesh`] instance's [morph targets]. These control the weights of
148/// specific "mesh primitives" in scene formats like GLTF. They can be set manually, but
149/// in most cases they should "automatically" synced by setting the [`MorphWeights`] component
150/// on a parent entity.
151///
152/// See [`MorphWeights`] for more details on Bevy's morph target implementation.
153///
154/// Add this to an [`Entity`] with a `Mesh3d` with a [`MorphAttributes`] set
155/// to control individual weights of each morph target.
156///
157/// [morph targets]: https://en.wikipedia.org/wiki/Morph_target_animation
158#[derive(Reflect, Default, Debug, Clone, Component)]
159#[reflect(Debug, Component, Default, Clone)]
160pub struct MeshMorphWeights {
161    weights: Vec<f32>,
162}
163impl MeshMorphWeights {
164    pub fn new(weights: Vec<f32>) -> Result<Self, MorphBuildError> {
165        if weights.len() > MAX_MORPH_WEIGHTS {
166            let target_count = weights.len();
167            return Err(MorphBuildError::TooManyTargets { target_count });
168        }
169        Ok(MeshMorphWeights { weights })
170    }
171    pub fn weights(&self) -> &[f32] {
172        &self.weights
173    }
174    pub fn weights_mut(&mut self) -> &mut [f32] {
175        &mut self.weights
176    }
177    pub fn clear_weights(&mut self) {
178        self.weights.clear();
179    }
180    pub fn extend_weights(&mut self, weights: &[f32]) {
181        self.weights.extend(weights);
182    }
183}
184
185/// Attributes **differences** used for morph targets.
186///
187/// See [`MorphTargetImage`] for more information.
188#[derive(Copy, Clone, PartialEq, Pod, Zeroable, Default)]
189#[repr(C)]
190pub struct MorphAttributes {
191    /// The vertex position difference between base mesh and this target.
192    pub position: Vec3,
193    /// The vertex normal difference between base mesh and this target.
194    pub normal: Vec3,
195    /// The vertex tangent difference between base mesh and this target.
196    ///
197    /// Note that tangents are a `Vec4`, but only the `xyz` components are
198    /// animated, as the `w` component is the sign and cannot be animated.
199    pub tangent: Vec3,
200}
201impl From<[Vec3; 3]> for MorphAttributes {
202    fn from([position, normal, tangent]: [Vec3; 3]) -> Self {
203        MorphAttributes {
204            position,
205            normal,
206            tangent,
207        }
208    }
209}
210impl MorphAttributes {
211    /// How many components `MorphAttributes` has.
212    ///
213    /// Each `Vec3` has 3 components, we have 3 `Vec3`, for a total of 9.
214    pub const COMPONENT_COUNT: usize = 9;
215
216    pub fn new(position: Vec3, normal: Vec3, tangent: Vec3) -> Self {
217        MorphAttributes {
218            position,
219            normal,
220            tangent,
221        }
222    }
223}
224
225struct Rect(u32, u32);
226
227/// Find the smallest rectangle of maximum edge size `max_edge` that contains
228/// at least `min_includes` cells. `u32` is how many extra cells the rectangle
229/// has.
230///
231/// The following rectangle contains 27 cells, and its longest edge is 9:
232/// ```text
233/// ----------------------------
234/// |1 |2 |3 |4 |5 |6 |7 |8 |9 |
235/// ----------------------------
236/// |2 |  |  |  |  |  |  |  |  |
237/// ----------------------------
238/// |3 |  |  |  |  |  |  |  |  |
239/// ----------------------------
240/// ```
241///
242/// Returns `None` if `max_edge` is too small to build a rectangle
243/// containing `min_includes` cells.
244fn lowest_2d(min_includes: u32, max_edge: u32) -> Option<(Rect, u32)> {
245    (1..=max_edge)
246        .filter_map(|a| {
247            let b = min_includes.div_ceil(a);
248            let diff = (a * b).checked_sub(min_includes)?;
249            Some((Rect(a, b), diff))
250        })
251        .filter_map(|(rect, diff)| (rect.1 <= max_edge).then_some((rect, diff)))
252        .min_by_key(|(_, diff)| *diff)
253}