Skip to main content

ifc_geometry/compile/
output.rs

1//! Curves and surfaces as output primitives (#458).
2//!
3//! A product's selected representation may hold curves (an `Axis`, a
4//! `FootPrint`, the curves of an `IfcAnnotation`), surfaces and solids, and
5//! a curve has no area, so it has no triangles. The representation is
6//! therefore split into leaves, and each leaf goes to the operation that
7//! compiles its dimensionality:
8//!
9//! - a **curve** leaf -- a curve, an open profile, or a placement of one --
10//!   to [`PolylineCompiler::compile_polyline`], one polyline per leaf, with
11//!   the backend's certified chord bound;
12//! - every **other** leaf to [`MeshCompiler::compile_mesh_reported`], as
13//!   one mesh whose closure says whether it bounds a solid
14//!   ([`MeshClosure::Solid`]) or is a surface ([`MeshClosure::Surface`]).
15//!
16//! Collections are opened, and a placement (a mapped item) only when it
17//! holds a curve: the polyline compiler takes one curve, so each curve
18//! under a placement is placed on its own by the same transform, composed.
19//! That regroups the lowered nodes exactly and evaluates nothing. A
20//! representation with no curve is compiled from its own root, as the Body
21//! path compiles it, so its mesh is unchanged. Nothing is tessellated,
22//! flattened or substituted here (ADR 0004).
23//!
24//! # Text and fill areas beside curves (#512)
25//!
26//! [`compile_product_curves_with`] reads the curves of a representation
27//! that also holds items with no curve to give: an `IfcTextLiteral` or
28//! `IfcTextLiteralWithExtent` (the value of a dimension) and an
29//! `IfcAnnotationFillArea`. Each such item of the representation's own
30//! `Items` is not lowered: it is listed, by id and [`NonCurveItem`] kind,
31//! in [`ProductPolylines::skipped`], and its reader is
32//! `ifc_style::StyleView` (`text_literal`, `text_literal_with_extent`,
33//! `annotation_fill_area`). Nothing is drawn in its place: a fill area's
34//! boundaries are not returned as polylines. Every other item lowers as
35//! before, and its refusal still refuses the product; a text literal nested
36//! in a mapped representation is refused, not skipped.
37//! [`compile_product_polylines_with`] keeps the strict rule and refuses
38//! such a representation as a whole.
39//!
40//! # Refused by name
41//!
42//! A backend that cannot compile a curve to a polyline refuses it, and
43//! the refusal is [`GeometryError::CompilationRefused`] carrying the
44//! backend's own reason. The reference compiler polylines trimmed,
45//! composite, offset and intrinsic curves since `axiolid-mesh-compile`
46//! 0.3.28 (axiolid/kernel#317; #506), and still refuses by name the forms
47//! it has no certified bound for: implicit and banked curves, a 3D
48//! intrinsic curve with torsion, a trim of a relation or of a placed
49//! curve, an offset of an offset, of a placed curve or of a chain, a 3D
50//! offset without a reference direction, an offset across a corner of its
51//! basis, and an offset by stations.
52
53use axiolid_contracts::ExecutionOptions;
54use axiolid_core::Transform3;
55use axiolid_mesh_compile_contract::MeshCompiler;
56use axiolid_model::{GeometryNode, Instance, NodeId};
57use ifc_model::{EntityId, Model};
58
59pub use axiolid_core::Point3;
60pub use axiolid_mesh_compile_contract::{ChordDeviation, MeshClosure, PolylineCompiler};
61
62use super::{refused, CompiledMesh, Tolerance};
63use crate::error::{GeometryError, GeometryResult};
64use crate::lower::context::lower_product_representation_leaving_out;
65use crate::lower::session::NodeShape;
66use crate::lower::{
67    lower_product_representation, LoweredGeometry, LoweringSession, RepresentationPurpose,
68};
69use crate::units;
70
71#[cfg(feature = "compile-reference-backend")]
72use super::default_backend;
73
74/// Nesting of collections and placements followed before refusing.
75const MAX_DEPTH: usize = 256;
76
77/// One curve of a representation as a 3D polyline.
78#[derive(Debug, Clone, PartialEq)]
79#[non_exhaustive]
80pub struct CompiledPolyline {
81    /// The IFC curve it was compiled from, when the lowering recorded one.
82    pub curve: Option<EntityId>,
83    /// The vertices in the curve's direction, world coordinates in metres.
84    /// A closed curve ends on the vertex it starts on.
85    pub points: Vec<Point3>,
86    /// Whether the curve is closed: the last vertex is the first.
87    pub closed: bool,
88    /// The chord budget asked for and the backend's certified bound on the
89    /// distance from every point of the exact curve to the polyline, in
90    /// metres. A polyline the file authored is its own curve: bound `0`.
91    pub deviation: ChordDeviation,
92}
93
94/// A representation item with no curve to give, which the curves reader
95/// leaves to its own reader (#512).
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
97#[non_exhaustive]
98pub enum NonCurveItem {
99    /// An `IfcTextLiteral` or `IfcTextLiteralWithExtent`: text, read by
100    /// `ifc_style::StyleView::text_literal` and `text_literal_with_extent`.
101    TextLiteral,
102    /// An `IfcAnnotationFillArea`: an area, read by
103    /// `ifc_style::StyleView::annotation_fill_area`.
104    AnnotationFillArea,
105}
106
107impl NonCurveItem {
108    /// The kind of a representation item, by STEP type name (any case),
109    /// `None` for every item that is lowered.
110    #[must_use]
111    pub fn of(type_name: &str) -> Option<Self> {
112        if type_name.eq_ignore_ascii_case("IFCTEXTLITERAL")
113            || type_name.eq_ignore_ascii_case("IFCTEXTLITERALWITHEXTENT")
114        {
115            Some(Self::TextLiteral)
116        } else if type_name.eq_ignore_ascii_case("IFCANNOTATIONFILLAREA") {
117            Some(Self::AnnotationFillArea)
118        } else {
119            None
120        }
121    }
122}
123
124/// A representation item the curves reader did not lower.
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
126#[non_exhaustive]
127pub struct SkippedItem {
128    /// The item, one of the representation's own `Items`.
129    pub item: EntityId,
130    /// Why it has no polyline.
131    pub kind: NonCurveItem,
132}
133
134/// The curves of one product's representation, and the items with no
135/// curve to give that were left out.
136#[derive(Debug, Clone, PartialEq, Default)]
137#[non_exhaustive]
138pub struct ProductPolylines {
139    /// One polyline per curve, in authored order.
140    pub polylines: Vec<CompiledPolyline>,
141    /// The text literals and fill areas of the representation, in
142    /// authored order, not lowered and not drawn.
143    pub skipped: Vec<SkippedItem>,
144}
145
146/// The curves of one product's representation for `purpose`, leaving its
147/// text literals and fill areas to their readers, with [`default_backend`].
148///
149/// # Errors
150///
151/// As [`compile_product_curves_with`].
152#[cfg(feature = "compile-reference-backend")]
153pub fn compile_product_curves(
154    model: &Model,
155    product: EntityId,
156    purpose: RepresentationPurpose,
157    tolerance: Tolerance,
158) -> GeometryResult<Option<ProductPolylines>> {
159    compile_product_curves_with(&default_backend(), model, product, purpose, tolerance)
160}
161
162/// The curves of one product's representation for `purpose` as
163/// polylines, leaving its text literals and fill areas to their readers
164/// (#512), with a caller-supplied backend.
165///
166/// As [`compile_product_polylines_with`], except that each
167/// `IfcTextLiteral`, `IfcTextLiteralWithExtent` and
168/// `IfcAnnotationFillArea` among the representation's own `Items` is not
169/// lowered but listed in [`ProductPolylines::skipped`]: a dimension
170/// (polylines and its value as text) gives its polylines. `Ok(None)` when
171/// the product has no representation for `purpose`.
172///
173/// # Errors
174///
175/// Any lowering error of an item not skipped, and
176/// [`GeometryError::CompilationRefused`] for a curve the backend refuses.
177/// One refused curve refuses the product.
178pub fn compile_product_curves_with<B: PolylineCompiler>(
179    backend: &B,
180    model: &Model,
181    product: EntityId,
182    purpose: RepresentationPurpose,
183    tolerance: Tolerance,
184) -> GeometryResult<Option<ProductPolylines>> {
185    let Some((split, left_out)) = lower_split(model, product, purpose, true)? else {
186        return Ok(None);
187    };
188    let skipped = left_out
189        .into_iter()
190        .filter_map(|(item, type_name)| {
191            NonCurveItem::of(&type_name).map(|kind| SkippedItem { item, kind })
192        })
193        .collect();
194    let polylines = match split {
195        Some(split) => compile_split(backend, &split, product, tolerance)?,
196        None => Vec::new(),
197    };
198    Ok(Some(ProductPolylines { polylines, skipped }))
199}
200
201/// The curves of one product's representation for `purpose` as
202/// polylines, with [`default_backend`].
203///
204/// # Errors
205///
206/// As [`compile_product_polylines_with`].
207#[cfg(feature = "compile-reference-backend")]
208pub fn compile_product_polylines(
209    model: &Model,
210    product: EntityId,
211    purpose: RepresentationPurpose,
212    tolerance: Tolerance,
213) -> GeometryResult<Option<Vec<CompiledPolyline>>> {
214    compile_product_polylines_with(&default_backend(), model, product, purpose, tolerance)
215}
216
217/// The curves of one product's representation for `purpose` as
218/// polylines, one per curve in authored order, with a caller-supplied
219/// backend.
220///
221/// `Ok(None)` when the product has no representation for `purpose`; an
222/// empty list when it has one with no curves (a solid Body). The chord
223/// budget is `tolerance`, in metres as for the meshes.
224///
225/// # Errors
226///
227/// Any lowering error, and [`GeometryError::CompilationRefused`], with the
228/// backend's reason, for a curve the backend refuses. One refused curve
229/// refuses the product: a partial outline is not returned as the whole.
230pub fn compile_product_polylines_with<B: PolylineCompiler>(
231    backend: &B,
232    model: &Model,
233    product: EntityId,
234    purpose: RepresentationPurpose,
235    tolerance: Tolerance,
236) -> GeometryResult<Option<Vec<CompiledPolyline>>> {
237    let Some((Some(split), _)) = lower_split(model, product, purpose, false)? else {
238        return Ok(None);
239    };
240    compile_split(backend, &split, product, tolerance).map(Some)
241}
242
243/// Each curve of `split` as a polyline, in order; one refusal refuses all.
244fn compile_split<B: PolylineCompiler>(
245    backend: &B,
246    split: &Split,
247    product: EntityId,
248    tolerance: Tolerance,
249) -> GeometryResult<Vec<CompiledPolyline>> {
250    let lowered = &split.lowered;
251    let options = ExecutionOptions::new(tolerance);
252    split
253        .curves
254        .iter()
255        .map(|&(leaf, curve)| {
256            backend
257                .compile_polyline(&lowered.graph, leaf, &options)
258                .map(|outcome| CompiledPolyline {
259                    curve,
260                    closed: outcome.closed,
261                    deviation: outcome.deviation,
262                    points: outcome.points,
263                })
264                .map_err(|error| refused(product, error, &lowered.provenance))
265        })
266        .collect()
267}
268
269/// The surfaces and solids of one product's representation for `purpose`
270/// as one mesh, with [`default_backend`].
271///
272/// # Errors
273///
274/// As [`compile_product_mesh_for_with`].
275#[cfg(feature = "compile-reference-backend")]
276pub fn compile_product_mesh_for(
277    model: &Model,
278    product: EntityId,
279    purpose: RepresentationPurpose,
280    tolerance: Tolerance,
281) -> GeometryResult<Option<CompiledMesh>> {
282    compile_product_mesh_for_with(&default_backend(), model, product, purpose, tolerance)
283}
284
285/// The surfaces and solids of one product's representation for `purpose`
286/// as one mesh, reporting its closure, with a caller-supplied backend.
287///
288/// Every leaf that is not a curve is compiled together, so a `Body` with
289/// no curves compiles from the same root, to the same mesh, as
290/// [`super::compile_product_mesh_reported_with`]. A surface -- a surface
291/// model, a face, a rectangular trimmed surface, a B-rep of loose faces --
292/// is [`MeshClosure::Surface`]. `Ok(None)` when the product has no
293/// representation for `purpose`, or one with curves only (an `Axis`):
294/// [`compile_product_polylines_with`] returns those.
295///
296/// # Errors
297///
298/// Any lowering error, and [`GeometryError::CompilationRefused`] when the
299/// backend refuses the mesh.
300pub fn compile_product_mesh_for_with<B: MeshCompiler>(
301    backend: &B,
302    model: &Model,
303    product: EntityId,
304    purpose: RepresentationPurpose,
305    tolerance: Tolerance,
306) -> GeometryResult<Option<CompiledMesh>> {
307    let Some((Some(split), _)) = lower_split(model, product, purpose, false)? else {
308        return Ok(None);
309    };
310    let Some(root) = split.mesh else {
311        return Ok(None);
312    };
313    let lowered = &split.lowered;
314    let options = ExecutionOptions::new(tolerance);
315    backend
316        .compile_mesh_reported(&lowered.graph, root, &options)
317        .map(|outcome| {
318            Some(CompiledMesh {
319                closure: outcome.closure,
320                mesh: outcome.mesh,
321            })
322        })
323        .map_err(|error| refused(product, error, &lowered.provenance))
324}
325
326/// A representation lowered and split by dimension.
327struct Split {
328    /// The lowered graph; the nodes below are among its nodes.
329    lowered: LoweredGeometry,
330    /// Each curve, placed, with the IFC curve it came from.
331    curves: Vec<(NodeId, Option<EntityId>)>,
332    /// The node holding every other leaf, `None` when there is none: the
333    /// representation's own root when it has no curve.
334    mesh: Option<NodeId>,
335}
336
337/// One leaf of a representation and the placement composed above it
338/// inside the representation, `None` when nothing there places it.
339type Leaf = (NodeId, Option<Transform3>);
340
341/// Items the curves reader left out: id and STEP type name.
342type LeftOut = Vec<(EntityId, std::sync::Arc<str>)>;
343
344/// The product's representation for `purpose`, lowered and placed, and
345/// split into its curves and the rest.
346///
347/// With `leave_out_non_curves`, the representation's own text literals
348/// and fill areas ([`NonCurveItem`]) are not lowered but returned; the
349/// split is `None` when nothing else remains. Without it, nothing is left
350/// out, and a representation of no items is `Ok(None)`.
351fn lower_split(
352    model: &Model,
353    product: EntityId,
354    purpose: RepresentationPurpose,
355    leave_out_non_curves: bool,
356) -> GeometryResult<Option<(Option<Split>, LeftOut)>> {
357    let scale = units::resolve(model)?;
358    let mut session = LoweringSession::new(model, &scale);
359    let (root, left_out) = if leave_out_non_curves {
360        let Some((root, left_out)) =
361            lower_product_representation_leaving_out(&mut session, product, purpose, |name| {
362                NonCurveItem::of(name).is_some()
363            })?
364        else {
365            return Ok(None);
366        };
367        let left_out = left_out
368            .into_iter()
369            .filter_map(|item| {
370                model
371                    .get(item)
372                    .map(|entity| (item, entity.type_name.clone()))
373            })
374            .collect();
375        (root, left_out)
376    } else {
377        let Some(root) = lower_product_representation(&mut session, product, purpose)? else {
378            return Ok(None);
379        };
380        (Some(root), Vec::new())
381    };
382    let Some(root) = root else {
383        return Ok(Some((None, left_out)));
384    };
385    let (mut curves, mut others) = (Vec::new(), Vec::new());
386    walk(&session, root, None, product, 0, &mut curves, &mut others)?;
387    let (curves, mesh) = if curves.is_empty() {
388        (Vec::new(), Some(root))
389    } else {
390        let curves = curves
391            .into_iter()
392            .map(|leaf| {
393                let source = session.provenance().source(leaf.0);
394                place(&mut session, leaf, product).map(|node| (node, source))
395            })
396            .collect::<GeometryResult<Vec<_>>>()?;
397        let others = others
398            .into_iter()
399            .map(|leaf| place(&mut session, leaf, product))
400            .collect::<GeometryResult<Vec<_>>>()?;
401        let mesh = match others.as_slice() {
402            [] => None,
403            [only] => Some(*only),
404            _ => Some(session.node_for(product, GeometryNode::Collection(others))?),
405        };
406        (curves, mesh)
407    };
408    let lowered = session.finish(root)?;
409    Ok(Some((
410        Some(Split {
411            lowered,
412            curves,
413            mesh,
414        }),
415        left_out,
416    )))
417}
418
419/// Sort the leaves under `node`, placed by `outer`, into `curves` and
420/// `others`, in authored order.
421fn walk(
422    session: &LoweringSession<'_>,
423    node: NodeId,
424    outer: Option<Transform3>,
425    product: EntityId,
426    depth: usize,
427    curves: &mut Vec<Leaf>,
428    others: &mut Vec<Leaf>,
429) -> GeometryResult<()> {
430    if depth > MAX_DEPTH {
431        return Err(GeometryError::ChainTooDeep {
432            entity: product,
433            kind: "representation leaf",
434            limit: MAX_DEPTH,
435        });
436    }
437    match session.shape(node) {
438        Some(NodeShape::Collection(members)) => {
439            for &member in members {
440                walk(session, member, outer, product, depth + 1, curves, others)?;
441            }
442        }
443        Some(&NodeShape::Instance { source, transform }) if holds_curve(session, source, 0) => {
444            // `outer` is applied after this instance's own transform.
445            let composed = outer.map_or(transform, |outer| outer * transform);
446            walk(
447                session,
448                source,
449                Some(composed),
450                product,
451                depth + 1,
452                curves,
453                others,
454            )?;
455        }
456        _ if is_curve(session, node) => curves.push((node, outer)),
457        _ => others.push((node, outer)),
458    }
459    Ok(())
460}
461
462/// Whether `node` is a curve, an open profile, or a curve placed at a
463/// station: each one curve to the polyline compiler.
464fn is_curve(session: &LoweringSession<'_>, node: NodeId) -> bool {
465    match session.shape(node) {
466        Some(NodeShape::Curve) => true,
467        _ => matches!(
468            session.relation(node),
469            Some(GeometryNode::InstanceAtStation(placed))
470                if matches!(session.shape(placed.source), Some(NodeShape::Curve))
471        ),
472    }
473}
474
475/// Whether a curve lies anywhere under `node`.
476fn holds_curve(session: &LoweringSession<'_>, node: NodeId, depth: usize) -> bool {
477    if depth > MAX_DEPTH {
478        return false;
479    }
480    match session.shape(node) {
481        Some(NodeShape::Collection(members)) => members
482            .iter()
483            .any(|&member| holds_curve(session, member, depth + 1)),
484        Some(&NodeShape::Instance { source, .. }) => holds_curve(session, source, depth + 1),
485        _ => is_curve(session, node),
486    }
487}
488
489/// `leaf` under the placement composed above it, as a new instance node,
490/// or the leaf itself when nothing places it.
491fn place(
492    session: &mut LoweringSession<'_>,
493    leaf: Leaf,
494    product: EntityId,
495) -> GeometryResult<NodeId> {
496    match leaf {
497        (node, None) => Ok(node),
498        (source, Some(transform)) => session.node_for(
499            product,
500            GeometryNode::Instance(Instance { source, transform }),
501        ),
502    }
503}