ifc-geometry 0.5.0

IFC semantic views lowered into the format-neutral geometry DAG.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! `IfcBSplineCurve` and its knotted / rational refinements.
//!
//! # What this module does and does not do
//!
//! It reads the NURBS *parameters*. It does not evaluate a basis function,
//! does not de-Boor, does not insert a knot. Those belong to a geometry
//! kernel. What this module does provide is the consistency checking a kernel
//! would otherwise have to repeat, because every one of these invariants shows
//! up in real files and every one of them produces a NaN or an out-of-bounds
//! read rather than an error.
//!
//! # The invariants worth enforcing at the boundary
//!
//! - **Knot vector length.** `sum(KnotMultiplicities)` must equal
//!   `ControlPoints + Degree + 1`. IFC stores knots in *compressed* form:
//!   distinct values plus their multiplicities, not the repeated vector a
//!   kernel wants. Getting this wrong is not detectable downstream, it just
//!   evaluates garbage.
//! - **Multiplicities and knots are parallel lists.** Different lengths mean
//!   the file is corrupt, not that the shorter one defaults.
//! - **Weights are positive and count-matched.** A zero weight divides by zero
//!   at the corresponding control point; a negative one produces a curve that
//!   flips through infinity. Both are legal IEEE arithmetic and neither is
//!   legal geometry.
//!
//! # Why `ClosedCurve` and `SelfIntersect` are only informational
//!
//! They are `IfcLogical`, may be `.U.`, and are derived facts a file asserts
//! rather than constraints it guarantees. They are exposed as `Option<bool>`
//! so a consumer can use them as a hint and never as a precondition.

use crate::error::GeometryResult;
use crate::resource::point::CartesianPoint;
use crate::resource::resolve;
use crate::slots::Slots;
use ifc_model::{Entity, EntityId, Model, Value};

/// `IfcBSplineCurve` family attribute slots.
///
/// From IFC4 ADD2 TC1. Slots 0-4 come from `IfcBSplineCurve`, 5-7 from
/// `IfcBSplineCurveWithKnots`, and 8 from
/// `IfcRationalBSplineCurveWithKnots`. Inherited attributes come first, so a
/// rational curve reads `Degree` at 0 and `WeightsData` at 8.
pub(crate) mod slot {
    /// `Degree`: `IfcInteger`, from `IfcBSplineCurve`.
    pub const DEGREE: usize = 0;
    /// `ControlPointsList`: `LIST [2:?] OF IfcCartesianPoint`.
    pub const CONTROL_POINTS: usize = 1;
    /// `CurveForm`: `IfcBSplineCurveForm`.
    pub const CURVE_FORM: usize = 2;
    /// `ClosedCurve`: `IfcLogical`.
    pub const CLOSED_CURVE: usize = 3;
    /// `SelfIntersect`: `IfcLogical`.
    pub const SELF_INTERSECT: usize = 4;
    /// `KnotMultiplicities`: from `IfcBSplineCurveWithKnots`.
    pub const KNOT_MULTIPLICITIES: usize = 5;
    /// `Knots`: distinct knot values, from `IfcBSplineCurveWithKnots`.
    pub const KNOTS: usize = 6;
    /// `KnotSpec`: `IfcKnotType`, from `IfcBSplineCurveWithKnots`.
    pub const KNOT_SPEC: usize = 7;
    /// `WeightsData`: from `IfcRationalBSplineCurveWithKnots`.
    pub const WEIGHTS_DATA: usize = 8;
}

/// `IfcBSplineCurveForm`: what shape the curve was originally.
///
/// Purely informational. A `CIRCULAR_ARC` form does not guarantee the control
/// points actually describe a circle, so it must never be used to substitute
/// an analytic curve for the spline. It is worth keeping because it lets a
/// consumer round-trip the hint and lets a UI say something useful.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BSplineCurveForm {
    /// The control points are a polyline.
    Polyline,
    /// Originally a circular arc.
    CircularArc,
    /// Originally an elliptic arc.
    EllipticArc,
    /// Originally a parabolic arc.
    ParabolicArc,
    /// Originally a hyperbolic arc.
    HyperbolicArc,
    /// No original form is claimed.
    Unspecified,
}

