cadmpeg-codec-catia 0.1.4

Read geometry and topology from .CATPart files.
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
// SPDX-License-Identifier: Apache-2.0
//! Counted topology records in the zero-entity `a9 03` stream family.

/// Resolved zero-entity `a9 03` stream: records, faces, loops, carrier runs,
/// and the edge/vertex tables recovered from them ([spec §8](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/catia.md#8-zero-entity-a9-03-variant)).
#[derive(Debug, Clone, PartialEq)]
pub struct ZeroEntityTopology {
    /// Every `a9 03` record found by the stream walk, in stream order.
    /// Indexed by `ordinal`, and by extension by every `*_ordinal` field
    /// below.
    pub records: Vec<ZeroEntityRecord>,
    /// `5f 0c` face records.
    pub faces: Vec<ZeroEntityFace>,
    /// `62 xx` loop records.
    pub loops: Vec<ZeroEntityLoop>,
    /// Carrier-then-supports runs: each surface carrier (`27 6a`/`28
    /// 8a`/`29 b8`/`2b c8`/`34 xx`) followed by its maximal run of `21 xx`
    /// support occurrences, one run per face ([spec §8](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/catia.md#8-zero-entity-a9-03-variant)).
    pub carrier_runs: Vec<ZeroCarrierRun>,
    /// `21 xx` curve-support-on-surface records, across all carrier runs.
    pub supports: Vec<ZeroSupport>,
    /// `5e 1a` edge-stride records.
    pub physical_edges: Vec<ZeroPhysicalEdge>,
    /// `06 38` coedge records, two per physical edge (one per side).
    pub coedge_twins: Vec<ZeroCoedgeTwin>,
    /// `25 69` side-pair header records, each identifying its two `06 38`
    /// twin coedges.
    pub side_pairs: Vec<ZeroSidePair>,
    /// `05 0b`/`05 10`/`05 15` vertex-incidence records paired with their
    /// following `5d 06` marker.
    pub vertices: Vec<ZeroVertex>,
}

/// A resolved vertex-incidence pair: a `05 0b`/`05 10`/`05 15` incidence
/// record immediately followed by its `5d 06` vertex marker ([spec §8](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/catia.md#8-zero-entity-a9-03-variant)).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ZeroVertex {
    /// `ordinal` of the following `5d 06` marker record.
    pub marker_ordinal: usize,
    /// `ordinal` of this `05 0x` incidence record.
    pub incidence_record_ordinal: usize,
    /// Referenced record ordinals from the incidence record's counted
    /// reference lane: 2 items for tag `0x0b`, 3 for `0x10`, 4 for `0x15`.
    pub incidence_items: Vec<u32>,
}

/// A resolved `5e 1a` edge-stride record (38 bytes; [spec §8](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/catia.md#8-zero-entity-a9-03-variant)).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ZeroPhysicalEdge {
    /// `ordinal` of this record.
    pub record_ordinal: usize,
    /// Six `0x10`-tagged `u32` reference tokens at fixed offsets `7, 12,
    /// 17, 22, 27, 32`; meaning not decoded further.
    pub references: [u32; 6],
}

/// A resolved `06 38` coedge record: one of the two per-side halves of a
/// physical edge (68 bytes; [spec §8](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/catia.md#8-zero-entity-a9-03-variant)).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ZeroCoedgeTwin {
    /// `ordinal` of this record.
    pub record_ordinal: usize,
    /// Side number, `1` or `2`, read from the byte following the `0x10`
    /// marker at the record's `0x83` position.
    pub side: u8,
    /// `0x10`-tagged `u32` reference tokens following the side byte, in
    /// serialized order.
    pub references: Vec<u32>,
}

