parry3d/transformation/to_trimesh/
capsule_to_trimesh.rs

1use crate::math::{Real, Vector3};
2use crate::shape::Capsule;
3use crate::transformation::utils;
4use alloc::vec::Vec;
5
6impl Capsule {
7    /// Discretize the boundary of this capsule as a triangle-mesh.
8    pub fn to_trimesh(
9        &self,
10        ntheta_subdiv: u32,
11        nphi_subdiv: u32,
12    ) -> (Vec<Vector3>, Vec<[u32; 3]>) {
13        let diameter = self.radius * 2.0;
14        let height = self.half_height() * 2.0;
15        let (vtx, idx) = canonical_capsule(diameter, height, ntheta_subdiv, nphi_subdiv);
16        (utils::transformed(vtx, self.canonical_transform()), idx)
17    }
18}
19
20/// Generates a capsule.
21pub(crate) fn canonical_capsule(
22    caps_diameter: Real,
23    cylinder_height: Real,
24    ntheta_subdiv: u32,
25    nphi_subdiv: u32,
26) -> (Vec<Vector3>, Vec<[u32; 3]>) {
27    let (coords, indices) = super::ball_to_trimesh::unit_hemisphere(ntheta_subdiv, nphi_subdiv / 2);
28    let mut bottom_coords = coords.clone();
29    let mut bottom_indices = indices.clone();
30    utils::reverse_clockwising(&mut bottom_indices[..]);
31
32    let mut top_coords = coords;
33    let mut top_indices = indices;
34
35    let half_height = cylinder_height * 0.5;
36
37    // shift the top
38    for coord in top_coords.iter_mut() {
39        coord.x *= caps_diameter;
40        coord.y = coord.y * caps_diameter + half_height;
41        coord.z *= caps_diameter;
42    }
43
44    // flip + shift the bottom
45    for coord in bottom_coords.iter_mut() {
46        coord.x *= caps_diameter;
47        coord.y = -(coord.y * caps_diameter) - half_height;
48        coord.z *= caps_diameter;
49    }
50
51    // shift the top index buffer
52    let base_top_coords = bottom_coords.len() as u32;
53
54    for idx in top_indices.iter_mut() {
55        idx[0] += base_top_coords;
56        idx[1] += base_top_coords;
57        idx[2] += base_top_coords;
58    }
59
60    // merge all buffers
61    bottom_coords.extend(top_coords);
62    bottom_indices.extend(top_indices);
63
64    // attach the two caps
65    utils::push_ring_indices(0, base_top_coords, ntheta_subdiv, &mut bottom_indices);
66
67    (bottom_coords, bottom_indices)
68}