impl BSplineCurveForm {
    /// Parse the enumeration token, `None` if unrecognised.
    pub fn from_token(token: &str) -> Option<Self> {
        match token.to_ascii_uppercase().as_str() {
            "POLYLINE_FORM" => Some(Self::Polyline),
            "CIRCULAR_ARC" => Some(Self::CircularArc),
            "ELLIPTIC_ARC" => Some(Self::EllipticArc),
            "PARABOLIC_ARC" => Some(Self::ParabolicArc),
            "HYPERBOLIC_ARC" => Some(Self::HyperbolicArc),
            "UNSPECIFIED" => Some(Self::Unspecified),
            _ => None,
        }
    }
}

/// `IfcKnotType`: the shape of the knot vector.
///
/// Also informational: the knots themselves are stored explicitly, so this
/// only describes them. A kernel should trust the values, not the label.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KnotType {
    /// Evenly spaced knots including the ends.
    Uniform,
    /// Uniform interior knots with clamped ends.
    QuasiUniform,
    /// Interior multiplicity equal to the degree; Bezier segments.
    PiecewiseBezier,
    /// Nothing is claimed about the knot vector.
    Unspecified,
}

impl KnotType {
    /// Parse the enumeration token, `None` if unrecognised.
    pub fn from_token(token: &str) -> Option<Self> {
        match token.to_ascii_uppercase().as_str() {
            "UNIFORM_KNOTS" => Some(Self::Uniform),
            "QUASI_UNIFORM_KNOTS" => Some(Self::QuasiUniform),
            "PIECEWISE_BEZIER_KNOTS" => Some(Self::PiecewiseBezier),
            "UNSPECIFIED" => Some(Self::Unspecified),
            _ => None,
        }
    }
}

/// A borrowed view of any `IfcBSplineCurve` subtype.
///
/// The knot and weight accessors return `Ok(None)` when the entity is a
/// plainer subtype that does not carry them, so one view serves the whole
/// family without the caller re-dispatching on the type name.
#[derive(Debug, Clone, Copy)]
pub struct BSplineCurve<'m> {
    slots: Slots<'m>,
}