/// A resolved `25 69` side-pair header record, linking two [`ZeroCoedgeTwin`]
/// records by side number ([spec §8](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/catia.md#8-zero-entity-a9-03-variant)).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ZeroSidePair {
    /// `ordinal` of this record.
    pub record_ordinal: usize,
    /// The header's two base columns `[B0, B1]`.
    pub bases: [u32; 2],
    /// `record_ordinal`s of the two following `06 38` records: side `1`
    /// first, side `2` second.
    pub coedge_ordinals: [usize; 2],
    /// `[bases[i] + side]` for `side` in `1, 2`; each side's composite key
    /// must equal the first two references of its paired coedge.
    pub composite_keys: [[u32; 2]; 2],
}

/// One surface carrier and its maximal run of `21 xx` support occurrences,
/// aligned 1:1 with a face ([spec §8](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/catia.md#8-zero-entity-a9-03-variant), "Carrier run = per-face surface").
#[derive(Debug, Clone, PartialEq)]
pub struct ZeroCarrierRun {
    /// `ordinal` of the carrier record (`27 6a`/`28 8a`/`29 b8`/`2b
    /// c8`/`34 xx`).
    pub carrier_ordinal: usize,
    /// `ordinal`s of the carrier's `21 xx` support records, in stream
    /// order.
    pub support_ordinals: Vec<usize>,
}

/// A resolved `21 xx` curve-support-on-surface record, with its UV
/// endpoints lifted through the owning carrier where possible ([spec §8](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/catia.md#8-zero-entity-a9-03-variant)).
#[derive(Debug, Clone, PartialEq)]
pub struct ZeroSupport {
    /// `ordinal` of this record.
    pub record_ordinal: usize,
    /// `ordinal` of the owning carrier record.
    pub owner_carrier_ordinal: usize,
    /// Local slot index at `+12`, used with a loop's `terminal_id` to
    /// address this support from a `62xx` loop member (`A = T - s`).
    pub slot: u32,
    /// `(u0,v0)`/`(u1,v1)` endpoint pairs read from the record's f64 tail
    /// at the family-specific offsets in [`support_uv_endpoints`], or
    /// `None` for an unrecognized support-record tag.
    pub uv_endpoints: Option<[[f64; 2]; 2]>,
    /// `uv_endpoints` lifted to world-frame 3D points through the owning
    /// carrier's analytic parameterization, or `None` when `uv_endpoints`
    /// is `None` or the carrier's tag is not one of the four supported
    /// analytic kinds ([`lift_endpoints`]).
    pub lifted_endpoints: Option<[[f64; 3]; 2]>,
}

/// One length-framed `a9 03` record as found by the stream walk: framing
/// `a9 03 XX YY <payload[YY+8]>`, `record_length = YY + 12` ([spec §8](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/catia.md#8-zero-entity-a9-03-variant)).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ZeroEntityRecord {
    /// This record's position in the stream walk order. Records reference
    /// each other by this ordinal, not by byte offset ([spec §8](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/catia.md#8-zero-entity-a9-03-variant)).
    pub ordinal: usize,
    /// Byte offset of the `a9 03` marker in the source stream.
    pub offset: usize,
    /// The two tag bytes (`XX`, `YY`) identifying the record family.
    pub tag: [u8; 2],
    /// The full record, including its `a9 03 XX YY` header.
    pub bytes: Vec<u8>,
}

/// A resolved `5f 0c` face record (24 bytes; [spec §8](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/catia.md#8-zero-entity-a9-03-variant)).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ZeroEntityFace {
    /// `ordinal` of this record.
    pub record_ordinal: usize,
    /// The record's counted reference lane `[R0, R1, ..., Rm]`: `R0` is
    /// the face's terminal base, `R1..` name loop terminals.
    pub references: Vec<u32>,
    /// Ordered loop terminals `T[j] = R0 - R[j+1]`, one per loop owned by
    /// this face.
    pub loop_terminals: Vec<u32>,
    /// Indices into the topology's `loops` vector, one per
    /// `loop_terminals` entry in the same order, resolved by
    /// [`bind_face_runs`]. Empty until binding runs.
    pub loop_indices: Vec<usize>,
    /// Index into the topology's `carrier_runs` vector for this face's
    /// surface carrier, resolved by [`bind_face_runs`]. `None` until
    /// binding runs or when no carrier run aligns with this face.
    pub carrier_run: Option<usize>,
}

