Skip to main content

ifc_geometry/resource/
resolve.rs

1//! Resolve a raw reference into a type-checked resource view.
2//!
3//! Curve, surface and solid views keep their raw `*_ref` getters, because a
4//! caller walking the graph often wants the id alone. The resolving accessors
5//! beside them all need the same two checks -- the reference is not dangling,
6//! and it names an entity of the declared type -- and doing those checks in one
7//! place keeps the errors identical everywhere:
8//!
9//! - a dangling reference is [`GeometryError::MissingEntity`] naming the
10//!   referrer, so the error points at the record that is wrong;
11//! - a reference to the wrong type is [`GeometryError::WrongEntityType`]
12//!   naming the target, never a view that silently misreads its slots.
13//!
14//! Only entity types are checked here. A view's own slot errors (a 1-element
15//! point, a zero direction) still surface when the caller reads it.
16//!
17//! An attribute typed by an abstract supertype (`IfcSurface`,
18//! `IfcBoundedCurve`) has no resolving accessor: it stays a reference,
19//! because choosing among the concrete subtypes is dispatch, and dispatch
20//! belongs to `lower`. `IfcProfileDef` has no view here either;
21//! `input::profile` owns profile reading.
22
23use crate::error::{GeometryError, GeometryResult};
24use crate::resource::direction::Direction;
25use crate::resource::placement::{
26    Axis1Placement, Axis2Placement, Axis2Placement2D, Axis2Placement3D,
27};
28use crate::resource::point::{
29    CartesianPoint, CartesianPointList, CartesianPointList2D, CartesianPointList3D,
30};
31use ifc_model::{Entity, EntityId, Model};
32
33/// Resolve a reference that must be an `IfcCartesianPoint`.
34pub fn cartesian_point<'m>(
35    model: &'m Model,
36    referrer: EntityId,
37    id: EntityId,
38) -> GeometryResult<CartesianPoint<'m>> {
39    let entity = typed(
40        model,
41        referrer,
42        id,
43        &["IFCCARTESIANPOINT"],
44        "IfcCartesianPoint",
45    )?;
46    Ok(CartesianPoint::new(id, entity))
47}
48
49/// Resolve every reference of a `LIST OF IfcCartesianPoint`, in order.
50///
51/// Stops at the first bad reference: a polyline with one dangling vertex has
52/// no defined shape, so a partial list would be a silent substitute.
53pub fn cartesian_points<'m>(
54    model: &'m Model,
55    referrer: EntityId,
56    ids: &[EntityId],
57) -> GeometryResult<Vec<CartesianPoint<'m>>> {
58    ids.iter()
59        .map(|&id| cartesian_point(model, referrer, id))
60        .collect()
61}
62
63/// Resolve a reference that must be an `IfcCartesianPointList3D`.
64pub fn cartesian_point_list_3d<'m>(
65    model: &'m Model,
66    referrer: EntityId,
67    id: EntityId,
68) -> GeometryResult<CartesianPointList3D<'m>> {
69    let entity = typed(
70        model,
71        referrer,
72        id,
73        &["IFCCARTESIANPOINTLIST3D"],
74        "IfcCartesianPointList3D",
75    )?;
76    Ok(CartesianPointList3D::new(id, entity))
77}
78
79/// Resolve a reference typed as the abstract `IfcCartesianPointList`.
80///
81/// The concrete subtype decides the row width, so it is carried in the
82/// returned enum instead of being guessed from the first row.
83pub fn cartesian_point_list<'m>(
84    model: &'m Model,
85    referrer: EntityId,
86    id: EntityId,
87) -> GeometryResult<CartesianPointList<'m>> {
88    let entity = typed(
89        model,
90        referrer,
91        id,
92        &["IFCCARTESIANPOINTLIST2D", "IFCCARTESIANPOINTLIST3D"],
93        "IfcCartesianPointList2D or IfcCartesianPointList3D",
94    )?;
95    Ok(if entity.is_type("IFCCARTESIANPOINTLIST2D") {
96        CartesianPointList::TwoD(CartesianPointList2D::new(id, entity))
97    } else {
98        CartesianPointList::ThreeD(CartesianPointList3D::new(id, entity))
99    })
100}
101
102/// Resolve a reference that must be an `IfcDirection`.
103///
104/// The view keeps the raw ratios; call [`Direction::unit`] to normalize.
105pub fn direction<'m>(
106    model: &'m Model,
107    referrer: EntityId,
108    id: EntityId,
109) -> GeometryResult<Direction<'m>> {
110    let entity = typed(model, referrer, id, &["IFCDIRECTION"], "IfcDirection")?;
111    Ok(Direction::new(id, entity))
112}
113
114/// Resolve a reference that must be an `IfcAxis1Placement`.
115pub fn axis1_placement<'m>(
116    model: &'m Model,
117    referrer: EntityId,
118    id: EntityId,
119) -> GeometryResult<Axis1Placement<'m>> {
120    let entity = typed(
121        model,
122        referrer,
123        id,
124        &["IFCAXIS1PLACEMENT"],
125        "IfcAxis1Placement",
126    )?;
127    Ok(Axis1Placement::new(id, entity))
128}
129
130/// Resolve a reference that must be an `IfcAxis2Placement3D`.
131pub fn axis2_placement_3d<'m>(
132    model: &'m Model,
133    referrer: EntityId,
134    id: EntityId,
135) -> GeometryResult<Axis2Placement3D<'m>> {
136    let entity = typed(
137        model,
138        referrer,
139        id,
140        &["IFCAXIS2PLACEMENT3D"],
141        "IfcAxis2Placement3D",
142    )?;
143    Ok(Axis2Placement3D::new(id, entity))
144}
145
146/// Resolve a reference typed as the `IfcAxis2Placement` SELECT.
147///
148/// `IfcAxis1Placement` is rejected, as in
149/// [`crate::resource::placement::axis_placement_transform`]: it has no local
150/// X, so it is not a member of the select.
151pub fn axis2_placement<'m>(
152    model: &'m Model,
153    referrer: EntityId,
154    id: EntityId,
155) -> GeometryResult<Axis2Placement<'m>> {
156    let entity = typed(
157        model,
158        referrer,
159        id,
160        &["IFCAXIS2PLACEMENT2D", "IFCAXIS2PLACEMENT3D"],
161        "IfcAxis2Placement2D or IfcAxis2Placement3D",
162    )?;
163    Ok(if entity.is_type("IFCAXIS2PLACEMENT2D") {
164        Axis2Placement::TwoD(Axis2Placement2D::new(id, entity))
165    } else {
166        Axis2Placement::ThreeD(Axis2Placement3D::new(id, entity))
167    })
168}
169
170/// Look `id` up and require one of `accepted` (upper-case STEP names).
171fn typed<'m>(
172    model: &'m Model,
173    referrer: EntityId,
174    id: EntityId,
175    accepted: &[&str],
176    expected: &'static str,
177) -> GeometryResult<&'m Entity> {
178    let entity = model.get(id).ok_or(GeometryError::MissingEntity {
179        referrer,
180        missing: id,
181    })?;
182    if accepted.iter().any(|name| entity.is_type(name)) {
183        Ok(entity)
184    } else {
185        Err(GeometryError::WrongEntityType {
186            entity: id,
187            actual: entity.type_name.to_string(),
188            expected,
189        })
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196    use ifc_model::Value;
197
198    fn reals(values: &[f64]) -> Value {
199        Value::List(values.iter().copied().map(Value::Real).collect())
200    }
201
202    fn model() -> Model {
203        let mut m = Model::new();
204        m.insert(
205            EntityId(1),
206            Entity::new("IFCCARTESIANPOINT", vec![reals(&[1.0, 2.0])]),
207        );
208        m.insert(
209            EntityId(2),
210            Entity::new("IFCDIRECTION", vec![reals(&[1.0, 0.0])]),
211        );
212        m.insert(
213            EntityId(3),
214            Entity::new("IFCAXIS2PLACEMENT2D", vec![Value::Ref(EntityId(1))]),
215        );
216        m.insert(
217            EntityId(4),
218            Entity::new(
219                "IFCCARTESIANPOINTLIST2D",
220                vec![Value::List(vec![reals(&[0.0, 0.0])])],
221            ),
222        );
223        m
224    }
225
226    #[test]
227    fn select_resolution_keeps_the_concrete_subtype() {
228        let m = model();
229        let placement = axis2_placement(&m, EntityId(9), EntityId(3)).unwrap();
230        assert!(matches!(placement, Axis2Placement::TwoD(_)));
231        let list = cartesian_point_list(&m, EntityId(9), EntityId(4)).unwrap();
232        assert_eq!(list.dimension(), 2);
233    }
234
235    #[test]
236    fn a_dangling_reference_names_the_referrer_not_the_target() {
237        let m = model();
238        let err = direction(&m, EntityId(9), EntityId(99)).unwrap_err();
239        assert!(matches!(
240            err,
241            GeometryError::MissingEntity {
242                referrer: EntityId(9),
243                missing: EntityId(99)
244            }
245        ));
246    }
247
248    #[test]
249    fn a_wrong_type_names_the_target_and_the_expected_family() {
250        let m = model();
251        let err = axis2_placement(&m, EntityId(9), EntityId(2)).unwrap_err();
252        assert!(matches!(
253            err,
254            GeometryError::WrongEntityType {
255                entity: EntityId(2),
256                expected: "IfcAxis2Placement2D or IfcAxis2Placement3D",
257                ..
258            }
259        ));
260    }
261
262    /// One bad vertex fails the whole list rather than dropping the vertex.
263    #[test]
264    fn a_point_list_with_one_bad_reference_fails_as_a_whole() {
265        let m = model();
266        let err = cartesian_points(&m, EntityId(9), &[EntityId(1), EntityId(2)]).unwrap_err();
267        assert!(matches!(err, GeometryError::WrongEntityType { .. }));
268        assert_eq!(
269            cartesian_points(&m, EntityId(9), &[EntityId(1)])
270                .unwrap()
271                .len(),
272            1
273        );
274    }
275}