Skip to main content

ifc_geometry/constraint/
local.rs

1//! `IfcLocalPlacement`: the nesting placement chain.
2//!
3//! # Semantics
4//!
5//! An `IfcLocalPlacement` has two attributes: `PlacementRelTo` (the parent
6//! placement, optional) and `RelativePlacement` (an `IfcAxis2Placement3D` or
7//! 2D giving the offset from that parent).
8//!
9//! **If `PlacementRelTo` is absent, the placement is absolute** in the project
10//! coordinate system. That is the recursion's base case.
11//!
12//! # Two traps, both from the spec
13//!
14//! 1. **Cycles happen.** The IFC specification says outright that "rules to
15//!    prevent cyclic relative placements have to be introduced on the
16//!    application level" -- meaning the schema does not forbid them and real
17//!    exporters have produced them. Naive recursion overflows the stack on a
18//!    file that merely looks valid.
19//!
20//! 2. **Chains are walked per element.** A model with 100k elements walks
21//!    100k chains that share their upper links. Resolving without a cache is
22//!    quadratic in the depth; hence [`PlacementResolver`].
23
24use crate::constraint::grid::resolve::grid_frame;
25use crate::constraint::grid::GridPlacement;
26use crate::constraint::placement::LinearResolution;
27use crate::constraint::tolerance::frames_agree;
28use crate::error::{GeometryError, GeometryResult};
29use crate::resource::placement::axis_placement_transform;
30use crate::slots::Slots;
31use crate::transform::Transform;
32use crate::units::UnitScale;
33use ifc_model::{EntityId, Model};
34use std::collections::HashMap;
35
36/// `IfcLocalPlacement` attribute slots.
37///
38/// From IFC4 ADD2 TC1: `IfcLocalPlacement` has no inherited explicit
39/// attributes (its supertype `IfcObjectPlacement` declares only the inverse
40/// `PlacesObject`), so these indices are its own.
41pub(crate) mod slot {
42    /// `PlacementRelTo`: the parent placement, optional.
43    pub const PLACEMENT_REL_TO: usize = 0;
44    /// `RelativePlacement`: offset from the parent.
45    pub const RELATIVE_PLACEMENT: usize = 1;
46}
47
48/// A borrowed view of an `IfcLocalPlacement`.
49#[derive(Debug, Clone, Copy)]
50pub struct LocalPlacement<'m> {
51    slots: Slots<'m>,
52}
53
54impl<'m> LocalPlacement<'m> {
55    /// Wrap an entity assumed to be an `IfcLocalPlacement`.
56    pub fn new(id: EntityId, entity: &'m ifc_model::Entity) -> Self {
57        Self {
58            slots: Slots::new(id, entity),
59        }
60    }
61
62    /// The entity id.
63    pub fn id(&self) -> EntityId {
64        self.slots.id()
65    }
66
67    /// The parent placement, if any.
68    ///
69    /// `None` means this placement is absolute in project coordinates.
70    pub fn parent(&self) -> Option<EntityId> {
71        self.slots.opt_ref(slot::PLACEMENT_REL_TO)
72    }
73
74    /// The `IfcAxis2Placement` giving the offset from the parent.
75    pub fn relative_placement(&self) -> GeometryResult<EntityId> {
76        self.slots
77            .req_ref(slot::RELATIVE_PLACEMENT, "RelativePlacement")
78    }
79
80    /// This placement's own offset, not including its parents.
81    pub fn local_transform(&self, model: &'m Model) -> GeometryResult<Transform> {
82        let placement_id = self.relative_placement()?;
83        let entity = self.slots.resolve(model, placement_id)?;
84        axis_placement_transform(model, placement_id, entity)
85    }
86}
87
88/// How deep a placement chain may go before we call it malformed.
89///
90/// Real hierarchies are site > building > storey > element > opening, so
91/// single digits. 64 leaves enormous headroom while still terminating on a
92/// corrupt file quickly. The limit counts every placement the walk is
93/// inside of, whatever its kind: a local placement relative to a grid
94/// placement whose grid is placed relative to a storey is four deep.
95const MAX_CHAIN_DEPTH: usize = 64;
96
97/// Resolves placement chains to world transforms, with memoization.
98///
99/// # Why a resolver rather than a free function
100///
101/// Placement chains share their upper links: every element in a storey walks
102/// the same storey-building-site tail. Caching per placement turns repeated
103/// work into a lookup, which matters because this runs once per element in the
104/// file.
105///
106/// # Every `IfcObjectPlacement` kind (#363)
107///
108/// IFC4.3 ADD2 declares `PlacementRelTo : OPTIONAL IfcObjectPlacement` on
109/// `IfcObjectPlacement` itself, so any placement may be relative to any
110/// other: a bracket on a linearly placed signal mast, a fixing on a column
111/// placed on a grid. The walk resolves each link by its kind --
112/// `IfcLocalPlacement` by its `RelativePlacement`, `IfcGridPlacement` by
113/// its grid intersection in the grid's frame (#362),
114/// `IfcLinearPlacement` along its basis curve in the alignment's frame
115/// (#357) -- and caches each. Grid and linear placements reach their frames
116/// through further placements (the grid's or the alignment's
117/// `ObjectPlacement`), so the walk follows those too; the depth limit and
118/// the cycle check cover the whole mixed chain.
119///
120/// A resolver's cache holds transforms resolved one way: the crate's entry
121/// points use a fresh resolver per resolution mode, so a cached linear
122/// placement never mixes a cache-only answer with a derived one.
123#[derive(Debug, Default)]
124pub struct PlacementResolver {
125    cache: HashMap<EntityId, Transform>,
126}
127
128/// One resolution's inputs and the placements it is currently inside of.
129struct Walk<'a, 'e> {
130    model: &'a Model,
131    units: &'a UnitScale,
132    linear: LinearResolution<'e>,
133    /// The placements being resolved, outermost first: a cycle revisits one.
134    active: Vec<EntityId>,
135}
136
137impl PlacementResolver {
138    /// A resolver with an empty cache.
139    pub fn new() -> Self {
140        Self::default()
141    }
142
143    /// How many placements are memoized.
144    pub fn cached(&self) -> usize {
145        self.cache.len()
146    }
147
148    /// Resolve a placement to its world transform, in FILE units.
149    ///
150    /// Walks `PlacementRelTo` to the root, then composes downward. Detects
151    /// cycles rather than overflowing the stack, and reports the entity where
152    /// the cycle closes so the file can be repaired.
153    ///
154    /// Every placement kind resolves (#363): an `IfcGridPlacement` with
155    /// straight axes, and an `IfcLinearPlacement` from its cached
156    /// `CartesianPosition`. Deriving an uncached linear placement or
157    /// intersecting curved grid axes needs a curve evaluator, which this
158    /// entry point does not take: those are refused by name, and
159    /// `product_world_transform_with_evaluator` (feature `compile`) resolves
160    /// them.
161    pub fn world_transform(
162        &mut self,
163        model: &Model,
164        placement: EntityId,
165    ) -> GeometryResult<Transform> {
166        // Unit factors of one: a linear placement's metric frame comes back
167        // in file units unchanged.
168        self.resolve(
169            model,
170            &UnitScale::SI,
171            placement,
172            LinearResolution::cache_only(),
173        )
174    }
175
176    /// [`Self::world_transform`] with the model's units and a linear
177    /// resolution mode, in FILE units.
178    pub(crate) fn resolve(
179        &mut self,
180        model: &Model,
181        units: &UnitScale,
182        placement: EntityId,
183        linear: LinearResolution<'_>,
184    ) -> GeometryResult<Transform> {
185        let mut walk = Walk {
186            model,
187            units,
188            linear,
189            active: Vec::new(),
190        };
191        self.resolve_in(&mut walk, placement, placement)
192    }
193
194    /// Resolve `id`, reached from `referrer`, through the cache.
195    fn resolve_in(
196        &mut self,
197        walk: &mut Walk<'_, '_>,
198        referrer: EntityId,
199        id: EntityId,
200    ) -> GeometryResult<Transform> {
201        if let Some(cached) = self.cache.get(&id) {
202            return Ok(*cached);
203        }
204        if walk.active.contains(&id) {
205            return Err(GeometryError::CyclicChain {
206                entity: id,
207                kind: "placement",
208            });
209        }
210        if walk.active.len() >= MAX_CHAIN_DEPTH {
211            return Err(GeometryError::ChainTooDeep {
212                entity: id,
213                kind: "placement",
214                limit: MAX_CHAIN_DEPTH,
215            });
216        }
217        let entity = walk.model.get(id).ok_or(GeometryError::MissingEntity {
218            referrer,
219            missing: id,
220        })?;
221        walk.active.push(id);
222        let resolved = self.compose(walk, id, entity);
223        walk.active.pop();
224        let world = resolved?;
225        self.cache.insert(id, world);
226        Ok(world)
227    }
228
229    /// Resolve one placement by its kind, its parents through the cache.
230    fn compose(
231        &mut self,
232        walk: &mut Walk<'_, '_>,
233        id: EntityId,
234        entity: &ifc_model::Entity,
235    ) -> GeometryResult<Transform> {
236        match entity.type_name.as_ref() {
237            "IFCLOCALPLACEMENT" => {
238                let view = LocalPlacement::new(id, entity);
239                let parent = match view.parent() {
240                    Some(parent) => self.resolve_in(walk, id, parent)?,
241                    None => Transform::identity(),
242                };
243                Ok(parent.compose(&view.local_transform(walk.model)?))
244            }
245            "IFCGRIDPLACEMENT" => self.grid(walk, id, entity),
246            "IFCLINEARPLACEMENT" => self.linear(walk, id),
247            other => Err(GeometryError::WrongEntityType {
248                entity: id,
249                actual: other.to_string(),
250                expected: "IfcObjectPlacement",
251            }),
252        }
253    }
254
255    /// An `IfcGridPlacement`: its grid's `ObjectPlacement`, then the
256    /// intersection frame in the grid's coordinates (#362).
257    fn grid(
258        &mut self,
259        walk: &mut Walk<'_, '_>,
260        id: EntityId,
261        entity: &ifc_model::Entity,
262    ) -> GeometryResult<Transform> {
263        let frame = grid_frame(walk.model, walk.units, id, walk.linear)?;
264        let grid_world = self.resolve_in(walk, id, frame.grid_placement)?;
265        // IFC4X3 states the grid's ObjectPlacement again as PlacementRelTo;
266        // it must agree with the grid the axes belong to.
267        if let Some(stated) = GridPlacement::new(id, entity).placement_rel_to() {
268            if stated != frame.grid_placement {
269                let stated_world = self.resolve_in(walk, id, stated)?;
270                if !frames_agree(walk.model, &stated_world, &grid_world)? {
271                    return Err(GeometryError::PlacementRelToConflict {
272                        placement: id,
273                        stated,
274                        implied: frame.grid_placement,
275                    });
276                }
277            }
278        }
279        Ok(grid_world.compose(&frame.local))
280    }
281
282    /// An `IfcLinearPlacement`: the frame its basis curve is stated in, then
283    /// the station frame on the curve (#357).
284    #[cfg(feature = "lowering")]
285    fn linear(&mut self, walk: &mut Walk<'_, '_>, id: EntityId) -> GeometryResult<Transform> {
286        use crate::constraint::placement::linear::{self, CurveFrame};
287        let (model, units) = (walk.model, walk.units);
288        let basis = linear::basis_curve(model, units, id)?;
289        let stated = linear::placement_rel_to(model, id);
290        let implied = match linear::curve_frame(model, basis, stated.is_none())? {
291            CurveFrame::Placed { placement, .. } => {
292                Some((placement, self.resolve_in(walk, id, placement)?))
293            }
294            CurveFrame::ModelSpace { product } => Some((product, Transform::identity())),
295            CurveFrame::Unknown => None,
296        };
297        let parent = match (stated, implied) {
298            (Some(stated), Some((implied, implied_world))) => {
299                let stated_world = self.resolve_in(walk, id, stated)?;
300                if stated != implied && !frames_agree(model, &stated_world, &implied_world)? {
301                    return Err(GeometryError::PlacementRelToConflict {
302                        placement: id,
303                        stated,
304                        implied,
305                    });
306                }
307                stated_world
308            }
309            (Some(stated), None) => self.resolve_in(walk, id, stated)?,
310            (None, Some((_, implied_world))) => implied_world,
311            (None, None) => Transform::identity(),
312        };
313        let scale = units.length_to_metres;
314        if !(scale.is_finite() && scale > 0.0) {
315            return Err(GeometryError::Units(format!(
316                "length factor {scale} cannot place a linear placement"
317            )));
318        }
319        let relative =
320            linear::relative_transform(model, units, id, walk.linear, &parent.to_metres(units))?;
321        // The station frame is metric; the chain composes in file units.
322        let relative = Transform {
323            basis: relative.basis,
324            origin: relative.origin.map(|coordinate| coordinate / scale),
325        };
326        Ok(parent.compose(&relative))
327    }
328
329    /// Without `lowering` there is no `ifc-alignment` to read the linear
330    /// expression with.
331    #[cfg(not(feature = "lowering"))]
332    fn linear(&mut self, walk: &mut Walk<'_, '_>, id: EntityId) -> GeometryResult<Transform> {
333        let _ = walk;
334        Err(GeometryError::Unsupported {
335            entity: id,
336            type_name: "IFCLINEARPLACEMENT".into(),
337            detail: "resolving a linear placement needs the `lowering` feature (ifc-alignment)",
338        })
339    }
340}
341
342#[cfg(test)]
343mod tests {
344    use super::*;
345    use ifc_model::{Entity, Value};
346
347    /// Build `#id = IFCAXIS2PLACEMENT3D(#point, $, $)` at the given offset.
348    fn placement_at(model: &mut Model, id: u64, point_id: u64, xyz: [f64; 3]) {
349        model.insert(
350            EntityId(point_id),
351            Entity::new(
352                "IFCCARTESIANPOINT",
353                vec![Value::List(
354                    xyz.iter().map(|v| Value::Real(*v)).collect::<Vec<_>>(),
355                )],
356            ),
357        );
358        model.insert(
359            EntityId(id),
360            Entity::new(
361                "IFCAXIS2PLACEMENT3D",
362                vec![Value::Ref(EntityId(point_id)), Value::Null, Value::Null],
363            ),
364        );
365    }
366
367    /// `#id = IFCLOCALPLACEMENT(parent, axis_placement)`
368    fn local(model: &mut Model, id: u64, parent: Option<u64>, axis: u64) {
369        model.insert(
370            EntityId(id),
371            Entity::new(
372                "IFCLOCALPLACEMENT",
373                vec![
374                    parent.map_or(Value::Null, |p| Value::Ref(EntityId(p))),
375                    Value::Ref(EntityId(axis)),
376                ],
377            ),
378        );
379    }
380
381    /// site(0,0,0) > storey(0,0,3) > wall(1,0,0) puts the wall at (1,0,3).
382    fn three_level_model() -> Model {
383        let mut model = Model::new();
384        placement_at(&mut model, 10, 11, [0.0, 0.0, 0.0]);
385        placement_at(&mut model, 20, 21, [0.0, 0.0, 3.0]);
386        placement_at(&mut model, 30, 31, [1.0, 0.0, 0.0]);
387        local(&mut model, 1, None, 10);
388        local(&mut model, 2, Some(1), 20);
389        local(&mut model, 3, Some(2), 30);
390        model
391    }
392
393    #[test]
394    fn absent_parent_means_world_coordinates() {
395        let model = three_level_model();
396        let mut resolver = PlacementResolver::new();
397        let t = resolver.world_transform(&model, EntityId(1)).unwrap();
398        assert!(t.is_identity(1e-12));
399    }
400
401    #[test]
402    fn chain_composes_from_root_downward() {
403        let model = three_level_model();
404        let mut resolver = PlacementResolver::new();
405        let t = resolver.world_transform(&model, EntityId(3)).unwrap();
406        assert_eq!(t.origin, [1.0, 0.0, 3.0], "storey height must accumulate");
407    }
408
409    /// The spec pushes cycle prevention to the application, so files contain
410    /// them. Detect, do not overflow.
411    #[test]
412    fn cyclic_chains_are_detected_not_stack_overflowed() {
413        let mut model = Model::new();
414        placement_at(&mut model, 10, 11, [0.0, 0.0, 0.0]);
415        local(&mut model, 1, Some(2), 10);
416        local(&mut model, 2, Some(1), 10);
417
418        let mut resolver = PlacementResolver::new();
419        let err = resolver.world_transform(&model, EntityId(1)).unwrap_err();
420        assert!(
421            matches!(err, GeometryError::CyclicChain { .. }),
422            "expected a cycle error, got {err}"
423        );
424    }
425
426    /// A self-referencing placement is the degenerate cycle.
427    #[test]
428    fn self_reference_is_a_cycle() {
429        let mut model = Model::new();
430        placement_at(&mut model, 10, 11, [0.0, 0.0, 0.0]);
431        local(&mut model, 1, Some(1), 10);
432
433        let mut resolver = PlacementResolver::new();
434        assert!(matches!(
435            resolver.world_transform(&model, EntityId(1)).unwrap_err(),
436            GeometryError::CyclicChain { .. }
437        ));
438    }
439
440    #[test]
441    fn shared_ancestors_are_resolved_once() {
442        let model = three_level_model();
443        let mut resolver = PlacementResolver::new();
444        resolver.world_transform(&model, EntityId(3)).unwrap();
445        let after_first = resolver.cached();
446
447        // A sibling under the same storey must reuse the cached tail.
448        resolver.world_transform(&model, EntityId(2)).unwrap();
449        assert_eq!(
450            resolver.cached(),
451            after_first,
452            "resolving an already-cached ancestor must not recompute"
453        );
454    }
455
456    #[test]
457    fn dangling_parent_reference_is_reported() {
458        let mut model = Model::new();
459        placement_at(&mut model, 10, 11, [0.0, 0.0, 0.0]);
460        local(&mut model, 1, Some(999), 10);
461
462        let mut resolver = PlacementResolver::new();
463        assert!(matches!(
464            resolver.world_transform(&model, EntityId(1)).unwrap_err(),
465            GeometryError::MissingEntity { .. }
466        ));
467    }
468
469    /// A grid placement is resolved now (#362); one without its
470    /// `PlacementLocation` is refused by name rather than placed at the
471    /// origin.
472    #[test]
473    fn grid_placement_without_a_location_is_refused_rather_than_defaulting_to_origin() {
474        let mut model = Model::new();
475        model.insert(
476            EntityId(1),
477            Entity::new("IFCGRIDPLACEMENT", vec![Value::Null, Value::Null]),
478        );
479        let mut resolver = PlacementResolver::new();
480        let err = resolver.world_transform(&model, EntityId(1)).unwrap_err();
481        assert!(
482            matches!(
483                err,
484                GeometryError::MissingAttribute {
485                    attribute: "PlacementLocation",
486                    ..
487                }
488            ),
489            "got {err}"
490        );
491    }
492}