Skip to main content

ifc_geometry/compile/
outline.rs

1//! An arbitrary profile's outline with its arcs sampled by the backend (#660).
2//!
3//! [`crate::profile_outline`] is exact and kernel-free, and so refuses an
4//! `IfcArcIndex`: a vertex list cannot state an arc. This is the sibling for a
5//! caller that wants a polygon anyway and says how closely. Each arc segment
6//! is lowered as the exact circle the file states and handed to a
7//! [`PolylineCompiler`], which chord-samples it within the caller's
8//! [`Tolerance`] and certifies how far the polygon may lie from the arc. No
9//! code here samples an arc; the bridge only asks (ADR 0004).
10//!
11//! # What is exact and what is sampled
12//!
13//! Every authored point appears once, bitwise the file's value in metres,
14//! and each sampled arc's two end vertices are the arc's authored end points
15//! (an `IfcArcIndex` mid point is on the arc but not a ring vertex), not the
16//! backend's evaluation of the circle there. The backend's own vertices
17//! are kept only strictly between them. [`SampledArc`] records which
18//! vertices those are and the bound for that arc, so a caller can tell the
19//! edges that are approximate from the ones that are not.
20//!
21//! A boundary is compiled one segment at a time, never as the whole
22//! composite curve: the backend would keep each earlier segment's *evaluated*
23//! last vertex at a joint, and report no segment, so neither "authored points
24//! are exact" nor "which edges are approximate" could be stated.
25//!
26//! A boundary without an arc is read as [`crate::profile_outline`] reads it,
27//! with no arcs and a bound of zero.
28
29use axiolid_contracts::ExecutionOptions;
30use axiolid_model::{CurveRelation, GeometryNode};
31use ifc_model::{EntityId, Model};
32
33use super::{refused, ChordDeviation, PolylineCompiler, Tolerance};
34use crate::curve::PolySegment;
35use crate::error::{GeometryError, GeometryResult};
36use crate::input::profile::{arc_boundary, boundary_curves, ring};
37use crate::lower::{lower_curve_node, LoweringSession};
38use crate::transform::Transform;
39use crate::units;
40
41#[cfg(feature = "compile-reference-backend")]
42use super::default_backend;
43
44/// An arbitrary profile's boundaries, arcs sampled.
45///
46/// Coordinates are in the profile's own 2D coordinate system, in metres.
47#[derive(Debug, Clone, PartialEq)]
48#[non_exhaustive]
49pub struct SampledProfileOutline {
50    /// The `IfcProfileDef` entity.
51    pub profile: EntityId,
52    /// `OuterCurve`, sampled.
53    pub outer: SampledRing,
54    /// Each `InnerCurves` ring, in file order. Empty for an
55    /// `IfcArbitraryClosedProfileDef`.
56    pub inner: Vec<SampledRing>,
57}
58
59/// One boundary curve as a ring of vertices.
60#[derive(Debug, Clone, PartialEq)]
61#[non_exhaustive]
62pub struct SampledRing {
63    /// The boundary curve the ring was read from.
64    pub curve: EntityId,
65    /// Profile 2D frame, metres, authored order, closing vertex not repeated.
66    pub vertices: Vec<[f64; 2]>,
67    /// One entry per `IfcArcIndex` segment, in segment order.
68    pub arcs: Vec<SampledArc>,
69    /// `requested` is `tolerance.linear()`; `bound` is the largest arc bound,
70    /// zero when the ring has no arcs.
71    pub deviation: ChordDeviation,
72}
73
74/// Where one sampled `IfcArcIndex` segment sits in its ring.
75#[derive(Debug, Clone, Copy, PartialEq)]
76#[non_exhaustive]
77pub struct SampledArc {
78    /// 0-based index into the curve's `Segments`.
79    pub segment: usize,
80    /// Index in [`SampledRing::vertices`] of the arc's authored start point.
81    pub start: usize,
82    /// Sampled vertices after `start`; the arc ends at vertex
83    /// `(start + samples + 1) % vertices.len()`, an authored point.
84    pub samples: usize,
85    /// The backend's certified bound for this arc plus the distance its end
86    /// vertices were snapped, in metres.
87    pub bound: f64,
88}
89
90/// Read an arbitrary profile's outline in metres, sampling each arc with
91/// `backend` within `tolerance`.
92///
93/// Accepts `IfcArbitraryClosedProfileDef` and
94/// `IfcArbitraryProfileDefWithVoids` whose boundaries are `IfcPolyline`s or
95/// `IfcIndexedPolyCurve`s. Refused, each naming the entity:
96///
97/// - any other profile family, and any other boundary curve family, as
98///   [`GeometryError::Unsupported`];
99/// - what [`crate::profile_outline`] refuses as `Degenerate`: a 3D point, a
100///   ring of fewer than three distinct vertices, segments that do not join,
101///   an open indexed curve, and an `IfcArcIndex` of coincident points;
102/// - a sampled arc vertex off the profile plane by more than the linear
103///   tolerance, as [`GeometryError::Degenerate`];
104/// - an arc the backend refuses, returns fewer than two vertices for,
105///   runs backwards, or ends more than the linear tolerance from the
106///   authored end points, as [`GeometryError::CompilationRefused`] naming the
107///   boundary curve.
108///
109/// # Errors
110///
111/// As above, plus whatever [`crate::describe_profile`] and unit resolution
112/// refuse.
113pub fn compile_profile_outline_with<B: PolylineCompiler>(
114    backend: &B,
115    model: &Model,
116    profile: EntityId,
117    tolerance: Tolerance,
118) -> GeometryResult<SampledProfileOutline> {
119    let scale = units::resolve(model)?;
120    let (outer, inner) = boundary_curves(model, &scale, profile)?;
121    let sample = |curve: EntityId| sampled_ring(backend, model, &scale, curve, tolerance);
122    Ok(SampledProfileOutline {
123        profile,
124        outer: sample(outer)?,
125        inner: inner
126            .into_iter()
127            .map(sample)
128            .collect::<GeometryResult<_>>()?,
129    })
130}
131
132/// [`compile_profile_outline_with`] with [`default_backend`].
133///
134/// # Errors
135///
136/// As [`compile_profile_outline_with`].
137#[cfg(feature = "compile-reference-backend")]
138pub fn compile_profile_outline(
139    model: &Model,
140    profile: EntityId,
141    tolerance: Tolerance,
142) -> GeometryResult<SampledProfileOutline> {
143    compile_profile_outline_with(&default_backend(), model, profile, tolerance)
144}
145
146fn sampled_ring<B: PolylineCompiler>(
147    backend: &B,
148    model: &Model,
149    scale: &units::UnitScale,
150    curve: EntityId,
151    tolerance: Tolerance,
152) -> GeometryResult<SampledRing> {
153    let none = ChordDeviation::new(tolerance.linear(), 0.0);
154    let entity = model.get(curve).ok_or(GeometryError::MissingEntity {
155        referrer: curve,
156        missing: curve,
157    })?;
158    let boundary = if entity.type_name.eq_ignore_ascii_case("IFCINDEXEDPOLYCURVE") {
159        arc_boundary(model, curve, entity)?
160    } else {
161        None
162    };
163    let Some(boundary) = boundary else {
164        return Ok(SampledRing {
165            curve,
166            vertices: ring(model, scale, curve)?,
167            arcs: Vec::new(),
168            deviation: none,
169        });
170    };
171
172    let mut session = LoweringSession::new(model, scale);
173    let node = lower_curve_node(&mut session, curve, Transform::identity())?;
174    let children: Vec<_> = match session.relation(node) {
175        Some(GeometryNode::CurveRelation(CurveRelation::Composite { segments }))
176            if segments.len() == boundary.segments.len() =>
177        {
178            segments.iter().map(|segment| segment.curve).collect()
179        }
180        _ => {
181            return Err(GeometryError::Unsupported {
182                entity: curve,
183                type_name: entity.type_name.to_ascii_uppercase(),
184                detail: "the lowered boundary is not one node per segment",
185            })
186        }
187    };
188    let lowered = session.finish(node)?;
189    let options = ExecutionOptions::new(tolerance);
190    let metres = |index: usize| {
191        let [x, y] = boundary.list[index];
192        [scale.length(x), scale.length(y)]
193    };
194
195    let mut vertices: Vec<[f64; 2]> = Vec::new();
196    let mut arcs = Vec::new();
197    let mut bound = 0.0_f64;
198    for (segment, (part, child)) in boundary.segments.iter().zip(children).enumerate() {
199        match part {
200            PolySegment::Line(run) => {
201                if vertices.is_empty() {
202                    vertices.push(metres(run[0]));
203                }
204                vertices.extend(run[1..].iter().map(|&index| metres(index)));
205            }
206            PolySegment::Arc { start, end, .. } => {
207                if vertices.is_empty() {
208                    vertices.push(metres(*start));
209                }
210                let outcome = backend
211                    .compile_polyline(&lowered.graph, child, &options)
212                    .map_err(|error| refused(curve, error, &lowered.provenance))?;
213                let points = &outcome.points;
214                if points.len() < 2 {
215                    return Err(GeometryError::CompilationRefused {
216                        entity: curve,
217                        reason: "the backend returned fewer than two vertices for an arc"
218                            .to_owned(),
219                    });
220                }
221                let authored_start = metres(*start);
222                let authored_end = metres(*end);
223                let to = |p: &super::Point3, q: [f64; 2]| (p.x - q[0]).hypot(p.y - q[1]).hypot(p.z);
224                let (first, last) = (&points[0], &points[points.len() - 1]);
225                if to(first, authored_end) < to(first, authored_start) {
226                    return Err(GeometryError::CompilationRefused {
227                        entity: curve,
228                        reason: "the backend's arc polyline runs from the arc's end to its start"
229                            .to_owned(),
230                    });
231                }
232                let snapped = to(first, authored_start).max(to(last, authored_end));
233                if snapped.is_nan() || snapped > tolerance.linear() {
234                    return Err(GeometryError::CompilationRefused {
235                        entity: curve,
236                        reason: format!(
237                            "the backend's arc ends are {snapped} m from the authored end \
238                             points, beyond the linear tolerance {}",
239                            tolerance.linear()
240                        ),
241                    });
242                }
243                let samples = &points[1..points.len() - 1];
244                if let Some(off) = samples.iter().find(|p| p.z.abs() > tolerance.linear()) {
245                    return Err(GeometryError::Degenerate {
246                        entity: curve,
247                        type_name: entity.type_name.to_ascii_uppercase(),
248                        detail: format!(
249                            "a sampled arc vertex leaves the profile plane (z = {})",
250                            off.z
251                        ),
252                    });
253                }
254                let arc_bound = outcome.deviation.bound + snapped;
255                arcs.push(SampledArc {
256                    segment,
257                    start: vertices.len() - 1,
258                    samples: samples.len(),
259                    bound: arc_bound,
260                });
261                bound = bound.max(arc_bound);
262                vertices.extend(samples.iter().map(|p| [p.x, p.y]));
263                // The authored end, not the backend's evaluation there.
264                vertices.push(metres(*end));
265            }
266        }
267    }
268    // The boundary closes by index: its last vertex is its first.
269    vertices.pop();
270    if vertices.len() < 3 {
271        return Err(GeometryError::Degenerate {
272            entity: curve,
273            type_name: entity.type_name.to_ascii_uppercase(),
274            detail: format!(
275                "a profile boundary needs at least 3 distinct vertices, found {}",
276                vertices.len()
277            ),
278        });
279    }
280    Ok(SampledRing {
281        curve,
282        vertices,
283        arcs,
284        deviation: ChordDeviation::new(tolerance.linear(), bound),
285    })
286}