Skip to main content

ifc_geometry/curve/
offset.rs

1//! Curves defined relative to another curve or to a surface.
2//!
3//! Covers `IfcOffsetCurve2D`, `IfcOffsetCurve3D`, `IfcPcurve` and
4//! `IfcSurfaceCurve` (with its `IfcIntersectionCurve` and `IfcSeamCurve`
5//! subtypes).
6//!
7//! # Why offsets are not just "the same curve, moved"
8//!
9//! An offset curve is not a translation. Every point moves perpendicular to
10//! the basis curve's local tangent, so where the basis curve bends more
11//! tightly than the offset distance the result self-intersects or vanishes.
12//! That is why both offset entities carry `SelfIntersect` and why this module
13//! surfaces it rather than dropping it: it is the file's only warning that
14//! offsetting will not produce a simple curve.
15//!
16//! # The 2D/3D asymmetry
17//!
18//! `IfcOffsetCurve2D` has no reference direction: in the plane, "perpendicular
19//! to the tangent" is unambiguous up to sign, and the sign comes from the
20//! `Distance` value. `IfcOffsetCurve3D` needs `RefDirection` because in space
21//! there is a whole circle of perpendiculars, and the offset direction is
22//! `RefDirection` cross tangent. A consumer that treats the two entities
23//! identically will place a 3D offset anywhere on that circle.
24//!
25//! # `IfcSurfaceCurve` carries the same curve twice
26//!
27//! `Curve3D` and `AssociatedGeometry` (one or two `IfcPcurve`s) describe the
28//! *same* curve in different spaces, and they will not agree exactly.
29//! `MasterRepresentation` says which one to believe. It matters most on a
30//! seam curve, where the two p-curves are the two sides of a periodic
31//! surface's seam and picking the wrong one puts an edge on the far side of a
32//! cylinder.
33
34use crate::error::GeometryResult;
35use crate::resource::direction::Direction;
36use crate::resource::resolve;
37use crate::slots::Slots;
38use ifc_model::{Entity, EntityId, Model};
39
40/// `IfcOffsetCurve2D` attribute slots, from IFC4 ADD2 TC1.
41mod offset_2d_slot {
42    /// `BasisCurve`: the `IfcCurve` being offset.
43    pub const BASIS_CURVE: usize = 0;
44    /// `Distance`: `IfcLengthMeasure`; sign picks the side.
45    pub const DISTANCE: usize = 1;
46    /// `SelfIntersect`: `IfcLogical`.
47    pub const SELF_INTERSECT: usize = 2;
48}
49
50/// `IfcOffsetCurve3D` attribute slots, from IFC4 ADD2 TC1.
51///
52/// Identical to the 2D form for slots 0-2, plus `RefDirection` at 3.
53mod offset_3d_slot {
54    /// `BasisCurve`: the `IfcCurve` being offset.
55    pub const BASIS_CURVE: usize = 0;
56    /// `Distance`: `IfcLengthMeasure`.
57    pub const DISTANCE: usize = 1;
58    /// `SelfIntersect`: `IfcLogical`.
59    pub const SELF_INTERSECT: usize = 2;
60    /// `RefDirection`: `IfcDirection` fixing which perpendicular is used.
61    pub const REF_DIRECTION: usize = 3;
62}
63
64/// `IfcPcurve` attribute slots, from IFC4 ADD2 TC1.
65pub(crate) mod pcurve_slot {
66    /// `BasisSurface`: the `IfcSurface` the curve lives on.
67    pub const BASIS_SURFACE: usize = 0;
68    /// `ReferenceCurve`: a 2D curve in the surface's parameter space.
69    pub const REFERENCE_CURVE: usize = 1;
70}
71
72/// `IfcSurfaceCurve` attribute slots, from IFC4 ADD2 TC1.
73///
74/// `IfcIntersectionCurve` and `IfcSeamCurve` add no explicit attributes, so
75/// these indices serve all three.
76pub(crate) mod surface_curve_slot {
77    /// `Curve3D`: the curve in model space.
78    pub const CURVE_3D: usize = 0;
79    /// `AssociatedGeometry`: `LIST [1:2] OF IfcPcurve`.
80    pub const ASSOCIATED_GEOMETRY: usize = 1;
81    /// `MasterRepresentation`: `IfcPreferredSurfaceCurveRepresentation`.
82    pub const MASTER_REPRESENTATION: usize = 2;
83}
84
85/// `IfcPreferredSurfaceCurveRepresentation`: which copy of the curve wins.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum PreferredSurfaceCurveRepresentation {
88    /// Believe `Curve3D`, the model-space curve.
89    Curve3D,
90    /// Believe the first `IfcPcurve` in `AssociatedGeometry`.
91    PCurveS1,
92    /// Believe the second `IfcPcurve` in `AssociatedGeometry`.
93    ///
94    /// Only meaningful when two are supplied; a file naming this with one
95    /// p-curve is inconsistent.
96    PCurveS2,
97}
98
99impl PreferredSurfaceCurveRepresentation {
100    /// Parse the enumeration token, `None` if unrecognised.
101    pub fn from_token(token: &str) -> Option<Self> {
102        match token.to_ascii_uppercase().as_str() {
103            "CURVE3D" => Some(Self::Curve3D),
104            "PCURVE_S1" => Some(Self::PCurveS1),
105            "PCURVE_S2" => Some(Self::PCurveS2),
106            _ => None,
107        }
108    }
109
110    /// Index into `AssociatedGeometry`, or `None` when 3D wins.
111    ///
112    /// Saves every caller from re-deriving that `PCURVE_S1` is element 0.
113    pub fn pcurve_index(&self) -> Option<usize> {
114        match self {
115            Self::Curve3D => None,
116            Self::PCurveS1 => Some(0),
117            Self::PCurveS2 => Some(1),
118        }
119    }
120}
121
122/// A borrowed view of an `IfcOffsetCurve2D`.
123#[derive(Debug, Clone, Copy)]
124pub struct OffsetCurve2D<'m> {
125    slots: Slots<'m>,
126}
127
128impl<'m> OffsetCurve2D<'m> {
129    /// Wrap an entity known to be an `IfcOffsetCurve2D`.
130    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
131        Self {
132            slots: Slots::new(id, entity),
133        }
134    }
135
136    /// The entity id.
137    pub fn id(&self) -> EntityId {
138        self.slots.id()
139    }
140
141    /// The curve being offset.
142    pub fn basis_curve_ref(&self) -> GeometryResult<EntityId> {
143        self.slots
144            .req_ref(offset_2d_slot::BASIS_CURVE, "BasisCurve")
145    }
146
147    /// The offset distance; the sign selects which side.
148    ///
149    /// Zero is legal and means the curve coincides with its basis, which some
150    /// exporters emit as a placeholder. Not treated as degenerate because the
151    /// resulting geometry is perfectly well defined.
152    pub fn distance(&self) -> GeometryResult<f64> {
153        self.slots.req_f64(offset_2d_slot::DISTANCE, "Distance")
154    }
155
156    /// The asserted `SelfIntersect` flag; `None` for `.U.` or absent.
157    pub fn self_intersect(&self) -> Option<bool> {
158        self.slots.opt_bool(offset_2d_slot::SELF_INTERSECT)
159    }
160}
161
162/// A borrowed view of an `IfcOffsetCurve3D`.
163#[derive(Debug, Clone, Copy)]
164pub struct OffsetCurve3D<'m> {
165    slots: Slots<'m>,
166}
167
168impl<'m> OffsetCurve3D<'m> {
169    /// Wrap an entity known to be an `IfcOffsetCurve3D`.
170    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
171        Self {
172            slots: Slots::new(id, entity),
173        }
174    }
175
176    /// The entity id.
177    pub fn id(&self) -> EntityId {
178        self.slots.id()
179    }
180
181    /// The curve being offset.
182    pub fn basis_curve_ref(&self) -> GeometryResult<EntityId> {
183        self.slots
184            .req_ref(offset_3d_slot::BASIS_CURVE, "BasisCurve")
185    }
186
187    /// The offset distance; the sign selects which side.
188    pub fn distance(&self) -> GeometryResult<f64> {
189        self.slots.req_f64(offset_3d_slot::DISTANCE, "Distance")
190    }
191
192    /// The asserted `SelfIntersect` flag; `None` for `.U.` or absent.
193    pub fn self_intersect(&self) -> Option<bool> {
194        self.slots.opt_bool(offset_3d_slot::SELF_INTERSECT)
195    }
196
197    /// The `IfcDirection` fixing which perpendicular the offset uses.
198    ///
199    /// Required by the schema and genuinely required by the geometry: without
200    /// it the offset direction is only known up to rotation about the tangent.
201    pub fn ref_direction_ref(&self) -> GeometryResult<EntityId> {
202        self.slots
203            .req_ref(offset_3d_slot::REF_DIRECTION, "RefDirection")
204    }
205
206    /// The reference direction as a typed view, resolved from the model.
207    ///
208    /// Left unnormalized: call [`Direction::unit`], which rejects a zero
209    /// direction rather than producing `NaN`.
210    pub fn ref_direction<'v>(&self, model: &'v Model) -> GeometryResult<Direction<'v>> {
211        resolve::direction(model, self.id(), self.ref_direction_ref()?)
212    }
213}
214
215/// A borrowed view of an `IfcPcurve`.
216///
217/// A curve defined in a surface's *parameter* space. `ReferenceCurve` is a 2D
218/// curve whose coordinates are `(u, v)` values, not lengths, so applying a
219/// length unit scale to them is wrong.
220#[derive(Debug, Clone, Copy)]
221pub struct PCurve<'m> {
222    slots: Slots<'m>,
223}
224
225impl<'m> PCurve<'m> {
226    /// Wrap an entity known to be an `IfcPcurve`.
227    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
228        Self {
229            slots: Slots::new(id, entity),
230        }
231    }
232
233    /// The entity id.
234    pub fn id(&self) -> EntityId {
235        self.slots.id()
236    }
237
238    /// The surface whose parameter space the curve lives in.
239    pub fn basis_surface_ref(&self) -> GeometryResult<EntityId> {
240        self.slots
241            .req_ref(pcurve_slot::BASIS_SURFACE, "BasisSurface")
242    }
243
244    /// The 2D curve in `(u, v)` parameter space.
245    ///
246    /// Its coordinates are surface parameters. For an `IfcPlane` those happen
247    /// to be lengths; for an `IfcCylindricalSurface` the first is an angle.
248    /// Unit conversion therefore depends on the basis surface, not on the
249    /// curve.
250    pub fn reference_curve_ref(&self) -> GeometryResult<EntityId> {
251        self.slots
252            .req_ref(pcurve_slot::REFERENCE_CURVE, "ReferenceCurve")
253    }
254}
255
256/// A borrowed view of an `IfcSurfaceCurve` and its subtypes.
257#[derive(Debug, Clone, Copy)]
258pub struct SurfaceCurve<'m> {
259    slots: Slots<'m>,
260}
261
262/// Which `IfcSurfaceCurve` subtype an entity is.
263#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264pub enum SurfaceCurveKind {
265    /// `IfcSurfaceCurve`: a curve lying on one or two surfaces.
266    Plain,
267    /// `IfcIntersectionCurve`: where two surfaces meet.
268    ///
269    /// Requires exactly two associated p-curves, one per surface.
270    Intersection,
271    /// `IfcSeamCurve`: the closing seam of a periodic surface.
272    ///
273    /// Its two p-curves lie on the *same* surface at the two ends of the
274    /// periodic parameter range, which is why they look like duplicates.
275    Seam,
276}
277
278impl<'m> SurfaceCurve<'m> {
279    /// Wrap an entity known to be an `IfcSurfaceCurve` subtype.
280    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
281        Self {
282            slots: Slots::new(id, entity),
283        }
284    }
285
286    /// The entity id.
287    pub fn id(&self) -> EntityId {
288        self.slots.id()
289    }
290
291    /// Which subtype this is, or `None` if the type name is not one of them.
292    pub fn kind(&self) -> Option<SurfaceCurveKind> {
293        match self.slots.entity().type_name.to_ascii_uppercase().as_str() {
294            "IFCSURFACECURVE" => Some(SurfaceCurveKind::Plain),
295            "IFCINTERSECTIONCURVE" => Some(SurfaceCurveKind::Intersection),
296            "IFCSEAMCURVE" => Some(SurfaceCurveKind::Seam),
297            _ => None,
298        }
299    }
300
301    /// The model-space curve.
302    pub fn curve_3d_ref(&self) -> GeometryResult<EntityId> {
303        self.slots.req_ref(surface_curve_slot::CURVE_3D, "Curve3D")
304    }
305
306    /// The associated `IfcPcurve` references, one or two.
307    ///
308    /// Cardinality is checked because `IfcIntersectionCurve` and
309    /// `IfcSeamCurve` both require exactly two, and a single-element list on
310    /// either means the second surface was lost.
311    pub fn associated_pcurve_refs(&self) -> GeometryResult<Vec<EntityId>> {
312        let pcurves = self.slots.req_ref_list(
313            surface_curve_slot::ASSOCIATED_GEOMETRY,
314            "AssociatedGeometry",
315        )?;
316        if pcurves.is_empty() || pcurves.len() > 2 {
317            return Err(self.slots.degenerate(format!(
318                "AssociatedGeometry must hold 1 or 2 IfcPcurves, found {}",
319                pcurves.len()
320            )));
321        }
322        if matches!(
323            self.kind(),
324            Some(SurfaceCurveKind::Intersection) | Some(SurfaceCurveKind::Seam)
325        ) && pcurves.len() != 2
326        {
327            return Err(self.slots.degenerate(format!(
328                "{} requires exactly 2 associated IfcPcurves, found {}",
329                self.slots.type_name(),
330                pcurves.len()
331            )));
332        }
333        Ok(pcurves)
334    }
335
336    /// Which representation is authoritative, defaulting to `Curve3D`.
337    ///
338    /// The 3D curve is the safe default: it exists on every surface curve,
339    /// whereas a p-curve index may point past the end of a short list.
340    pub fn master_representation(&self) -> PreferredSurfaceCurveRepresentation {
341        self.slots
342            .opt_enum(surface_curve_slot::MASTER_REPRESENTATION)
343            .and_then(PreferredSurfaceCurveRepresentation::from_token)
344            .unwrap_or(PreferredSurfaceCurveRepresentation::Curve3D)
345    }
346
347    /// The reference the `MasterRepresentation` actually names.
348    ///
349    /// Resolves the enumeration against the real list length, so a file
350    /// naming `PCURVE_S2` with only one p-curve fails here rather than
351    /// indexing out of bounds in a kernel.
352    pub fn master_curve_ref(&self) -> GeometryResult<EntityId> {
353        match self.master_representation().pcurve_index() {
354            None => self.curve_3d_ref(),
355            Some(index) => {
356                let pcurves = self.associated_pcurve_refs()?;
357                pcurves.get(index).copied().ok_or_else(|| {
358                    self.slots.degenerate(format!(
359                        "MasterRepresentation names p-curve {} but AssociatedGeometry holds {}",
360                        index + 1,
361                        pcurves.len()
362                    ))
363                })
364            }
365        }
366    }
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372    use ifc_model::Value;
373
374    fn offset_2d(distance: f64) -> Entity {
375        Entity::new(
376            "IFCOFFSETCURVE2D",
377            vec![
378                Value::Ref(EntityId(30)),
379                Value::Real(distance),
380                Value::Bool(false),
381            ],
382        )
383    }
384
385    fn offset_3d(distance: f64) -> Entity {
386        Entity::new(
387            "IFCOFFSETCURVE3D",
388            vec![
389                Value::Ref(EntityId(30)),
390                Value::Real(distance),
391                Value::Bool(false),
392                Value::Ref(EntityId(31)),
393            ],
394        )
395    }
396
397    fn surface_curve(type_name: &str, pcurves: &[u64], preference: &str) -> Entity {
398        Entity::new(
399            type_name,
400            vec![
401                Value::Ref(EntityId(40)),
402                Value::List(pcurves.iter().map(|i| Value::Ref(EntityId(*i))).collect()),
403                Value::Enum(preference.into()),
404            ],
405        )
406    }
407
408    /// The sign of Distance is the only thing selecting the offset side, so it
409    /// must survive unchanged.
410    #[test]
411    fn offset_distance_keeps_its_sign() {
412        let e = offset_2d(-0.5);
413        assert_eq!(
414            OffsetCurve2D::new(EntityId(1), &e).distance().unwrap(),
415            -0.5
416        );
417    }
418
419    /// A zero offset is well-defined geometry, not corruption.
420    #[test]
421    fn a_zero_offset_distance_is_accepted() {
422        let e = offset_2d(0.0);
423        assert_eq!(OffsetCurve2D::new(EntityId(1), &e).distance().unwrap(), 0.0);
424    }
425
426    /// The 3D form needs RefDirection to pick one of infinitely many
427    /// perpendiculars; the 2D form has no such slot.
428    #[test]
429    fn only_the_3d_offset_carries_a_reference_direction() {
430        let e = offset_3d(1.0);
431        let view = OffsetCurve3D::new(EntityId(1), &e);
432        assert_eq!(view.basis_curve_ref().unwrap(), EntityId(30));
433        assert_eq!(view.ref_direction_ref().unwrap(), EntityId(31));
434        assert_eq!(view.self_intersect(), Some(false));
435    }
436
437    #[test]
438    fn the_reference_direction_resolves_unnormalized() {
439        let mut model = Model::new();
440        let ratios = Value::List(vec![Value::Real(0.0), Value::Real(0.0), Value::Real(5.0)]);
441        model.insert(EntityId(31), Entity::new("IFCDIRECTION", vec![ratios]));
442        let e = offset_3d(1.0);
443        let direction = OffsetCurve3D::new(EntityId(1), &e)
444            .ref_direction(&model)
445            .unwrap();
446        assert_eq!(direction.ratios().unwrap(), vec![0.0, 0.0, 5.0]);
447        assert_eq!(direction.unit().unwrap(), [0.0, 0.0, 1.0]);
448    }
449
450    #[test]
451    fn a_reference_direction_that_is_a_point_is_a_typed_error() {
452        let mut model = Model::new();
453        model.insert(EntityId(31), Entity::new("IFCCARTESIANPOINT", vec![]));
454        let e = offset_3d(1.0);
455        let err = OffsetCurve3D::new(EntityId(1), &e)
456            .ref_direction(&model)
457            .unwrap_err();
458        assert!(matches!(
459            err,
460            crate::GeometryError::WrongEntityType {
461                entity: EntityId(31),
462                expected: "IfcDirection",
463                ..
464            }
465        ));
466    }
467
468    #[test]
469    fn a_3d_offset_missing_its_reference_direction_is_reported_by_name() {
470        let e = Entity::new(
471            "IFCOFFSETCURVE3D",
472            vec![
473                Value::Ref(EntityId(30)),
474                Value::Real(1.0),
475                Value::Bool(false),
476            ],
477        );
478        let err = OffsetCurve3D::new(EntityId(1), &e)
479            .ref_direction_ref()
480            .unwrap_err();
481        assert!(err.to_string().contains("RefDirection"), "got: {err}");
482    }
483
484    #[test]
485    fn pcurve_names_its_surface_and_its_parameter_space_curve() {
486        let e = Entity::new(
487            "IFCPCURVE",
488            vec![Value::Ref(EntityId(50)), Value::Ref(EntityId(51))],
489        );
490        let view = PCurve::new(EntityId(1), &e);
491        assert_eq!(view.basis_surface_ref().unwrap(), EntityId(50));
492        assert_eq!(view.reference_curve_ref().unwrap(), EntityId(51));
493    }
494
495    /// PCURVE_S1 is element 0 and PCURVE_S2 element 1; getting that backwards
496    /// puts an edge on the wrong surface.
497    #[test]
498    fn master_representation_resolves_to_the_right_geometry() {
499        let by_3d = surface_curve("IFCSURFACECURVE", &[60, 61], "CURVE3D");
500        assert_eq!(
501            SurfaceCurve::new(EntityId(1), &by_3d)
502                .master_curve_ref()
503                .unwrap(),
504            EntityId(40)
505        );
506
507        let by_s1 = surface_curve("IFCSURFACECURVE", &[60, 61], "PCURVE_S1");
508        assert_eq!(
509            SurfaceCurve::new(EntityId(1), &by_s1)
510                .master_curve_ref()
511                .unwrap(),
512            EntityId(60)
513        );
514
515        let by_s2 = surface_curve("IFCSURFACECURVE", &[60, 61], "PCURVE_S2");
516        assert_eq!(
517            SurfaceCurve::new(EntityId(1), &by_s2)
518                .master_curve_ref()
519                .unwrap(),
520            EntityId(61)
521        );
522    }
523
524    #[test]
525    fn naming_a_pcurve_the_file_does_not_have_fails_instead_of_indexing_out_of_bounds() {
526        let e = surface_curve("IFCSURFACECURVE", &[60], "PCURVE_S2");
527        let err = SurfaceCurve::new(EntityId(3), &e)
528            .master_curve_ref()
529            .unwrap_err();
530        assert!(err.to_string().contains("#3"), "got: {err}");
531    }
532
533    #[test]
534    fn an_absent_master_representation_defaults_to_the_3d_curve() {
535        let e = Entity::new(
536            "IFCSURFACECURVE",
537            vec![
538                Value::Ref(EntityId(40)),
539                Value::List(vec![Value::Ref(EntityId(60))]),
540            ],
541        );
542        assert_eq!(
543            SurfaceCurve::new(EntityId(1), &e).master_representation(),
544            PreferredSurfaceCurveRepresentation::Curve3D
545        );
546    }
547
548    /// An intersection curve with one p-curve has lost a surface, and a seam
549    /// curve with one has lost the far side of the seam.
550    #[test]
551    fn intersection_and_seam_curves_require_exactly_two_pcurves() {
552        for type_name in ["IFCINTERSECTIONCURVE", "IFCSEAMCURVE"] {
553            let e = surface_curve(type_name, &[60], "CURVE3D");
554            let err = SurfaceCurve::new(EntityId(1), &e)
555                .associated_pcurve_refs()
556                .unwrap_err();
557            assert!(err.to_string().contains("exactly 2"), "{type_name}: {err}");
558        }
559        // The plain supertype is happy with one.
560        let plain = surface_curve("IFCSURFACECURVE", &[60], "CURVE3D");
561        assert_eq!(
562            SurfaceCurve::new(EntityId(1), &plain)
563                .associated_pcurve_refs()
564                .unwrap()
565                .len(),
566            1
567        );
568    }
569
570    #[test]
571    fn surface_curve_subtypes_are_classified_from_the_type_name() {
572        for (type_name, expected) in [
573            ("IFCSURFACECURVE", SurfaceCurveKind::Plain),
574            ("IFCINTERSECTIONCURVE", SurfaceCurveKind::Intersection),
575            ("IFCSEAMCURVE", SurfaceCurveKind::Seam),
576        ] {
577            let e = surface_curve(type_name, &[60, 61], "CURVE3D");
578            assert_eq!(SurfaceCurve::new(EntityId(1), &e).kind(), Some(expected));
579        }
580        let other = surface_curve("IFCPOLYLINE", &[60], "CURVE3D");
581        assert_eq!(SurfaceCurve::new(EntityId(1), &other).kind(), None);
582    }
583
584    #[test]
585    fn preferred_representation_tokens_map_to_list_positions() {
586        assert_eq!(
587            PreferredSurfaceCurveRepresentation::Curve3D.pcurve_index(),
588            None
589        );
590        assert_eq!(
591            PreferredSurfaceCurveRepresentation::PCurveS1.pcurve_index(),
592            Some(0)
593        );
594        assert_eq!(
595            PreferredSurfaceCurveRepresentation::PCurveS2.pcurve_index(),
596            Some(1)
597        );
598        assert_eq!(
599            PreferredSurfaceCurveRepresentation::from_token("NOPE"),
600            None
601        );
602    }
603}