1use 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#[derive(Debug, Clone, PartialEq)]
48#[non_exhaustive]
49pub struct SampledProfileOutline {
50 pub profile: EntityId,
52 pub outer: SampledRing,
54 pub inner: Vec<SampledRing>,
57}
58
59#[derive(Debug, Clone, PartialEq)]
61#[non_exhaustive]
62pub struct SampledRing {
63 pub curve: EntityId,
65 pub vertices: Vec<[f64; 2]>,
67 pub arcs: Vec<SampledArc>,
69 pub deviation: ChordDeviation,
72}
73
74#[derive(Debug, Clone, Copy, PartialEq)]
76#[non_exhaustive]
77pub struct SampledArc {
78 pub segment: usize,
80 pub start: usize,
82 pub samples: usize,
85 pub bound: f64,
88}
89
90pub 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#[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 vertices.push(metres(*end));
265 }
266 }
267 }
268 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}