Skip to main content

brep_render/
draft_analysis.rs

1//! DRAFT ANALYSIS: every face of the shown model coloured by its draft angle
2//! against a pull direction and a minimum (docs/features/draft.md).
3//!
4//! Display only. Nothing here touches the history, the document or undo: the
5//! classes are read off the DISPLAY mesh (its outward normals, inside each
6//! face's own triangle range, so a trimmed face is judged on what is there,
7//! not on its whole carrier), and the colour is an analysis tint on the face
8//! ([`crate::scene::FaceDisplay::analysis_color`]) that wins over the user's
9//! face colour while the analysis is on and leaves it untouched.
10//!
11//! The draft angle of a surface point is the angle between its outward normal
12//! and the plane square to the pull: `asin(n · pull)`, so a wall along the
13//! pull reads 0°, a wall leaning away from the pull as it rises (the material
14//! side narrowing, the way a drafted boss is) reads positive, and a face that
15//! faces along the pull reads +90°. A flat face has one angle. A curved face
16//! is SAMPLED at its mesh vertices, and its class comes from the least and the
17//! greatest sample; the exact extreme can sit between samples, so a curved
18//! face whose sampled range ends within [`NEAR_LIMIT_DEG`] of the minimum is
19//! marked `nearLimit`.
20
21use serde::Serialize;
22
23/// Within this of the minimum, a CURVED face's sampled range is "near the
24/// limit": the samples could have missed an extreme just over it.
25pub const NEAR_LIMIT_DEG: f64 = 0.05;
26/// A face within this of ±90° everywhere is square to the pull (a cap, or a
27/// parting face).
28pub const CAP_TOL_DEG: f64 = 0.01;
29/// Triangle normals that agree to this (1 − cos) make a flat face.
30const FLAT_TOL: f64 = 1e-6;
31
32/// The classes, in legend order.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
34#[serde(rename_all = "camelCase")]
35pub enum DraftClass {
36    /// Every point leans with the pull by at least the minimum.
37    Positive,
38    /// Every point leans against the pull by at least the minimum.
39    Negative,
40    /// Some of the face is under the minimum either way (a wall straight
41    /// along the pull, or a face that reaches one).
42    NeedsDraft,
43    /// The face runs both ways: part of it positive and part negative, each
44    /// past the minimum (a sphere, a torus about the pull).
45    Straddle,
46    /// Square to the pull everywhere: a cap or a parting face.
47    Cap,
48}
49
50impl DraftClass {
51    pub const ALL: [DraftClass; 5] =
52        [DraftClass::Positive, DraftClass::Negative, DraftClass::NeedsDraft, DraftClass::Straddle, DraftClass::Cap];
53
54    /// The legend row's words.
55    pub fn label(self) -> &'static str {
56        match self {
57            DraftClass::Positive => "Positive draft",
58            DraftClass::Negative => "Negative draft",
59            DraftClass::NeedsDraft => "Needs draft",
60            DraftClass::Straddle => "Straddle",
61            DraftClass::Cap => "Parting / cap (perpendicular)",
62        }
63    }
64
65    /// The key a legend row and a JSON reading use.
66    pub fn key(self) -> &'static str {
67        match self {
68            DraftClass::Positive => "positive",
69            DraftClass::Negative => "negative",
70            DraftClass::NeedsDraft => "needsDraft",
71            DraftClass::Straddle => "straddle",
72            DraftClass::Cap => "cap",
73        }
74    }
75
76    /// The tint, sRGB 0..1. Green / red / yellow / orange as the mould tools
77    /// draw them; the cap a neutral grey-blue so it reads apart from all four.
78    pub fn color(self) -> [f32; 3] {
79        match self {
80            DraftClass::Positive => [0.20, 0.72, 0.30],
81            DraftClass::Negative => [0.85, 0.22, 0.20],
82            DraftClass::NeedsDraft => [0.95, 0.80, 0.15],
83            DraftClass::Straddle => [0.96, 0.52, 0.12],
84            DraftClass::Cap => [0.55, 0.62, 0.70],
85        }
86    }
87}
88
89/// One face's reading.
90#[derive(Debug, Clone, PartialEq, Serialize)]
91#[serde(rename_all = "camelCase")]
92pub struct FaceDraft {
93    pub solid: String,
94    pub face: String,
95    /// The least and greatest draft angle found on the face, degrees.
96    pub min_deg: f64,
97    pub max_deg: f64,
98    pub class: DraftClass,
99    /// Whether the face is curved (its angle is sampled, not exact).
100    pub curved: bool,
101    /// A curved face whose sampled range ends within [`NEAR_LIMIT_DEG`] of ±min.
102    pub near_limit: bool,
103}
104
105impl FaceDraft {
106    /// The hover line: `Box_PX: +3.00° (Positive draft)`, a curved face's
107    /// range, and the near-limit note when it applies.
108    pub fn hover_text(&self) -> String {
109        let angle = if self.curved && (self.max_deg - self.min_deg).abs() > 0.005 {
110            format!("{:+.2}° to {:+.2}° (sampled)", self.min_deg, self.max_deg)
111        } else {
112            format!("{:+.2}°", 0.5 * (self.min_deg + self.max_deg))
113        };
114        let mut text = format!("{}: {angle}, {}", self.face, self.class.label());
115        if self.near_limit {
116            text.push_str(&format!(
117                "\nnear limit: the sampled range ends within {NEAR_LIMIT_DEG}° of the minimum, and sampling can miss the exact extreme"
118            ));
119        }
120        text
121    }
122}
123
124/// The class of a face whose draft runs from `min_deg` to `max_deg`, against
125/// a minimum of `minimum_deg` (≥ 0).
126pub fn classify(min_deg: f64, max_deg: f64, minimum_deg: f64) -> DraftClass {
127    let m = minimum_deg.abs();
128    if min_deg >= 90.0 - CAP_TOL_DEG || max_deg <= -(90.0 - CAP_TOL_DEG) {
129        DraftClass::Cap
130    } else if min_deg >= m {
131        DraftClass::Positive
132    } else if max_deg <= -m {
133        DraftClass::Negative
134    } else if min_deg <= -m && max_deg >= m && m > 0.0 {
135        DraftClass::Straddle
136    } else {
137        DraftClass::NeedsDraft
138    }
139}
140
141/// Whether a curved face's sampled range ends within [`NEAR_LIMIT_DEG`] of the
142/// minimum on either side.
143pub fn near_limit(min_deg: f64, max_deg: f64, minimum_deg: f64) -> bool {
144    let m = minimum_deg.abs();
145    [min_deg, max_deg].iter().any(|&a| (a.abs() - m).abs() < NEAR_LIMIT_DEG)
146}
147
148fn norm(v: [f64; 3]) -> f64 {
149    (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt()
150}
151
152fn unit(v: [f64; 3]) -> Option<[f64; 3]> {
153    let l = norm(v);
154    (l > 1e-12).then(|| [v[0] / l, v[1] / l, v[2] / l])
155}
156
157fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
158    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
159}
160
161fn to64(v: [f32; 3]) -> [f64; 3] {
162    [v[0] as f64, v[1] as f64, v[2] as f64]
163}
164
165/// The draft angle of a unit normal against a unit pull, degrees.
166fn angle_deg(normal: [f64; 3], pull: [f64; 3]) -> f64 {
167    dot(normal, pull).clamp(-1.0, 1.0).asin().to_degrees()
168}
169
170/// The outward normals one face of `solid` presents in WORLD space: one for
171/// a flat face (its triangles' common normal, signed by the mesh normals),
172/// else every vertex normal of its triangles. `None` for a face with none.
173pub fn face_normals(solid: &crate::scene::SolidDisplay, face_index: usize) -> Option<(Vec<[f64; 3]>, bool)> {
174    let face = solid.faces.get(face_index)?;
175    let mesh = &solid.mesh;
176    let start = face.tri_start as usize;
177    let end = start + face.tri_count as usize;
178    let mut tri_normals: Vec<[f64; 3]> = Vec::new();
179    let mut vertex_normals: Vec<[f64; 3]> = Vec::new();
180    for tri in start..end.min(mesh.indices.len() / 3) {
181        let ids = [mesh.indices[3 * tri] as usize, mesh.indices[3 * tri + 1] as usize, mesh.indices[3 * tri + 2] as usize];
182        let (Some(a), Some(b), Some(c)) = (mesh.positions.get(ids[0]), mesh.positions.get(ids[1]), mesh.positions.get(ids[2])) else {
183            continue;
184        };
185        let (a, b, c) = (to64(*a), to64(*b), to64(*c));
186        let e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
187        let e2 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
188        let mut geometric = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]];
189        let mut shading = [0.0; 3];
190        for &id in &ids {
191            if let Some(n) = mesh.normals.get(id).copied().map(to64).and_then(unit) {
192                vertex_normals.push(n);
193                shading = [shading[0] + n[0], shading[1] + n[1], shading[2] + n[2]];
194            }
195        }
196        if dot(geometric, shading) < 0.0 {
197            geometric = [-geometric[0], -geometric[1], -geometric[2]];
198        }
199        if let Some(n) = unit(geometric) {
200            tri_normals.push(n);
201        }
202    }
203    let first = *tri_normals.first()?;
204    let flat = tri_normals.iter().all(|n| dot(*n, first) >= 1.0 - FLAT_TOL);
205    // The display's positions and normals are already where the solid is
206    // shown (a `pose` only tells the renderer how they moved), so they are
207    // read as they stand.
208    let normals = if flat {
209        // The area-free mean of the triangle normals: the face's own normal.
210        let sum = tri_normals.iter().fold([0.0; 3], |s, n| [s[0] + n[0], s[1] + n[1], s[2] + n[2]]);
211        vec![unit(sum).unwrap_or(first)]
212    } else {
213        vertex_normals
214    };
215    Some((normals, !flat))
216}
217
218/// Read every face of `solid` against the unit `pull` and `minimum_deg`.
219pub fn analyse_solid(solid: &crate::scene::SolidDisplay, pull: [f64; 3], minimum_deg: f64) -> Vec<FaceDraft> {
220    let mut out = Vec::with_capacity(solid.faces.len());
221    for (index, face) in solid.faces.iter().enumerate() {
222        if face.kind == crate::scene::FaceKind::SectionCap {
223            continue;
224        }
225        let Some((normals, curved)) = face_normals(solid, index) else {
226            continue;
227        };
228        let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
229        for n in &normals {
230            let a = angle_deg(*n, pull);
231            lo = lo.min(a);
232            hi = hi.max(a);
233        }
234        out.push(FaceDraft {
235            solid: solid.name.clone(),
236            face: face.name.clone(),
237            min_deg: lo,
238            max_deg: hi,
239            class: classify(lo, hi, minimum_deg),
240            curved,
241            near_limit: curved && near_limit(lo, hi, minimum_deg),
242        });
243    }
244    out
245}
246