impl<'m> BSplineCurve<'m> {
    /// Wrap an entity known to be an `IfcBSplineCurve` subtype.
    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
        Self {
            slots: Slots::new(id, entity),
        }
    }

    /// The entity id.
    pub fn id(&self) -> EntityId {
        self.slots.id()
    }

    /// The polynomial degree, guaranteed to be at least 1 and smaller than
    /// the number of control points.
    ///
    /// IFC requires `Degree <= UpperIndexOnControlPoints`; because the upper
    /// index is `control_points.len() - 1`, `degree >= len` is invalid.
    pub fn degree(&self) -> GeometryResult<usize> {
        let raw = self.slots.req_i64(slot::DEGREE, "Degree")?;
        if raw < 1 {
            return Err(self
                .slots
                .degenerate(format!("Degree must be at least 1, found {raw}")));
        }
        let degree = usize::try_from(raw)
            .map_err(|_| self.slots.degenerate("Degree exceeds platform limits"))?;
        let control_count = self.control_point_refs()?.len();
        if degree >= control_count {
            return Err(self.slots.degenerate(format!(
                "Degree {degree} must be smaller than the {control_count} control points"
            )));
        }
        Ok(degree)
    }

    /// The `IfcCartesianPoint` control point references, in order.
    ///
    /// Order defines the curve; sorting or deduplicating them destroys it.
    pub fn control_point_refs(&self) -> GeometryResult<Vec<EntityId>> {
        let points = self
            .slots
            .req_ref_list(slot::CONTROL_POINTS, "ControlPointsList")?;
        if points.len() < 2 {
            return Err(self.slots.degenerate(format!(
                "ControlPointsList needs at least 2 points, found {}",
                points.len()
            )));
        }
        Ok(points)
    }

    /// The control points as typed point views, resolved from the model.
    ///
    /// All or nothing: a missing control point changes the curve, so one bad
    /// reference fails the call.
    pub fn control_points<'v>(&self, model: &'v Model) -> GeometryResult<Vec<CartesianPoint<'v>>> {
        resolve::cartesian_points(model, self.id(), &self.control_point_refs()?)
    }

    /// The declared original form, defaulting to `Unspecified`.
    pub fn curve_form(&self) -> BSplineCurveForm {
        self.slots
            .opt_enum(slot::CURVE_FORM)
            .and_then(BSplineCurveForm::from_token)
            .unwrap_or(BSplineCurveForm::Unspecified)
    }

    /// The asserted `ClosedCurve` flag; `None` for `.U.` or absent.
    ///
    /// A hint only: nothing verifies that the first and last control points
    /// coincide.
    pub fn closed_curve(&self) -> Option<bool> {
        self.slots.opt_bool(slot::CLOSED_CURVE)
    }

    /// The asserted `SelfIntersect` flag; `None` for `.U.` or absent.
    pub fn self_intersect(&self) -> Option<bool> {
        self.slots.opt_bool(slot::SELF_INTERSECT)
    }

    /// The declared knot type, defaulting to `Unspecified`.
    pub fn knot_spec(&self) -> KnotType {
        self.slots
            .opt_enum(slot::KNOT_SPEC)
            .and_then(KnotType::from_token)
            .unwrap_or(KnotType::Unspecified)
    }

    /// Is this the knotted subtype?
    pub fn has_knots(&self) -> bool {
        self.slots.opt(slot::KNOTS).is_some()
    }

    /// Whether the entity declares the rational subtype.
    ///
    /// Subtype identity, not accidental trailing-slot presence, owns this
    /// semantic. A malformed rational entity with missing weights must fail;
    /// it must never be silently downgraded to a polynomial curve.
    pub fn is_rational(&self) -> bool {
        self.slots
            .type_name()
            .eq_ignore_ascii_case("IFCRATIONALBSPLINECURVEWITHKNOTS")
    }

    /// The compressed knot vector: distinct values with their multiplicities.
    ///
    /// Returns `Ok(None)` for a curve without knots. When present, the two
    /// lists are validated to be the same length and the total multiplicity is
    /// checked against `ControlPoints + Degree + 1`, which is the invariant
    /// that silently produces garbage when violated.
    pub fn knots(&self) -> GeometryResult<Option<KnotVector>> {
        if !self.has_knots() {
            return Ok(None);
        }
        let values = self.slots.req_f64_list(slot::KNOTS, "Knots")?;
        let multiplicities = self.integer_list(slot::KNOT_MULTIPLICITIES, "KnotMultiplicities")?;

        if values.len() != multiplicities.len() {
            return Err(self.slots.degenerate(format!(
                "Knots has {} entries but KnotMultiplicities has {}; \
                 they are parallel lists",
                values.len(),
                multiplicities.len()
            )));
        }
        if values.is_empty() {
            return Err(self.slots.degenerate("Knots is empty"));
        }
        for (i, m) in multiplicities.iter().enumerate() {
            if *m < 1 {
                return Err(self.slots.degenerate(format!(
                    "knot multiplicity {m} at position {i} is not positive"
                )));
            }
        }
        for (index, value) in values.iter().enumerate() {
            if !value.is_finite() {
                return Err(self
                    .slots
                    .degenerate(format!("Knots[{index}] must be finite, found {value}")));
            }
        }
        // Knots must be strictly increasing: IFC stores each distinct value
        // once, so a repeat means the multiplicity was written twice instead
        // of being folded, which shifts the whole vector.
        for pair in values.windows(2) {
            if pair[1] <= pair[0] {
                return Err(self.slots.degenerate(format!(
                    "Knots must be strictly increasing; found {} after {}",
                    pair[1], pair[0]
                )));
            }
        }

        let multiplicities = multiplicities
            .into_iter()
            .map(|value| {
                usize::try_from(value).map_err(|_| {
                    self.slots
                        .degenerate("knot multiplicity exceeds platform limits")
                })
            })
            .collect::<GeometryResult<Vec<_>>>()?;
        let total = multiplicities.iter().try_fold(0usize, |total, &value| {
            total.checked_add(value).ok_or_else(|| {
                self.slots
                    .degenerate("knot multiplicity total overflows usize")
            })
        })?;
        let expected = self
            .control_point_refs()?
            .len()
            .checked_add(self.degree()?)
            .and_then(|value| value.checked_add(1))
            .ok_or_else(|| self.slots.degenerate("expected knot count overflows usize"))?;
        if total != expected {
            return Err(self.slots.degenerate(format!(
                "knot multiplicities sum to {total} but must equal \
                 ControlPoints + Degree + 1 = {expected}"
            )));
        }

        Ok(Some(KnotVector {
            values,
            multiplicities,
        }))
    }

    /// The rational weights, one per control point, all finite and positive.
    ///
    /// Returns `Ok(None)` for a non-rational curve. A zero weight is a
    /// division by zero at evaluation time and a negative one flips the curve
    /// through infinity; both are rejected here rather than in the kernel.
    pub fn weights(&self) -> GeometryResult<Option<Vec<f64>>> {
        let supplied = self.slots.opt(slot::WEIGHTS_DATA).is_some();
        match (self.is_rational(), supplied) {
            (false, false) => return Ok(None),
            (true, false) => {
                return Err(self
                    .slots
                    .degenerate("rational B-spline curve is missing WeightsData"));
            }
            (false, true) => {
                return Err(self
                    .slots
                    .degenerate("polynomial B-spline curve must not carry WeightsData"));
            }
            (true, true) => {}
        }
        let weights = self.slots.req_f64_list(slot::WEIGHTS_DATA, "WeightsData")?;
        let control_points = self.control_point_refs()?.len();
        if weights.len() != control_points {
            return Err(self.slots.degenerate(format!(
                "WeightsData has {} entries but there are {control_points} control points",
                weights.len()
            )));
        }
        for (i, w) in weights.iter().enumerate() {
            if !w.is_finite() {
                return Err(self
                    .slots
                    .degenerate(format!("weight {w} at control point {i} must be finite")));
            }
            if *w <= 0.0 {
                return Err(self
                    .slots
                    .degenerate(format!("weight {w} at control point {i} must be positive")));
            }
        }
        Ok(Some(weights))
    }

    /// Read a list of integers, rejecting reals.
    ///
    /// Multiplicities are counts. A real here means the file lied about a
    /// count and rounding it would hide the corruption.
    fn integer_list(&self, index: usize, name: &'static str) -> GeometryResult<Vec<i64>> {
        let value = self.slots.req(index, name)?;
        let items = value
            .as_list()
            .ok_or_else(|| self.slots.degenerate(format!("{name} must be a list")))?;
        items
            .iter()
            .map(|v| match v.unwrap_typed() {
                Value::Integer(i) => Ok(*i),
                other => Err(self
                    .slots
                    .degenerate(format!("{name} entry is not an integer: {other:?}"))),
            })
            .collect()
    }
}

