ifc_geometry/constraint/placement/mod.rs
1//! Product placement resolution: the answer to "where is this in the world".
2//!
3//! This is the single most-reused operation in any IFC consumer, and the one
4//! most often reimplemented incorrectly. It lives here rather than in `lower`
5//! because a 2D drawing needs world coordinates just as much as a 3D
6//! tessellation does, and must not have to compile a solid kernel to get them.
7//!
8//! # Composition order
9//!
10//! An `IfcLocalPlacement` points at its *parent* through `PlacementRelTo`, so
11//! the walk is upward and composition is outermost-last. Reversing that
12//! silently mirrors the model about its ancestors.
13//!
14//! # Units are converted once, at the end
15//!
16//! Placement coordinates are raw file units. The chain composes unconverted
17//! and the composed result is converted once. Converting per link would raise
18//! the scale factor to the power of the chain depth -- a millimetre file three
19//! levels deep would land a thousand times too far out.
20
21use ifc_model::{EntityId, Model};
22
23#[cfg(feature = "lowering")]
24pub(crate) mod linear;
25
26#[cfg(feature = "compile")]
27pub mod derive;
28
29#[cfg(feature = "compile")]
30pub use derive::CachedPositionPolicy;
31
32use crate::constraint::local::PlacementResolver;
33use crate::error::{GeometryError, GeometryResult};
34use crate::input::product::Product;
35use crate::transform::Transform;
36use crate::units::UnitScale;
37
38/// The world transform for one product, in metres.
39///
40/// Resolves the placement chain -- `IfcLocalPlacement`, `IfcGridPlacement`
41/// and `IfcLinearPlacement` links alike (#357, #362, #363) -- and converts
42/// the composed result once. A linear placement reads its cached
43/// `CartesianPosition`, and curved grid axes are refused by name: both
44/// need a curve evaluator, which `product_world_transform_with_evaluator`
45/// (feature `compile`) takes. A product with no `ObjectPlacement` is model-space, which the schema
46/// allows, so it yields the identity rather than an error.
47///
48/// Cyclic and over-deep chains are reported as errors rather than hanging or
49/// overflowing the stack, so a malformed file cannot lock up a viewer.
50///
51/// ```no_run
52/// # use ifc_model::{EntityId, Model};
53/// # use ifc_geometry::{product_world_transform, units::UnitScale};
54/// # fn demo(model: &Model, units: &UnitScale, wall: EntityId) {
55/// let world = product_world_transform(model, units, wall).unwrap();
56/// let [x, y, z] = world.origin;
57/// # let _ = (x, y, z);
58/// # }
59/// ```
60///
61/// Resolving many products reuses ancestor transforms through
62/// [`PlacementResolver`]; see [`products_world_transforms`] for the batch form,
63/// which is what a whole-model walk should use.
64pub fn product_world_transform(
65 model: &Model,
66 units: &UnitScale,
67 product: EntityId,
68) -> GeometryResult<Transform> {
69 let mut resolver = PlacementResolver::new();
70 resolve_with(
71 &mut resolver,
72 model,
73 units,
74 product,
75 LinearResolution::cache_only(),
76 )
77}
78
79/// [`product_world_transform`], deriving an `IfcLinearPlacement` through a
80/// caller-supplied evaluator (#353), and intersecting curved grid axes
81/// through it (#362).
82///
83/// A linear placement without a cached `CartesianPosition` is derived from
84/// its `RelativePlacement` with
85/// [`derive_linear_placement_transform`](derive::derive_linear_placement_transform);
86/// one with a cache is handled by `cached` ([`CachedPositionPolicy`], #354).
87/// Either is composed with the frame its basis curve is stated in (#357).
88/// An `IfcGridPlacement` whose axes are not straight is intersected through
89/// the evaluator. Every other placement resolves exactly as
90/// [`product_world_transform`] does, and the evaluator is never called for
91/// it.
92///
93/// # Errors
94///
95/// As [`product_world_transform`], plus the derivation's refusals (an
96/// `IfcParameterValue` on an alignment centreline is refused by name, #347)
97/// and [`GeometryError::CachedPlacementMismatch`] for a stale cache under
98/// [`CachedPositionPolicy::Verify`].
99#[cfg(feature = "compile")]
100pub fn product_world_transform_with_evaluator(
101 model: &Model,
102 units: &UnitScale,
103 product: EntityId,
104 evaluator: &dyn axiolid_curve_evaluate_contract::CurveEvaluator,
105 cached: CachedPositionPolicy,
106) -> GeometryResult<Transform> {
107 let mut resolver = PlacementResolver::new();
108 resolve_with(
109 &mut resolver,
110 model,
111 units,
112 product,
113 LinearResolution::derive(evaluator, cached),
114 )
115}
116
117/// How an `IfcLinearPlacement` is resolved: from its cache only, or, with
118/// the `compile` feature, through a caller-supplied evaluator. The same
119/// evaluator intersects curved grid axes (#362).
120#[derive(Debug, Clone, Copy)]
121pub(crate) struct LinearResolution<'e> {
122 #[cfg(feature = "compile")]
123 pub(crate) derivation: Option<derive::Derivation<'e>>,
124 #[cfg(not(feature = "compile"))]
125 cache_only: std::marker::PhantomData<&'e ()>,
126}
127
128impl<'e> LinearResolution<'e> {
129 /// The cached `CartesianPosition` or a refusal; no evaluation.
130 pub(crate) fn cache_only() -> Self {
131 Self {
132 #[cfg(feature = "compile")]
133 derivation: None,
134 #[cfg(not(feature = "compile"))]
135 cache_only: std::marker::PhantomData,
136 }
137 }
138
139 /// Derive through `evaluator`, treating a cache by `cached`.
140 #[cfg(feature = "compile")]
141 pub(crate) fn derive(
142 evaluator: &'e dyn axiolid_curve_evaluate_contract::CurveEvaluator,
143 cached: CachedPositionPolicy,
144 ) -> Self {
145 Self {
146 derivation: Some(derive::Derivation { evaluator, cached }),
147 }
148 }
149}
150
151/// World transforms for many products, sharing one placement cache.
152///
153/// Products in the same storey share the whole storey-building-site tail, so
154/// resolving each independently repeats that walk once per element. This
155/// resolves them against a single cache instead.
156///
157/// Errors are per-product: one malformed placement chain does not abort the
158/// others, because a viewer should still draw the rest of the building.
159pub fn products_world_transforms(
160 model: &Model,
161 units: &UnitScale,
162 products: impl IntoIterator<Item = EntityId>,
163) -> Vec<(EntityId, GeometryResult<Transform>)> {
164 let mut resolver = PlacementResolver::new();
165 products
166 .into_iter()
167 .map(|product| {
168 let resolved = resolve_with(
169 &mut resolver,
170 model,
171 units,
172 product,
173 LinearResolution::cache_only(),
174 );
175 (product, resolved)
176 })
177 .collect()
178}
179
180/// Shared body: resolve one product against a caller-owned resolver.
181pub(crate) fn resolve_with(
182 resolver: &mut PlacementResolver,
183 model: &Model,
184 units: &UnitScale,
185 product: EntityId,
186 linear: LinearResolution<'_>,
187) -> GeometryResult<Transform> {
188 let entity = model.get(product).ok_or(GeometryError::MissingEntity {
189 referrer: product,
190 missing: product,
191 })?;
192 let Some(placement) = Product::new(product, entity).object_placement() else {
193 return Ok(Transform::identity());
194 };
195 // Every IfcObjectPlacement kind resolves through the one walk (#363):
196 // local, grid (#362) and linear (#357) placements, each as a product's
197 // own placement or as another's PlacementRelTo.
198 let file_units = resolver.resolve(model, units, placement, linear)?;
199 Ok(file_units.to_metres(units))
200}
201
202#[cfg(test)]
203mod tests;