ifc_geometry/compile.rs
1//! Mesh compilation: run the lowered DAG through a geometry backend.
2//!
3//! Gated behind the opt-in `compile` feature. ADR 0004 keeps this crate a
4//! bridge, and compilation is the one narrow exception: it selects an
5//! execution provider and a memory budget, which are application policy
6//! rather than properties of the file. Nothing here is reachable in a
7//! default build.
8//!
9//! The bridge still implements no geometry. It calls a compiler that
10//! already exists and translates the refusal into IFC terms.
11//!
12//! # Bringing your own kernel
13//!
14//! Every entry point is generic over [`MeshCompiler`], so a caller may bring
15//! CGAL, OCCT, a GPU tessellator, or a research prototype without forking
16//! this crate. Two granularities are supported:
17//!
18//! * **Whole-kernel.** Implement [`MeshCompiler`] over your own engine and
19//! pass it to [`compile_product_mesh_with`]. Enable `compile` alone and
20//! none of the reference execution path is even linked.
21//! * **Per-area.** Keep the reference compiler's traversal and swap only the
22//! area a kernel does well, e.g. `ReferenceMeshCompiler::new(MyBoolean)`
23//! to replace boolean evaluation while retaining everything else. That
24//! needs the `compile-reference-backend` feature for the traversal.
25//!
26//! Selection is the application's, never the file's: two backends given the
27//! same model must agree on what the file means, so choosing between them is
28//! a question of speed, robustness, or licence -- which is why this module
29//! refuses to pick for you beyond the documented default.
30//!
31//! # Comparing backends
32//!
33//! Because the backend is a parameter, comparing two kernels over one corpus
34//! is a loop. The `backend_compare` example ([source][backend-compare], #31)
35//! is that loop, written as a caller would: it compiles a fixed corpus of
36//! committed fixtures through the reference backend and through a small
37//! [`MeshCompiler`] defined in the example itself, prints wall time and mesh
38//! size per fixture keyed by `BackendId`, and checks that the two agree on
39//! volume, area and bounding box, listing every divergence and every
40//! refusal. Its own backend builds under `compile` alone. The timings carry
41//! their method and are not a cross-kernel performance claim.
42//!
43//! ```text
44//! cargo run --release -p ifc-geometry --features compile-reference-backend \
45//! --example backend_compare
46//! ```
47//!
48//! [backend-compare]: https://github.com/openbimrs/ifc/tree/main/crates/ifc-geometry/examples/backend_compare
49
50mod bounds;
51mod directrix;
52mod items;
53mod layers;
54mod outline;
55mod output;
56mod window;
57
58#[cfg(feature = "compile-reference-backend")]
59pub use directrix::compile_sweep_directrix;
60pub use directrix::compile_sweep_directrix_with;
61#[cfg(feature = "compile-reference-backend")]
62pub use items::compile_product_item_meshes;
63pub use items::{compile_product_item_meshes_with, ItemMesh};
64#[cfg(feature = "compile-reference-backend")]
65pub use layers::compile_product_layer_meshes;
66pub use layers::{compile_product_layer_meshes_with, LayerMesh, LayerMeshes};
67#[cfg(feature = "compile-reference-backend")]
68pub use outline::compile_profile_outline;
69pub use outline::{compile_profile_outline_with, SampledArc, SampledProfileOutline, SampledRing};
70#[cfg(feature = "compile-reference-backend")]
71pub use output::{compile_product_curves, compile_product_mesh_for, compile_product_polylines};
72pub use output::{
73 compile_product_curves_with, compile_product_mesh_for_with, compile_product_polylines_with,
74 ChordDeviation, CompiledPolyline, MeshClosure, NonCurveItem, Point3, PolylineCompiler,
75 ProductPolylines, SkippedItem,
76};
77pub use window::SeamWindowRefusal;
78
79/// The tolerance every entry point takes and the mesh it returns,
80/// re-exported so a caller that names no `axiolid-*` crate -- the
81/// `openbim-ifc` facade and the language bindings above it (ADR 0004,
82/// #328) -- can call them and read the result.
83pub use axiolid_core::Tolerance;
84pub use axiolid_mesh::TriMesh;
85
86use axiolid_contracts::ExecutionOptions;
87use axiolid_core::Aabb;
88use axiolid_mesh_compile_contract::MeshCompiler;
89use ifc_model::{EntityId, Model};
90
91use crate::error::{GeometryError, GeometryResult};
92use crate::lower::{
93 lower_product_net, lower_product_representation, LoweringSession, NetLowering,
94 RepresentationPurpose,
95};
96use crate::units;
97
98#[cfg(feature = "compile-reference-backend")]
99use axiolid_mesh_boolean_boolmesh::BoolmeshBoolean;
100#[cfg(feature = "compile-reference-backend")]
101use axiolid_mesh_compile::ReferenceMeshCompiler;
102
103/// The backend used when a caller expresses no preference.
104///
105/// Named and returned rather than constructed inline so a caller can ask
106/// what the default *is* -- to log it beside a benchmark, or to compare
107/// against it -- without hard-coding the same type this module does.
108#[cfg(feature = "compile-reference-backend")]
109#[must_use]
110pub fn default_backend() -> ReferenceMeshCompiler<BoolmeshBoolean> {
111 ReferenceMeshCompiler::new(BoolmeshBoolean)
112}
113
114/// Compile one product's body representation into triangles.
115///
116/// Uses [`default_backend`]. Call [`compile_product_mesh_with`] to supply
117/// your own.
118///
119/// Returns `Ok(None)` when the product has no body representation at all,
120/// which is ordinary -- a spatial container or an annotation-only product is
121/// not an error.
122///
123/// # Tolerance
124///
125/// Lowering converts every length to metres, and the backend reads tolerance
126/// in the model's current length unit, so [`Tolerance::MILLIMETRE`] (1e-3) is
127/// a millimetre here regardless of what the file declared. Deriving a
128/// tolerance from the file's unit scale would double-apply the conversion.
129///
130/// # Errors
131///
132/// Returns [`GeometryError::CompilationRefused`] when the backend cannot
133/// produce a mesh, and any lowering error the representation raises first.
134#[cfg(feature = "compile-reference-backend")]
135pub fn compile_product_mesh(
136 model: &Model,
137 product: EntityId,
138 tolerance: Tolerance,
139) -> GeometryResult<Option<TriMesh>> {
140 compile_product_mesh_with(&default_backend(), model, product, tolerance)
141}
142
143/// Compile one product's body representation with a caller-supplied backend.
144///
145/// The backend is borrowed, so one instance serves a whole run: building a
146/// compiler per product would discard whatever caches or device handles an
147/// implementation holds.
148///
149/// # Errors
150///
151/// Returns [`GeometryError::CompilationRefused`] when the backend cannot
152/// produce a mesh, and any lowering error the representation raises first.
153///
154/// # Examples
155///
156/// Swapping only boolean evaluation, keeping the reference traversal:
157///
158/// ```no_run
159/// # #[cfg(feature = "compile-reference-backend")] {
160/// # use axiolid_core::Tolerance;
161/// # use axiolid_mesh_boolean_boolmesh::BoolmeshBoolean;
162/// # use axiolid_mesh_compile::ReferenceMeshCompiler;
163/// # use ifc_geometry::compile::compile_product_mesh_with;
164/// # use ifc_model::{EntityId, Model};
165/// # fn run(model: &Model, product: EntityId) -> Result<(), Box<dyn std::error::Error>> {
166/// let backend = ReferenceMeshCompiler::new(BoolmeshBoolean);
167/// let mesh = compile_product_mesh_with(&backend, model, product, Tolerance::MILLIMETRE)?;
168/// # let _ = mesh;
169/// # Ok(())
170/// # }
171/// # }
172/// ```
173pub fn compile_product_mesh_with<B: MeshCompiler>(
174 backend: &B,
175 model: &Model,
176 product: EntityId,
177 tolerance: Tolerance,
178) -> GeometryResult<Option<TriMesh>> {
179 let scale = units::resolve(model)?;
180 let mut session = LoweringSession::new(model, &scale);
181 let Some(root) =
182 lower_product_representation(&mut session, product, RepresentationPurpose::Body)?
183 else {
184 return Ok(None);
185 };
186 let lowered = session.finish(root)?;
187
188 let options = ExecutionOptions::new(tolerance);
189 backend
190 .compile_mesh(&lowered.graph, lowered.root, &options)
191 .map(Some)
192 .map_err(|error| refused(product, error, &lowered.provenance))
193}
194
195/// A compiled mesh and whether it bounds a solid.
196///
197/// IFC distinguishes solids (`IfcFacetedBrep`, `IfcExtrudedAreaSolid`,
198/// `IfcPolygonalFaceSet` with `Closed`) from surface models
199/// (`IfcShellBasedSurfaceModel`, `IfcFaceBasedSurfaceModel`), and a surface
200/// model has an area but no volume -- even when its shells happen to close.
201/// A bare `TriMesh` cannot say which one it is, so a caller summing a
202/// divergence volume over every compiled product silently reports a volume
203/// for surfaces. `closure` carries the backend's answer instead.
204#[derive(Debug, Clone)]
205#[non_exhaustive]
206pub struct CompiledMesh {
207 /// The triangles.
208 pub mesh: TriMesh,
209 /// [`MeshClosure::Solid`] when the mesh bounds a volume the file
210 /// declared, [`MeshClosure::Surface`] for a surface model, and
211 /// [`MeshClosure::Unknown`] when the backend does not report it.
212 pub closure: MeshClosure,
213}
214
215impl CompiledMesh {
216 /// The mesh, only when it bounds a declared solid.
217 ///
218 /// Use this, not `mesh`, before measuring a volume or feeding a boolean.
219 ///
220 /// # Errors
221 ///
222 /// [`GeometryError::NotASolid`] naming `product` for a surface model, and
223 /// for a backend that does not report closure: an unknown closure is not
224 /// evidence of a solid.
225 pub fn solid_mesh(&self, product: EntityId) -> GeometryResult<&TriMesh> {
226 match self.closure {
227 MeshClosure::Solid => Ok(&self.mesh),
228 closure => Err(GeometryError::NotASolid {
229 entity: product,
230 closure,
231 }),
232 }
233 }
234}
235
236/// Compile one product's body and report whether it bounds a solid.
237///
238/// Uses [`default_backend`]; [`compile_product_mesh_reported_with`] takes
239/// your own. Same triangles as [`compile_product_mesh`], plus the closure a
240/// volume reader needs (axiolid/kernel#161).
241///
242/// # Errors
243///
244/// As [`compile_product_mesh`].
245#[cfg(feature = "compile-reference-backend")]
246pub fn compile_product_mesh_reported(
247 model: &Model,
248 product: EntityId,
249 tolerance: Tolerance,
250) -> GeometryResult<Option<CompiledMesh>> {
251 compile_product_mesh_reported_with(&default_backend(), model, product, tolerance)
252}
253
254/// Compile one product's body with a caller-supplied backend and report
255/// whether it bounds a solid.
256///
257/// A backend that does not override `MeshCompiler::compile_mesh_reported`
258/// reports [`MeshClosure::Unknown`], which [`CompiledMesh::solid_mesh`]
259/// refuses. That is deliberate: a volume needs evidence, not a default.
260///
261/// # Errors
262///
263/// As [`compile_product_mesh_with`].
264pub fn compile_product_mesh_reported_with<B: MeshCompiler>(
265 backend: &B,
266 model: &Model,
267 product: EntityId,
268 tolerance: Tolerance,
269) -> GeometryResult<Option<CompiledMesh>> {
270 let scale = units::resolve(model)?;
271 let mut session = LoweringSession::new(model, &scale);
272 let Some(root) =
273 lower_product_representation(&mut session, product, RepresentationPurpose::Body)?
274 else {
275 return Ok(None);
276 };
277 let lowered = session.finish(root)?;
278
279 let options = ExecutionOptions::new(tolerance);
280 backend
281 .compile_mesh_reported(&lowered.graph, lowered.root, &options)
282 .map(|outcome| {
283 Some(CompiledMesh {
284 closure: outcome.closure,
285 mesh: outcome.mesh,
286 })
287 })
288 .map_err(|error| refused(product, error, &lowered.provenance))
289}
290
291/// A product's NET mesh and the openings removed to produce it.
292#[derive(Debug, Clone)]
293#[non_exhaustive]
294pub struct NetMesh {
295 /// The Body with every voiding opening subtracted.
296 pub mesh: TriMesh,
297 /// The openings subtracted, in ascending id. Empty when none void it.
298 pub openings: Vec<EntityId>,
299 /// Whether `mesh` bounds a solid. A net body is [`MeshClosure::Solid`]
300 /// whenever a subtraction ran, since a boolean refuses a surface operand;
301 /// a host with no openings keeps whatever its gross body reported.
302 pub closure: MeshClosure,
303}
304
305/// Compile one product's Body with every voiding opening subtracted (#44).
306///
307/// Uses [`default_backend`]; [`compile_product_mesh_net_with`] takes your own.
308/// [`compile_product_mesh`] stays the gross body: quantity takeoff wants
309/// gross, clearance and ratio checks want net, so neither replaces the other.
310///
311/// # Errors
312///
313/// [`GeometryError::OpeningNotSubtracted`] naming the opening when one cannot
314/// be removed. The gross body is never returned in place of the net one.
315#[cfg(feature = "compile-reference-backend")]
316pub fn compile_product_mesh_net(
317 model: &Model,
318 product: EntityId,
319 tolerance: Tolerance,
320) -> GeometryResult<Option<NetMesh>> {
321 compile_product_mesh_net_with(&default_backend(), model, product, tolerance)
322}
323
324/// Compile one product's net Body with a caller-supplied backend.
325///
326/// # Cost
327///
328/// The success path compiles the net graph once; the backend's own cache
329/// shares the host and opening meshes across the chain. Only a refusal pays
330/// more: the host is compiled alone, then the chain one subtraction at a
331/// time, to name the opening at fault. That is a
332/// diagnostic pass on a path that has already failed, so it trades time for a
333/// precise error rather than slowing every successful call.
334///
335/// # Errors
336///
337/// A refusal the host's gross body alone would raise stays
338/// [`GeometryError::CompilationRefused`] on the host. A refusal that only an
339/// opening explains is [`GeometryError::OpeningNotSubtracted`] naming it.
340pub fn compile_product_mesh_net_with<B: MeshCompiler>(
341 backend: &B,
342 model: &Model,
343 product: EntityId,
344 tolerance: Tolerance,
345) -> GeometryResult<Option<NetMesh>> {
346 let scale = units::resolve(model)?;
347 let mut session = LoweringSession::new(model, &scale);
348 let Some(net) = lower_product_net(&mut session, product)? else {
349 return Ok(None);
350 };
351 let openings = net.openings();
352 let lowered = session.finish(net.root)?;
353 let options = ExecutionOptions::new(tolerance);
354
355 match backend.compile_mesh_reported(&lowered.graph, lowered.root, &options) {
356 Ok(outcome) => Ok(Some(NetMesh {
357 closure: outcome.closure,
358 mesh: outcome.mesh,
359 openings,
360 })),
361 Err(error) => Err(attribute_net_refusal(
362 backend, &lowered, &net, &options, product, error,
363 )),
364 }
365}
366
367/// Find the part of a net graph the backend cannot compile, and name it.
368///
369/// Order matters: a broken host would fail every step, so it is checked
370/// first; then the chain is walked to the first step the kernel refuses. If
371/// every step compiles alone, the refusal is reported on the host,
372/// unattributed, rather than guessed.
373fn attribute_net_refusal<B: MeshCompiler>(
374 backend: &B,
375 lowered: &crate::lower::LoweredGeometry,
376 net: &NetLowering,
377 options: &ExecutionOptions,
378 product: EntityId,
379 original: axiolid_contracts::GeomError,
380) -> GeometryError {
381 let (graph, provenance) = (&lowered.graph, &lowered.provenance);
382 if let Err(error) = backend.compile_mesh(graph, net.gross, options) {
383 return refused(product, error, provenance);
384 }
385 let blame = |opening: EntityId, error| GeometryError::OpeningNotSubtracted {
386 host: product,
387 opening,
388 cause: Box::new(refused(opening, error, provenance)),
389 };
390 // Step k's graph holds the host, bodies 1..=k and subtractions 1..=k, so
391 // the first failing step is the first opening whose body OR whose cut the
392 // backend refuses. No separate per-body pass is needed.
393 for step in &net.subtractions {
394 if let Err(error) = backend.compile_mesh(graph, step.result, options) {
395 return blame(step.opening, error);
396 }
397 }
398 refused(product, original, provenance)
399}
400
401/// How a product's bounds were obtained.
402#[derive(Debug, Clone, Copy, PartialEq, Eq)]
403#[non_exhaustive]
404pub enum BoundsSource {
405 /// Read off the exact lowered geometry without tessellating: every leaf
406 /// was a mesh, an authored bounding box, a polygonal extrusion or a
407 /// block, bounded from its vertices, so the box is the shape's.
408 Exact,
409 /// Taken from the compiled mesh. Exact for planar geometry; for curved
410 /// geometry the mesh's vertices lie on the surface and chords cut
411 /// inside it, so the box can fall short of the true surface by up to
412 /// the compile tolerance.
413 Tessellated,
414}
415
416/// A product's axis-aligned bounds in world coordinates, in metres.
417#[derive(Debug, Clone, Copy, PartialEq)]
418#[non_exhaustive]
419pub struct ProductBounds {
420 /// The box, after placement.
421 pub aabb: Aabb,
422 /// Whether it came from the exact graph or a compiled mesh.
423 pub source: BoundsSource,
424}
425
426/// The world-space axis-aligned bounding box of one product's body.
427///
428/// Uses [`default_backend`] for the tessellated fallback; see
429/// [`product_bounds_with`].
430///
431/// # Errors
432///
433/// As [`product_bounds_with`].
434#[cfg(feature = "compile-reference-backend")]
435pub fn product_bounds(
436 model: &Model,
437 product: EntityId,
438 tolerance: Tolerance,
439) -> GeometryResult<Option<ProductBounds>> {
440 product_bounds_with(&default_backend(), model, product, tolerance)
441}
442
443/// The world-space axis-aligned bounding box of one product's body.
444///
445/// The body is resolved and placed exactly as [`compile_product_mesh_with`]
446/// does, and returns `Ok(None)` in the same case: a product with no body
447/// representation. When every leaf is a mesh, an authored bounding box, a
448/// linear extrusion of a straight-edged profile or a block, the box is read
449/// off the lowered graph from their vertices without tessellating
450/// ([`BoundsSource::Exact`]). Otherwise -- a curved profile or surface, a
451/// boolean -- the body is compiled with `backend` and the mesh's bounds are
452/// used ([`BoundsSource::Tessellated`]).
453///
454/// The result feeds a spatial index such as `axiolid_spatial::Bvh` directly;
455/// this crate computes the leaf boxes and leaves the index to Axiolid.
456///
457/// # Errors
458///
459/// Any lowering error, [`GeometryError::CompilationRefused`] when the
460/// fallback cannot compile, and [`GeometryError::Degenerate`] when the body
461/// has no finite extent (an empty or non-finite mesh): an empty box is not
462/// a bound.
463pub fn product_bounds_with<B: MeshCompiler>(
464 backend: &B,
465 model: &Model,
466 product: EntityId,
467 tolerance: Tolerance,
468) -> GeometryResult<Option<ProductBounds>> {
469 let scale = units::resolve(model)?;
470 let mut session = LoweringSession::new(model, &scale);
471 let Some(root) =
472 lower_product_representation(&mut session, product, RepresentationPurpose::Body)?
473 else {
474 return Ok(None);
475 };
476 let lowered = session.finish(root)?;
477 let (aabb, source) = match bounds::exact(&lowered.graph, lowered.root) {
478 Some(aabb) => (aabb, BoundsSource::Exact),
479 None => {
480 let options = ExecutionOptions::new(tolerance);
481 let mesh = backend
482 .compile_mesh(&lowered.graph, lowered.root, &options)
483 .map_err(|error| refused(product, error, &lowered.provenance))?;
484 (mesh.bounds(), BoundsSource::Tessellated)
485 }
486 };
487 if aabb.is_empty() || !aabb.is_finite() {
488 return Err(GeometryError::Degenerate {
489 entity: product,
490 type_name: model
491 .get(product)
492 .map_or_else(String::new, |entity| entity.type_name.to_string()),
493 detail: "body has no finite extent to bound".into(),
494 });
495 }
496 Ok(Some(ProductBounds { aabb, source }))
497}
498
499/// The backend's refusal of `entity`'s graph, in IFC terms: a refusal of a
500/// seam-snapping window, or of a run's order once snapped or once its
501/// basis's end is resolved (#433), names the runs (#429) or else the
502/// stations (#423) lowered with one (`provenance`), anything else is
503/// [`GeometryError::CompilationRefused`].
504fn refused(
505 entity: EntityId,
506 error: axiolid_contracts::GeomError,
507 provenance: &crate::lower::ProvenanceMap,
508) -> GeometryError {
509 if let Some(refusal) = SeamWindowRefusal::of(&error) {
510 let stations: Vec<EntityId> = provenance.seam_windows().collect();
511 let runs: Vec<EntityId> = provenance.seam_window_runs().collect();
512 if !runs.is_empty() {
513 return GeometryError::RunSeamWindowRefused {
514 product: entity,
515 runs,
516 stations,
517 refusal,
518 };
519 }
520 // Only a run's stations have an order to refuse.
521 let of_a_run = matches!(
522 refusal,
523 SeamWindowRefusal::NotIncreasing | SeamWindowRefusal::PastBasisEnd
524 );
525 if !stations.is_empty() && !of_a_run {
526 return GeometryError::StationSeamWindowRefused {
527 product: entity,
528 stations,
529 refusal,
530 };
531 }
532 }
533 GeometryError::CompilationRefused {
534 entity,
535 reason: format!("{error:?}"),
536 }
537}