/// A knot vector as IFC stores it: distinct values plus multiplicities.
///
/// Kept compressed because that is what the file says. [`Self::expanded`]
/// produces the repeated vector a kernel wants, in one place, so no consumer
/// re-implements the expansion.
#[derive(Debug, Clone, PartialEq)]
pub struct KnotVector {
    /// The distinct knot values, finite and strictly increasing.
    pub values: Vec<f64>,
    /// How many times each value repeats; parallel to `values`.
    pub multiplicities: Vec<usize>,
}

impl KnotVector {
    /// The full, repeated knot vector.
    ///
    /// Length equals `ControlPoints + Degree + 1` for a valid curve, which
    /// [`BSplineCurve::knots`] has already checked.
    ///
    /// Returns `None` when the multiplicities sum beyond `usize`, which only a
    /// hostile or corrupt file achieves. Callers must refuse such a curve
    /// rather than expand it; see [`Self::total_multiplicity`].
    pub fn expanded(&self) -> Option<Vec<f64>> {
        let total = self.total_multiplicity()?;
        let mut out = Vec::with_capacity(total);
        for (value, multiplicity) in self.values.iter().zip(&self.multiplicities) {
            out.extend(std::iter::repeat_n(*value, *multiplicity));
        }
        Some(out)
    }