/// A resolved `62 xx` loop record: an alternating even/odd reference lane
/// plus a packed 3-bit-per-member sense stream ([spec §8](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/catia.md#8-zero-entity-a9-03-variant)).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ZeroEntityLoop {
    /// `ordinal` of this record.
    pub record_ordinal: usize,
    /// Even-lane reference ids `A[j]`, one per loop member, satisfying
    /// `A[j] = T - g - j` for this loop's `terminal_id` (`T`) and `gap`
    /// (`g`).
    pub member_ids: Vec<u32>,
    /// Odd-lane reference ids interleaved with `member_ids`; meaning not
    /// decoded further.
    pub secondary_refs: Vec<u32>,
    /// The loop's terminal id `T`: the last entry of the record's counted
    /// reference lane.
    pub terminal_id: u32,
    /// `T - member_ids[0]`: the offset between the terminal id and the
    /// first even-lane member.
    pub gap: u32,
    /// Loop-class byte from the record header: `0x50` marks an inner
    /// (hole) loop, `0x41`/`0xc1` mark a non-inner loop.
    pub loop_class: u8,
    /// `true` when `loop_class == 0x50` (an inner/hole loop).
    pub inner: bool,
    /// Per-member coedge sense decoded from the packed 3-bit stream: code
    /// `7` (`.T.`, forward) decodes to `false`, code `2` (`.F.`, reversed)
    /// decodes to `true`. Index-aligned with `member_ids`.
    pub reversed: Vec<bool>,
    /// Per-member index into the topology's `supports` vector, resolved by
    /// [`bind_face_runs`] from each member's local slot `A = T - s`.
    /// `None` for a member whose slot resolves to no support in the
    /// owning carrier run, or before binding runs.
    pub support_indices: Vec<Option<usize>>,
}

/// Walk native zero-entity records by `YY + 12`, then decode face counted
/// references and `62xx` alternating loop lanes with packed 3-bit senses.
#[must_use]
pub fn parse(bytes: &[u8]) -> Option<ZeroEntityTopology> {
    let records = walk_records(bytes);
    if records.is_empty() {
        return None;
    }
    let mut faces = records
        .iter()
        .filter(|record| record.tag[0] == 0x5f)
        .map(parse_face)
        .collect::<Option<Vec<_>>>()?;
    let mut loops = records
        .iter()
        .filter(|record| record.tag[0] == 0x62)
        .map(parse_loop)
        .collect::<Option<Vec<_>>>()?;
    if faces.is_empty() || loops.is_empty() {
        return None;
    }
    let (carrier_runs, supports) = parse_carrier_runs(&records)?;
    let physical_edges = records
        .iter()
        .filter(|record| record.tag == [0x5e, 0x1a])
        .map(parse_physical_edge)
        .collect::<Option<Vec<_>>>()?;
    let coedge_twins = records
        .iter()
        .filter(|record| record.tag == [0x06, 0x38])
        .map(parse_coedge_twin)
        .collect::<Option<Vec<_>>>()?;
    let side_pairs = parse_side_pairs(&records, &coedge_twins)?;
    let vertices = parse_vertices(&records)?;
    bind_face_runs(&mut faces, &mut loops, &carrier_runs, &supports);
    Some(ZeroEntityTopology {
        records,
        faces,
        loops,
        carrier_runs,
        supports,
        physical_edges,
        coedge_twins,
        side_pairs,
        vertices,
    })
}

