microcad_core/geo3d/
triangle.rs

1// Copyright © 2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Specializations for 3D triangles.
5
6use cgmath::InnerSpace;
7
8use crate::*;
9
10impl Triangle<Vertex> {
11    /// Get normal of triangle
12    pub fn normal(&self) -> Vec3 {
13        (self.2.pos - self.0.pos).cross(self.1.pos - self.0.pos)
14    }
15}
16
17impl Triangle<&Vertex> {
18    /// Get normal of triangle
19    pub fn normal(&self) -> Vec3 {
20        (self.2.pos - self.0.pos).cross(self.1.pos - self.0.pos)
21    }
22
23    /// Get area of triangle.
24    pub fn area(&self) -> Scalar {
25        self.normal().magnitude()
26    }
27
28    /// Get signed volume of triangle
29    ///
30    /// <https://stackoverflow.com/questions/1406029/how-to-calculate-the-volume-of-a-3d-mesh-object-the-surface-of-which-is-made-up>
31    pub fn signed_volume(&self) -> f64 {
32        let v210 = self.2.pos.x * self.1.pos.y * self.0.pos.z;
33        let v120 = self.1.pos.x * self.2.pos.y * self.0.pos.z;
34        let v201 = self.2.pos.x * self.0.pos.y * self.1.pos.z;
35        let v021 = self.0.pos.x * self.2.pos.y * self.1.pos.z;
36        let v102 = self.1.pos.x * self.0.pos.y * self.2.pos.z;
37        let v012 = self.0.pos.x * self.1.pos.y * self.2.pos.z;
38
39        (1.0 / 6.0) * (-v210 + v120 + v201 - v021 - v102 + v012)
40    }
41}