Skip to main content

cranpose_ui_graphics/space/
mesh.rs

1use std::{
2    f32::consts::PI,
3    fmt,
4    sync::{OnceLock, atomic::Ordering},
5};
6
7use portable_atomic::AtomicU64;
8
9use super::math::{Mat4, Vec3};
10
11static NEXT_MESH_ID: AtomicU64 = AtomicU64::new(1);
12
13/// Why the parts given to [`Mesh::new`] do not make a mesh.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum MeshError {
16    /// The texture coordinates or the normals do not have one entry for
17    /// each position.
18    AttributeCountMismatch,
19    /// The number of indices is not a multiple of three.
20    IndicesNotTriangles,
21    /// An index names a vertex past the last one.
22    IndexOutOfRange,
23    /// The mesh has no triangle.
24    Empty,
25}
26
27impl fmt::Display for MeshError {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        f.write_str(match self {
30            Self::AttributeCountMismatch => {
31                "texture coordinates and normals need one entry for each position"
32            }
33            Self::IndicesNotTriangles => "the index count is not a multiple of three",
34            Self::IndexOutOfRange => "an index names a vertex past the last one",
35            Self::Empty => "the mesh has no triangle",
36        })
37    }
38}
39
40impl std::error::Error for MeshError {}
41
42/// What the edges of a mesh's texture are on the mesh, which decides how
43/// its outline is drawn.
44#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
45pub enum TextureEdges {
46    /// Seams, or no edges at all: the texture wraps a closed shape, as on a
47    /// sphere, or each face shows it whole, as on a cube. The renderer
48    /// draws the mesh's outline as its triangles cover pixels.
49    #[default]
50    Seams,
51    /// The mesh's outline: the mesh is an open sheet, as a plane or a cloth,
52    /// whose edges are the texture's edges. The renderer covers a pixel the
53    /// outline crosses in part, so the outline shows smooth at any angle.
54    Outline,
55}
56
57/// Where a ray meets a mesh.
58#[derive(Clone, Copy, Debug, PartialEq)]
59pub struct MeshHit {
60    /// How far along the ray the hit is, in units of the ray's direction.
61    pub distance: f32,
62    /// The index of the triangle that the ray meets.
63    pub triangle: u32,
64    /// The texture coordinate at the hit.
65    pub uv: [f32; 2],
66}
67
68/// The point of a placed mesh nearest some point.
69#[derive(Clone, Copy, Debug, PartialEq)]
70pub struct MeshContact {
71    /// The nearest point.
72    pub point: Vec3,
73    /// How far it lies from the point asked about.
74    pub distance: f32,
75    /// The texture coordinate there.
76    pub uv: [f32; 2],
77}
78
79/// Triangles in 3D that a composable can be drawn on.
80///
81/// Each vertex has a position, a normal and a texture coordinate. A
82/// composable drawn on the mesh shows its content point `(x, y)` where the
83/// texture coordinate is `(x / width, y / height)`: `(0, 0)` is the content's
84/// top left corner and `(1, 1)` its bottom right.
85///
86/// ```
87/// use cranpose_ui_graphics::space::{Mesh, Vec3};
88///
89/// let sphere = Mesh::sphere(32, 16);
90/// // The middle of the texture faces the viewer.
91/// let front = sphere
92///     .point_at([0.5, 0.5])
93///     .expect("the sphere covers its texture");
94/// assert!((front - Vec3::new(0.0, 0.0, -1.0)).length() < 1e-3);
95/// ```
96///
97/// Two meshes are equal when they are the same mesh: a mesh does not change
98/// once made.
99pub struct Mesh {
100    id: u64,
101    positions: Vec<[f32; 3]>,
102    normals: Vec<[f32; 3]>,
103    uvs: Vec<[f32; 2]>,
104    indices: Vec<u32>,
105    texture_edges: TextureEdges,
106    texture_plane: OnceLock<Option<TexturePlane>>,
107    bounds: OnceLock<(Vec3, Vec3)>,
108}
109
110impl PartialEq for Mesh {
111    fn eq(&self, other: &Self) -> bool {
112        self.id == other.id
113    }
114}
115
116impl fmt::Debug for Mesh {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.debug_struct("Mesh")
119            .field("id", &self.id)
120            .field("vertices", &self.positions.len())
121            .field("triangles", &self.triangle_count())
122            .finish()
123    }
124}
125
126/// The plane that carries texture coordinates onto a mesh: `(u, v)` lies at
127/// `origin + u_axis * u + v_axis * v`. A flat mesh lies in it; a curved one
128/// touches it where the texture's middle lies.
129#[derive(Clone, Copy, Debug, PartialEq)]
130pub struct TexturePlane {
131    /// Where `(0, 0)` lies.
132    pub origin: Vec3,
133    /// The step from `(0, 0)` to `(1, 0)`.
134    pub u_axis: Vec3,
135    /// The step from `(0, 0)` to `(0, 1)`.
136    pub v_axis: Vec3,
137}
138
139impl Mesh {
140    /// A mesh from its vertices and the indices of its triangles' corners,
141    /// three to a triangle. Without `normals`, each vertex takes the mean
142    /// direction of the triangles around it.
143    pub fn new(
144        positions: Vec<[f32; 3]>,
145        uvs: Vec<[f32; 2]>,
146        normals: Option<Vec<[f32; 3]>>,
147        indices: Vec<u32>,
148    ) -> Result<Self, MeshError> {
149        if uvs.len() != positions.len()
150            || normals
151                .as_ref()
152                .is_some_and(|normals| normals.len() != positions.len())
153        {
154            return Err(MeshError::AttributeCountMismatch);
155        }
156        if !indices.len().is_multiple_of(3) {
157            return Err(MeshError::IndicesNotTriangles);
158        }
159        if indices.is_empty() {
160            return Err(MeshError::Empty);
161        }
162        if indices
163            .iter()
164            .any(|&index| index as usize >= positions.len())
165        {
166            return Err(MeshError::IndexOutOfRange);
167        }
168        let normals = normals.unwrap_or_else(|| smooth_normals(&positions, &indices));
169        Ok(Self::assembled(positions, uvs, normals, indices))
170    }
171
172    /// The unit square from `(0, 0, 0)` to `(1, 1, 0)`, facing the viewer,
173    /// with the texture coordinate equal to the position. Scaled by a
174    /// composable's size it shows the composable as it is laid out.
175    pub fn plane() -> Self {
176        let mut parts = MeshParts::default();
177        parts.quad(
178            Vec3::ZERO,
179            Vec3::new(1.0, 0.0, 0.0),
180            Vec3::new(0.0, 1.0, 0.0),
181        );
182        parts.into_mesh().with_texture_edges(TextureEdges::Outline)
183    }
184
185    /// The mesh with `edges` as what its texture's edges are on it: an open
186    /// sheet whose outline is the texture's edge, as a cloth, takes
187    /// [`TextureEdges::Outline`] and shows a smooth outline. A mesh is
188    /// [`TextureEdges::Seams`] unless made otherwise; [`plane`](Self::plane)
189    /// is an outline.
190    #[must_use]
191    pub fn with_texture_edges(mut self, edges: TextureEdges) -> Self {
192        self.texture_edges = edges;
193        self
194    }
195
196    /// What the edges of the mesh's texture are on the mesh.
197    pub fn texture_edges(&self) -> TextureEdges {
198        self.texture_edges
199    }
200
201    /// The unit cube from `(-0.5, -0.5, -0.5)` to `(0.5, 0.5, 0.5)`. Each
202    /// face shows the whole texture, upright when seen from outside; the top
203    /// and bottom faces have the texture's top toward the back.
204    pub fn cuboid() -> Self {
205        let mut parts = MeshParts::default();
206        let (x, y, z) = (
207            Vec3::new(1.0, 0.0, 0.0),
208            Vec3::new(0.0, 1.0, 0.0),
209            Vec3::new(0.0, 0.0, 1.0),
210        );
211        let h = 0.5;
212        parts.quad(Vec3::new(-h, -h, -h), x, y);
213        parts.quad(Vec3::new(h, -h, h), -x, y);
214        parts.quad(Vec3::new(-h, -h, h), -z, y);
215        parts.quad(Vec3::new(h, -h, -h), z, y);
216        parts.quad(Vec3::new(-h, -h, h), x, -z);
217        parts.quad(Vec3::new(-h, h, -h), x, z);
218        parts.into_mesh()
219    }
220
221    /// The sphere of radius one about the origin, with `segments` slices
222    /// around and `rings` from top to bottom. The texture wraps around it
223    /// once: its left and right edges meet at the back, its top and bottom
224    /// edges are the poles, and its middle faces the viewer.
225    pub fn sphere(segments: u32, rings: u32) -> Self {
226        let (segments, rings) = (segments.max(3), rings.max(2));
227        let columns = segments + 1;
228        let mut positions = Vec::with_capacity((columns * (rings + 1)) as usize);
229        let mut uvs = Vec::with_capacity(positions.capacity());
230        for ring in 0..=rings {
231            let v = ring as f32 / rings as f32;
232            let (sin_polar, cos_polar) = (v * PI).sin_cos();
233            for segment in 0..=segments {
234                let u = segment as f32 / segments as f32;
235                let (sin_around, cos_around) = ((u - 0.5) * 2.0 * PI).sin_cos();
236                positions.push([sin_polar * sin_around, -cos_polar, -sin_polar * cos_around]);
237                uvs.push([u, v]);
238            }
239        }
240        let indices = wrapped_grid_indices(segments, rings);
241        let normals = positions.clone();
242        Self::assembled(positions, uvs, normals, indices)
243    }
244
245    /// The tube of radius one about the y axis from `y = -0.5` to `0.5`,
246    /// open at both ends, with `segments` slices around. The texture wraps
247    /// around it once as it does around [`sphere`](Self::sphere): its left
248    /// and right edges meet at the back, its top edge is the end at
249    /// `y = -0.5`, and its middle faces the viewer.
250    ///
251    /// ```
252    /// use cranpose_ui_graphics::space::{Mesh, Vec3};
253    ///
254    /// let tube = Mesh::cylinder(24);
255    /// let front = tube
256    ///     .point_at([0.5, 0.5])
257    ///     .expect("the tube covers its texture");
258    /// assert!((front - Vec3::new(0.0, 0.0, -1.0)).length() < 1e-3);
259    /// ```
260    pub fn cylinder(segments: u32) -> Self {
261        let segments = segments.max(3);
262        let columns = segments + 1;
263        let mut positions = Vec::with_capacity((columns * 2) as usize);
264        let mut normals = Vec::with_capacity(positions.capacity());
265        let mut uvs = Vec::with_capacity(positions.capacity());
266        for v in [0.0, 1.0] {
267            for segment in 0..=segments {
268                let u = segment as f32 / segments as f32;
269                let (sin_around, cos_around) = ((u - 0.5) * 2.0 * PI).sin_cos();
270                positions.push([sin_around, v - 0.5, -cos_around]);
271                normals.push([sin_around, 0.0, -cos_around]);
272                uvs.push([u, v]);
273            }
274        }
275        let indices = wrapped_grid_indices(segments, 1);
276        Self::assembled(positions, uvs, normals, indices)
277    }
278
279    /// A number that no other mesh made in this process has. Renderers keep
280    /// a mesh's buffers under it.
281    pub fn id(&self) -> u64 {
282        self.id
283    }
284
285    /// The vertex positions.
286    pub fn positions(&self) -> &[[f32; 3]] {
287        &self.positions
288    }
289
290    /// The vertex normals, one for each position, each of length one.
291    pub fn normals(&self) -> &[[f32; 3]] {
292        &self.normals
293    }
294
295    /// The vertex texture coordinates, one for each position.
296    pub fn uvs(&self) -> &[[f32; 2]] {
297        &self.uvs
298    }
299
300    /// The vertex indices of the triangles' corners, three to a triangle.
301    pub fn indices(&self) -> &[u32] {
302        &self.indices
303    }
304
305    /// The nearest place in front of `origin` where the ray along
306    /// `direction` meets a triangle, from either side.
307    pub fn cast(&self, origin: Vec3, direction: Vec3) -> Option<MeshHit> {
308        let mut nearest: Option<MeshHit> = None;
309        for triangle in 0..self.triangle_count() {
310            let [a, b, c] = self.corners(triangle);
311            let Some((distance, weights)) = ray_triangle(origin, direction, [a, b, c]) else {
312                continue;
313            };
314            if nearest.is_some_and(|hit| hit.distance <= distance) {
315                continue;
316            }
317            nearest = Some(MeshHit {
318                distance,
319                triangle,
320                uv: self.uv_at(triangle, weights),
321            });
322        }
323        nearest
324    }
325
326    /// Where the ray meets the plane of `triangle`, as a texture coordinate
327    /// carried on from the triangle's corners: it lies outside the triangle
328    /// when the ray misses it. `None` when the ray runs along the plane or
329    /// meets it behind `origin`, or for a triangle that does not exist.
330    pub fn cast_plane(&self, origin: Vec3, direction: Vec3, triangle: u32) -> Option<[f32; 2]> {
331        if triangle >= self.triangle_count() {
332            return None;
333        }
334        let [a, b, c] = self.corners(triangle);
335        let normal = (b - a).cross(c - a);
336        let along = normal.dot(direction);
337        if along.abs() <= f32::EPSILON * normal.length() * direction.length() {
338            return None;
339        }
340        let distance = normal.dot(a - origin) / along;
341        if distance <= 0.0 {
342            return None;
343        }
344        let point = origin + direction * distance;
345        let weights = barycentric(point, [a, b, c], normal)?;
346        Some(self.uv_at(triangle, weights))
347    }
348
349    /// The position where the texture coordinate `uv` lies on the mesh, from
350    /// the first triangle that covers it; `None` when none does.
351    pub fn point_at(&self, uv: [f32; 2]) -> Option<Vec3> {
352        const EDGE: f32 = 1.0e-4;
353        let point = Vec3::new(uv[0], uv[1], 0.0);
354        (0..self.triangle_count()).find_map(|triangle| {
355            let [ia, ib, ic] = self.triangle_indices(triangle);
356            let corner = |index: usize| {
357                let [u, v] = self.uvs[index];
358                Vec3::new(u, v, 0.0)
359            };
360            let flat = [corner(ia), corner(ib), corner(ic)];
361            let normal = (flat[1] - flat[0]).cross(flat[2] - flat[0]);
362            let [wa, wb, wc] = barycentric(point, flat, normal)?;
363            (wa >= -EDGE && wb >= -EDGE && wc >= -EDGE).then(|| {
364                let position = |index: usize| Vec3::from_array(self.positions[index]);
365                position(ia) * wa + position(ib) * wb + position(ic) * wc
366            })
367        })
368    }
369
370    /// The point of the mesh, placed by `transform`, nearest `point`, with
371    /// the texture coordinate there; `None` for a mesh without triangles.
372    pub fn nearest(&self, point: Vec3, transform: &Mat4) -> Option<MeshContact> {
373        let mut nearest: Option<MeshContact> = None;
374        for triangle in 0..self.triangle_count() {
375            let corners = self
376                .corners(triangle)
377                .map(|corner| transform.transform_point(corner));
378            let (at, weights) = nearest_on_triangle(point, corners);
379            let distance = (point - at).length();
380            if nearest.is_some_and(|known| known.distance <= distance) {
381                continue;
382            }
383            nearest = Some(MeshContact {
384                point: at,
385                distance,
386                uv: self.uv_at(triangle, weights),
387            });
388        }
389        nearest
390    }
391
392    /// The smallest box along the axes that holds every vertex: its lowest
393    /// and highest corners.
394    pub fn bounds(&self) -> (Vec3, Vec3) {
395        *self.bounds.get_or_init(|| {
396            let mut low = Vec3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY);
397            let mut high = -low;
398            for &position in &self.positions {
399                let point = Vec3::from_array(position);
400                (low, high) = (low.min(point), high.max(point));
401            }
402            (low, high)
403        })
404    }
405
406    /// The smallest box along the axes that holds the corners of
407    /// [`Self::bounds`] that `transform` maps: its lowest and highest
408    /// corners.
409    pub fn bounds_in(&self, transform: &Mat4) -> (Vec3, Vec3) {
410        let (mesh_low, mesh_high) = self.bounds();
411        let mut low = Vec3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY);
412        let mut high = -low;
413        for corner in 0..8 {
414            let pick = |bit: u32, low: f32, high: f32| if corner & bit == 0 { low } else { high };
415            let point = transform.transform_point(Vec3::new(
416                pick(1, mesh_low.x, mesh_high.x),
417                pick(2, mesh_low.y, mesh_high.y),
418                pick(4, mesh_low.z, mesh_high.z),
419            ));
420            (low, high) = (low.min(point), high.max(point));
421        }
422        (low, high)
423    }
424
425    /// The plane that carries texture coordinates onto the mesh, worked out
426    /// once: the plane of a flat mesh, or the one that touches a curved mesh
427    /// at the texture's middle. `None` when the texture's middle does not lie
428    /// on the mesh, or the mesh stretches it to a line there.
429    pub fn texture_plane(&self) -> Option<TexturePlane> {
430        *self.texture_plane.get_or_init(|| {
431            self.flat_texture_plane()
432                .or_else(|| self.tangent_texture_plane())
433        })
434    }
435
436    fn flat_texture_plane(&self) -> Option<TexturePlane> {
437        let origin = self.point_at([0.0, 0.0])?;
438        let u_axis = self.point_at([1.0, 0.0])? - origin;
439        let v_axis = self.point_at([0.0, 1.0])? - origin;
440        let plane = TexturePlane {
441            origin,
442            u_axis,
443            v_axis,
444        };
445        let tolerance = 1.0e-3 * (u_axis.length() + v_axis.length());
446        let lies_flat = [[1.0, 1.0], [0.5, 0.5], [0.25, 0.75]].iter().all(|&uv| {
447            self.point_at(uv)
448                .is_some_and(|point| (point - plane.at(uv)).length() <= tolerance)
449        });
450        (lies_flat && u_axis.cross(v_axis).length() > tolerance * tolerance).then_some(plane)
451    }
452
453    fn tangent_texture_plane(&self) -> Option<TexturePlane> {
454        const STEP: f32 = 1.0 / 64.0;
455        let middle = self.point_at([0.5, 0.5])?;
456        let u_axis = (self.point_at([0.5 + STEP, 0.5])? - middle) * (1.0 / STEP);
457        let v_axis = (self.point_at([0.5, 0.5 + STEP])? - middle) * (1.0 / STEP);
458        (u_axis.cross(v_axis).length() > f32::EPSILON).then(|| TexturePlane {
459            origin: middle - u_axis * 0.5 - v_axis * 0.5,
460            u_axis,
461            v_axis,
462        })
463    }
464
465    fn triangle_count(&self) -> u32 {
466        (self.indices.len() / 3) as u32
467    }
468
469    fn triangle_indices(&self, triangle: u32) -> [usize; 3] {
470        let first = triangle as usize * 3;
471        [0, 1, 2].map(|corner| self.indices[first + corner] as usize)
472    }
473
474    fn corners(&self, triangle: u32) -> [Vec3; 3] {
475        self.triangle_indices(triangle)
476            .map(|index| Vec3::from_array(self.positions[index]))
477    }
478
479    fn uv_at(&self, triangle: u32, [wa, wb, wc]: [f32; 3]) -> [f32; 2] {
480        let [a, b, c] = self.triangle_indices(triangle).map(|index| self.uvs[index]);
481        [
482            a[0] * wa + b[0] * wb + c[0] * wc,
483            a[1] * wa + b[1] * wb + c[1] * wc,
484        ]
485    }
486
487    pub(super) fn assembled(
488        positions: Vec<[f32; 3]>,
489        uvs: Vec<[f32; 2]>,
490        normals: Vec<[f32; 3]>,
491        indices: Vec<u32>,
492    ) -> Self {
493        Self {
494            id: NEXT_MESH_ID.fetch_add(1, Ordering::Relaxed),
495            positions,
496            normals,
497            uvs,
498            indices,
499            texture_edges: TextureEdges::Seams,
500            texture_plane: OnceLock::new(),
501            bounds: OnceLock::new(),
502        }
503    }
504}
505
506impl TexturePlane {
507    /// Where `uv` lies in the plane.
508    pub fn at(&self, [u, v]: [f32; 2]) -> Vec3 {
509        self.origin + self.u_axis * u + self.v_axis * v
510    }
511}
512
513#[derive(Default)]
514struct MeshParts {
515    positions: Vec<[f32; 3]>,
516    normals: Vec<[f32; 3]>,
517    uvs: Vec<[f32; 2]>,
518    indices: Vec<u32>,
519}
520
521impl MeshParts {
522    /// A square face with the texture's top left corner at `top_left`, its
523    /// x along `right` and its y along `down`, facing the side from which
524    /// `right` turns clockwise into `down`.
525    fn quad(&mut self, top_left: Vec3, right: Vec3, down: Vec3) {
526        let base = self.positions.len() as u32;
527        let normal = down.cross(right).normalized().unwrap_or(Vec3::ZERO);
528        for (corner, uv) in [
529            (top_left, [0.0, 0.0]),
530            (top_left + right, [1.0, 0.0]),
531            (top_left + down, [0.0, 1.0]),
532            (top_left + right + down, [1.0, 1.0]),
533        ] {
534            self.positions.push(corner.to_array());
535            self.normals.push(normal.to_array());
536            self.uvs.push(uv);
537        }
538        self.indices
539            .extend([base, base + 1, base + 2, base + 2, base + 1, base + 3]);
540    }
541
542    fn into_mesh(self) -> Mesh {
543        Mesh::assembled(self.positions, self.uvs, self.normals, self.indices)
544    }
545}
546
547/// Normals that follow the triangles around each vertex, weighted by their
548/// areas.
549pub(super) fn smooth_normals(positions: &[[f32; 3]], indices: &[u32]) -> Vec<[f32; 3]> {
550    let mut sums = vec![Vec3::ZERO; positions.len()];
551    for triangle in indices.as_chunks::<3>().0 {
552        let corner = |index: u32| Vec3::from_array(positions[index as usize]);
553        let (a, b, c) = (
554            corner(triangle[0]),
555            corner(triangle[1]),
556            corner(triangle[2]),
557        );
558        let face = (b - a).cross(c - a);
559        for &index in triangle {
560            sums[index as usize] = sums[index as usize] + face;
561        }
562    }
563    sums.into_iter()
564        .map(|sum| {
565            sum.normalized()
566                .unwrap_or(Vec3::new(0.0, 0.0, -1.0))
567                .to_array()
568        })
569        .collect()
570}
571
572// The triangles of a grid of `rows + 1` rows of `segments + 1` vertices
573// that wraps around an axis: two to each cell, the first column repeated
574// as the last so the texture's seam has vertices of its own on each side.
575fn wrapped_grid_indices(segments: u32, rows: u32) -> Vec<u32> {
576    let columns = segments + 1;
577    let mut indices = Vec::with_capacity((segments * rows * 6) as usize);
578    for row in 0..rows {
579        for segment in 0..segments {
580            let top_left = row * columns + segment;
581            let bottom_left = top_left + columns;
582            indices.extend([
583                top_left,
584                top_left + 1,
585                bottom_left,
586                bottom_left,
587                top_left + 1,
588                bottom_left + 1,
589            ]);
590        }
591    }
592    indices
593}
594
595/// Where the ray meets the triangle, from either side: the distance along
596/// `direction` and the corners' weights at the hit.
597fn ray_triangle(origin: Vec3, direction: Vec3, [a, b, c]: [Vec3; 3]) -> Option<(f32, [f32; 3])> {
598    let (edge_b, edge_c) = (b - a, c - a);
599    let p = direction.cross(edge_c);
600    let determinant = edge_b.dot(p);
601    if determinant.abs() <= f32::EPSILON * edge_b.length() * edge_c.length() * direction.length() {
602        return None;
603    }
604    let inverse = 1.0 / determinant;
605    let offset = origin - a;
606    let wb = offset.dot(p) * inverse;
607    if !(0.0..=1.0).contains(&wb) {
608        return None;
609    }
610    let q = offset.cross(edge_b);
611    let wc = direction.dot(q) * inverse;
612    if wc < 0.0 || wb + wc > 1.0 {
613        return None;
614    }
615    let distance = edge_c.dot(q) * inverse;
616    (distance > 0.0).then_some((distance, [1.0 - wb - wc, wb, wc]))
617}
618
619/// The point of the triangle nearest `point`, and the weights of its corners
620/// there, by the regions of the triangle's corners and edges (Ericson, Real-
621/// Time Collision Detection, 5.1.5).
622fn nearest_on_triangle(point: Vec3, [a, b, c]: [Vec3; 3]) -> (Vec3, [f32; 3]) {
623    let (ab, ac) = (b - a, c - a);
624    let (d1, d2) = (ab.dot(point - a), ac.dot(point - a));
625    if d1 <= 0.0 && d2 <= 0.0 {
626        return (a, [1.0, 0.0, 0.0]);
627    }
628    let (d3, d4) = (ab.dot(point - b), ac.dot(point - b));
629    if d3 >= 0.0 && d4 <= d3 {
630        return (b, [0.0, 1.0, 0.0]);
631    }
632    let vc = d1 * d4 - d3 * d2;
633    if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
634        let v = d1 / (d1 - d3);
635        return (a + ab * v, [1.0 - v, v, 0.0]);
636    }
637    let (d5, d6) = (ab.dot(point - c), ac.dot(point - c));
638    if d6 >= 0.0 && d5 <= d6 {
639        return (c, [0.0, 0.0, 1.0]);
640    }
641    let vb = d5 * d2 - d1 * d6;
642    if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
643        let w = d2 / (d2 - d6);
644        return (a + ac * w, [1.0 - w, 0.0, w]);
645    }
646    let va = d3 * d6 - d5 * d4;
647    if va <= 0.0 && d4 - d3 >= 0.0 && d5 - d6 >= 0.0 {
648        let w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
649        return (b + (c - b) * w, [0.0, 1.0 - w, w]);
650    }
651    let total = va + vb + vc;
652    if !total.is_normal() {
653        return (a, [1.0, 0.0, 0.0]);
654    }
655    let (v, w) = (vb / total, vc / total);
656    (a + ab * v + ac * w, [1.0 - v - w, v, w])
657}
658
659/// The weights of the triangle's corners at `point`, which lies in its
660/// plane; `normal` is the plane's. `None` for a triangle with no area.
661fn barycentric(point: Vec3, [a, b, c]: [Vec3; 3], normal: Vec3) -> Option<[f32; 3]> {
662    let area = normal.dot(normal);
663    if !area.is_normal() {
664        return None;
665    }
666    let wb = normal.dot((point - a).cross(c - a)) / area;
667    let wc = normal.dot((b - a).cross(point - a)) / area;
668    Some([1.0 - wb - wc, wb, wc])
669}