fn parse_vertices(records: &[ZeroEntityRecord]) -> Option<Vec<ZeroVertex>> {
    let mut vertices = Vec::new();
    for (index, record) in records.iter().enumerate() {
        if !matches!(record.tag, [0x05, 0x0b | 0x10 | 0x15]) {
            continue;
        }
        let marker = records.get(index + 1)?;
        if marker.tag != [0x5d, 0x06] {
            return None;
        }
        let (incidence_items, end) = counted_references(&record.bytes, 12)?;
        if end != record.bytes.len()
            || incidence_items.len()
                != match record.tag[1] {
                    0x0b => 2,
                    0x10 => 3,
                    0x15 => 4,
                    _ => unreachable!(),
                }
        {
            return None;
        }
        vertices.push(ZeroVertex {
            marker_ordinal: marker.ordinal,
            incidence_record_ordinal: record.ordinal,
            incidence_items,
        });
    }
    Some(vertices)
}

fn parse_physical_edge(record: &ZeroEntityRecord) -> Option<ZeroPhysicalEdge> {
    let mut references = [0; 6];
    for (target, offset) in references.iter_mut().zip([7usize, 12, 17, 22, 27, 32]) {
        *target = token_u32(&record.bytes, offset)?;
    }
    Some(ZeroPhysicalEdge {
        record_ordinal: record.ordinal,
        references,
    })
}

fn parse_coedge_twin(record: &ZeroEntityRecord) -> Option<ZeroCoedgeTwin> {
    let marker = record
        .bytes
        .get(7..)?
        .windows(1)
        .position(|value| value == [0x83])?
        + 7;
    if record.bytes.get(marker + 1) != Some(&0x10) {
        return None;
    }
    let side = *record.bytes.get(marker + 2)?;
    if !matches!(side, 1 | 2) {
        return None;
    }
    let mut references = Vec::new();
    let mut position = marker + 3;
    while position + 5 <= record.bytes.len() {
        if record.bytes[position] == 0x10 {
            references.push(token_u32(&record.bytes, position)?);
            position += 5;
        } else {
            position += 1;
        }
    }
    Some(ZeroCoedgeTwin {
        record_ordinal: record.ordinal,
        side,
        references,
    })
}

fn parse_side_pairs(
    records: &[ZeroEntityRecord],
    coedges: &[ZeroCoedgeTwin],
) -> Option<Vec<ZeroSidePair>> {
    let mut pairs = Vec::new();
    for (index, record) in records.iter().enumerate() {
        if record.tag != [0x25, 0x69] {
            continue;
        }
        let (references, _) = counted_references(&record.bytes, 12)?;
        let bases: [u32; 2] = references.try_into().ok()?;
        let first = records.get(index + 1)?;
        let second = records.get(index + 2)?;
        let coedge0 = coedges
            .iter()
            .find(|coedge| coedge.record_ordinal == first.ordinal)?;
        let coedge1 = coedges
            .iter()
            .find(|coedge| coedge.record_ordinal == second.ordinal)?;
        if coedge0.side != 1 || coedge1.side != 2 {
            return None;
        }
        let composite_keys = [
            [bases[0].checked_add(1)?, bases[1].checked_add(1)?],
            [bases[0].checked_add(2)?, bases[1].checked_add(2)?],
        ];
        if coedge0.references.get(..2) != Some(&composite_keys[0])
            || coedge1.references.get(..2) != Some(&composite_keys[1])
        {
            return None;
        }
        pairs.push(ZeroSidePair {
            record_ordinal: record.ordinal,
            bases,
            coedge_ordinals: [coedge0.record_ordinal, coedge1.record_ordinal],
            composite_keys,
        });
    }
    Some(pairs)
}

