1use crate::error::GeometryResult;
21use crate::resource::point::{CartesianPoint, CartesianPointList};
22use crate::resource::resolve;
23use crate::slots::Slots;
24use ifc_model::{Entity, EntityId, Model, Value};
25
26pub(crate) mod polyline_slot {
31 pub const POINTS: usize = 0;
33}
34
35pub(crate) mod indexed_slot {
39 pub const POINTS: usize = 0;
41 pub const SEGMENTS: usize = 1;
43 pub const SELF_INTERSECT: usize = 2;
45}
46
47#[derive(Debug, Clone, Copy)]
49pub struct Polyline<'m> {
50 slots: Slots<'m>,
51}
52
53impl<'m> Polyline<'m> {
54 pub fn new(id: EntityId, entity: &'m Entity) -> Self {
56 Self {
57 slots: Slots::new(id, entity),
58 }
59 }
60
61 pub fn id(&self) -> EntityId {
63 self.slots.id()
64 }
65
66 pub fn point_refs(&self) -> GeometryResult<Vec<EntityId>> {
72 let points = self.slots.req_ref_list(polyline_slot::POINTS, "Points")?;
73 if points.len() < 2 {
74 return Err(self.slots.degenerate(format!(
75 "Points must hold at least 2 entries, found {}",
76 points.len()
77 )));
78 }
79 Ok(points)
80 }
81
82 pub fn points<'v>(&self, model: &'v Model) -> GeometryResult<Vec<CartesianPoint<'v>>> {
87 resolve::cartesian_points(model, self.id(), &self.point_refs()?)
88 }
89
90 pub fn closes_by_repeating_first_point(&self) -> GeometryResult<bool> {
102 let points = self.point_refs()?;
103 Ok(points.first() == points.last())
104 }
105}
106
107#[derive(Debug, Clone, PartialEq, Eq)]
113pub enum PolySegment {
114 Line(Vec<usize>),
119 Arc {
124 start: usize,
126 mid: usize,
128 end: usize,
130 },
131}
132
133impl PolySegment {
134 pub fn indices(&self) -> Vec<usize> {
136 match self {
137 Self::Line(indices) => indices.clone(),
138 Self::Arc { start, mid, end } => vec![*start, *mid, *end],
139 }
140 }
141
142 pub fn is_arc(&self) -> bool {
144 matches!(self, Self::Arc { .. })
145 }
146}
147
148#[derive(Debug, Clone, Copy)]
150pub struct IndexedPolyCurve<'m> {
151 slots: Slots<'m>,
152}
153
154impl<'m> IndexedPolyCurve<'m> {
155 pub fn new(id: EntityId, entity: &'m Entity) -> Self {
157 Self {
158 slots: Slots::new(id, entity),
159 }
160 }
161
162 pub fn id(&self) -> EntityId {
164 self.slots.id()
165 }
166
167 pub fn points_ref(&self) -> GeometryResult<EntityId> {
169 self.slots.req_ref(indexed_slot::POINTS, "Points")
170 }
171
172 pub fn points<'v>(&self, model: &'v Model) -> GeometryResult<CartesianPointList<'v>> {
176 resolve::cartesian_point_list(model, self.id(), self.points_ref()?)
177 }
178
179 pub fn self_intersect(&self) -> Option<bool> {
181 self.slots.opt_bool(indexed_slot::SELF_INTERSECT)
182 }
183
184 pub fn has_explicit_segments(&self) -> bool {
191 self.slots.opt(indexed_slot::SEGMENTS).is_some()
192 }
193
194 pub fn segments(&self, point_count: usize) -> GeometryResult<Vec<PolySegment>> {
205 let Some(value) = self.slots.opt(indexed_slot::SEGMENTS) else {
206 return Ok(Vec::new());
207 };
208 let items = value.as_list().ok_or_else(|| {
209 self.slots
210 .degenerate("Segments must be a list of IfcSegmentIndexSelect")
211 })?;
212 items
213 .iter()
214 .map(|item| self.parse_segment(item, point_count))
215 .collect()
216 }
217
218 pub fn implicit_polyline_indices(point_count: usize) -> Vec<usize> {
223 (0..point_count).collect()
224 }
225
226 fn parse_segment(&self, item: &Value, point_count: usize) -> GeometryResult<PolySegment> {
227 let Value::Typed { type_name, value } = item else {
232 return Err(self.slots.degenerate(
233 "segment is not a typed IfcLineIndex/IfcArcIndex; the select tag is required \
234 to tell a line from an arc",
235 ));
236 };
237 let raw = value.as_list().ok_or_else(|| {
238 self.slots
239 .degenerate(format!("{type_name} must wrap a list of indices"))
240 })?;
241
242 let mut indices = Vec::with_capacity(raw.len());
243 for v in raw {
244 let n = match v.unwrap_typed() {
245 Value::Integer(i) => *i,
246 other => {
247 return Err(self
248 .slots
249 .degenerate(format!("{type_name} index is not an integer: {other:?}")));
250 }
251 };
252 if n < 1 {
255 return Err(self.slots.degenerate(format!(
256 "{type_name} index {n} is not a positive integer; \
257 IfcPositiveInteger starts at 1"
258 )));
259 }
260 let zero_based = (n - 1) as usize;
261 if zero_based >= point_count {
262 return Err(self.slots.degenerate(format!(
263 "{type_name} index {n} is out of range for a point list of {point_count}"
264 )));
265 }
266 indices.push(zero_based);
267 }
268
269 match type_name.to_ascii_uppercase().as_str() {
270 "IFCLINEINDEX" => {
271 if indices.len() < 2 {
272 return Err(self.slots.degenerate(format!(
273 "IfcLineIndex needs at least 2 indices, found {}",
274 indices.len()
275 )));
276 }
277 Ok(PolySegment::Line(indices))
278 }
279 "IFCARCINDEX" => {
280 if indices.len() != 3 {
281 return Err(self.slots.degenerate(format!(
282 "IfcArcIndex needs exactly 3 indices (start, on-arc, end), found {}",
283 indices.len()
284 )));
285 }
286 Ok(PolySegment::Arc {
287 start: indices[0],
288 mid: indices[1],
289 end: indices[2],
290 })
291 }
292 other => Err(self
293 .slots
294 .degenerate(format!("{other} is not an IfcSegmentIndexSelect member"))),
295 }
296 }
297}
298
299#[cfg(test)]
300mod tests {
301 use super::*;
302
303 fn refs(ids: &[u64]) -> Value {
304 Value::List(ids.iter().map(|i| Value::Ref(EntityId(*i))).collect())
305 }
306
307 fn index_select(name: &str, indices: &[i64]) -> Value {
308 Value::Typed {
309 type_name: name.into(),
310 value: Box::new(Value::List(
311 indices.iter().map(|i| Value::Integer(*i)).collect(),
312 )),
313 }
314 }
315
316 fn indexed(segments: Value) -> Entity {
317 Entity::new(
318 "IFCINDEXEDPOLYCURVE",
319 vec![Value::Ref(EntityId(100)), segments, Value::Bool(false)],
320 )
321 }
322
323 fn point(values: &[f64]) -> Entity {
324 Entity::new(
325 "IFCCARTESIANPOINT",
326 vec![Value::List(
327 values.iter().copied().map(Value::Real).collect(),
328 )],
329 )
330 }
331
332 #[test]
333 fn polyline_points_resolve_in_file_order() {
334 let mut model = Model::new();
335 model.insert(EntityId(1), point(&[0.0, 0.0]));
336 model.insert(EntityId(2), point(&[1.0, 0.0]));
337 let e = Entity::new("IFCPOLYLINE", vec![refs(&[2, 1])]);
338 let points = Polyline::new(EntityId(9), &e).points(&model).unwrap();
339 let ids: Vec<_> = points.iter().map(|p| p.id()).collect();
340 assert_eq!(ids, vec![EntityId(2), EntityId(1)]);
341 assert_eq!(points[0].coordinates().unwrap(), vec![1.0, 0.0]);
342 }
343
344 #[test]
345 fn a_polyline_vertex_of_the_wrong_type_fails_the_whole_list() {
346 let mut model = Model::new();
347 model.insert(EntityId(1), point(&[0.0, 0.0]));
348 model.insert(EntityId(2), Entity::new("IFCDIRECTION", vec![]));
349 let e = Entity::new("IFCPOLYLINE", vec![refs(&[1, 2])]);
350 let err = Polyline::new(EntityId(9), &e).points(&model).unwrap_err();
351 assert!(matches!(
352 err,
353 crate::GeometryError::WrongEntityType {
354 entity: EntityId(2),
355 ..
356 }
357 ));
358 }
359
360 #[test]
361 fn indexed_points_resolve_to_the_declared_list_subtype() {
362 let mut model = Model::new();
363 model.insert(
364 EntityId(100),
365 Entity::new(
366 "IFCCARTESIANPOINTLIST3D",
367 vec![Value::List(vec![Value::List(vec![
368 Value::Real(0.0),
369 Value::Real(0.0),
370 Value::Real(1.0),
371 ])])],
372 ),
373 );
374 let e = indexed(Value::Null);
375 let list = IndexedPolyCurve::new(EntityId(9), &e)
376 .points(&model)
377 .unwrap();
378 assert_eq!(list.id(), EntityId(100));
379 assert_eq!(list.dimension(), 3);
380 }
381
382 #[test]
383 fn indexed_points_reject_a_single_point_and_a_dangling_list() {
384 let mut model = Model::new();
385 model.insert(EntityId(100), point(&[0.0, 0.0]));
386 let e = indexed(Value::Null);
387 let view = IndexedPolyCurve::new(EntityId(9), &e);
388 assert!(matches!(
389 view.points(&model).unwrap_err(),
390 crate::GeometryError::WrongEntityType { .. }
391 ));
392 let err = view.points(&Model::new()).unwrap_err();
393 assert_eq!(err.entity(), Some(EntityId(9)));
394 }
395
396 #[test]
397 fn polyline_reads_its_points_in_file_order() {
398 let e = Entity::new("IFCPOLYLINE", vec![refs(&[1, 2, 3])]);
399 let view = Polyline::new(EntityId(1), &e);
400 assert_eq!(
401 view.point_refs().unwrap(),
402 vec![EntityId(1), EntityId(2), EntityId(3)]
403 );
404 }
405
406 #[test]
407 fn polyline_with_fewer_than_two_points_is_degenerate() {
408 let e = Entity::new("IFCPOLYLINE", vec![refs(&[1])]);
409 let err = Polyline::new(EntityId(4), &e).point_refs().unwrap_err();
410 assert!(err.to_string().contains("#4"), "got: {err}");
411 }
412
413 #[test]
416 fn polyline_closure_is_detected_from_a_repeated_first_reference() {
417 let closed = Entity::new("IFCPOLYLINE", vec![refs(&[1, 2, 3, 1])]);
418 let open = Entity::new("IFCPOLYLINE", vec![refs(&[1, 2, 3])]);
419 assert!(Polyline::new(EntityId(1), &closed)
420 .closes_by_repeating_first_point()
421 .unwrap());
422 assert!(!Polyline::new(EntityId(1), &open)
423 .closes_by_repeating_first_point()
424 .unwrap());
425 }
426
427 #[test]
430 fn one_based_file_indices_become_zero_based_rust_indices() {
431 let e = indexed(Value::List(vec![index_select("IFCLINEINDEX", &[1, 2, 3])]));
432 let segments = IndexedPolyCurve::new(EntityId(1), &e).segments(5).unwrap();
433 assert_eq!(segments, vec![PolySegment::Line(vec![0, 1, 2])]);
434 }
435
436 #[test]
437 fn arc_index_names_its_middle_point_as_on_arc_not_as_a_centre() {
438 let e = indexed(Value::List(vec![index_select("IFCARCINDEX", &[3, 4, 5])]));
439 let segments = IndexedPolyCurve::new(EntityId(1), &e).segments(9).unwrap();
440 assert_eq!(
441 segments,
442 vec![PolySegment::Arc {
443 start: 2,
444 mid: 3,
445 end: 4
446 }]
447 );
448 assert!(segments[0].is_arc());
449 }
450
451 #[test]
452 fn an_index_past_the_end_of_the_point_list_is_rejected() {
453 let e = indexed(Value::List(vec![index_select("IFCLINEINDEX", &[1, 9])]));
454 let err = IndexedPolyCurve::new(EntityId(2), &e)
455 .segments(3)
456 .unwrap_err();
457 assert!(err.to_string().contains("out of range"), "got: {err}");
458 }
459
460 #[test]
463 fn index_zero_is_rejected_rather_than_underflowing() {
464 let e = indexed(Value::List(vec![index_select("IFCLINEINDEX", &[0, 1])]));
465 assert!(IndexedPolyCurve::new(EntityId(1), &e).segments(3).is_err());
466 }
467
468 #[test]
469 fn arc_index_with_the_wrong_cardinality_is_rejected() {
470 let e = indexed(Value::List(vec![index_select("IFCARCINDEX", &[1, 2])]));
471 let err = IndexedPolyCurve::new(EntityId(1), &e)
472 .segments(5)
473 .unwrap_err();
474 assert!(err.to_string().contains("exactly 3"), "got: {err}");
475 }
476
477 #[test]
478 fn line_index_needs_at_least_two_indices() {
479 let e = indexed(Value::List(vec![index_select("IFCLINEINDEX", &[2])]));
480 assert!(IndexedPolyCurve::new(EntityId(1), &e).segments(5).is_err());
481 }
482
483 #[test]
486 fn an_untagged_segment_is_rejected_rather_than_assumed_to_be_a_line() {
487 let e = indexed(Value::List(vec![Value::List(vec![
488 Value::Integer(1),
489 Value::Integer(2),
490 ])]));
491 let err = IndexedPolyCurve::new(EntityId(1), &e)
492 .segments(5)
493 .unwrap_err();
494 assert!(err.to_string().contains("select tag"), "got: {err}");
495 }
496
497 #[test]
500 fn absent_segments_is_distinguishable_from_an_empty_segment_list() {
501 let absent = Entity::new("IFCINDEXEDPOLYCURVE", vec![Value::Ref(EntityId(100))]);
502 let view = IndexedPolyCurve::new(EntityId(1), &absent);
503 assert!(!view.has_explicit_segments());
504 assert!(view.segments(4).unwrap().is_empty());
505 assert_eq!(
506 IndexedPolyCurve::implicit_polyline_indices(4),
507 vec![0, 1, 2, 3]
508 );
509
510 let empty = indexed(Value::List(vec![]));
511 assert!(IndexedPolyCurve::new(EntityId(1), &empty).has_explicit_segments());
512 }
513
514 #[test]
515 fn mixed_line_and_arc_segments_keep_their_file_order() {
516 let e = indexed(Value::List(vec![
517 index_select("IFCLINEINDEX", &[1, 2]),
518 index_select("IFCARCINDEX", &[2, 3, 4]),
519 index_select("IFCLINEINDEX", &[4, 5]),
520 ]));
521 let segments = IndexedPolyCurve::new(EntityId(1), &e).segments(5).unwrap();
522 assert_eq!(segments.len(), 3);
523 assert!(!segments[0].is_arc());
524 assert!(segments[1].is_arc());
525 assert_eq!(segments[2].indices(), vec![3, 4]);
526 }
527}