1use crate::error::GeometryResult;
33use crate::resource::point::CartesianPoint;
34use crate::resource::resolve;
35use crate::slots::Slots;
36use ifc_model::{Entity, EntityId, Model, Value};
37
38pub(crate) mod slot {
45 pub const DEGREE: usize = 0;
47 pub const CONTROL_POINTS: usize = 1;
49 pub const CURVE_FORM: usize = 2;
51 pub const CLOSED_CURVE: usize = 3;
53 pub const SELF_INTERSECT: usize = 4;
55 pub const KNOT_MULTIPLICITIES: usize = 5;
57 pub const KNOTS: usize = 6;
59 pub const KNOT_SPEC: usize = 7;
61 pub const WEIGHTS_DATA: usize = 8;
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum BSplineCurveForm {
73 Polyline,
75 CircularArc,
77 EllipticArc,
79 ParabolicArc,
81 HyperbolicArc,
83 Unspecified,
85}
86
87impl BSplineCurveForm {
88 pub fn from_token(token: &str) -> Option<Self> {
90 match token.to_ascii_uppercase().as_str() {
91 "POLYLINE_FORM" => Some(Self::Polyline),
92 "CIRCULAR_ARC" => Some(Self::CircularArc),
93 "ELLIPTIC_ARC" => Some(Self::EllipticArc),
94 "PARABOLIC_ARC" => Some(Self::ParabolicArc),
95 "HYPERBOLIC_ARC" => Some(Self::HyperbolicArc),
96 "UNSPECIFIED" => Some(Self::Unspecified),
97 _ => None,
98 }
99 }
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum KnotType {
108 Uniform,
110 QuasiUniform,
112 PiecewiseBezier,
114 Unspecified,
116}
117
118impl KnotType {
119 pub fn from_token(token: &str) -> Option<Self> {
121 match token.to_ascii_uppercase().as_str() {
122 "UNIFORM_KNOTS" => Some(Self::Uniform),
123 "QUASI_UNIFORM_KNOTS" => Some(Self::QuasiUniform),
124 "PIECEWISE_BEZIER_KNOTS" => Some(Self::PiecewiseBezier),
125 "UNSPECIFIED" => Some(Self::Unspecified),
126 _ => None,
127 }
128 }
129}
130
131#[derive(Debug, Clone, Copy)]
137pub struct BSplineCurve<'m> {
138 slots: Slots<'m>,
139}
140
141impl<'m> BSplineCurve<'m> {
142 pub fn new(id: EntityId, entity: &'m Entity) -> Self {
144 Self {
145 slots: Slots::new(id, entity),
146 }
147 }
148
149 pub fn id(&self) -> EntityId {
151 self.slots.id()
152 }
153
154 pub fn degree(&self) -> GeometryResult<usize> {
160 let raw = self.slots.req_i64(slot::DEGREE, "Degree")?;
161 if raw < 1 {
162 return Err(self
163 .slots
164 .degenerate(format!("Degree must be at least 1, found {raw}")));
165 }
166 let degree = usize::try_from(raw)
167 .map_err(|_| self.slots.degenerate("Degree exceeds platform limits"))?;
168 let control_count = self.control_point_refs()?.len();
169 if degree >= control_count {
170 return Err(self.slots.degenerate(format!(
171 "Degree {degree} must be smaller than the {control_count} control points"
172 )));
173 }
174 Ok(degree)
175 }
176
177 pub fn control_point_refs(&self) -> GeometryResult<Vec<EntityId>> {
181 let points = self
182 .slots
183 .req_ref_list(slot::CONTROL_POINTS, "ControlPointsList")?;
184 if points.len() < 2 {
185 return Err(self.slots.degenerate(format!(
186 "ControlPointsList needs at least 2 points, found {}",
187 points.len()
188 )));
189 }
190 Ok(points)
191 }
192
193 pub fn control_points<'v>(&self, model: &'v Model) -> GeometryResult<Vec<CartesianPoint<'v>>> {
198 resolve::cartesian_points(model, self.id(), &self.control_point_refs()?)
199 }
200
201 pub fn curve_form(&self) -> BSplineCurveForm {
203 self.slots
204 .opt_enum(slot::CURVE_FORM)
205 .and_then(BSplineCurveForm::from_token)
206 .unwrap_or(BSplineCurveForm::Unspecified)
207 }
208
209 pub fn closed_curve(&self) -> Option<bool> {
214 self.slots.opt_bool(slot::CLOSED_CURVE)
215 }
216
217 pub fn self_intersect(&self) -> Option<bool> {
219 self.slots.opt_bool(slot::SELF_INTERSECT)
220 }
221
222 pub fn knot_spec(&self) -> KnotType {
224 self.slots
225 .opt_enum(slot::KNOT_SPEC)
226 .and_then(KnotType::from_token)
227 .unwrap_or(KnotType::Unspecified)
228 }
229
230 pub fn has_knots(&self) -> bool {
232 self.slots.opt(slot::KNOTS).is_some()
233 }
234
235 pub fn is_rational(&self) -> bool {
241 self.slots
242 .type_name()
243 .eq_ignore_ascii_case("IFCRATIONALBSPLINECURVEWITHKNOTS")
244 }
245
246 pub fn knots(&self) -> GeometryResult<Option<KnotVector>> {
253 if !self.has_knots() {
254 return Ok(None);
255 }
256 let values = self.slots.req_f64_list(slot::KNOTS, "Knots")?;
257 let multiplicities = self.integer_list(slot::KNOT_MULTIPLICITIES, "KnotMultiplicities")?;
258
259 if values.len() != multiplicities.len() {
260 return Err(self.slots.degenerate(format!(
261 "Knots has {} entries but KnotMultiplicities has {}; \
262 they are parallel lists",
263 values.len(),
264 multiplicities.len()
265 )));
266 }
267 if values.is_empty() {
268 return Err(self.slots.degenerate("Knots is empty"));
269 }
270 for (i, m) in multiplicities.iter().enumerate() {
271 if *m < 1 {
272 return Err(self.slots.degenerate(format!(
273 "knot multiplicity {m} at position {i} is not positive"
274 )));
275 }
276 }
277 for (index, value) in values.iter().enumerate() {
278 if !value.is_finite() {
279 return Err(self
280 .slots
281 .degenerate(format!("Knots[{index}] must be finite, found {value}")));
282 }
283 }
284 for pair in values.windows(2) {
288 if pair[1] <= pair[0] {
289 return Err(self.slots.degenerate(format!(
290 "Knots must be strictly increasing; found {} after {}",
291 pair[1], pair[0]
292 )));
293 }
294 }
295
296 let multiplicities = multiplicities
297 .into_iter()
298 .map(|value| {
299 usize::try_from(value).map_err(|_| {
300 self.slots
301 .degenerate("knot multiplicity exceeds platform limits")
302 })
303 })
304 .collect::<GeometryResult<Vec<_>>>()?;
305 let total = multiplicities.iter().try_fold(0usize, |total, &value| {
306 total.checked_add(value).ok_or_else(|| {
307 self.slots
308 .degenerate("knot multiplicity total overflows usize")
309 })
310 })?;
311 let expected = self
312 .control_point_refs()?
313 .len()
314 .checked_add(self.degree()?)
315 .and_then(|value| value.checked_add(1))
316 .ok_or_else(|| self.slots.degenerate("expected knot count overflows usize"))?;
317 if total != expected {
318 return Err(self.slots.degenerate(format!(
319 "knot multiplicities sum to {total} but must equal \
320 ControlPoints + Degree + 1 = {expected}"
321 )));
322 }
323
324 Ok(Some(KnotVector {
325 values,
326 multiplicities,
327 }))
328 }
329
330 pub fn weights(&self) -> GeometryResult<Option<Vec<f64>>> {
336 let supplied = self.slots.opt(slot::WEIGHTS_DATA).is_some();
337 match (self.is_rational(), supplied) {
338 (false, false) => return Ok(None),
339 (true, false) => {
340 return Err(self
341 .slots
342 .degenerate("rational B-spline curve is missing WeightsData"));
343 }
344 (false, true) => {
345 return Err(self
346 .slots
347 .degenerate("polynomial B-spline curve must not carry WeightsData"));
348 }
349 (true, true) => {}
350 }
351 let weights = self.slots.req_f64_list(slot::WEIGHTS_DATA, "WeightsData")?;
352 let control_points = self.control_point_refs()?.len();
353 if weights.len() != control_points {
354 return Err(self.slots.degenerate(format!(
355 "WeightsData has {} entries but there are {control_points} control points",
356 weights.len()
357 )));
358 }
359 for (i, w) in weights.iter().enumerate() {
360 if !w.is_finite() {
361 return Err(self
362 .slots
363 .degenerate(format!("weight {w} at control point {i} must be finite")));
364 }
365 if *w <= 0.0 {
366 return Err(self
367 .slots
368 .degenerate(format!("weight {w} at control point {i} must be positive")));
369 }
370 }
371 Ok(Some(weights))
372 }
373
374 fn integer_list(&self, index: usize, name: &'static str) -> GeometryResult<Vec<i64>> {
379 let value = self.slots.req(index, name)?;
380 let items = value
381 .as_list()
382 .ok_or_else(|| self.slots.degenerate(format!("{name} must be a list")))?;
383 items
384 .iter()
385 .map(|v| match v.unwrap_typed() {
386 Value::Integer(i) => Ok(*i),
387 other => Err(self
388 .slots
389 .degenerate(format!("{name} entry is not an integer: {other:?}"))),
390 })
391 .collect()
392 }
393}
394
395#[derive(Debug, Clone, PartialEq)]
401pub struct KnotVector {
402 pub values: Vec<f64>,
404 pub multiplicities: Vec<usize>,
406}
407
408impl KnotVector {
409 pub fn expanded(&self) -> Option<Vec<f64>> {
418 let total = self.total_multiplicity()?;
419 let mut out = Vec::with_capacity(total);
420 for (value, multiplicity) in self.values.iter().zip(&self.multiplicities) {
421 out.extend(std::iter::repeat_n(*value, *multiplicity));
422 }
423 Some(out)
424 }
425
426 pub fn total_multiplicity(&self) -> Option<usize> {
432 self.multiplicities
433 .iter()
434 .try_fold(0usize, |acc, m| acc.checked_add(*m))
435 }
436
437 pub fn is_clamped(&self, degree: usize) -> bool {
445 let want = degree + 1;
446 self.multiplicities.first() == Some(&want) && self.multiplicities.last() == Some(&want)
447 }
448}
449
450#[cfg(test)]
451mod tests {
452 use super::*;
453
454 fn refs(n: usize) -> Value {
455 Value::List((0..n).map(|i| Value::Ref(EntityId(i as u64 + 1))).collect())
456 }
457
458 fn integers(values: &[i64]) -> Value {
459 Value::List(values.iter().map(|i| Value::Integer(*i)).collect())
460 }
461
462 fn reals(values: &[f64]) -> Value {
463 Value::List(values.iter().map(|r| Value::Real(*r)).collect())
464 }
465
466 fn with_knots(control_points: usize, multiplicities: &[i64], knots: &[f64]) -> Entity {
468 Entity::new(
469 "IFCBSPLINECURVEWITHKNOTS",
470 vec![
471 Value::Integer(3),
472 refs(control_points),
473 Value::Enum("UNSPECIFIED".into()),
474 Value::Bool(false),
475 Value::Bool(false),
476 integers(multiplicities),
477 reals(knots),
478 Value::Enum("UNSPECIFIED".into()),
479 ],
480 )
481 }
482
483 fn rational(control_points: usize, weights: &[f64]) -> Entity {
484 let mut attributes = with_knots(control_points, &[4, 4], &[0.0, 1.0]).attributes;
485 attributes.push(reals(weights));
486 Entity::new("IFCRATIONALBSPLINECURVEWITHKNOTS", attributes)
487 }
488
489 #[test]
490 fn control_points_resolve_in_order_and_fail_on_a_dangling_one() {
491 let e = with_knots(4, &[4, 4], &[0.0, 1.0]);
492 let view = BSplineCurve::new(EntityId(9), &e);
493 let model_with = |ids: &[u64]| {
494 let mut model = Model::new();
495 for &i in ids {
496 let point = Entity::new("IFCCARTESIANPOINT", vec![reals(&[i as f64, 0.0])]);
497 model.insert(EntityId(i), point);
498 }
499 model
500 };
501 let model = model_with(&[1, 2, 3, 4]);
502 let points = view.control_points(&model).unwrap();
503 assert_eq!(points[3].coordinates().unwrap(), vec![4.0, 0.0]);
504 let err = view.control_points(&model_with(&[1, 2, 4])).unwrap_err();
505 assert!(matches!(
506 err,
507 crate::GeometryError::MissingEntity {
508 referrer: EntityId(9),
509 missing: EntityId(3)
510 }
511 ));
512 }
513
514 #[test]
515 fn inherited_bspline_slots_are_read_before_the_subtype_own_slots() {
516 let e = with_knots(4, &[4, 4], &[0.0, 1.0]);
517 let view = BSplineCurve::new(EntityId(1), &e);
518 assert_eq!(view.degree().unwrap(), 3);
519 assert_eq!(view.control_point_refs().unwrap().len(), 4);
520 assert!(view.has_knots());
521 assert!(!view.is_rational());
522 }
523
524 #[test]
525 fn a_valid_knot_vector_expands_to_control_points_plus_degree_plus_one() {
526 let e = with_knots(4, &[4, 4], &[0.0, 1.0]);
527 let knots = BSplineCurve::new(EntityId(1), &e).knots().unwrap().unwrap();
528 assert_eq!(
529 knots.expanded(),
530 Some(vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0])
531 );
532 assert_eq!(knots.total_multiplicity(), Some(4 + 3 + 1));
533 assert!(knots.is_clamped(3));
534 }
535
536 #[test]
537 fn a_knot_multiplicity_sum_that_disagrees_with_the_degree_is_rejected() {
538 let e = with_knots(4, &[4, 3], &[0.0, 1.0]);
539 let err = BSplineCurve::new(EntityId(6), &e).knots().unwrap_err();
540 assert!(err.to_string().contains("must equal"), "got: {err}");
541 assert!(err.to_string().contains("#6"), "got: {err}");
542 }
543
544 #[test]
547 fn multiplicities_summing_past_usize_report_rather_than_panic() {
548 let kv = KnotVector {
549 values: vec![0.0, 1.0],
550 multiplicities: vec![usize::MAX, 2],
551 };
552 assert_eq!(kv.total_multiplicity(), None);
553 assert_eq!(kv.expanded(), None);
554 }
555
556 #[test]
557 fn knots_and_multiplicities_of_different_lengths_are_rejected() {
558 let e = with_knots(4, &[4, 4], &[0.0, 0.5, 1.0]);
559 let err = BSplineCurve::new(EntityId(1), &e).knots().unwrap_err();
560 assert!(err.to_string().contains("parallel"), "got: {err}");
561 }
562
563 #[test]
566 fn non_increasing_knot_values_are_rejected() {
567 let e = with_knots(5, &[4, 1, 4], &[0.0, 1.0, 1.0]);
568 let err = BSplineCurve::new(EntityId(1), &e).knots().unwrap_err();
569 assert!(err.to_string().contains("increasing"), "got: {err}");
570 }
571
572 #[test]
573 fn non_finite_knot_values_are_rejected_by_the_typed_view() {
574 for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
575 let values = if bad.is_sign_negative() {
576 [bad, 1.0]
577 } else {
578 [0.0, bad]
579 };
580 let e = with_knots(4, &[4, 4], &values);
581 let err = BSplineCurve::new(EntityId(13), &e).knots().unwrap_err();
582 assert!(err.to_string().contains("finite"), "knot {bad}: {err}");
583 }
584 }
585
586 #[test]
587 fn an_unclamped_knot_vector_is_recognised_as_such() {
588 let e = Entity::new(
590 "IFCBSPLINECURVEWITHKNOTS",
591 vec![
592 Value::Integer(3),
593 refs(6),
594 Value::Enum("UNSPECIFIED".into()),
595 Value::Bool(false),
596 Value::Bool(false),
597 integers(&[1; 10]),
598 reals(&[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]),
599 Value::Enum("UNIFORM_KNOTS".into()),
600 ],
601 );
602 let view = BSplineCurve::new(EntityId(1), &e);
603 let knots = view.knots().unwrap().unwrap();
604 assert!(!knots.is_clamped(3));
605 assert_eq!(view.knot_spec(), KnotType::Uniform);
606 }
607
608 #[test]
609 fn a_curve_without_knots_reports_none_rather_than_failing() {
610 let e = Entity::new(
611 "IFCBSPLINECURVE",
612 vec![
613 Value::Integer(3),
614 refs(4),
615 Value::Enum("UNSPECIFIED".into()),
616 Value::Bool(false),
617 Value::Bool(false),
618 ],
619 );
620 let view = BSplineCurve::new(EntityId(1), &e);
621 assert_eq!(view.knots().unwrap(), None);
622 assert_eq!(view.weights().unwrap(), None);
623 }
624
625 #[test]
626 fn rational_weights_are_read_from_the_slot_after_the_knot_attributes() {
627 let e = rational(4, &[1.0, 0.5, 0.5, 1.0]);
628 let view = BSplineCurve::new(EntityId(1), &e);
629 assert!(view.is_rational());
630 assert_eq!(view.weights().unwrap().unwrap(), vec![1.0, 0.5, 0.5, 1.0]);
631 }
632
633 #[test]
636 fn a_zero_weight_is_degenerate() {
637 let e = rational(4, &[1.0, 0.0, 1.0, 1.0]);
638 let err = BSplineCurve::new(EntityId(2), &e).weights().unwrap_err();
639 assert!(err.to_string().contains("positive"), "got: {err}");
640 }
641
642 #[test]
643 fn a_negative_weight_is_degenerate() {
644 let e = rational(4, &[1.0, -1.0, 1.0, 1.0]);
645 assert!(BSplineCurve::new(EntityId(1), &e).weights().is_err());
646 }
647
648 #[test]
649 fn non_finite_weights_are_rejected_by_the_typed_view() {
650 for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
651 let e = rational(4, &[1.0, bad, 1.0, 1.0]);
652 let err = BSplineCurve::new(EntityId(14), &e).weights().unwrap_err();
653 assert!(err.to_string().contains("finite"), "weight {bad}: {err}");
654 }
655 }
656
657 #[test]
658 fn a_weight_count_that_differs_from_the_control_point_count_is_rejected() {
659 let e = rational(4, &[1.0, 1.0, 1.0]);
660 let err = BSplineCurve::new(EntityId(1), &e).weights().unwrap_err();
661 assert!(err.to_string().contains("control points"), "got: {err}");
662 }
663
664 #[test]
665 fn multiplicity_overflow_is_a_typed_error_not_a_panic() {
666 let e = with_knots(4, &[i64::MAX, i64::MAX, i64::MAX], &[0.0, 0.5, 1.0]);
667 let err = BSplineCurve::new(EntityId(8), &e).knots().unwrap_err();
668 assert!(err.to_string().contains("overflow"), "got: {err}");
669 }
670
671 #[test]
672 fn degree_must_not_exceed_the_control_point_upper_index() {
673 let mut e = with_knots(4, &[4, 4], &[0.0, 1.0]);
674 e.attributes[slot::DEGREE] = Value::Integer(4);
675 let err = BSplineCurve::new(EntityId(9), &e).degree().unwrap_err();
676 assert!(err.to_string().contains("control points"), "got: {err}");
677 }
678
679 #[test]
680 fn rational_subtype_requires_weights_and_polynomial_rejects_them() {
681 let attributes = with_knots(4, &[4, 4], &[0.0, 1.0]).attributes;
682 let rational = Entity::new("IFCRATIONALBSPLINECURVEWITHKNOTS", attributes.clone());
683 assert!(BSplineCurve::new(EntityId(10), &rational)
684 .weights()
685 .unwrap_err()
686 .to_string()
687 .contains("missing WeightsData"));
688
689 let mut polynomial_attributes = attributes;
690 polynomial_attributes.push(reals(&[1.0; 4]));
691 let polynomial = Entity::new("IFCBSPLINECURVEWITHKNOTS", polynomial_attributes);
692 assert!(BSplineCurve::new(EntityId(11), &polynomial)
693 .weights()
694 .unwrap_err()
695 .to_string()
696 .contains("must not carry WeightsData"));
697 }
698
699 #[test]
700 fn degree_zero_is_rejected_because_it_describes_no_curve() {
701 let mut e = with_knots(4, &[4, 4], &[0.0, 1.0]);
702 e.attributes[0] = Value::Integer(0);
703 assert!(BSplineCurve::new(EntityId(1), &e).degree().is_err());
704 }
705
706 #[test]
709 fn curve_form_tokens_parse_without_altering_the_control_points() {
710 assert_eq!(
711 BSplineCurveForm::from_token("CIRCULAR_ARC"),
712 Some(BSplineCurveForm::CircularArc)
713 );
714 assert_eq!(BSplineCurveForm::from_token("SPIRAL"), None);
715 assert_eq!(
716 KnotType::from_token("PIECEWISE_BEZIER_KNOTS"),
717 Some(KnotType::PiecewiseBezier)
718 );
719 assert_eq!(KnotType::from_token("WEIRD"), None);
720 }
721}