    /// The length the expanded vector would have.
    ///
    /// `None` on overflow. Multiplicities come straight from the file, so a
    /// plain `sum()` here panics in debug and wraps in release on input a
    /// hostile file fully controls.
    pub fn total_multiplicity(&self) -> Option<usize> {
        self.multiplicities
            .iter()
            .try_fold(0usize, |acc, m| acc.checked_add(*m))
    }

    /// Is the curve clamped, i.e. does it touch its first and last control
    /// point?
    ///
    /// True when the end multiplicities equal `degree + 1`. Worth asking
    /// because an unclamped curve starts somewhere in the middle of its
    /// control polygon, which looks like a modelling error to anyone who has
    /// only seen clamped splines.
    pub fn is_clamped(&self, degree: usize) -> bool {
        let want = degree + 1;
        self.multiplicities.first() == Some(&want) && self.multiplicities.last() == Some(&want)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn refs(n: usize) -> Value {
        Value::List((0..n).map(|i| Value::Ref(EntityId(i as u64 + 1))).collect())
    }

    fn integers(values: &[i64]) -> Value {
        Value::List(values.iter().map(|i| Value::Integer(*i)).collect())
    }

    fn reals(values: &[f64]) -> Value {
        Value::List(values.iter().map(|r| Value::Real(*r)).collect())
    }

    /// A degree-3 curve with 4 control points: knots 0 and 1, each x4.
    fn with_knots(control_points: usize, multiplicities: &[i64], knots: &[f64]) -> Entity {
        Entity::new(
            "IFCBSPLINECURVEWITHKNOTS",
            vec![
                Value::Integer(3),
                refs(control_points),
                Value::Enum("UNSPECIFIED".into()),
                Value::Bool(false),
                Value::Bool(false),
                integers(multiplicities),
                reals(knots),
                Value::Enum("UNSPECIFIED".into()),
            ],
        )
    }

    fn rational(control_points: usize, weights: &[f64]) -> Entity {
        let mut attributes = with_knots(control_points, &[4, 4], &[0.0, 1.0]).attributes;
        attributes.push(reals(weights));
        Entity::new("IFCRATIONALBSPLINECURVEWITHKNOTS", attributes)
    }

    #[test]
    fn control_points_resolve_in_order_and_fail_on_a_dangling_one() {
        let e = with_knots(4, &[4, 4], &[0.0, 1.0]);
        let view = BSplineCurve::new(EntityId(9), &e);
        let model_with = |ids: &[u64]| {
            let mut model = Model::new();
            for &i in ids {
                let point = Entity::new("IFCCARTESIANPOINT", vec![reals(&[i as f64, 0.0])]);
                model.insert(EntityId(i), point);
            }
            model
        };
        let model = model_with(&[1, 2, 3, 4]);
        let points = view.control_points(&model).unwrap();
        assert_eq!(points[3].coordinates().unwrap(), vec![4.0, 0.0]);
        let err = view.control_points(&model_with(&[1, 2, 4])).unwrap_err();
        assert!(matches!(
            err,
            crate::GeometryError::MissingEntity {
                referrer: EntityId(9),
                missing: EntityId(3)
            }
        ));
    }

    #[test]
    fn inherited_bspline_slots_are_read_before_the_subtype_own_slots() {
        let e = with_knots(4, &[4, 4], &[0.0, 1.0]);
        let view = BSplineCurve::new(EntityId(1), &e);
        assert_eq!(view.degree().unwrap(), 3);
        assert_eq!(view.control_point_refs().unwrap().len(), 4);
        assert!(view.has_knots());
        assert!(!view.is_rational());
    }

    #[test]
    fn a_valid_knot_vector_expands_to_control_points_plus_degree_plus_one() {
        let e = with_knots(4, &[4, 4], &[0.0, 1.0]);
        let knots = BSplineCurve::new(EntityId(1), &e).knots().unwrap().unwrap();
        assert_eq!(
            knots.expanded(),
            Some(vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0])
        );
        assert_eq!(knots.total_multiplicity(), Some(4 + 3 + 1));
        assert!(knots.is_clamped(3));
    }

