Skip to main content

kernel_api/
mesh.rs

1//! Meshes the kernel draws: tessellation settings and triangle meshes with
2//! their faces' names and surfaces.
3
4use serde::{Deserialize, Serialize};
5
6use crate::*;
7
8/// How linear (chord) deflection is chosen for kernel meshing.
9///
10/// The default is **bbox-scaled** deflection: absolute chord height is derived
11/// from the sum of the shape's bounding-box extents and a dimensionless
12/// multiplier ([`TessellationSettings::mesh_deviation`], typically `0.2`).
13/// This produces visually consistent tessellation across small and large
14/// parts without per-model tuning.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
16#[serde(rename_all = "snake_case")]
17pub enum LinearDeflectionMode {
18    /// Bounding-box scaled: linear deflection = `(dx + dy + dz) / 300 ×`
19    /// [`TessellationSettings::mesh_deviation`].
20    #[default]
21    BboxScaled,
22    /// Fixed absolute linear deflection in model units (millimetres for STEP geometry).
23    AbsoluteMm,
24}
25
26/// Parameters controlling tessellation quality for viewport rendering.
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28pub struct TessellationSettings {
29    #[serde(default)]
30    pub linear_deflection_mode: LinearDeflectionMode,
31    /// Dimensionless multiplier applied to the bbox-derived chord height when
32    /// [`Self::linear_deflection_mode`] is [`LinearDeflectionMode::BboxScaled`].
33    /// Typical range `0.05..=1.0`; smaller values yield finer triangulation.
34    #[serde(default = "default_mesh_deviation")]
35    pub mesh_deviation: f32,
36    /// Absolute chord height in model units when using [`LinearDeflectionMode::AbsoluteMm`].
37    pub chord_tolerance: f32,
38    pub angular_tolerance_deg: f32,
39    /// When true, the kernel collapses vertices that share a position across
40    /// multiple faces *and* whose face normals are within
41    /// [`Self::weld_angle_threshold_deg`] of each other. This typically
42    /// shrinks vertex counts by 4–6× on dense CAD models without flattening
43    /// genuine sharp edges, since dissimilar face normals stay separate.
44    #[serde(default = "default_weld_cross_face")]
45    pub weld_cross_face: bool,
46    /// Maximum angle between two face normals at a shared position for them
47    /// to be merged into a single welded vertex. Above this angle the kernel
48    /// keeps them separate so hard CAD edges stay crisp under shading.
49    /// Defaults to 30°.
50    #[serde(default = "default_weld_angle_threshold_deg")]
51    pub weld_angle_threshold_deg: f32,
52    /// When true, import keeps each body's shape snapshot in `brep_blob`
53    /// beside its mesh. Meshing happens during the import either way;
54    /// serializing the snapshots is most of the work of reading a large
55    /// assembly, and turning this off skips it. The STEP asset remains
56    /// available in the document regardless.
57    #[serde(default = "default_persist_brep_snapshot")]
58    pub persist_brep_snapshot: bool,
59    /// When true, compute mesh outline / edge segments for the viewport (face
60    /// boundaries). Skipping saves CPU on huge imports when outlines are not needed.
61    #[serde(default = "default_generate_boundary_edges")]
62    pub generate_boundary_edges: bool,
63}
64
65fn default_weld_cross_face() -> bool {
66    false
67}
68
69fn default_weld_angle_threshold_deg() -> f32 {
70    30.0
71}
72
73fn default_mesh_deviation() -> f32 {
74    0.2
75}
76
77fn default_persist_brep_snapshot() -> bool {
78    true
79}
80
81fn default_generate_boundary_edges() -> bool {
82    true
83}
84
85impl Default for TessellationSettings {
86    fn default() -> Self {
87        Self {
88            linear_deflection_mode: LinearDeflectionMode::default(),
89            mesh_deviation: default_mesh_deviation(),
90            chord_tolerance: 0.1,
91            angular_tolerance_deg: 28.65,
92            weld_cross_face: default_weld_cross_face(),
93            weld_angle_threshold_deg: default_weld_angle_threshold_deg(),
94            persist_brep_snapshot: default_persist_brep_snapshot(),
95            generate_boundary_edges: default_generate_boundary_edges(),
96        }
97    }
98}
99
100/// Triangular mesh generated from kernel bodies for viewports and export.
101#[derive(Debug, Clone, Default, Serialize, Deserialize)]
102pub struct TriMesh {
103    pub positions: Vec<[f32; 3]>,
104    pub normals: Vec<[f32; 3]>,
105    pub indices: Vec<u32>,
106    /// Optional line-list of feature edges that should be drawn as outlines on
107    /// top of the shaded surface (e.g. face boundaries from a STEP import).
108    /// Stored as flat pairs of indices into [`Self::positions`]; the slice
109    /// length is therefore always a multiple of two. Empty when the source has
110    /// no edge information available.
111    #[serde(default)]
112    pub edges: Vec<u32>,
113    /// Optional per-vertex linear RGB albedo in 0..1 (same length as [`Self::positions`] when set).
114    /// Empty means the renderer uses the body tint from push constants only.
115    #[serde(default)]
116    pub colors: Vec<[f32; 3]>,
117    /// Which kernel face each triangle was cut from: one entry per triangle
118    /// (`indices.len() / 3`), an index into the body's faces in the kernel's
119    /// own order. A curved face is many triangles with many normals, and
120    /// this is what lets a click on one of them select the whole face.
121    /// Empty when the source has no faces (a sketch, a datum, a mesh saved
122    /// before faces were recorded), and a consumer falls back to geometry.
123    #[serde(default)]
124    pub faces: Vec<u32>,
125    /// Which kernel edge each outline segment belongs to: one entry per
126    /// pair in [`Self::edges`], an index into the body's edges in the
127    /// kernel's own order. A curved edge is many segments, and this is what
128    /// lets a click on one of them select the whole edge. Empty when the
129    /// outline came from triangle boundaries rather than kernel edges.
130    #[serde(default)]
131    pub edge_ids: Vec<u32>,
132    /// The exact surface of each kernel face, indexed like [`Self::faces`]:
133    /// what a picked face is, beyond the triangles drawn for it. Empty when
134    /// the source has no faces.
135    #[serde(default, skip_serializing_if = "Vec::is_empty")]
136    pub face_surfaces: Vec<FaceSurface>,
137    /// The name of each kernel face, indexed like [`Self::faces`]: what a
138    /// pick keeps so a rebuild finds the face again. Zero where a face has
139    /// none; empty when the source names none.
140    #[serde(default, skip_serializing_if = "Vec::is_empty")]
141    pub face_names: Vec<TopoName>,
142    /// The tag of the op that made each kernel face, indexed like
143    /// [`Self::faces`]: the name of the feature a body's chain built it
144    /// under (`naming::name_of_id` of its id), kept by a face a later op
145    /// splits or trims. Zero where unknown; empty when the source names
146    /// none.
147    #[serde(default, skip_serializing_if = "Vec::is_empty")]
148    pub face_makers: Vec<TopoName>,
149    /// The names of the two faces each kernel edge runs between, indexed
150    /// like [`Self::edge_ids`].
151    #[serde(default, skip_serializing_if = "Vec::is_empty")]
152    pub edge_faces: Vec<[TopoName; 2]>,
153}
154
155/// The kind and placement of a kernel face's surface, in the mesh's frame.
156#[cfg_attr(not(feature = "exhaustive"), non_exhaustive)]
157#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
158pub enum FaceSurface {
159    /// A plane through `origin`, with the face's outward `normal`.
160    Plane { origin: [f32; 3], normal: [f32; 3] },
161    /// A circular cylinder about the line through `origin` along `axis`.
162    Cylinder {
163        origin: [f32; 3],
164        axis: [f32; 3],
165        radius: f32,
166    },
167    /// A circular cone about the line through `apex` along `axis`, its
168    /// wall `half_angle` (radians, positive) off the axis.
169    Cone {
170        apex: [f32; 3],
171        axis: [f32; 3],
172        #[serde(default)]
173        half_angle: f32,
174    },
175    /// A sphere.
176    Sphere { center: [f32; 3], radius: f32 },
177    /// A torus about the line through `center` along `axis`: its tube's
178    /// centre `major_radius` from the axis, the tube `minor_radius` round.
179    Torus {
180        center: [f32; 3],
181        axis: [f32; 3],
182        #[serde(default)]
183        major_radius: f32,
184        #[serde(default)]
185        minor_radius: f32,
186    },
187    /// Any other surface: a spline, a sweep.
188    #[default]
189    Other,
190}
191
192impl FaceSurface {
193    /// The axis a turned face turns about, as a point on it and its
194    /// direction: a cylinder's, a cone's or a torus's.
195    pub fn axis(&self) -> Option<([f32; 3], [f32; 3])> {
196        match *self {
197            FaceSurface::Cylinder { origin, axis, .. } => Some((origin, axis)),
198            FaceSurface::Cone { apex, axis, .. } => Some((apex, axis)),
199            FaceSurface::Torus { center, axis, .. } => Some((center, axis)),
200            _ => None,
201        }
202    }
203
204    /// The same surface moved: `point` maps points, `direction` maps
205    /// directions (a rigid motion, so lengths stay).
206    pub fn moved(
207        &self,
208        point: impl Fn([f32; 3]) -> [f32; 3],
209        direction: impl Fn([f32; 3]) -> [f32; 3],
210    ) -> Self {
211        match *self {
212            FaceSurface::Plane { origin, normal } => FaceSurface::Plane {
213                origin: point(origin),
214                normal: direction(normal),
215            },
216            FaceSurface::Cylinder {
217                origin,
218                axis,
219                radius,
220            } => FaceSurface::Cylinder {
221                origin: point(origin),
222                axis: direction(axis),
223                radius,
224            },
225            FaceSurface::Cone {
226                apex,
227                axis,
228                half_angle,
229            } => FaceSurface::Cone {
230                apex: point(apex),
231                axis: direction(axis),
232                half_angle,
233            },
234            FaceSurface::Sphere { center, radius } => FaceSurface::Sphere {
235                center: point(center),
236                radius,
237            },
238            FaceSurface::Torus {
239                center,
240                axis,
241                major_radius,
242                minor_radius,
243            } => FaceSurface::Torus {
244                center: point(center),
245                axis: direction(axis),
246                major_radius,
247                minor_radius,
248            },
249            FaceSurface::Other => FaceSurface::Other,
250        }
251    }
252}
253
254impl TriMesh {
255    /// Compute axis-aligned bounding box `(min, max)` of the mesh, if non-empty.
256    pub fn bounds(&self) -> Option<([f32; 3], [f32; 3])> {
257        self.aabb().map(Into::into)
258    }
259
260    /// The box around the mesh's points; `None` for a mesh with none.
261    pub fn aabb(&self) -> Option<crate::Aabb> {
262        crate::Aabb::around(self.positions.iter().copied())
263    }
264}