fn bind_face_runs(
    faces: &mut [ZeroEntityFace],
    loops: &mut [ZeroEntityLoop],
    carrier_runs: &[ZeroCarrierRun],
    supports: &[ZeroSupport],
) {
    let mut loop_cursor = 0;
    for (face_index, face) in faces.iter_mut().enumerate() {
        for terminal in &face.loop_terminals {
            let Some(relative) = loops[loop_cursor..]
                .iter()
                .position(|loop_| loop_.terminal_id == *terminal)
            else {
                return;
            };
            let loop_index = loop_cursor + relative;
            face.loop_indices.push(loop_index);
            loop_cursor = loop_index + 1;
        }
        let Some(run) = carrier_runs.get(face_index) else {
            continue;
        };
        face.carrier_run = Some(face_index);
        let slot_to_support: std::collections::HashMap<u32, usize> = run
            .support_ordinals
            .iter()
            .filter_map(|ordinal| {
                supports
                    .iter()
                    .position(|support| support.record_ordinal == *ordinal)
                    .map(|index| (supports[index].slot, index))
            })
            .collect();
        for &loop_index in &face.loop_indices {
            let loop_ = &mut loops[loop_index];
            loop_.support_indices = loop_
                .member_ids
                .iter()
                .map(|member| {
                    loop_
                        .terminal_id
                        .checked_sub(*member)
                        .and_then(|slot| slot_to_support.get(&slot).copied())
                })
                .collect();
        }
    }
}

fn parse_carrier_runs(
    records: &[ZeroEntityRecord],
) -> Option<(Vec<ZeroCarrierRun>, Vec<ZeroSupport>)> {
    let mut runs = Vec::new();
    let mut supports = Vec::new();
    let mut position = 0;
    while position < records.len() {
        if !matches!(records[position].tag[0], 0x27 | 0x28 | 0x29 | 0x2b | 0x34) {
            position += 1;
            continue;
        }
        let carrier = position;
        position += 1;
        let mut support_ordinals = Vec::new();
        while position < records.len() && records[position].tag[0] == 0x21 {
            let record = &records[position];
            let slot = token_u32(&record.bytes, 12)?;
            let uv_endpoints = support_uv_endpoints(record);
            let lifted_endpoints =
                uv_endpoints.and_then(|uv| lift_endpoints(&records[carrier], uv));
            supports.push(ZeroSupport {
                record_ordinal: record.ordinal,
                owner_carrier_ordinal: records[carrier].ordinal,
                slot,
                uv_endpoints,
                lifted_endpoints,
            });
            support_ordinals.push(record.ordinal);
            position += 1;
        }
        if !support_ordinals.is_empty() {
            runs.push(ZeroCarrierRun {
                carrier_ordinal: records[carrier].ordinal,
                support_ordinals,
            });
        }
    }
    Some((runs, supports))
}

fn lift_endpoints(carrier: &ZeroEntityRecord, uv: [[f64; 2]; 2]) -> Option<[[f64; 3]; 2]> {
    let payload = carrier.bytes.get(4..)?;
    let lifted = match carrier.tag {
        [0x27, 0x6a] => {
            let origin = point(payload, 10)?;
            let x = point(payload, 34)?;
            let y = point(payload, 58)?;
            uv.map(|[u, v]| add(origin, add(scale(x, u), scale(y, v))))
        }
        [0x28, 0x8a] => {
            let origin = point(payload, 8)?;
            let x = unit(point(payload, 33)?)?;
            let axis = unit(cross(x, point(payload, 57)?))?;
            let y = cross(axis, x);
            let radius = scalar(payload, 81)?;
            if radius <= 0.0 {
                return None;
            }
            uv.map(|[u, v]| {
                let angle = u / radius;
                add(
                    origin,
                    add(
                        scale(add(scale(x, angle.cos()), scale(y, angle.sin())), radius),
                        scale(axis, v),
                    ),
                )
            })
        }
        [0x29, 0xb8] => {
            let origin = point(payload, 8)?;
            let x = unit(point(payload, 32)?)?;
            let y = unit(point(payload, 56)?)?;
            let axis = unit(point(payload, 80)?)?;
            let half_angle = std::f64::consts::FRAC_PI_2 - scalar(payload, 104)?;
            let radius = scalar(payload, 112)?;
            uv.map(|[u, v]| {
                let radial = radius + v * half_angle.sin();
                add(
                    origin,
                    add(
                        scale(add(scale(x, u.cos()), scale(y, u.sin())), radial),
                        scale(axis, v * half_angle.cos()),
                    ),
                )
            })
        }
        [0x2b, 0xc8] => {
            let center = point(payload, 8)?;
            let x = unit(point(payload, 32)?)?;
            let y = unit(point(payload, 56)?)?;
            let axis = unit(point(payload, 80)?)?;
            let major = scalar(payload, 104)?;
            let minor = scalar(payload, 112)?;
            if major <= 0.0 || minor <= 0.0 {
                return None;
            }
            uv.map(|[u, v]| {
                let theta = u / major;
                let phi = v / minor;
                let radial = major + minor * phi.cos();
                add(
                    center,
                    add(
                        scale(add(scale(x, theta.cos()), scale(y, theta.sin())), radial),
                        scale(axis, minor * phi.sin()),
                    ),
                )
            })
        }
        _ => return None,
    };
    lifted
        .iter()
        .flatten()
        .all(|value| value.is_finite())
        .then_some(lifted)
}

