Skip to main content

ifc_geometry/input/body/
mod.rs

1//! What a product's selected representation is made of, without lowering it.
2//!
3//! # Why a description and not a mesh
4//!
5//! Rule checks on structural members and walls ask how a body is modelled:
6//! "is this beam an extrusion of an I-section, how deep is the web, which way
7//! does it run". A mesh has lost every one of those answers. This module
8//! reads them from the representation items directly, in SI units and world
9//! coordinates (or, for `local_sweep`, the item's own frame), and links no
10//! geometry kernel.
11//!
12//! # One entry per item, never a merged answer
13//!
14//! A Body representation may hold several items, and a mapped item may map
15//! several more. [`body_description`] reports one [`BodyItem`] per resolved
16//! geometric item, in authored order, rather than refusing or picking one:
17//! a column with a base plate is two extrusions, and both are facts a rule
18//! check may need. [`BodyDescription::sole_item`] is the convenience for the
19//! common single-item case.
20//!
21//! # All or nothing
22//!
23//! If any item cannot be described exactly (an unsupported family, a dangling
24//! reference, a profile that bounds no area), the whole call fails with
25//! a typed error naming the entity. A partial list would let a caller treat a
26//! body as fully checked when part of it was never read.
27//!
28//! # Purposes
29//!
30//! [`body_description`] reads the Body representation. [`body_description_for`]
31//! reads another purpose, such as the `Reference` void of an IFC4 Reference
32//! View `IfcOpeningElement`, which is not subtracted from its host. A product
33//! without that purpose's representation yields `Ok(None)`; no other
34//! representation stands in for it.
35//!
36//! # Frames
37//!
38//! Items are placed exactly as lowering places them: the representation
39//! context's `WorldCoordinateSystem`, then the product's placement chain, then
40//! for a mapped item `MappingTarget` and `MappingOrigin`, then the item's own
41//! `Position`. Mapped geometry therefore resolves to the same answer as the
42//! same geometry authored in place.
43
44mod bounds;
45mod disk;
46mod kind;
47mod local;
48mod sweep;
49
50pub use kind::BodyKind;
51
52use ifc_model::{EntityId, Model};
53
54use super::context::product_representation_frame;
55use super::profile::ProfileDescription;
56use super::representation::{select_product_representation, Representation, RepresentationPurpose};
57use crate::error::{GeometryError, GeometryResult};
58use crate::resource::mapped::MappingWalker;
59use crate::resource::operator::operator_transform;
60use crate::resource::placement::axis_placement_transform;
61use crate::slots::Slots;
62use crate::transform::Transform;
63use crate::units::UnitScale;
64
65/// The representation of one product selected for a purpose (the Body by
66/// default), one entry per geometric item.
67#[derive(Debug, Clone, PartialEq)]
68#[non_exhaustive]
69pub struct BodyDescription {
70    /// The product described.
71    pub product: EntityId,
72    /// The representation selected for [`Self::purpose`]
73    /// ([`crate::select_product_representation`]; for `Body` that is
74    /// [`crate::select_shape_representation`]).
75    pub representation: EntityId,
76    /// The purpose the representation was selected for.
77    pub purpose: RepresentationPurpose,
78    /// The frame of the selected representation, in metres: the representation
79    /// context's `WorldCoordinateSystem` and the product placement
80    /// ([`product_representation_frame`]'s answer for [`Self::purpose`]).
81    /// Every [`BodyItem::item_world`] is this frame composed with the item's
82    /// mappings, and every [`BodyItemBounds`] is expressed in it.
83    pub frame: Transform,
84    /// One entry per geometric item, mapped items resolved, in authored order.
85    pub items: Vec<BodyItem>,
86}
87
88impl BodyDescription {
89    /// The only item, when the body has exactly one.
90    ///
91    /// `None` for an empty body and for a body of several items; a caller
92    /// that needs every item reads [`Self::items`].
93    pub fn sole_item(&self) -> Option<&BodyItem> {
94        match self.items.as_slice() {
95            [item] => Some(item),
96            _ => None,
97        }
98    }
99}
100
101/// One geometric representation item of a body.
102#[derive(Debug, Clone, PartialEq)]
103#[non_exhaustive]
104pub struct BodyItem {
105    /// The geometric item itself, never an `IfcMappedItem`.
106    pub item: EntityId,
107    /// Its concrete IFC type in upper case.
108    pub type_name: String,
109    /// The `IfcMappedItem`s this item was reached through, outermost first.
110    /// Empty when the item is authored directly in the body.
111    pub mapped_by: Vec<EntityId>,
112    /// How the item models its shape.
113    pub kind: BodyKind,
114    /// Profile and path in world coordinates, for the swept-area families
115    /// ([`BodyKind::is_swept_area`]); `None` for every other kind and for a
116    /// swept-area item whose [`Self::item_world`] is not rigid (a mapping
117    /// scaled or mirrored it). [`Self::local_sweep`] still describes it.
118    pub swept: Option<SweptSolid>,
119    /// Profile, `Position` and path in the item's own frame, for every
120    /// swept-area family ([`BodyKind::is_swept_area`]); `None` for every other
121    /// kind. These are the authored parameters whatever the mapping does;
122    /// [`Self::item_world`] places them.
123    pub local_sweep: Option<LocalSweptSolid>,
124    /// Radii, directrix and parameter range, for [`BodyKind::SweptDisk`];
125    /// `None` for every other kind. The authored parameters in the item's own
126    /// frame, whatever the mappings do; [`Self::item_world`] places them.
127    pub swept_disk: Option<SweptDisk>,
128    /// The frame the item's own coordinates are placed in, in metres: the
129    /// representation context's `WorldCoordinateSystem` and the product
130    /// placement, composed with every `MappingTarget o MappingOrigin` in
131    /// [`Self::mapped_by`] (#185). The identity composition for an item
132    /// authored directly in a body at the origin.
133    ///
134    /// Unlike [`SweptSolid::placement_world`] it is not required to be rigid:
135    /// a mapping may scale or mirror any item kind, and this frame says so.
136    /// A swept solid's world placement is this frame composed with the
137    /// solid's own `Position` ([`LocalSweptSolid::position`]); it is
138    /// `placement_world` when this frame is rigid.
139    pub item_world: Transform,
140    /// The exact bounds of a tessellated item's referenced vertices, in the
141    /// representation frame ([`BodyDescription::frame`]): the item's mappings
142    /// are applied, the frame is not. The frame maps the corner points: a
143    /// world box needs all eight corners transformed, not just `min` and
144    /// `max`. `Some` for
145    /// [`BodyKind::Tessellated`], `None` for every other kind.
146    pub bounds: Option<BodyItemBounds>,
147}
148
149/// A swept disk (`IfcSweptDiskSolid`, `IfcSweptDiskSolidPolygonal`): a pipe,
150/// duct or reinforcing bar, in its own item frame.
151///
152/// Radii are in metres. The directrix is reported by reference and lies in the
153/// frame [`BodyItem::item_world`] places; a non-rigid `item_world` does not
154/// refuse the item.
155#[derive(Debug, Clone, PartialEq)]
156#[non_exhaustive]
157pub struct SweptDisk {
158    /// `Radius`, in metres; positive.
159    pub radius: f64,
160    /// `InnerRadius` of a tube, in metres; smaller than [`Self::radius`].
161    pub inner_radius: Option<f64>,
162    /// `FilletRadius` of an `IfcSweptDiskSolidPolygonal`, in metres; `None`
163    /// for sharp corners and for an `IfcSweptDiskSolid`.
164    pub fillet_radius: Option<f64>,
165    /// The `Directrix` curve, in the item frame.
166    pub directrix: EntityId,
167    /// `(StartParam, EndParam)` as authored, unconverted: the unit depends on
168    /// the directrix family.
169    ///
170    /// - A conic (`IfcCircle`, `IfcEllipse`): an angle in the file's plane-angle
171    ///   unit.
172    /// - `IfcPolyline`: 1 per edge.
173    /// - `IfcLine`: multiples of the direction vector.
174    /// - `IfcTrimmedCurve`: the parameter of its basis curve.
175    /// - `IfcCompositeCurve`: parametric length.
176    /// - `IfcIndexedPolyCurve`: see #694.
177    ///
178    /// `None` when the disk is not trimmed; one end without the other is
179    /// refused.
180    pub parameter_range: Option<(f64, f64)>,
181}
182
183/// An axis-aligned box in the representation frame
184/// ([`BodyDescription::frame`]), in metres.
185///
186/// Exact over the vertices a face set's faces address, never over unreferenced
187/// entries of its point list.
188#[derive(Debug, Clone, Copy, PartialEq)]
189#[non_exhaustive]
190pub struct BodyItemBounds {
191    /// The smallest coordinate on each axis.
192    pub min: [f64; 3],
193    /// The largest coordinate on each axis.
194    pub max: [f64; 3],
195}
196
197impl BodyItem {
198    /// Whether the item is placed mirrored: [`Self::item_world`] reverses
199    /// handedness, so a left-hand part appears as its right-hand twin.
200    ///
201    /// `None` when the frame is degenerate (a zero or non-finite
202    /// determinant), which no valid placement or mapping produces.
203    pub fn is_mirrored(&self) -> Option<bool> {
204        let determinant = self.item_world.determinant();
205        (determinant.is_finite() && determinant != 0.0).then_some(determinant < 0.0)
206    }
207}
208
209/// A swept-area solid: its profile, where it sits, and the path it follows.
210#[derive(Debug, Clone, PartialEq)]
211#[non_exhaustive]
212pub struct SweptSolid {
213    /// `SweptArea`, in metres and radians.
214    pub profile: ProfileDescription,
215    /// `EndSweptArea` of a tapered sweep; `None` otherwise.
216    pub end_profile: Option<ProfileDescription>,
217    /// The solid's `Position` composed into world coordinates, in metres:
218    /// [`BodyItem::item_world`] composed with [`LocalSweptSolid::position`].
219    ///
220    /// The profile lies in this frame's XY plane. Rigid by construction: a
221    /// swept solid whose `item_world` scales or mirrors has no `SweptSolid`
222    /// (`BodyItem::swept` is `None`), because its profile parameters would no
223    /// longer be the authored ones; [`LocalSweptSolid`] describes it instead.
224    pub placement_world: Transform,
225    /// The path the profile follows.
226    pub path: SweepPath,
227}
228
229/// A swept-area solid in its own item frame: the frame
230/// [`BodyItem::item_world`] places, before any mapping or product placement.
231///
232/// Every parameter is the authored one in metres and radians, whatever scale
233/// or mirror the item's mappings apply. The world answer for a rigid
234/// `item_world` is [`SweptSolid`]; in general it is
235/// `item_world.compose(&position)`.
236#[derive(Debug, Clone, PartialEq)]
237#[non_exhaustive]
238pub struct LocalSweptSolid {
239    /// `SweptArea`, in metres and radians.
240    pub profile: ProfileDescription,
241    /// `EndSweptArea` of a tapered sweep; `None` otherwise.
242    pub end_profile: Option<ProfileDescription>,
243    /// The solid's `Position` in the item frame, in metres; `None` when the
244    /// file omits it (IFC4 OPTIONAL), which is the identity. Rigid, being an
245    /// `IfcAxis2Placement3D`.
246    pub position: Option<Transform>,
247    /// The path the profile follows, in the `Position` frame.
248    pub path: LocalSweepPath,
249}
250
251/// The path of a swept-area solid, in its `Position` frame.
252#[derive(Debug, Clone, PartialEq)]
253#[non_exhaustive]
254pub enum LocalSweepPath {
255    /// A straight extrusion (plain or tapered).
256    #[non_exhaustive]
257    Extrusion {
258        /// `ExtrudedDirection` in the `Position` frame, unit length.
259        direction: [f64; 3],
260        /// `Depth`, in metres, measured along `direction`.
261        depth: f64,
262    },
263    /// A revolution about an axis (plain or tapered).
264    #[non_exhaustive]
265    Revolution {
266        /// The axis origin in the `Position` frame, in metres.
267        axis_origin: [f64; 3],
268        /// The axis direction in the `Position` frame, unit length.
269        axis_direction: [f64; 3],
270        /// `Angle`, in radians.
271        angle: f64,
272    },
273    /// A sweep along a directrix curve, reported by reference.
274    ///
275    /// The curve and its `StartParam`/`EndParam` live in the directrix's own
276    /// parameterisation; reading them is a curve question, not a body one.
277    #[non_exhaustive]
278    Directrix {
279        /// The `Directrix` curve.
280        directrix: EntityId,
281    },
282}
283
284/// The path of a swept-area solid, in world coordinates.
285#[derive(Debug, Clone, PartialEq)]
286#[non_exhaustive]
287pub enum SweepPath {
288    /// A straight extrusion (plain or tapered).
289    #[non_exhaustive]
290    Extrusion {
291        /// `ExtrudedDirection` in world coordinates, unit length.
292        direction_world: [f64; 3],
293        /// `Depth`, in metres, measured along `direction_world`.
294        depth: f64,
295    },
296    /// A revolution about an axis (plain or tapered).
297    #[non_exhaustive]
298    Revolution {
299        /// The axis origin in world coordinates, in metres.
300        axis_origin_world: [f64; 3],
301        /// The axis direction in world coordinates, unit length.
302        axis_direction_world: [f64; 3],
303        /// `Angle`, in radians.
304        angle: f64,
305    },
306    /// A sweep along a directrix curve, reported by reference.
307    ///
308    /// The curve and its `StartParam`/`EndParam` live in the directrix's own
309    /// parameterisation; reading them is a curve question, not a body one.
310    #[non_exhaustive]
311    Directrix {
312        /// The `Directrix` curve.
313        directrix: EntityId,
314    },
315}
316
317/// Describe the Body representation of `product`.
318///
319/// Returns `Ok(None)` when the product has no body representation (only an
320/// Axis or FootPrint, or none at all): that is an answer, not a failure. A
321/// body whose representation lists no items yields an empty `items`.
322/// Equivalent to [`body_description_for`] with [`RepresentationPurpose::Body`].
323///
324/// Every item is described or the call fails; see the module docs. A Body
325/// tessellated item is now read for its bounds, so a malformed face set or a
326/// TIN with void or hole flags fails the whole description. Kernel-free:
327/// available with `--no-default-features`.
328///
329/// ```no_run
330/// # use ifc_model::{EntityId, Model};
331/// # use ifc_geometry::{body_description, units, BodyKind, SweepPath};
332/// # fn demo(model: &Model, beam: EntityId) -> ifc_geometry::GeometryResult<()> {
333/// let scale = units::resolve(model)?;
334/// let body = body_description(model, &scale, beam).unwrap().expect("a body");
335/// let item = body.sole_item().expect("one item");
336/// if item.kind == BodyKind::Extrusion {
337///     let swept = item.swept.as_ref().unwrap();
338///     if let SweepPath::Extrusion { direction_world, depth, .. } = swept.path {
339///         let _ = (swept.profile.type_name.as_str(), direction_world, depth);
340///     }
341/// }
342/// # Ok(())
343/// # }
344/// ```
345pub fn body_description(
346    model: &Model,
347    units: &UnitScale,
348    product: EntityId,
349) -> GeometryResult<Option<BodyDescription>> {
350    body_description_for(model, units, product, RepresentationPurpose::Body)
351}
352
353/// Describe the representation of `product` selected for `purpose`.
354///
355/// Like [`body_description`] for any purpose: the items of the selected
356/// representation, mapped items resolved. `Ok(None)` when the product has no
357/// representation for `purpose`; another purpose's representation is never
358/// substituted. A tessellated item also carries its exact
359/// [`BodyItem::bounds`], which refuses by name a face set lowering would
360/// refuse. Kernel-free: available with `--no-default-features`.
361pub fn body_description_for(
362    model: &Model,
363    units: &UnitScale,
364    product: EntityId,
365    purpose: RepresentationPurpose,
366) -> GeometryResult<Option<BodyDescription>> {
367    let Some(representation) = select_product_representation(model, product, purpose)? else {
368        return Ok(None);
369    };
370    // The same frame lowering places the representation's items in.
371    let Some(frame) = product_representation_frame(model, units, product, purpose)? else {
372        return Ok(None);
373    };
374
375    let mut walk = Walk {
376        model,
377        units,
378        walker: MappingWalker::new(),
379        mapped_by: Vec::new(),
380        items: Vec::new(),
381    };
382    walk.representation(product, representation, frame, Transform::identity())?;
383    Ok(Some(BodyDescription {
384        product,
385        representation,
386        purpose,
387        frame,
388        items: walk.items,
389    }))
390}
391
392/// State for one body walk: the mapped-item stack and the collected items.
393struct Walk<'m> {
394    model: &'m Model,
395    units: &'m UnitScale,
396    walker: MappingWalker,
397    mapped_by: Vec<EntityId>,
398    items: Vec<BodyItem>,
399}
400
401impl Walk<'_> {
402    /// Describe every item of one `IfcRepresentation` under `frame`; `local` is the
403    /// mappings alone, without the representation frame.
404    fn representation(
405        &mut self,
406        referrer: EntityId,
407        representation: EntityId,
408        frame: Transform,
409        local: Transform,
410    ) -> GeometryResult<()> {
411        let entity = self
412            .model
413            .get(representation)
414            .ok_or(GeometryError::MissingEntity {
415                referrer,
416                missing: representation,
417            })?;
418        for item in Representation::new(representation, entity).items()? {
419            self.item(representation, item, frame, local)?;
420        }
421        Ok(())
422    }
423
424    /// Describe one item, resolving a mapped item to what it maps.
425    fn item(
426        &mut self,
427        referrer: EntityId,
428        item: EntityId,
429        frame: Transform,
430        local: Transform,
431    ) -> GeometryResult<()> {
432        let entity = self.model.get(item).ok_or(GeometryError::MissingEntity {
433            referrer,
434            missing: item,
435        })?;
436        let type_name = entity.type_name.to_ascii_uppercase();
437        if type_name == "IFCMAPPEDITEM" {
438            return self.mapped(item, frame, local);
439        }
440        let kind = BodyKind::classify(&type_name).ok_or_else(|| {
441            Slots::new(item, entity).unsupported("representation item family is not described")
442        })?;
443        let (local_sweep, swept) = if kind.is_swept_area() {
444            let local = local::describe(self.model, self.units, item, entity)?;
445            let swept = sweep::world(&local, item, entity, frame)?;
446            (Some(local), swept)
447        } else {
448            (None, None)
449        };
450        let swept_disk = if kind == BodyKind::SweptDisk {
451            Some(disk::describe(
452                self.model, self.units, item, entity, &type_name,
453            )?)
454        } else {
455            None
456        };
457        let bounds = if kind == BodyKind::Tessellated {
458            Some(bounds::tessellated(
459                self.model, self.units, item, entity, &type_name, local,
460            )?)
461        } else {
462            None
463        };
464        self.items.push(BodyItem {
465            item,
466            type_name,
467            mapped_by: self.mapped_by.clone(),
468            kind,
469            swept,
470            local_sweep,
471            swept_disk,
472            item_world: frame,
473            bounds,
474        });
475        Ok(())
476    }
477
478    /// Resolve an `IfcMappedItem`: `frame o MappingTarget o MappingOrigin`.
479    ///
480    /// The same composition as `lower::mapped`, so a mapped body and the same
481    /// body authored in place describe identically.
482    fn mapped(&mut self, item: EntityId, frame: Transform, local: Transform) -> GeometryResult<()> {
483        self.walker.enter(item)?;
484        let result = self.mapped_inner(item, frame, local);
485        self.walker.exit();
486        result
487    }
488
489    fn mapped_inner(
490        &mut self,
491        item: EntityId,
492        frame: Transform,
493        local: Transform,
494    ) -> GeometryResult<()> {
495        let instance = self.walker.resolve(self.model, item)?;
496        let target_entity =
497            self.model
498                .get(instance.mapping_target)
499                .ok_or(GeometryError::MissingEntity {
500                    referrer: item,
501                    missing: instance.mapping_target,
502                })?;
503        // Both frames carry file-unit coordinates; convert exactly once here.
504        let target = operator_transform(self.model, instance.mapping_target, target_entity)?
505            .to_metres(self.units);
506        let origin_entity =
507            self.model
508                .get(instance.mapping_origin)
509                .ok_or(GeometryError::MissingEntity {
510                    referrer: item,
511                    missing: instance.mapping_origin,
512                })?;
513        let origin = axis_placement_transform(self.model, instance.mapping_origin, origin_entity)?
514            .to_metres(self.units);
515        let inner = frame.compose(&target).compose(&origin);
516        let inner_local = local.compose(&target).compose(&origin);
517
518        self.mapped_by.push(item);
519        let result = self.representation(item, instance.mapped_representation, inner, inner_local);
520        self.mapped_by.pop();
521        result
522    }
523}