1use 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
36pub(crate) mod slot {
42 pub const PLACEMENT_REL_TO: usize = 0;
44 pub const RELATIVE_PLACEMENT: usize = 1;
46}
47
48#[derive(Debug, Clone, Copy)]
50pub struct LocalPlacement<'m> {
51 slots: Slots<'m>,
52}
53
54impl<'m> LocalPlacement<'m> {
55 pub fn new(id: EntityId, entity: &'m ifc_model::Entity) -> Self {
57 Self {
58 slots: Slots::new(id, entity),
59 }
60 }
61
62 pub fn id(&self) -> EntityId {
64 self.slots.id()
65 }
66
67 pub fn parent(&self) -> Option<EntityId> {
71 self.slots.opt_ref(slot::PLACEMENT_REL_TO)
72 }
73
74 pub fn relative_placement(&self) -> GeometryResult<EntityId> {
76 self.slots
77 .req_ref(slot::RELATIVE_PLACEMENT, "RelativePlacement")
78 }
79
80 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
88const MAX_CHAIN_DEPTH: usize = 64;
96
97#[derive(Debug, Default)]
124pub struct PlacementResolver {
125 cache: HashMap<EntityId, Transform>,
126}
127
128struct Walk<'a, 'e> {
130 model: &'a Model,
131 units: &'a UnitScale,
132 linear: LinearResolution<'e>,
133 active: Vec<EntityId>,
135}
136
137impl PlacementResolver {
138 pub fn new() -> Self {
140 Self::default()
141 }
142
143 pub fn cached(&self) -> usize {
145 self.cache.len()
146 }
147
148 pub fn world_transform(
162 &mut self,
163 model: &Model,
164 placement: EntityId,
165 ) -> GeometryResult<Transform> {
166 self.resolve(
169 model,
170 &UnitScale::SI,
171 placement,
172 LinearResolution::cache_only(),
173 )
174 }
175
176 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 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 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 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 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 #[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 let relative = Transform {
323 basis: relative.basis,
324 origin: relative.origin.map(|coordinate| coordinate / scale),
325 };
326 Ok(parent.compose(&relative))
327 }
328
329 #[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 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 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 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 #[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 #[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 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 #[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}