fn scalar(bytes: &[u8], offset: usize) -> Option<f64> {
    let value = f64::from_le_bytes(bytes.get(offset..offset + 8)?.try_into().ok()?);
    value.is_finite().then_some(value)
}

fn point(bytes: &[u8], offset: usize) -> Option<[f64; 3]> {
    Some([
        scalar(bytes, offset)?,
        scalar(bytes, offset + 8)?,
        scalar(bytes, offset + 16)?,
    ])
}

fn add(left: [f64; 3], right: [f64; 3]) -> [f64; 3] {
    [left[0] + right[0], left[1] + right[1], left[2] + right[2]]
}

fn scale(value: [f64; 3], scalar: f64) -> [f64; 3] {
    [value[0] * scalar, value[1] * scalar, value[2] * scalar]
}

fn cross(left: [f64; 3], right: [f64; 3]) -> [f64; 3] {
    [
        left[1] * right[2] - left[2] * right[1],
        left[2] * right[0] - left[0] * right[2],
        left[0] * right[1] - left[1] * right[0],
    ]
}

fn unit(value: [f64; 3]) -> Option<[f64; 3]> {
    let length = value
        .iter()
        .map(|component| component * component)
        .sum::<f64>()
        .sqrt();
    (length > f64::EPSILON).then(|| scale(value, 1.0 / length))
}

fn support_uv_endpoints(record: &ZeroEntityRecord) -> Option<[[f64; 2]; 2]> {
    let offsets = match record.tag {
        [0x21, 0x71] => [93, 101, 109, 117],
        [0x21, 0x91] => [93, 101, 141, 149],
        [0x21, 0x99] => [93, 101, 125, 133],
        [0x21, 0xd6] => [106, 114, 170, 178],
        [0x21, 0xe8] => [132, 140, 228, 236],
        _ => return None,
    };
    let values = offsets.map(|offset| {
        f64::from_le_bytes(
            record.bytes[offset..offset + 8]
                .try_into()
                .expect("validated record-family offset"),
        )
    });
    values
        .iter()
        .all(|value| value.is_finite())
        .then_some([[values[0], values[1]], [values[2], values[3]]])
}

fn token_u32(bytes: &[u8], offset: usize) -> Option<u32> {
    if bytes.get(offset) != Some(&0x10) {
        return None;
    }
    Some(u32::from_le_bytes(
        bytes.get(offset + 1..offset + 5)?.try_into().ok()?,
    ))
}