    #[test]
    fn a_knot_multiplicity_sum_that_disagrees_with_the_degree_is_rejected() {
        let e = with_knots(4, &[4, 3], &[0.0, 1.0]);
        let err = BSplineCurve::new(EntityId(6), &e).knots().unwrap_err();
        assert!(err.to_string().contains("must equal"), "got: {err}");
        assert!(err.to_string().contains("#6"), "got: {err}");
    }

    /// A knot vector whose multiplicities sum past `usize` must report, not
    /// panic. A plain `sum()` here aborts the process on input a file controls.
    #[test]
    fn multiplicities_summing_past_usize_report_rather_than_panic() {
        let kv = KnotVector {
            values: vec![0.0, 1.0],
            multiplicities: vec![usize::MAX, 2],
        };
        assert_eq!(kv.total_multiplicity(), None);
        assert_eq!(kv.expanded(), None);
    }

    #[test]
    fn knots_and_multiplicities_of_different_lengths_are_rejected() {
        let e = with_knots(4, &[4, 4], &[0.0, 0.5, 1.0]);
        let err = BSplineCurve::new(EntityId(1), &e).knots().unwrap_err();
        assert!(err.to_string().contains("parallel"), "got: {err}");
    }

    /// IFC stores each distinct knot once; a repeat means the file folded the
    /// multiplicity wrongly and every later knot is shifted.
    #[test]
    fn non_increasing_knot_values_are_rejected() {
        let e = with_knots(5, &[4, 1, 4], &[0.0, 1.0, 1.0]);
        let err = BSplineCurve::new(EntityId(1), &e).knots().unwrap_err();
        assert!(err.to_string().contains("increasing"), "got: {err}");
    }

