bevy_mesh/primitives/dim3/
tetrahedron.rs

1use super::triangle3d;
2use crate::{Indices, Mesh, MeshBuilder, Meshable};
3use bevy_asset::RenderAssetUsages;
4use bevy_math::primitives::{Tetrahedron, Triangle3d};
5use wgpu::PrimitiveTopology;
6
7/// A builder used for creating a [`Mesh`] with a [`Tetrahedron`] shape.
8pub struct TetrahedronMeshBuilder {
9    tetrahedron: Tetrahedron,
10}
11
12impl MeshBuilder for TetrahedronMeshBuilder {
13    fn build(&self) -> Mesh {
14        let mut faces: Vec<_> = self.tetrahedron.faces().into();
15
16        // If the tetrahedron has negative orientation, reverse all the triangles so that
17        // they still face outward.
18        if self.tetrahedron.signed_volume().is_sign_negative() {
19            faces.iter_mut().for_each(Triangle3d::reverse);
20        }
21
22        let mut positions = vec![];
23        let mut normals = vec![];
24        let mut uvs = vec![];
25
26        // Each face is meshed as a `Triangle3d`, and we just shove the data into the
27        // vertex attributes sequentially.
28        for face in faces {
29            positions.extend(face.vertices);
30
31            let face_normal = triangle3d::normal_vec(&face);
32            normals.extend(vec![face_normal; 3]);
33
34            let face_uvs = triangle3d::uv_coords(&face);
35            uvs.extend(face_uvs);
36        }
37
38        // There are four faces and none of them share vertices.
39        let indices = Indices::U32(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
40
41        Mesh::new(
42            PrimitiveTopology::TriangleList,
43            RenderAssetUsages::default(),
44        )
45        .with_inserted_indices(indices)
46        .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
47        .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
48        .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
49    }
50}
51
52impl Meshable for Tetrahedron {
53    type Output = TetrahedronMeshBuilder;
54
55    fn mesh(&self) -> Self::Output {
56        TetrahedronMeshBuilder { tetrahedron: *self }
57    }
58}
59
60impl From<Tetrahedron> for Mesh {
61    fn from(tetrahedron: Tetrahedron) -> Self {
62        tetrahedron.mesh().build()
63    }
64}