fn walk_records(bytes: &[u8]) -> Vec<ZeroEntityRecord> {
    let mut records = Vec::new();
    let mut position = 0;
    while position + 4 <= bytes.len() {
        if bytes.get(position..position + 2) != Some(&[0xa9, 0x03]) {
            position += 1;
            continue;
        }
        let length = usize::from(bytes[position + 3]) + 12;
        let Some(end) = position.checked_add(length) else {
            break;
        };
        if end > bytes.len() {
            break;
        }
        records.push(ZeroEntityRecord {
            ordinal: records.len(),
            offset: position,
            tag: [bytes[position + 2], bytes[position + 3]],
            bytes: bytes[position..end].to_vec(),
        });
        position = end;
    }
    records
}

fn parse_face(record: &ZeroEntityRecord) -> Option<ZeroEntityFace> {
    let (references, _) = counted_references(&record.bytes, 12)?;
    if references.len() < 2 {
        return None;
    }
    let base = references[0];
    let loop_terminals = references[1..]
        .iter()
        .map(|reference| base.checked_sub(*reference))
        .collect::<Option<Vec<_>>>()?;
    Some(ZeroEntityFace {
        record_ordinal: record.ordinal,
        references,
        loop_terminals,
        loop_indices: Vec::new(),
        carrier_run: None,
    })
}

fn parse_loop(record: &ZeroEntityRecord) -> Option<ZeroEntityLoop> {
    let (references, mut position) = counted_references(&record.bytes, 12)?;
    if references.len() < 3 || references.len() % 2 == 0 {
        return None;
    }
    let segment_count = (references.len() - 1) / 2;
    let member_ids: Vec<u32> = references[..references.len() - 1]
        .iter()
        .step_by(2)
        .copied()
        .collect();
    let secondary_refs: Vec<u32> = references[1..references.len() - 1]
        .iter()
        .step_by(2)
        .copied()
        .collect();
    let terminal_id = *references.last()?;
    let gap = terminal_id.checked_sub(*member_ids.first()?)?;
    for (index, member) in member_ids.iter().enumerate() {
        if *member != terminal_id - gap - u32::try_from(index).ok()? {
            return None;
        }
    }
    if record.bytes.get(position) != Some(&(0x80u8.checked_add(u8::try_from(segment_count).ok()?)?))
    {
        return None;
    }
    let loop_class = *record.bytes.get(position + 1)?;
    position += 2;
    let packed_length = (3 * segment_count).div_ceil(8);
    let packed = record.bytes.get(position..position + packed_length)?;
    position += packed_length;
    if record.bytes.get(position) != Some(&0x01) {
        return None;
    }
    let mut reversed = Vec::with_capacity(segment_count);
    for member in 0..segment_count {
        let mut code = 0u8;
        for bit in 0..3 {
            let bit_position = member * 3 + bit;
            code |= ((packed[bit_position / 8] >> (bit_position % 8)) & 1) << bit;
        }
        reversed.push(match code {
            7 => false,
            2 => true,
            _ => return None,
        });
    }
    if matches!(loop_class, 0x41 | 0xc1) && !matches!(gap, 1 | 2) {
        return None;
    }
    Some(ZeroEntityLoop {
        record_ordinal: record.ordinal,
        member_ids,
        secondary_refs,
        terminal_id,
        gap,
        loop_class,
        inner: loop_class == 0x50,
        reversed,
        support_indices: Vec::new(),
    })
}

fn counted_references(bytes: &[u8], position: usize) -> Option<(Vec<u32>, usize)> {
    let count = usize::from(bytes.get(position)?.checked_sub(0x80)?);
    let mut cursor = position + 1;
    let mut references = Vec::with_capacity(count);
    for _ in 0..count {
        if bytes.get(cursor) != Some(&0x10) {
            return None;
        }
        references.push(u32::from_le_bytes(
            bytes.get(cursor + 1..cursor + 5)?.try_into().ok()?,
        ));
        cursor += 5;
    }
    Some((references, cursor))
}