Skip to main content

brep_topology/brep/
solid_tolerance.rs

1//! Model scale and size of a solid, for the tolerance bands of `KernelTolerances`.
2
3use crate::topology::BrepSolid;
4use crate::*;
5
6impl crate::SolidScale for BrepSolid {
7    fn solid_scale(&self) -> f64 {
8        solid_scale(self)
9    }
10}
11
12
13/// [`model_scale`] of a solid's vertices — the RAW bounding-box diagonal, with
14/// no `>= 1.0` floor.  This is what direct-edit wants: a sub-unit part must keep
15/// sub-unit bands.  (`BrepSolid::validate` wants the same thing and still
16/// hand-rolls it, for the reason its own comment gives — it answers `0.0`, not
17/// `1.0`, for a vertexless solid.  Reconciling that contract is a follow-up, not
18/// a free ride-along.)  Use [`solid_scale`] for the floored variant the
19/// tolerance policy is built on.
20pub fn solid_model_scale(solid: &BrepSolid) -> f64 {
21    model_scale(solid.vertices.iter().map(|vertex| vertex.point))
22}
23
24/// [`solid_model_scale`] floored at 1.0 — the characteristic length
25/// [`KernelTolerances::for_solid`] and the boolean/imprint/heal sites are tuned
26/// against.  The floor keeps a unit-and-below part on the historical bands those
27/// call sites were fitted to; new size-relative sites should prefer the unfloored
28/// [`model_scale`] family and floor explicitly where they mean to.
29pub fn solid_scale(solid: &BrepSolid) -> f64 {
30    solid_model_scale(solid).max(1.0)
31}
32
33/// The app's display chord tolerance (`BetterSolid._kernelTessellationOptions`):
34/// vertex |coord| extent — falling back to the control-point hull / sqrt(2) for
35/// vertex-free solids (full spheres/tori) — times 1.5e-3, times the render-LOD
36/// factor (1.0 = the app's "Normal" preset).
37pub fn display_chord_tolerance(solid: &BrepSolid, lod_factor: f64) -> f64 {
38    let mut extent = 0.0f64;
39    for vertex in &solid.vertices {
40        extent = extent
41            .max(vertex.point.x.abs())
42            .max(vertex.point.y.abs())
43            .max(vertex.point.z.abs());
44    }
45    if extent <= 0.0 {
46        let mut control_point_extent = 0.0f64;
47        for shell in &solid.shells {
48            for face in &shell.faces {
49                for row in &face.surface.control_points {
50                    for cp in row {
51                        let w = if cp.w != 0.0 { cp.w } else { 1.0 };
52                        control_point_extent = control_point_extent
53                            .max((cp.x / w).abs())
54                            .max((cp.y / w).abs())
55                            .max((cp.z / w).abs());
56                    }
57                }
58            }
59        }
60        extent = control_point_extent / std::f64::consts::SQRT_2;
61    }
62    extent.max(1e-9) * 1.5e-3 * lod_factor
63}