ifc_geometry/input/profile/
outline.rs1use 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
43const SAME_VERTEX: f64 = 1e-12;
48
49#[derive(Debug, Clone, PartialEq)]
55#[non_exhaustive]
56pub struct ProfileOutline {
57 pub profile: EntityId,
59 pub outer: Vec<[f64; 2]>,
61 pub inner: Vec<Vec<[f64; 2]>>,
64}
65
66pub 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
98pub(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
123pub(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 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
198fn 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
222fn 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
263fn 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
276fn 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")]
296pub(crate) struct ArcBoundary {
298 pub(crate) list: Vec<[f64; 2]>,
300 pub(crate) segments: Vec<PolySegment>,
302}
303
304#[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}