ifc_lite_geometry/placement/
chain.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! The world transform of an `IfcObjectPlacement`: [`resolve_chain`] and
6//! friends. `PlacementRelTo` has fan-out 1, so the walk is a loop with a
7//! visited set and **no depth cap** (D27): a cycle is refused and counted, a
8//! chain of any length resolves in full, and the memo entry of a placement is
9//! a pure function of `(content, id)`.
10//!
11//! The memo is the decoder's `placement_transform_cache`. This module owes it
12//! the discipline its doc names: complete results only, **unscaled** (file
13//! units), column-major, keyed by placement id (plus the owning-grid axis id,
14//! which holds the grid's `ObjectPlacement` world). Errors are never memoised.
15
16use super::chain_walk::{climb, Climb, Frame};
17use super::{grid, linear, missing, unsupported, Axis2Placement, PlacementResult};
18use crate::math::mat4;
19use ifc_lite_core::{slot, DecodedEntity, EntityDecoder};
20use nalgebra::Matrix4;
21use smallvec::SmallVec;
22
23/// What a placement in a chain is.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum LinkKind {
26    /// `IfcLocalPlacement`
27    Local,
28    /// `IfcLinearPlacement`
29    Linear,
30    /// `IfcGridPlacement`
31    Grid,
32}
33
34/// One placement of a chain.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct Link {
37    pub id: u32,
38    pub kind: LinkKind,
39}
40
41/// The unscaled world transform of `placement`, composed
42/// `((T_root·L_1)·L_2)…·L_leaf` up `PlacementRelTo`.
43///
44/// Nothing is defaulted (D30): a record that is not a placement, a `$`
45/// `RelativePlacement`, a `RelativePlacement` that is not an `IfcAxis2Placement`
46/// and a linear or grid frame that cannot be sampled are refused and counted.
47/// A 2D `RelativePlacement` is honoured, as the IFC select allows.
48pub fn resolve_chain(placement: &DecodedEntity, decoder: &mut EntityDecoder) -> PlacementResult<Matrix4<f64>> {
49    // The hot path: a memo hit is one lookup, before anything is allocated.
50    if let Some(m) = decoder.get_placement_transform_cached(placement.id) {
51        return Ok(Matrix4::from_column_slice(&m));
52    }
53    let mut climbed = Climb::new();
54    climb(&mut climbed, placement, decoder, true, true, None)?;
55    if let Some((at, found)) = climbed.stopped_at {
56        return Err(unsupported(decoder, at, found));
57    }
58    let mut acc = climbed.base;
59    for frame in climbed.frames.iter().rev() {
60        if let Some(axis_id) = frame.alias {
61            decoder.cache_placement_transform(axis_id, mat4::col_major_array(&acc));
62        }
63        acc *= frame_matrix(frame, decoder)?;
64        decoder.cache_placement_transform(frame.entity.id, mat4::col_major_array(&acc));
65    }
66    Ok(acc)
67}
68
69
70/// The unscaled world transform of `product`'s `ObjectPlacement` (attribute 5).
71/// `Ok(None)` iff it is `$`, `*` or absent: "genuinely missing"
72/// stays the identity at the caller (#2256).
73pub fn resolve_object_placement(
74    product: &DecodedEntity,
75    decoder: &mut EntityDecoder,
76) -> PlacementResult<Option<Matrix4<f64>>> {
77    match decoder.resolve_optional(product, slot::IfcProduct::OBJECT_PLACEMENT.index())? {
78        Some(placement) => resolve_chain(&placement, decoder).map(Some),
79        None => Ok(None),
80    }
81}
82
83/// `placement` expressed in the frame of the placement `base`:
84/// `base_world⁻¹ · placement_world`, unscaled.
85///
86/// Composed from the links below the nearest placement the two chains share,
87/// so nothing at or above it enters the arithmetic: with `base` the root of
88/// `placement`'s chain, moving the root leaves the result bit-identical, and
89/// no inverse is taken at all. The memo is not consulted, since it holds
90/// world transforms.
91pub fn resolve_chain_relative(
92    placement: &DecodedEntity,
93    base: &DecodedEntity,
94    decoder: &mut EntityDecoder,
95) -> PlacementResult<Matrix4<f64>> {
96    // Climbed first, so a cyclic placement is refused even as its own base;
97    // as its own base its own frame is read too, as the path below reads the
98    // frames below the shared one, and an unreadable one is refused.
99    let target = full_climb(placement, decoder)?;
100    if placement.id == base.id {
101        if let Some(own) = target.frames.first() {
102            frame_matrix(own, decoder)?;
103        }
104        return Ok(Matrix4::identity());
105    }
106    let origin = full_climb(base, decoder)?;
107    let shared = target.frames.iter().enumerate().find_map(|(i, frame)| {
108        origin.frames.iter().position(|b| b.entity.id == frame.entity.id).map(|j| (i, j))
109    });
110    let (target_links, base_links) = shared.unwrap_or((target.frames.len(), origin.frames.len()));
111    let mut to_shared = Matrix4::<f64>::identity();
112    for frame in target.frames[..target_links].iter().rev() {
113        to_shared *= frame_matrix(frame, decoder)?;
114    }
115    if base_links == 0 {
116        return Ok(to_shared);
117    }
118    let mut base_to_shared = Matrix4::<f64>::identity();
119    for frame in origin.frames[..base_links].iter().rev() {
120        base_to_shared *= frame_matrix(frame, decoder)?;
121    }
122    let inverse = base_to_shared
123        .try_inverse()
124        .ok_or(super::PlacementError::Policy { at: base.id, rule: "placement frame is not invertible" })?;
125    Ok(inverse * to_shared)
126}
127
128/// The whole path from `placement` to its root, leaf first, memo not consulted.
129fn full_climb(placement: &DecodedEntity, decoder: &mut EntityDecoder) -> PlacementResult<Climb> {
130    let mut climbed = Climb::new();
131    climb(&mut climbed, placement, decoder, false, false, None)?;
132    match climbed.stopped_at {
133        Some((at, found)) => Err(unsupported(decoder, at, found)),
134        None => Ok(climbed),
135    }
136}
137
138/// The placements from `placement` up to the root, leaf first, cycle-checked.
139/// No transforms are composed and the memo is not consulted.
140pub fn chain(placement: &DecodedEntity, decoder: &mut EntityDecoder) -> PlacementResult<SmallVec<[Link; 8]>> {
141    Ok(full_climb(placement, decoder)?.frames.iter().map(|f| Link { id: f.entity.id, kind: f.kind }).collect())
142}
143
144/// The local-to-parent frame of one link. A frame that cannot be read or
145/// sampled is refused, never the identity: the element would sit at its
146/// parent's origin instead of being counted as lost (D3, D30).
147pub(super) fn frame_matrix(frame: &Frame, decoder: &mut EntityDecoder) -> PlacementResult<Matrix4<f64>> {
148    let entity = &frame.entity;
149    let at = entity.id;
150    Ok(match frame.kind {
151        LinkKind::Local => {
152            let rel = decoder
153                .resolve_optional(entity, slot::IfcLocalPlacement::RELATIVE_PLACEMENT.index())?
154                .ok_or_else(|| missing(decoder, at, "RelativePlacement"))?;
155            Axis2Placement::read(&rel, decoder)?.matrix()
156        }
157        LinkKind::Linear => linear::local_frame(entity, decoder)?,
158        LinkKind::Grid => {
159            let ctx = frame.grid.as_ref()
160                .ok_or_else(|| missing(decoder, at, "a resolvable grid intersection"))?;
161            grid::local_frame(entity, ctx, decoder)?
162        }
163    })
164}