Skip to main content

brep_kernel/
solid_display.rs

1//! A solid as a viewer draws it: each face meshed on its own with the exact
2//! surface's outward normal at every vertex, and every edge as a polyline
3//! with the faces it bounds. Built from the watertight tessellation (so the
4//! faces' boundaries meet vertex for vertex and the mesh they make closes)
5//! before any normal smoothing: each vertex's normal is read from its own
6//! face's surface.
7//!
8//! A vertex where the face's normal is not continuous (a crease inside one
9//! face, a pole, an apex) is given one copy per triangle, with the normal
10//! along that triangle. A crease is told from curvature by three probes into
11//! each triangle; one shallower than their second difference (about the
12//! surface's curvature times the probes' step squared: below 1e-7 of a
13//! radian for chords at a display tolerance) may share one side's normal.
14
15use crate::{BrepSolid, KernelRefusal, KernelStage, Vec3};
16use std::collections::HashMap;
17
18/// One face of a [`SolidDisplay`]: its own vertices, the surface's outward
19/// normal at each, and its triangles over them (counter-clockwise outward).
20#[derive(Clone, Debug, Default)]
21pub struct DisplayFace {
22    /// The face's id in the solid.
23    pub face_id: u64,
24    pub positions: Vec<Vec3>,
25    pub normals: Vec<Vec3>,
26    pub triangles: Vec<[u32; 3]>,
27}
28
29/// One edge of a [`SolidDisplay`]: its polyline (the same samples the faces'
30/// boundaries use) and the indices into [`SolidDisplay::faces`] of the faces
31/// it bounds, one per use.
32#[derive(Clone, Debug, Default)]
33pub struct DisplayEdge {
34    /// The edge's id in the solid.
35    pub edge_id: u64,
36    pub points: Vec<Vec3>,
37    pub faces: Vec<u32>,
38}
39
40/// A solid as a viewer draws it (see the module docs). Seams, where a face
41/// meets itself, are kept apart from the edges between faces.
42#[derive(Clone, Debug, Default)]
43pub struct SolidDisplay {
44    pub faces: Vec<DisplayFace>,
45    pub edges: Vec<DisplayEdge>,
46    pub seams: Vec<Vec<Vec3>>,
47}
48
49/// The face's unit normal at `q` on it (by its recorded sense), or None
50/// where its surface's parameter derivatives give none (their cross product
51/// zero or unread).
52fn surface_normal(face: &crate::FaceRecord, q: Vec3) -> Option<Vec3> {
53    let hit = crate::project_point_to_surface(&face.surface, q).ok()?;
54    normal_at(face, hit.u, hit.v)
55}
56
57/// The face's unit normal at the parameters (u, v), by its recorded sense.
58fn normal_at(face: &crate::FaceRecord, u: f64, v: f64) -> Option<Vec3> {
59    let (_, su, sv) = face.surface.deriv1(u, v).ok()?;
60    let cross = su.cross(sv);
61    let length = cross.length();
62    if !(length > 0.0 && length.is_finite()) {
63        return None;
64    }
65    let n = cross.scale(1.0 / length);
66    Some(if face.same_sense { n } else { n.scale(-1.0) })
67}
68
69/// How far (as a chord of unit normals) a vertex's shared normal may differ
70/// from the normal carried back along a triangle beyond the probes' own
71/// spread (see `solid_display`): rounding only.
72const AGREE: f64 = 1e-9;
73
74/// The display of `solid` with chords within `tolerance` of it.
75pub fn solid_display(solid: &BrepSolid, tolerance: f64) -> Result<SolidDisplay, KernelRefusal> {
76    if !(tolerance > 0.0 && tolerance.is_finite()) {
77        return Err(KernelRefusal::input(KernelStage::Collect, "display_tolerance", "solid_display: the tolerance must be positive and finite"));
78    }
79    let failed = |message: String| KernelRefusal::internal(KernelStage::Refine, "display_tessellation", format!("solid_display: {message}"));
80    let mesh = crate::tessellate_brep_watertight(solid, tolerance).map_err(failed)?;
81    // The mesh's face ids number the faces in shell order.
82    let faces: Vec<&crate::FaceRecord> = solid.shells.iter().flat_map(|shell| &shell.faces).collect();
83    let point = |i: u32| {
84        let k = 3 * i as usize;
85        Vec3::new(mesh.positions[k], mesh.positions[k + 1], mesh.positions[k + 2])
86    };
87    // Each face's triangles over the mesh's vertices, in mesh order.
88    let mut order: Vec<usize> = Vec::new();
89    let mut by_face: HashMap<usize, Vec<[u32; 3]>> = HashMap::new();
90    for (t, corners) in mesh.indices.chunks_exact(3).enumerate() {
91        let index = *mesh.face_ids.get(t).ok_or_else(|| failed(format!("triangle {t} names no face")))? as usize;
92        if index >= faces.len() {
93            return Err(failed(format!("triangle {t} names face {index} of {}", faces.len())));
94        }
95        by_face.entry(index).or_insert_with(|| {
96            order.push(index);
97            Vec::new()
98        }).push([corners[0], corners[1], corners[2]]);
99    }
100    let probe_floor = 1e-5 * crate::solid_model_scale(solid).max(1e-300);
101    let mut out = SolidDisplay::default();
102    let mut slot_of_face: HashMap<usize, usize> = HashMap::new();
103    for index in order {
104        let face = faces[index];
105        let triangles = &by_face[&index];
106        slot_of_face.insert(index, out.faces.len());
107        // Each triangle's winding normal (its area vector; the tessellation
108        // orients the mesh outward, repairing a reversed sense).
109        let winding: Vec<Vec3> = triangles.iter().map(|t| {
110            let [a, b, c] = t.map(point);
111            b.sub(a).cross(c.sub(a))
112        }).collect();
113        // Each shared vertex's surface normal, turned the way its triangles
114        // face (per vertex, so a face whose surface folds keeps each part's).
115        let mut shared: HashMap<u32, Option<Vec3>> = HashMap::new();
116        for tri in triangles {
117            for &v in tri {
118                shared.entry(v).or_insert_with(|| surface_normal(face, point(v)));
119            }
120        }
121        let mut lean: HashMap<u32, f64> = HashMap::new();
122        for (t, tri) in triangles.iter().enumerate() {
123            for &v in tri {
124                if let Some(Some(n)) = shared.get(&v) {
125                    *lean.entry(v).or_default() += winding[t].dot(*n);
126                }
127            }
128        }
129        for (v, n) in shared.iter_mut() {
130            if let Some(n) = n {
131                if lean.get(v).copied().unwrap_or(0.0) < 0.0 {
132                    *n = n.scale(-1.0);
133                }
134            }
135        }
136        let mut display = DisplayFace { face_id: face.id, ..DisplayFace::default() };
137        let mut local: HashMap<u32, u32> = HashMap::new();
138        for (t, tri) in triangles.iter().enumerate() {
139            let w = winding[t];
140            let unit = if w.length() > 0.0 { Some(w.scale(1.0 / w.length())) } else { None };
141            let centroid = tri.iter().map(|&v| point(v)).fold(Vec3::new(0.0, 0.0, 0.0), |m, p| m.add(p)).scale(1.0 / 3.0);
142            let mut corners = [0u32; 3];
143            for (k, &v) in tri.iter().enumerate() {
144                let q = point(v);
145                let normal = shared[&v];
146                // The normal along this triangle at the vertex: read at three
147                // points 1, 2 and 3 thousandths of the way to the centroid
148                // (projected: far above the projector's floor, and on the
149                // triangle's own side of a seam or a crease), carried back to
150                // the vertex by the parabola through them, turned the way the
151                // triangle faces. Its error is the normals' third difference
152                // (a smooth surface's change of curvature over the step,
153                // cubed); a crease, pole or apex differs by an angle that
154                // does not shrink with the step.
155                // The step: a thousandth of the way in, but never closer to
156                // the vertex than 1e-5 of the model's scale (the projector
157                // stops within 1e-7: a probe nearer than that could read the
158                // vertex's own side), nor past a third of the way.
159                let toward = centroid.sub(q);
160                let reach = toward.length();
161                let step = if reach > 0.0 { (1e-3f64).max((probe_floor / reach).min(1.0 / 9.0)) } else { 1e-3 };
162                let face_normal = |k: f64| surface_normal(face, q.add(toward.scale(k))).map(|n| if unit.is_some_and(|u| n.dot(u) < 0.0) { n.scale(-1.0) } else { n });
163                let probes = [face_normal(step), face_normal(2.0 * step), face_normal(3.0 * step)];
164                let (along, slack) = match probes {
165                    [Some(a), Some(b), Some(c)] => {
166                        let back = a.scale(3.0).sub(b.scale(3.0)).add(c);
167                        // The second difference bounds what the parabola
168                        // misses by the step's next power.
169                        let bend = a.sub(b.scale(2.0)).add(c).length();
170                        (back.normalized().ok(), bend)
171                    }
172                    [Some(a), ..] => (Some(a), f64::INFINITY),
173                    _ => (None, 0.0),
174                };
175                let agrees = match (normal, along) {
176                    (Some(n), Some(a)) => n.sub(a).length() <= AGREE + slack,
177                    (Some(_), None) => true,
178                    (None, _) => false,
179                };
180                corners[k] = if agrees {
181                    *local.entry(v).or_insert_with(|| {
182                        display.positions.push(q);
183                        display.normals.push(normal.expect("agrees"));
184                        (display.positions.len() - 1) as u32
185                    })
186                } else {
187                    // No normal here that this triangle bears out (an apex, a
188                    // pole, a crease inside the face): its own copy of the
189                    // vertex, with the normal just inside it.
190                    let n = along.ok_or_else(|| failed(format!("face {} has no normal near {q:?}", face.id)))?;
191                    display.positions.push(q);
192                    display.normals.push(n);
193                    (display.positions.len() - 1) as u32
194                };
195            }
196            display.triangles.push(corners);
197        }
198        out.faces.push(display);
199    }
200    // Every edge's polyline, with the display faces it bounds; a face meeting
201    // itself is a seam.
202    let mut uses: HashMap<u64, Vec<u32>> = HashMap::new();
203    for (index, face) in faces.iter().enumerate() {
204        let Some(&slot) = slot_of_face.get(&index) else { continue };
205        for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
206            uses.entry(coedge.edge_id).or_default().push(slot as u32);
207        }
208    }
209    for (edge_id, points) in crate::sample_edge_polylines(solid, tolerance).map_err(failed)? {
210        let used = uses.remove(&edge_id).unwrap_or_default();
211        if used.len() >= 2 && used.iter().all(|&f| f == used[0]) {
212            out.seams.push(points);
213        } else {
214            out.edges.push(DisplayEdge { edge_id, points, faces: used });
215        }
216    }
217    Ok(out)
218}
219