    #[test]
    fn non_finite_knot_values_are_rejected_by_the_typed_view() {
        for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
            let values = if bad.is_sign_negative() {
                [bad, 1.0]
            } else {
                [0.0, bad]
            };
            let e = with_knots(4, &[4, 4], &values);
            let err = BSplineCurve::new(EntityId(13), &e).knots().unwrap_err();
            assert!(err.to_string().contains("finite"), "knot {bad}: {err}");
        }
    }

    #[test]
    fn an_unclamped_knot_vector_is_recognised_as_such() {
        // Degree 3, 6 control points, all multiplicities 1: 10 knots.
        let e = Entity::new(
            "IFCBSPLINECURVEWITHKNOTS",
            vec![
                Value::Integer(3),
                refs(6),
                Value::Enum("UNSPECIFIED".into()),
                Value::Bool(false),
                Value::Bool(false),
                integers(&[1; 10]),
                reals(&[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]),
                Value::Enum("UNIFORM_KNOTS".into()),
            ],
        );
        let view = BSplineCurve::new(EntityId(1), &e);
        let knots = view.knots().unwrap().unwrap();
        assert!(!knots.is_clamped(3));
        assert_eq!(view.knot_spec(), KnotType::Uniform);
    }

    #[test]
    fn a_curve_without_knots_reports_none_rather_than_failing() {
        let e = Entity::new(
            "IFCBSPLINECURVE",
            vec![
                Value::Integer(3),
                refs(4),
                Value::Enum("UNSPECIFIED".into()),
                Value::Bool(false),
                Value::Bool(false),
            ],
        );
        let view = BSplineCurve::new(EntityId(1), &e);
        assert_eq!(view.knots().unwrap(), None);
        assert_eq!(view.weights().unwrap(), None);
    }

    #[test]
    fn rational_weights_are_read_from_the_slot_after_the_knot_attributes() {
        let e = rational(4, &[1.0, 0.5, 0.5, 1.0]);
        let view = BSplineCurve::new(EntityId(1), &e);
        assert!(view.is_rational());
        assert_eq!(view.weights().unwrap().unwrap(), vec![1.0, 0.5, 0.5, 1.0]);
    }

    /// A zero weight is a division by zero at the control point; IEEE will
    /// happily produce an infinity rather than an error.
    #[test]
    fn a_zero_weight_is_degenerate() {
        let e = rational(4, &[1.0, 0.0, 1.0, 1.0]);
        let err = BSplineCurve::new(EntityId(2), &e).weights().unwrap_err();
        assert!(err.to_string().contains("positive"), "got: {err}");
    }

    #[test]
    fn a_negative_weight_is_degenerate() {
        let e = rational(4, &[1.0, -1.0, 1.0, 1.0]);
        assert!(BSplineCurve::new(EntityId(1), &e).weights().is_err());
    }

    #[test]
    fn non_finite_weights_are_rejected_by_the_typed_view() {
        for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
            let e = rational(4, &[1.0, bad, 1.0, 1.0]);
            let err = BSplineCurve::new(EntityId(14), &e).weights().unwrap_err();
            assert!(err.to_string().contains("finite"), "weight {bad}: {err}");
        }
    }

    #[test]
    fn a_weight_count_that_differs_from_the_control_point_count_is_rejected() {
        let e = rational(4, &[1.0, 1.0, 1.0]);
        let err = BSplineCurve::new(EntityId(1), &e).weights().unwrap_err();
        assert!(err.to_string().contains("control points"), "got: {err}");
    }

    #[test]
    fn multiplicity_overflow_is_a_typed_error_not_a_panic() {
        let e = with_knots(4, &[i64::MAX, i64::MAX, i64::MAX], &[0.0, 0.5, 1.0]);
        let err = BSplineCurve::new(EntityId(8), &e).knots().unwrap_err();
        assert!(err.to_string().contains("overflow"), "got: {err}");
    }

    #[test]
    fn degree_must_not_exceed_the_control_point_upper_index() {
        let mut e = with_knots(4, &[4, 4], &[0.0, 1.0]);
        e.attributes[slot::DEGREE] = Value::Integer(4);
        let err = BSplineCurve::new(EntityId(9), &e).degree().unwrap_err();
        assert!(err.to_string().contains("control points"), "got: {err}");
    }

    #[test]
    fn rational_subtype_requires_weights_and_polynomial_rejects_them() {
        let attributes = with_knots(4, &[4, 4], &[0.0, 1.0]).attributes;
        let rational = Entity::new("IFCRATIONALBSPLINECURVEWITHKNOTS", attributes.clone());
        assert!(BSplineCurve::new(EntityId(10), &rational)
            .weights()
            .unwrap_err()
            .to_string()
            .contains("missing WeightsData"));

        let mut polynomial_attributes = attributes;
        polynomial_attributes.push(reals(&[1.0; 4]));
        let polynomial = Entity::new("IFCBSPLINECURVEWITHKNOTS", polynomial_attributes);
        assert!(BSplineCurve::new(EntityId(11), &polynomial)
            .weights()
            .unwrap_err()
            .to_string()
            .contains("must not carry WeightsData"));
    }

    #[test]
    fn degree_zero_is_rejected_because_it_describes_no_curve() {
        let mut e = with_knots(4, &[4, 4], &[0.0, 1.0]);
        e.attributes[0] = Value::Integer(0);
        assert!(BSplineCurve::new(EntityId(1), &e).degree().is_err());
    }

    /// The form is a hint about provenance and must never license swapping in
    /// an analytic circle, so it is read but kept separate from the geometry.
    #[test]
    fn curve_form_tokens_parse_without_altering_the_control_points() {
        assert_eq!(
            BSplineCurveForm::from_token("CIRCULAR_ARC"),
            Some(BSplineCurveForm::CircularArc)
        );
        assert_eq!(BSplineCurveForm::from_token("SPIRAL"), None);
        assert_eq!(
            KnotType::from_token("PIECEWISE_BEZIER_KNOTS"),
            Some(KnotType::PiecewiseBezier)
        );
        assert_eq!(KnotType::from_token("WEIRD"), None);
    }
}