Skip to main content

ifc_geometry/input/profile/
outline.rs

1//! The straight-edged outline of an arbitrary profile, in metres (#166).
2//!
3//! [`super::describe_profile`] names an arbitrary profile's boundary curves by
4//! id. A rule check that bounds a section -- openings in a wall whose outline
5//! is a free polyline at a mitred join -- needs the vertices themselves, and
6//! must not link a kernel to get them. This reads them for boundaries whose
7//! every edge is straight, which a vertex list states exactly.
8//!
9//! # Curved edges are refused, never chorded
10//!
11//! A vertex list cannot state an arc. Chording one would hand the caller a
12//! polygon that differs from the file by an error nobody chose, so an
13//! `IfcArcIndex` segment, and any curve family other than `IfcPolyline` and
14//! `IfcIndexedPolyCurve`, is [`GeometryError::Unsupported`] naming the curve.
15//! A caller that wants the polygon anyway, within a stated tolerance, asks
16//! `compile::compile_profile_outline_with` (feature `compile`), which has the
17//! backend sample each arc and reports its certified bound.
18//!
19//! # Rings
20//!
21//! Each boundary is returned as a ring: authored order, the closing vertex not
22//! repeated. IFC closes a polyline by repeating its first point, and a closed
23//! indexed curve by ending on its first index; both are dropped here, as the
24//! profile lowering drops them, so the ring is the loop the kernel receives.
25//!
26//! An `IfcIndexedPolyCurve` must be closed in the schema's sense, as the
27//! profile lowering requires (#335): with `Segments`, the last index of the
28//! last segment is the first index of the first; without, the first and last
29//! points coincide within the model's `Precision`. An open one is
30//! [`GeometryError::Degenerate`], never closed with an edge the file did not
31//! author. (An `IfcPolyline` ring keeps its implicit closing edge, as the
32//! lowering gives it.)
33
34use ifc_model::{EntityId, Model};
35
36use super::{describe_profile, ProfileParameters};
37use crate::constraint::tolerance::{model_precision_metres, points_coincide};
38use crate::curve::{IndexedPolyCurve, PolySegment, Polyline};
39use crate::error::{GeometryError, GeometryResult};
40use crate::resource::point::CartesianPointList;
41use crate::units::UnitScale;
42
43/// Two vertices closer than this, in metres, are the same vertex.
44///
45/// The value the profile lowering uses for the closing duplicate, so both
46/// agree on whether a ring repeats its first vertex.
47const SAME_VERTEX: f64 = 1e-12;
48
49/// An arbitrary profile's boundaries as rings of vertices.
50///
51/// Coordinates are in the profile's own 2D coordinate system, in metres.
52/// Arbitrary profiles have no `Position`, so these are the curve coordinates
53/// the file authored, converted once.
54#[derive(Debug, Clone, PartialEq)]
55#[non_exhaustive]
56pub struct ProfileOutline {
57    /// The `IfcProfileDef` entity.
58    pub profile: EntityId,
59    /// `OuterCurve`'s vertices, in authored order, the first not repeated.
60    pub outer: Vec<[f64; 2]>,
61    /// Each `IfcArbitraryProfileDefWithVoids.InnerCurves` ring, in file
62    /// order. Empty for an `IfcArbitraryClosedProfileDef`.
63    pub inner: Vec<Vec<[f64; 2]>>,
64}
65
66/// Read an arbitrary closed profile's outline, in metres.
67///
68/// Accepts `IfcArbitraryClosedProfileDef` and
69/// `IfcArbitraryProfileDefWithVoids` whose boundaries are `IfcPolyline`s or
70/// line-only `IfcIndexedPolyCurve`s. Refused, each naming the entity:
71///
72/// - any other profile family, and any other boundary curve family, as
73///   [`GeometryError::Unsupported`];
74/// - an `IfcArcIndex` segment, as [`GeometryError::Unsupported`]: the
75///   outline states straight edges only;
76/// - a 3D point, a ring of fewer than three distinct vertices, indexed
77///   segments that do not join, or an open `IfcIndexedPolyCurve`, as
78///   [`GeometryError::Degenerate`];
79/// - whatever [`describe_profile`] refuses for the profile itself.
80///
81/// Kernel-free.
82pub fn profile_outline(
83    model: &Model,
84    units: &UnitScale,
85    profile: EntityId,
86) -> GeometryResult<ProfileOutline> {
87    let (outer, inner) = boundary_curves(model, units, profile)?;
88    Ok(ProfileOutline {
89        profile,
90        outer: ring(model, units, outer)?,
91        inner: inner
92            .iter()
93            .map(|curve| ring(model, units, *curve))
94            .collect::<GeometryResult<_>>()?,
95    })
96}
97
98/// An arbitrary profile's outer curve and inner curves.
99pub(crate) fn boundary_curves(
100    model: &Model,
101    units: &UnitScale,
102    profile: EntityId,
103) -> GeometryResult<(EntityId, Vec<EntityId>)> {
104    let description = describe_profile(model, units, profile)?;
105    let (outer, inner): (EntityId, &[EntityId]) = match &description.parameters {
106        ProfileParameters::ArbitraryClosed { outer_curve } => (*outer_curve, &[]),
107        ProfileParameters::ArbitraryWithVoids {
108            outer_curve,
109            inner_curves,
110        } => (*outer_curve, inner_curves),
111        _ => {
112            return Err(GeometryError::Unsupported {
113                entity: profile,
114                type_name: description.type_name,
115                detail: "only IfcArbitraryClosedProfileDef and IfcArbitraryProfileDefWithVoids \
116                         have an authored outline; describe_profile states the other families",
117            })
118        }
119    };
120    Ok((outer, inner.to_vec()))
121}
122
123/// One boundary curve as a ring of distinct vertices, in metres.
124pub(crate) fn ring(
125    model: &Model,
126    units: &UnitScale,
127    curve: EntityId,
128) -> GeometryResult<Vec<[f64; 2]>> {
129    let entity = model.get(curve).ok_or(GeometryError::MissingEntity {
130        referrer: curve,
131        missing: curve,
132    })?;
133    let type_name = entity.type_name.to_ascii_uppercase();
134    let raw = match type_name.as_str() {
135        "IFCPOLYLINE" => polyline(model, curve, entity)?,
136        "IFCINDEXEDPOLYCURVE" => {
137            let (raw, closed) = indexed(model, curve, entity)?;
138            let closed = match closed {
139                Some(closed) => closed,
140                None => {
141                    let precision = model_precision_metres(model, units)?;
142                    let metres = |p: &[f64; 2]| [units.length(p[0]), units.length(p[1])];
143                    match (raw.first(), raw.last()) {
144                        (Some(first), Some(last)) if raw.len() >= 2 => {
145                            points_coincide(precision, metres(first), metres(last))
146                        }
147                        _ => false,
148                    }
149                }
150            };
151            if !closed {
152                return Err(GeometryError::Degenerate {
153                    entity: curve,
154                    type_name,
155                    detail: "the indexed curve is open, and a profile boundary must be closed"
156                        .to_owned(),
157                });
158            }
159            raw
160        }
161        _ => {
162            return Err(GeometryError::Unsupported {
163                entity: curve,
164                type_name,
165                detail: "outline vertices are read from IfcPolyline and line-only \
166                         IfcIndexedPolyCurve boundaries; other curve families may be curved",
167            })
168        }
169    };
170    let mut vertices: Vec<[f64; 2]> = raw
171        .into_iter()
172        .map(|[x, y]| [units.length(x), units.length(y)])
173        .collect();
174    if let (Some(first), Some(last)) = (vertices.first(), vertices.last()) {
175        let same = if type_name == "IFCINDEXEDPOLYCURVE" {
176            // Closed, checked above: the last vertex is the first.
177            true
178        } else {
179            distance(*first, *last) < SAME_VERTEX
180        };
181        if vertices.len() >= 2 && same {
182            vertices.pop();
183        }
184    }
185    if vertices.len() < 3 {
186        return Err(GeometryError::Degenerate {
187            entity: curve,
188            type_name,
189            detail: format!(
190                "a profile boundary needs at least 3 distinct vertices, found {}",
191                vertices.len()
192            ),
193        });
194    }
195    Ok(vertices)
196}
197
198/// An `IfcPolyline`'s points, in file units. Each must be 2D.
199fn polyline(
200    model: &Model,
201    curve: EntityId,
202    entity: &ifc_model::Entity,
203) -> GeometryResult<Vec<[f64; 2]>> {
204    Polyline::new(curve, entity)
205        .points(model)?
206        .iter()
207        .map(|point| match point.coordinates()?.as_slice() {
208            [x, y] => Ok([*x, *y]),
209            other => Err(GeometryError::Degenerate {
210                entity: point.id(),
211                type_name: "IFCCARTESIANPOINT".to_owned(),
212                detail: format!(
213                    "a profile boundary point is 2D (OuterCurve.Dim = 2), this one has {} \
214                     coordinates",
215                    other.len()
216                ),
217            }),
218        })
219        .collect()
220}
221
222/// A line-only `IfcIndexedPolyCurve`'s path, in file units, and whether it
223/// closes by index (`None` without `Segments`, where closure is by point).
224///
225/// Without `Segments` the path is every point in list order. With them, each
226/// `IfcLineIndex` run must start where the previous one ended
227/// (`IfcConsecutiveSegments`), and an `IfcArcIndex` is refused.
228fn indexed(
229    model: &Model,
230    curve: EntityId,
231    entity: &ifc_model::Entity,
232) -> GeometryResult<(Vec<[f64; 2]>, Option<bool>)> {
233    let view = IndexedPolyCurve::new(curve, entity);
234    let list = indexed_list(model, &view)?;
235    if !view.has_explicit_segments() {
236        return Ok((list, None));
237    }
238    let mut indices: Vec<usize> = Vec::new();
239    for segment in view.segments(list.len())? {
240        let PolySegment::Line(run) = segment else {
241            return Err(GeometryError::Unsupported {
242                entity: curve,
243                type_name: entity.type_name.to_ascii_uppercase(),
244                detail: "an IfcArcIndex segment is a circular arc, which a vertex outline \
245                         cannot state; it is refused rather than chorded",
246            });
247        };
248        match indices.last() {
249            None => indices.extend_from_slice(&run),
250            Some(end) => {
251                consecutive(curve, entity, Some(*end), run[0])?;
252                indices.extend_from_slice(&run[1..]);
253            }
254        }
255    }
256    let closed = indices.len() >= 2 && indices.first() == indices.last();
257    Ok((
258        indices.into_iter().map(|index| list[index]).collect(),
259        Some(closed),
260    ))
261}
262
263/// An indexed curve's 2D point list, in file units.
264fn indexed_list(model: &Model, view: &IndexedPolyCurve<'_>) -> GeometryResult<Vec<[f64; 2]>> {
265    match view.points(model)? {
266        CartesianPointList::TwoD(list) => list.coordinates(),
267        CartesianPointList::ThreeD(list) => Err(GeometryError::Degenerate {
268            entity: list.id(),
269            type_name: "IFCCARTESIANPOINTLIST3D".to_owned(),
270            detail: "a profile boundary is 2D (OuterCurve.Dim = 2), this point list is 3D"
271                .to_owned(),
272        }),
273    }
274}
275
276/// `IfcConsecutiveSegments`: a segment starts where the previous one ended.
277fn consecutive(
278    curve: EntityId,
279    entity: &ifc_model::Entity,
280    previous_end: Option<usize>,
281    start: usize,
282) -> GeometryResult<()> {
283    match previous_end {
284        Some(end) if end != start => Err(GeometryError::Degenerate {
285            entity: curve,
286            type_name: entity.type_name.to_ascii_uppercase(),
287            detail: "Segments are not consecutive (WHERE rule Consecutive), so the \
288                     boundary is not one ring"
289                .to_owned(),
290        }),
291        _ => Ok(()),
292    }
293}
294
295#[cfg(feature = "compile")]
296/// An `IfcIndexedPolyCurve` boundary that holds an `IfcArcIndex`, checked.
297pub(crate) struct ArcBoundary {
298    /// The point list, in file units.
299    pub(crate) list: Vec<[f64; 2]>,
300    /// The segments in file order, consecutive and closed by index.
301    pub(crate) segments: Vec<PolySegment>,
302}
303
304/// The segments of an `IfcIndexedPolyCurve` boundary with an arc, or `None`
305/// when it has none (the exact outline reads it).
306///
307/// Checks what [`profile_outline`] checks of a boundary: a 2D point list,
308/// consecutive segments, closed by index. Each refusal is
309/// [`GeometryError::Degenerate`].
310#[cfg(feature = "compile")]
311pub(crate) fn arc_boundary(
312    model: &Model,
313    curve: EntityId,
314    entity: &ifc_model::Entity,
315) -> GeometryResult<Option<ArcBoundary>> {
316    let view = IndexedPolyCurve::new(curve, entity);
317    if !view.has_explicit_segments() {
318        return Ok(None);
319    }
320    let list = indexed_list(model, &view)?;
321    let segments = view.segments(list.len())?;
322    if !segments
323        .iter()
324        .any(|s| matches!(s, PolySegment::Arc { .. }))
325    {
326        return Ok(None);
327    }
328    let mut end = None;
329    let mut first = None;
330    for segment in &segments {
331        let (start, last) = match segment {
332            PolySegment::Line(run) => (run[0], run[run.len() - 1]),
333            PolySegment::Arc { start, end, .. } => (*start, *end),
334        };
335        consecutive(curve, entity, end, start)?;
336        first.get_or_insert(start);
337        end = Some(last);
338    }
339    if first != end {
340        return Err(GeometryError::Degenerate {
341            entity: curve,
342            type_name: entity.type_name.to_ascii_uppercase(),
343            detail: "the indexed curve is open, and a profile boundary must be closed".to_owned(),
344        });
345    }
346    Ok(Some(ArcBoundary { list, segments }))
347}
348
349fn distance(a: [f64; 2], b: [f64; 2]) -> f64 {
350    (a[0] - b[0]).hypot(a[1] - b[1])
351}