Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Mesh transformation #11454

Merged
merged 11 commits into from
Jan 29, 2024
31 changes: 31 additions & 0 deletions crates/bevy_render/src/mesh/mesh/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod conversions;
pub mod skinning;
use bevy_transform::components::Transform;
pub use wgpu::PrimitiveTopology;

use crate::{
Expand Down Expand Up @@ -572,6 +573,36 @@ impl Mesh {
Ok(self)
}

/// Transforms the vertex positions, normals, and tangents of the mesh by the given [`Transform`].
pub fn transform_by(&mut self, transform: Transform) {
if let Some(VertexAttributeValues::Float32x3(ref mut positions)) =
self.attribute_mut(Mesh::ATTRIBUTE_POSITION)
{
// Apply scale, rotation, and translation to vertex positions
positions
.iter_mut()
.for_each(|pos| *pos = transform.transform_point(Vec3::from_slice(pos)).to_array());
}

if let Some(VertexAttributeValues::Float32x3(ref mut normals)) =
self.attribute_mut(Mesh::ATTRIBUTE_NORMAL)
{
// Rotate normals by transform rotation
Jondolf marked this conversation as resolved.
Show resolved Hide resolved
normals.iter_mut().for_each(|normal| {
*normal = (transform.rotation * Vec3::from_slice(normal)).to_array();
});
}

if let Some(VertexAttributeValues::Float32x3(ref mut tangents)) =
self.attribute_mut(Mesh::ATTRIBUTE_TANGENT)
{
// Rotate tangents by transform rotation
tangents.iter_mut().for_each(|tangent| {
*tangent = (transform.rotation * Vec3::from_slice(tangent)).to_array();
});
}
}

/// Compute the Axis-Aligned Bounding Box of the mesh vertices in model space
///
/// Returns `None` if `self` doesn't have [`Mesh::ATTRIBUTE_POSITION`] of
Expand Down