Skip to main content

ifc_geometry/resource/
placement.rs

1//! `IfcPlacement` and its three subtypes: where a local coordinate system is.
2//!
3//! # What the schema actually says
4//!
5//! `IfcPlacement` contributes `Location` (an `IfcCartesianPoint`) and nothing
6//! else. Its subtypes add axes:
7//!
8//! | Entity | Adds | Meaning |
9//! | --- | --- | --- |
10//! | `IfcAxis1Placement` | `Axis` | one direction: a rotation/extrusion axis |
11//! | `IfcAxis2Placement2D` | `RefDirection` | local X in the plane |
12//! | `IfcAxis2Placement3D` | `Axis`, `RefDirection` | local Z and approximate local X |
13//!
14//! Because `Location` is inherited, it is **slot 0 in every subtype** and the
15//! subtype's own attributes start at 1. Using local indices puts `Axis` where
16//! `Location` is, which produces geometry that is placed plausibly but wrongly
17//! -- the worst failure mode there is.
18//!
19//! # RefDirection is only approximate
20//!
21//! `IfcAxis2Placement3D` explicitly permits `Axis` and `RefDirection` to be
22//! non-perpendicular; the derived `P` runs `IfcFirstProjAxis`, which projects
23//! `RefDirection` onto the plane normal to `Axis`. That projection lives in
24//! [`crate::transform::Transform::from_axes`] and is not repeated here.
25//!
26//! # Both axes are optional, and so is neither
27//!
28//! `AxisAndRefDirProvision` says `NOT (EXISTS(Axis) XOR EXISTS(RefDirection))`
29//! -- give both or give neither. Files break this rule, so this module accepts
30//! one alone and lets `from_axes` supply the schema default for the other
31//! (global Z for `Axis`, projected global X for `RefDirection`) rather than
32//! rejecting a file over a WHERE rule that costs nothing to tolerate.
33
34use crate::error::{GeometryError, GeometryResult};
35use crate::resource::direction::resolve_unit;
36use crate::resource::point::cartesian_point_3d;
37use crate::slots::Slots;
38use crate::transform::Transform;
39use ifc_model::{Entity, EntityId, Model};
40
41/// Attribute slots as ABSOLUTE STEP positions, inherited attributes first.
42pub(crate) mod slot {
43    /// `Location : IfcCartesianPoint`, declared by `IfcPlacement`.
44    ///
45    /// Inherited, therefore slot 0 of `IfcAxis1Placement`,
46    /// `IfcAxis2Placement2D` and `IfcAxis2Placement3D` alike.
47    pub const LOCATION: usize = 0;
48
49    /// `IfcAxis1Placement`.
50    pub mod axis1 {
51        /// `Axis : OPTIONAL IfcDirection` (after inherited `Location`).
52        pub const AXIS: usize = 1;
53    }
54
55    /// `IfcAxis2Placement2D`.
56    pub mod axis2_2d {
57        /// `RefDirection : OPTIONAL IfcDirection` (after inherited `Location`).
58        pub const REF_DIRECTION: usize = 1;
59    }
60
61    /// `IfcAxis2Placement3D`.
62    pub mod axis2_3d {
63        /// `Axis : OPTIONAL IfcDirection` (after inherited `Location`).
64        pub const AXIS: usize = 1;
65        /// `RefDirection : OPTIONAL IfcDirection`.
66        pub const REF_DIRECTION: usize = 2;
67    }
68}
69
70/// The part of a placement every subtype shares: its `Location`.
71///
72/// Exists so the three subtype views do not each re-derive location handling,
73/// and so a caller holding an unknown `IfcPlacement` can still read the origin
74/// without dispatching on the concrete type.
75#[derive(Debug, Clone, Copy)]
76pub struct Placement<'m> {
77    slots: Slots<'m>,
78}
79
80impl<'m> Placement<'m> {
81    /// Wrap an entity assumed to be an `IfcPlacement` subtype.
82    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
83        Self {
84            slots: Slots::new(id, entity),
85        }
86    }
87
88    /// The entity id.
89    pub fn id(&self) -> EntityId {
90        self.slots.id()
91    }
92
93    /// The `IfcCartesianPoint` reference giving the origin.
94    pub fn location_ref(&self) -> GeometryResult<EntityId> {
95        self.slots.req_ref(slot::LOCATION, "Location")
96    }
97
98    /// The origin in the parent coordinate system, promoted to 3D.
99    ///
100    /// A 2D `Location` (legal under `IfcAxis2Placement2D`) becomes `z = 0`,
101    /// which is the correct reading: the 2D system lies in the parent's
102    /// z=0 plane.
103    pub fn location(&self, model: &'m Model) -> GeometryResult<[f64; 3]> {
104        cartesian_point_3d(model, self.id(), self.location_ref()?)
105    }
106}
107
108/// A borrowed view of an `IfcAxis1Placement`: a point and one axis.
109///
110/// Used where only a single direction is meaningful -- a revolution axis, for
111/// example. There is no local X, so this does **not** define a full coordinate
112/// system and deliberately offers no `Transform`: manufacturing one would
113/// invent an arbitrary rotation about the axis.
114#[derive(Debug, Clone, Copy)]
115pub struct Axis1Placement<'m> {
116    placement: Placement<'m>,
117}
118
119impl<'m> Axis1Placement<'m> {
120    /// Wrap an entity assumed to be an `IfcAxis1Placement`.
121    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
122        Self {
123            placement: Placement::new(id, entity),
124        }
125    }
126
127    /// The entity id.
128    pub fn id(&self) -> EntityId {
129        self.placement.id()
130    }
131
132    /// The origin, promoted to 3D.
133    pub fn location(&self, model: &'m Model) -> GeometryResult<[f64; 3]> {
134        self.placement.location(model)
135    }
136
137    /// The axis direction, normalized; global Z when `Axis` is absent.
138    ///
139    /// The default matches the derived `Z` attribute:
140    /// `NVL(IfcNormalise(Axis), IfcDirection([0,0,1]))`.
141    pub fn axis(&self, model: &'m Model) -> GeometryResult<[f64; 3]> {
142        match self.placement.slots.opt_ref(slot::axis1::AXIS) {
143            Some(id) => resolve_unit(model, self.id(), id),
144            None => Ok([0.0, 0.0, 1.0]),
145        }
146    }
147}
148
149/// A borrowed view of an `IfcAxis2Placement2D`: origin plus local X.
150///
151/// The local Y is not stored: it is the 90-degree counter-clockwise rotation
152/// of X (`IfcOrthogonalComplement`), so it is derived here rather than read.
153#[derive(Debug, Clone, Copy)]
154pub struct Axis2Placement2D<'m> {
155    placement: Placement<'m>,
156}
157
158impl<'m> Axis2Placement2D<'m> {
159    /// Wrap an entity assumed to be an `IfcAxis2Placement2D`.
160    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
161        Self {
162            placement: Placement::new(id, entity),
163        }
164    }
165
166    /// The entity id.
167    pub fn id(&self) -> EntityId {
168        self.placement.id()
169    }
170
171    /// The origin, promoted to 3D (`z = 0`).
172    pub fn location(&self, model: &'m Model) -> GeometryResult<[f64; 3]> {
173        self.placement.location(model)
174    }
175
176    /// The local X direction, normalized; global X when absent.
177    pub fn ref_direction(&self, model: &'m Model) -> GeometryResult<[f64; 3]> {
178        match self.placement.slots.opt_ref(slot::axis2_2d::REF_DIRECTION) {
179            Some(id) => resolve_unit(model, self.id(), id),
180            None => Ok([1.0, 0.0, 0.0]),
181        }
182    }
183
184    /// The placement as a 3D transform in the z=0 plane.
185    ///
186    /// Local Z is forced to global Z so the derived Y matches
187    /// `IfcOrthogonalComplement` (`[-x2, x1]`), i.e. X rotated a quarter turn
188    /// counter-clockwise. Any other Z would silently mirror 2D profiles.
189    pub fn transform(&self, model: &'m Model) -> GeometryResult<Transform> {
190        let origin = self.location(model)?;
191        let x = self.ref_direction(model)?;
192        Transform::from_axes(origin, Some([0.0, 0.0, 1.0]), Some(x)).ok_or_else(|| {
193            self.placement
194                .slots
195                .degenerate("RefDirection is parallel to the plane normal or zero-length")
196        })
197    }
198}
199
200/// A borrowed view of an `IfcAxis2Placement3D`: origin, local Z, local X.
201#[derive(Debug, Clone, Copy)]
202pub struct Axis2Placement3D<'m> {
203    placement: Placement<'m>,
204}
205
206impl<'m> Axis2Placement3D<'m> {
207    /// Wrap an entity assumed to be an `IfcAxis2Placement3D`.
208    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
209        Self {
210            placement: Placement::new(id, entity),
211        }
212    }
213
214    /// The entity id.
215    pub fn id(&self) -> EntityId {
216        self.placement.id()
217    }
218
219    /// The origin, promoted to 3D.
220    pub fn location(&self, model: &'m Model) -> GeometryResult<[f64; 3]> {
221        self.placement.location(model)
222    }
223
224    /// The local Z direction if `Axis` is present, normalized.
225    ///
226    /// `None` means the file omitted it, which is legal and means global Z.
227    /// The distinction is kept rather than defaulted here so
228    /// [`Self::transform`] can hand `from_axes` the real "absent" case and get
229    /// the spec's paired default for `RefDirection` too.
230    pub fn axis(&self, model: &'m Model) -> GeometryResult<Option<[f64; 3]>> {
231        self.optional_direction(model, slot::axis2_3d::AXIS)
232    }
233
234    /// The approximate local X direction if `RefDirection` is present.
235    ///
236    /// "Approximate" because the schema only requires it to be non-parallel to
237    /// `Axis`; the true X is its projection onto the plane normal to `Axis`.
238    pub fn ref_direction(&self, model: &'m Model) -> GeometryResult<Option<[f64; 3]>> {
239        self.optional_direction(model, slot::axis2_3d::REF_DIRECTION)
240    }
241
242    /// The placement as an orthonormal transform.
243    ///
244    /// Delegates the Gram-Schmidt projection to
245    /// [`Transform::from_axes`], which also supplies the schema defaults when
246    /// `Axis` or `RefDirection` is absent. Parallel axes are
247    /// [`crate::GeometryError::Degenerate`] -- they define no unique frame, and the
248    /// schema's `AxisToRefDirPosition` rule forbids them.
249    pub fn transform(&self, model: &'m Model) -> GeometryResult<Transform> {
250        let origin = self.location(model)?;
251        let axis = self.axis(model)?;
252        let ref_direction = self.ref_direction(model)?;
253        Transform::from_axes(origin, axis, ref_direction).ok_or_else(|| {
254            self.placement
255                .slots
256                .degenerate("Axis and RefDirection are parallel, so they define no frame")
257        })
258    }
259
260    /// Read an optional direction slot, normalizing when present.
261    fn optional_direction(
262        &self,
263        model: &'m Model,
264        index: usize,
265    ) -> GeometryResult<Option<[f64; 3]>> {
266        match self.placement.slots.opt_ref(index) {
267            Some(id) => resolve_unit(model, self.id(), id).map(Some),
268            None => Ok(None),
269        }
270    }
271}
272
273/// A member of the `IfcAxis2Placement` SELECT, dispatched once.
274///
275/// Slots such as `IfcConic.Position` are typed by the select, so the view is
276/// 2D or 3D depending on the file. Produced by
277/// [`crate::resource::resolve::axis2_placement`].
278#[derive(Debug, Clone, Copy)]
279pub enum Axis2Placement<'m> {
280    /// An `IfcAxis2Placement2D`.
281    TwoD(Axis2Placement2D<'m>),
282    /// An `IfcAxis2Placement3D`.
283    ThreeD(Axis2Placement3D<'m>),
284}
285
286impl<'m> Axis2Placement<'m> {
287    /// The entity id.
288    pub fn id(&self) -> EntityId {
289        match self {
290            Self::TwoD(p) => p.id(),
291            Self::ThreeD(p) => p.id(),
292        }
293    }
294
295    /// The origin, promoted to 3D.
296    pub fn location(&self, model: &'m Model) -> GeometryResult<[f64; 3]> {
297        match self {
298            Self::TwoD(p) => p.location(model),
299            Self::ThreeD(p) => p.location(model),
300        }
301    }
302
303    /// The placement as a transform; a 2D placement lies in the z=0 plane.
304    pub fn transform(&self, model: &'m Model) -> GeometryResult<Transform> {
305        match self {
306            Self::TwoD(p) => p.transform(model),
307            Self::ThreeD(p) => p.transform(model),
308        }
309    }
310}
311
312/// Resolve any `IfcAxis2Placement` reference to a transform.
313///
314/// `IfcAxis2Placement` is a SELECT over the 2D and 3D forms, so a slot typed
315/// that way may hold either and every consumer has to dispatch. Doing it once
316/// here keeps that dispatch from being re-invented -- and the 2D case quietly
317/// mishandled -- at each call site.
318///
319/// `IfcAxis1Placement` is rejected rather than coerced: it carries one axis and
320/// no local X, so any frame built from it would invent a rotation.
321pub fn axis_placement_transform(
322    model: &Model,
323    id: EntityId,
324    entity: &Entity,
325) -> GeometryResult<Transform> {
326    match entity.type_name.as_ref() {
327        "IFCAXIS2PLACEMENT3D" => Axis2Placement3D::new(id, entity).transform(model),
328        "IFCAXIS2PLACEMENT2D" => Axis2Placement2D::new(id, entity).transform(model),
329        other => Err(GeometryError::WrongEntityType {
330            entity: id,
331            actual: other.to_string(),
332            expected: "IfcAxis2Placement2D or IfcAxis2Placement3D",
333        }),
334    }
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340    use ifc_model::Value;
341
342    fn coords(values: &[f64]) -> Value {
343        Value::List(values.iter().copied().map(Value::Real).collect())
344    }
345
346    fn model_with_frame() -> Model {
347        let mut model = Model::new();
348        model.insert(
349            EntityId(1),
350            Entity::new("IFCCARTESIANPOINT", vec![coords(&[1.0, 2.0, 3.0])]),
351        );
352        model.insert(
353            EntityId(2),
354            Entity::new("IFCDIRECTION", vec![coords(&[0.0, 0.0, 1.0])]),
355        );
356        model.insert(
357            EntityId(3),
358            Entity::new("IFCDIRECTION", vec![coords(&[1.0, 0.0, 0.0])]),
359        );
360        model
361    }
362
363    fn close(a: [f64; 3], b: [f64; 3]) -> bool {
364        a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9)
365    }
366
367    /// `Location` is inherited from `IfcPlacement`, so it must be read at
368    /// slot 0 even though the subtype declares `Axis` first in its own list.
369    #[test]
370    fn inherited_location_is_slot_zero_not_the_subtypes_first_attribute() {
371        let model = model_with_frame();
372        let e = Entity::new(
373            "IFCAXIS2PLACEMENT3D",
374            vec![
375                Value::Ref(EntityId(1)),
376                Value::Ref(EntityId(2)),
377                Value::Ref(EntityId(3)),
378            ],
379        );
380        let p = Axis2Placement3D::new(EntityId(10), &e);
381        assert_eq!(p.location(&model).unwrap(), [1.0, 2.0, 3.0]);
382        assert_eq!(p.axis(&model).unwrap(), Some([0.0, 0.0, 1.0]));
383    }
384
385    /// Both are optional; absent must mean global Z and X, not an error.
386    #[test]
387    fn absent_axis_and_ref_direction_default_to_global_z_and_x() {
388        let model = model_with_frame();
389        let e = Entity::new(
390            "IFCAXIS2PLACEMENT3D",
391            vec![Value::Ref(EntityId(1)), Value::Null, Value::Null],
392        );
393        let p = Axis2Placement3D::new(EntityId(10), &e);
394        assert_eq!(p.axis(&model).unwrap(), None);
395        assert_eq!(p.ref_direction(&model).unwrap(), None);
396
397        let t = p.transform(&model).unwrap();
398        assert!(close(t.basis[0], [1.0, 0.0, 0.0]));
399        assert!(close(t.basis[1], [0.0, 1.0, 0.0]));
400        assert!(close(t.basis[2], [0.0, 0.0, 1.0]));
401        assert_eq!(t.origin, [1.0, 2.0, 3.0]);
402    }
403
404    /// A short record (trailing optionals simply omitted) is common and must
405    /// behave exactly like explicit `$`.
406    #[test]
407    fn a_record_missing_its_trailing_optionals_still_places() {
408        let model = model_with_frame();
409        let e = Entity::new("IFCAXIS2PLACEMENT3D", vec![Value::Ref(EntityId(1))]);
410        let t = Axis2Placement3D::new(EntityId(10), &e)
411            .transform(&model)
412            .unwrap();
413        assert_eq!(t.origin, [1.0, 2.0, 3.0]);
414        assert!(close(t.basis[2], [0.0, 0.0, 1.0]));
415    }
416
417    /// The spec derives X by projecting RefDirection onto the plane normal to
418    /// Axis. Skipping that yields a sheared basis that looks almost right.
419    #[test]
420    fn non_perpendicular_ref_direction_is_projected_into_an_orthonormal_basis() {
421        let mut model = model_with_frame();
422        // RefDirection tilted 45 degrees out of the XY plane.
423        model.insert(
424            EntityId(4),
425            Entity::new("IFCDIRECTION", vec![coords(&[1.0, 0.0, 1.0])]),
426        );
427        let e = Entity::new(
428            "IFCAXIS2PLACEMENT3D",
429            vec![
430                Value::Ref(EntityId(1)),
431                Value::Ref(EntityId(2)),
432                Value::Ref(EntityId(4)),
433            ],
434        );
435        let t = Axis2Placement3D::new(EntityId(10), &e)
436            .transform(&model)
437            .unwrap();
438        assert!(close(t.basis[0], [1.0, 0.0, 0.0]), "got {:?}", t.basis[0]);
439        assert!(
440            t.basis[0]
441                .iter()
442                .zip(t.basis[2])
443                .map(|(a, b)| a * b)
444                .sum::<f64>()
445                .abs()
446                < 1e-12,
447            "X must end up perpendicular to Z"
448        );
449    }
450
451    /// Parallel axes define no unique frame; the result would be NaN.
452    #[test]
453    fn axis_parallel_to_ref_direction_is_degenerate() {
454        let model = model_with_frame();
455        let e = Entity::new(
456            "IFCAXIS2PLACEMENT3D",
457            vec![
458                Value::Ref(EntityId(1)),
459                Value::Ref(EntityId(2)),
460                Value::Ref(EntityId(2)),
461            ],
462        );
463        let err = Axis2Placement3D::new(EntityId(10), &e)
464            .transform(&model)
465            .unwrap_err();
466        assert!(matches!(err, GeometryError::Degenerate { .. }), "{err}");
467    }
468
469    /// A zero-length Axis must fail before it can produce NaN components.
470    #[test]
471    fn zero_length_axis_is_degenerate_rather_than_nan() {
472        let mut model = model_with_frame();
473        model.insert(
474            EntityId(5),
475            Entity::new("IFCDIRECTION", vec![coords(&[0.0, 0.0, 0.0])]),
476        );
477        let e = Entity::new(
478            "IFCAXIS2PLACEMENT3D",
479            vec![
480                Value::Ref(EntityId(1)),
481                Value::Ref(EntityId(5)),
482                Value::Null,
483            ],
484        );
485        let err = Axis2Placement3D::new(EntityId(10), &e)
486            .transform(&model)
487            .unwrap_err();
488        assert!(matches!(err, GeometryError::Degenerate { .. }), "{err}");
489    }
490
491    /// The schema pairs Axis and RefDirection, but files give one alone; the
492    /// spec default for the other is well defined, so tolerate it.
493    #[test]
494    fn only_one_of_the_paired_axes_still_yields_a_frame() {
495        let model = model_with_frame();
496        let e = Entity::new(
497            "IFCAXIS2PLACEMENT3D",
498            vec![
499                Value::Ref(EntityId(1)),
500                Value::Null,
501                Value::Ref(EntityId(3)),
502            ],
503        );
504        let t = Axis2Placement3D::new(EntityId(10), &e)
505            .transform(&model)
506            .unwrap();
507        assert!(close(t.basis[0], [1.0, 0.0, 0.0]));
508        assert!(close(t.basis[2], [0.0, 0.0, 1.0]));
509    }
510
511    /// 2D placements keep `RefDirection` at slot 1, after inherited Location.
512    #[test]
513    fn two_d_placement_derives_y_as_a_quarter_turn_from_x() {
514        let mut model = Model::new();
515        model.insert(
516            EntityId(1),
517            Entity::new("IFCCARTESIANPOINT", vec![coords(&[4.0, 5.0])]),
518        );
519        model.insert(
520            EntityId(2),
521            Entity::new("IFCDIRECTION", vec![coords(&[0.0, 1.0])]),
522        );
523        let e = Entity::new(
524            "IFCAXIS2PLACEMENT2D",
525            vec![Value::Ref(EntityId(1)), Value::Ref(EntityId(2))],
526        );
527        let t = Axis2Placement2D::new(EntityId(10), &e)
528            .transform(&model)
529            .unwrap();
530        assert_eq!(t.origin, [4.0, 5.0, 0.0], "2D location pads z with 0");
531        assert!(close(t.basis[0], [0.0, 1.0, 0.0]));
532        assert!(
533            close(t.basis[1], [-1.0, 0.0, 0.0]),
534            "Y must be X rotated a quarter turn counter-clockwise, got {:?}",
535            t.basis[1]
536        );
537    }
538
539    #[test]
540    fn two_d_placement_without_ref_direction_defaults_to_global_x() {
541        let mut model = Model::new();
542        model.insert(
543            EntityId(1),
544            Entity::new("IFCCARTESIANPOINT", vec![coords(&[0.0, 0.0])]),
545        );
546        let e = Entity::new("IFCAXIS2PLACEMENT2D", vec![Value::Ref(EntityId(1))]);
547        let p = Axis2Placement2D::new(EntityId(10), &e);
548        assert_eq!(p.ref_direction(&model).unwrap(), [1.0, 0.0, 0.0]);
549        assert!(p.transform(&model).unwrap().is_identity(1e-12));
550    }
551
552    /// `IfcAxis1Placement` has only one axis, so it defines no full frame and
553    /// exposes no transform; the axis default is global Z.
554    #[test]
555    fn axis1_placement_defaults_its_axis_to_global_z() {
556        let model = model_with_frame();
557        let e = Entity::new("IFCAXIS1PLACEMENT", vec![Value::Ref(EntityId(1))]);
558        let p = Axis1Placement::new(EntityId(10), &e);
559        assert_eq!(p.axis(&model).unwrap(), [0.0, 0.0, 1.0]);
560        assert_eq!(p.location(&model).unwrap(), [1.0, 2.0, 3.0]);
561    }
562
563    #[test]
564    fn axis1_placement_reads_its_axis_after_the_inherited_location() {
565        let model = model_with_frame();
566        let e = Entity::new(
567            "IFCAXIS1PLACEMENT",
568            vec![Value::Ref(EntityId(1)), Value::Ref(EntityId(3))],
569        );
570        assert_eq!(
571            Axis1Placement::new(EntityId(10), &e).axis(&model).unwrap(),
572            [1.0, 0.0, 0.0]
573        );
574    }
575
576    #[test]
577    fn a_missing_location_names_the_entity_and_attribute() {
578        let model = Model::new();
579        let e = Entity::new("IFCAXIS2PLACEMENT3D", vec![]);
580        let err = Axis2Placement3D::new(EntityId(77), &e)
581            .location(&model)
582            .unwrap_err();
583        assert!(err.to_string().contains("#77"), "got: {err}");
584        assert!(err.to_string().contains("Location"), "got: {err}");
585    }
586
587    #[test]
588    fn a_dangling_location_reference_names_the_placement_as_referrer() {
589        let model = Model::new();
590        let e = Entity::new("IFCAXIS2PLACEMENT3D", vec![Value::Ref(EntityId(99))]);
591        let err = Axis2Placement3D::new(EntityId(7), &e)
592            .location(&model)
593            .unwrap_err();
594        assert_eq!(err.entity(), Some(EntityId(7)));
595    }
596}