Skip to main content

ifc_geometry/curve/
conic.rs

1//! `IfcConic` subtypes: `IfcCircle` and `IfcEllipse`.
2//!
3//! # Shared shape
4//!
5//! `IfcConic` contributes exactly one attribute, `Position`, which is an
6//! `IfcAxis2Placement` *select*: an `IfcAxis2Placement2D` for a planar conic
7//! or an `IfcAxis2Placement3D` for one in space. Both subtypes therefore read
8//! `Position` from slot 0 and their own radii from slot 1 onwards.
9//!
10//! # Why radii are validated here
11//!
12//! `IfcPositiveLengthMeasure` is a *constrained type*, not a Rust type: STEP
13//! parsers do not enforce it and real exporters emit zero-radius circles for
14//! degenerate sweeps. A zero radius reaches a kernel as a division by zero or
15//! a NaN vertex thousands of entities later. Rejecting it at the view boundary
16//! turns an unfindable numerical bug into a located [`crate::GeometryError`].
17//!
18//! Note that IFC constrains the two ellipse semi-axes only to be positive. It
19//! does *not* require `SemiAxis1 >= SemiAxis2`, so a "prolate" ellipse whose
20//! major axis is the local Y direction is legal and must not be normalised
21//! away: the placement's `RefDirection` fixes which axis is which.
22
23use crate::error::GeometryResult;
24use crate::resource::placement::Axis2Placement;
25use crate::resource::resolve;
26use crate::slots::Slots;
27use ifc_model::{Entity, EntityId, Model};
28
29/// `IfcCircle` attribute slots.
30///
31/// From IFC4 ADD2 TC1: slot 0 `Position` is inherited from `IfcConic`; slot 1
32/// `Radius` is the subtype's own.
33pub(crate) mod circle_slot {
34    /// `Position`: `IfcAxis2Placement` (2D or 3D), from `IfcConic`.
35    pub const POSITION: usize = 0;
36    /// `Radius`: `IfcPositiveLengthMeasure`.
37    pub const RADIUS: usize = 1;
38}
39
40/// `IfcEllipse` attribute slots.
41///
42/// From IFC4 ADD2 TC1: slot 0 `Position` is inherited from `IfcConic`.
43pub(crate) mod ellipse_slot {
44    /// `Position`: `IfcAxis2Placement` (2D or 3D), from `IfcConic`.
45    pub const POSITION: usize = 0;
46    /// `SemiAxis1`: extent along the placement's local X direction.
47    pub const SEMI_AXIS_1: usize = 1;
48    /// `SemiAxis2`: extent along the placement's local Y direction.
49    pub const SEMI_AXIS_2: usize = 2;
50}
51
52/// A borrowed view of an `IfcCircle`.
53#[derive(Debug, Clone, Copy)]
54pub struct Circle<'m> {
55    slots: Slots<'m>,
56}
57
58impl<'m> Circle<'m> {
59    /// Wrap an entity known to be an `IfcCircle`.
60    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
61        Self {
62            slots: Slots::new(id, entity),
63        }
64    }
65
66    /// The entity id.
67    pub fn id(&self) -> EntityId {
68        self.slots.id()
69    }
70
71    /// The `IfcAxis2Placement` reference locating the circle.
72    ///
73    /// May resolve to either an `IfcAxis2Placement2D` or an
74    /// `IfcAxis2Placement3D`; the select is not narrowed by the schema and
75    /// both occur in practice for the same geometry depending on whether the
76    /// circle is a profile outline or a swept directrix.
77    pub fn position_ref(&self) -> GeometryResult<EntityId> {
78        self.slots.req_ref(circle_slot::POSITION, "Position")
79    }
80
81    /// The placement as a typed view, resolved from the model.
82    ///
83    /// The select is not narrowed, so the result keeps whichever of the 2D
84    /// or 3D forms the file wrote; [`Axis2Placement::transform`] handles both.
85    pub fn position<'v>(&self, model: &'v Model) -> GeometryResult<Axis2Placement<'v>> {
86        resolve::axis2_placement(model, self.id(), self.position_ref()?)
87    }
88
89    /// The radius, guaranteed positive.
90    ///
91    /// A zero or negative radius is [`crate::GeometryError::Degenerate`]: the
92    /// file parses but the circle does not exist.
93    pub fn radius(&self) -> GeometryResult<f64> {
94        let r = self.slots.req_f64(circle_slot::RADIUS, "Radius")?;
95        if r > 0.0 {
96            Ok(r)
97        } else {
98            Err(self
99                .slots
100                .degenerate(format!("Radius must be positive, found {r}")))
101        }
102    }
103}
104
105/// A borrowed view of an `IfcEllipse`.
106#[derive(Debug, Clone, Copy)]
107pub struct Ellipse<'m> {
108    slots: Slots<'m>,
109}
110
111impl<'m> Ellipse<'m> {
112    /// Wrap an entity known to be an `IfcEllipse`.
113    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
114        Self {
115            slots: Slots::new(id, entity),
116        }
117    }
118
119    /// The entity id.
120    pub fn id(&self) -> EntityId {
121        self.slots.id()
122    }
123
124    /// The `IfcAxis2Placement` reference locating the ellipse.
125    pub fn position_ref(&self) -> GeometryResult<EntityId> {
126        self.slots.req_ref(ellipse_slot::POSITION, "Position")
127    }
128
129    /// The placement as a typed view, resolved from the model.
130    ///
131    /// Its local X is the `SemiAxis1` direction, so the ellipse's orientation
132    /// is only known once this is resolved.
133    pub fn position<'v>(&self, model: &'v Model) -> GeometryResult<Axis2Placement<'v>> {
134        resolve::axis2_placement(model, self.id(), self.position_ref()?)
135    }
136
137    /// Semi-axis along the placement's local X direction, guaranteed positive.
138    pub fn semi_axis_1(&self) -> GeometryResult<f64> {
139        self.positive(ellipse_slot::SEMI_AXIS_1, "SemiAxis1")
140    }
141
142    /// Semi-axis along the placement's local Y direction, guaranteed positive.
143    ///
144    /// May legitimately exceed [`Self::semi_axis_1`]; IFC does not order them.
145    pub fn semi_axis_2(&self) -> GeometryResult<f64> {
146        self.positive(ellipse_slot::SEMI_AXIS_2, "SemiAxis2")
147    }
148
149    /// Both semi-axes in declaration order.
150    ///
151    /// Offered because a kernel almost always needs the pair together, and
152    /// fetching them separately doubles the chance of a caller swapping them.
153    pub fn semi_axes(&self) -> GeometryResult<(f64, f64)> {
154        Ok((self.semi_axis_1()?, self.semi_axis_2()?))
155    }
156
157    fn positive(&self, index: usize, name: &'static str) -> GeometryResult<f64> {
158        let v = self.slots.req_f64(index, name)?;
159        if v > 0.0 {
160            Ok(v)
161        } else {
162            Err(self
163                .slots
164                .degenerate(format!("{name} must be positive, found {v}")))
165        }
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172    use ifc_model::Value;
173
174    fn circle(radius: Value) -> Entity {
175        Entity::new("IFCCIRCLE", vec![Value::Ref(EntityId(5)), radius])
176    }
177
178    fn ellipse(a: f64, b: f64) -> Entity {
179        Entity::new(
180            "IFCELLIPSE",
181            vec![Value::Ref(EntityId(5)), Value::Real(a), Value::Real(b)],
182        )
183    }
184
185    fn placement_model(type_name: &str) -> Model {
186        let mut model = Model::new();
187        let coords = Value::List(vec![Value::Real(1.0), Value::Real(2.0)]);
188        model.insert(EntityId(4), Entity::new("IFCCARTESIANPOINT", vec![coords]));
189        let placement = Entity::new(type_name, vec![Value::Ref(EntityId(4))]);
190        model.insert(EntityId(5), placement);
191        model
192    }
193
194    /// Both members of the select resolve, each to its own variant.
195    #[test]
196    fn conic_positions_resolve_to_the_select_member_the_file_wrote() {
197        let e = circle(Value::Real(1.0));
198        let model = placement_model("IFCAXIS2PLACEMENT2D");
199        let position = Circle::new(EntityId(1), &e).position(&model).unwrap();
200        assert!(matches!(position, Axis2Placement::TwoD(_)));
201        assert_eq!(position.location(&model).unwrap(), [1.0, 2.0, 0.0]);
202
203        let e = ellipse(2.0, 1.0);
204        let model = placement_model("IFCAXIS2PLACEMENT3D");
205        let position = Ellipse::new(EntityId(1), &e).position(&model).unwrap();
206        assert!(matches!(position, Axis2Placement::ThreeD(_)));
207        let transform = position.transform(&model).unwrap();
208        assert_eq!(transform.apply([0.0; 3]), [1.0, 2.0, 0.0]);
209    }
210
211    /// An `IfcAxis1Placement` is not in the select: it has no local X.
212    #[test]
213    fn a_conic_placed_by_an_axis1_placement_is_a_typed_error() {
214        let model = placement_model("IFCAXIS1PLACEMENT");
215        let e = circle(Value::Real(1.0));
216        let err = Circle::new(EntityId(1), &e).position(&model).unwrap_err();
217        assert!(matches!(
218            err,
219            crate::GeometryError::WrongEntityType {
220                entity: EntityId(5),
221                ..
222            }
223        ));
224        let e = ellipse(2.0, 1.0);
225        let err = Ellipse::new(EntityId(1), &e)
226            .position(&Model::new())
227            .unwrap_err();
228        assert_eq!(err.entity(), Some(EntityId(1)));
229    }
230
231    #[test]
232    fn circle_reads_position_and_radius_from_conic_inherited_slots() {
233        let e = circle(Value::Real(2.5));
234        let view = Circle::new(EntityId(1), &e);
235        assert_eq!(view.position_ref().unwrap(), EntityId(5));
236        assert_eq!(view.radius().unwrap(), 2.5);
237    }
238
239    /// A measure wrapper is how conforming files write this; it must not hide
240    /// the number.
241    #[test]
242    fn circle_radius_reads_through_a_positive_length_measure_wrapper() {
243        let e = circle(Value::Typed {
244            type_name: "IFCPOSITIVELENGTHMEASURE".into(),
245            value: Box::new(Value::Real(3.0)),
246        });
247        assert_eq!(Circle::new(EntityId(1), &e).radius().unwrap(), 3.0);
248    }
249
250    #[test]
251    fn zero_radius_circle_is_degenerate_not_a_zero_length_curve() {
252        let e = circle(Value::Real(0.0));
253        let err = Circle::new(EntityId(9), &e).radius().unwrap_err();
254        assert!(err.to_string().contains("#9"), "got: {err}");
255        assert!(err.to_string().contains("positive"), "got: {err}");
256        assert!(
257            !err.is_unsupported(),
258            "a bad radius is corruption, not a gap"
259        );
260    }
261
262    #[test]
263    fn negative_radius_circle_is_degenerate() {
264        let e = circle(Value::Real(-1.0));
265        assert!(Circle::new(EntityId(1), &e).radius().is_err());
266    }
267
268    #[test]
269    fn ellipse_returns_both_semi_axes_in_declaration_order() {
270        let e = ellipse(4.0, 2.0);
271        assert_eq!(
272            Ellipse::new(EntityId(1), &e).semi_axes().unwrap(),
273            (4.0, 2.0)
274        );
275    }
276
277    /// IFC does not require SemiAxis1 >= SemiAxis2; normalising would rotate
278    /// the ellipse ninety degrees.
279    #[test]
280    fn ellipse_accepts_a_second_semi_axis_larger_than_the_first() {
281        let e = ellipse(1.0, 7.0);
282        assert_eq!(
283            Ellipse::new(EntityId(1), &e).semi_axes().unwrap(),
284            (1.0, 7.0)
285        );
286    }
287
288    #[test]
289    fn zero_semi_axis_is_degenerate_and_names_which_one() {
290        let e = ellipse(4.0, 0.0);
291        let err = Ellipse::new(EntityId(1), &e).semi_axis_2().unwrap_err();
292        assert!(err.to_string().contains("SemiAxis2"), "got: {err}");
293    }
294}