catwalk3d 2.0.0

Headless model thumbnails rendered entirely in Rust
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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
//! Static Alembic schemas, read from bounded Ogawa groups or pure Rust HDF5.
//! Storage and transform conventions follow the primary Alembic sources:
//! <https://github.com/alembic/alembic/tree/master/lib/Alembic/AbcCoreOgawa>
//! <https://github.com/alembic/alembic/tree/master/lib/Alembic/AbcGeom>
use super::{
    MAX_INPUT_BYTES, hdf5_owned::Hdf5File, mesh::triangulate_polygon, read_file,
    transform::Transform,
};
use crate::{
    Result,
    scene::{Line, Point, Scene, Triangle, Vec3},
};
use hdf5_reader::{Attribute, ByteOrder, Datatype, group::Group};
use std::{
    collections::{HashMap, HashSet},
    path::Path,
};

/// High bit identifying an Ogawa data pointer rather than a group pointer.
const DATA: u64 = 1 << 63;
/// Maximum decoded numeric components and geometry elements.
const MAX_ITEMS: usize = 5_000_000;
/// Maximum archive objects and properties traversed.
const MAX_NODES: usize = 100_000;
/// Maximum archive hierarchy and instance expansion depth.
const MAX_DEPTH: usize = 256;
/// Alembic schema metadata decoded from semicolon-separated key-value pairs.
type Metadata = HashMap<String, String>;

#[derive(Default)]
/// A compound or sampled Alembic property.
struct Property {
    /// Property name within its owning compound.
    name: String,
    /// Schema and interpretation metadata.
    metadata: Metadata,
    /// Nested properties for a compound property.
    children: Vec<Property>,
    /// First authored sample for a scalar or array property.
    sample: Option<Sample>,
}
/// Raw first-sample data with its declared component encoding.
struct Sample {
    /// Alembic POD component type tag.
    pod: u8,
    /// Number of scalar components in each logical sample element.
    extent: usize,
    /// Whether numeric components use big-endian byte order.
    big_endian: bool,
    /// Raw component bytes, bounded by the aggregate decoding budget.
    bytes: Vec<u8>,
}
/// One archive object with its properties and nested objects.
struct Object {
    /// Absolute object path used to resolve archive instances.
    path: String,
    /// Object schema and instance metadata.
    metadata: Metadata,
    /// Root compound property for this object.
    properties: Property,
    /// Child objects in archive order.
    children: Vec<Object>,
}
impl Property {
    /// Find a direct property child by name.
    fn child(&self, name: &str) -> Option<&Self> {
        self.children.iter().find(|p| p.name == name)
    }
    /// Decode the property's first sample as finite numeric components.
    fn numbers(&self) -> Result<Vec<f64>> {
        self.sample
            .as_ref()
            .ok_or_else(|| format!("Alembic property {} has no sample", self.name).into())
            .and_then(Sample::numbers)
    }
    /// Require a named property child needed by the current schema.
    fn required(&self, name: &str) -> Result<&Self> {
        self.child(name)
            .ok_or_else(|| format!("Alembic schema is missing {name}").into())
    }
    /// Read a single UTF-8 string sample, allowing one trailing terminator.
    fn text(&self) -> Result<&str> {
        let sample = self
            .sample
            .as_ref()
            .ok_or("Alembic string property has no sample")?;
        if sample.pod != 12 {
            return Err("Alembic string property has a non-string type".into());
        }
        let bytes = sample.bytes.strip_suffix(&[0]).unwrap_or(&sample.bytes);
        if bytes.contains(&0) {
            return Err("Alembic string property contains multiple values".into());
        }
        Ok(std::str::from_utf8(bytes)?)
    }
}
impl Sample {
    /// Decode aligned POD numeric bytes according to their declared width and byte order.
    #[allow(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        clippy::cast_possible_wrap,
        reason = "POD width bounds each bit reinterpretation; integer samples intentionally convert to the common f64 geometry representation."
    )]
    fn numbers(&self) -> Result<Vec<f64>> {
        let width = pod_width(self.pod)?;
        if !self.bytes.len().is_multiple_of(width) {
            return Err("misaligned Alembic numeric sample".into());
        }
        let count = self.bytes.len() / width;
        if count > MAX_ITEMS {
            return Err("Alembic sample exceeds five million components".into());
        }
        self.bytes
            .chunks_exact(width)
            .map(|bytes| {
                let unsigned = if self.big_endian {
                    bytes.iter().fold(0u64, |v, &b| (v << 8) | u64::from(b))
                } else {
                    bytes
                        .iter()
                        .rev()
                        .fold(0u64, |v, &b| (v << 8) | u64::from(b))
                };
                let value = match self.pod {
                    0 => f64::from(unsigned != 0),
                    1 | 3 | 5 | 7 => unsigned as f64,
                    2 => f64::from(unsigned as i8),
                    4 => f64::from(unsigned as i16),
                    6 => f64::from(unsigned as i32),
                    8 => unsigned as i64 as f64,
                    9 => half(unsigned as u16),
                    10 => f64::from(f32::from_bits(unsigned as u32)),
                    11 => f64::from_bits(unsigned),
                    _ => return Err("Alembic string/wide-string values are not numeric".into()),
                };
                if !value.is_finite() {
                    return Err("Alembic numeric samples must be finite".into());
                }
                Ok(value)
            })
            .collect()
    }
}
/// Decode a binary16 component, preserving non-finite encodings for later rejection.
fn half(bits: u16) -> f64 {
    let sign = if bits & 0x8000 == 0 { 1. } else { -1. };
    let e = (bits >> 10) & 31;
    let m = bits & 1023;
    sign * match e {
        0 => f64::from(m) * 2f64.powi(-24),
        31 => {
            if m == 0 {
                f64::INFINITY
            } else {
                f64::NAN
            }
        }
        _ => (1. + f64::from(m) / 1024.) * 2f64.powi(i32::from(e) - 15),
    }
}
/// Return the component byte width for a supported Alembic POD type.
fn pod_width(pod: u8) -> Result<usize> {
    match pod {
        0..=2 | 12 => Ok(1),
        3 | 4 | 9 => Ok(2),
        5 | 6 | 10 | 13 => Ok(4),
        7 | 8 | 11 => Ok(8),
        _ => Err("unknown Alembic POD type".into()),
    }
}
/// Parse bounded UTF-8 schema metadata into key-value pairs.
fn metadata(bytes: &[u8]) -> Result<Metadata> {
    if bytes.len() > 1_048_576 {
        return Err("Alembic metadata exceeds one MiB".into());
    }
    let text = std::str::from_utf8(bytes)?;
    Ok(text
        .split(';')
        .filter_map(|p| p.split_once('='))
        .map(|(k, v)| (k.to_owned(), v.to_owned()))
        .collect())
}
#[derive(Default)]
/// Aggregate archive traversal and first-sample allocation counters.
struct Budget {
    /// Objects and properties visited so far.
    nodes: usize,
    /// Total first-sample bytes decoded across the archive.
    decoded: u64,
}
impl Budget {
    /// Charge one hierarchy item and enforce node and depth limits.
    fn node(&mut self, depth: usize) -> Result<()> {
        self.nodes += 1;
        if depth > MAX_DEPTH || self.nodes > MAX_NODES {
            return Err("Alembic hierarchy exceeds 256 levels/100000 nodes".into());
        }
        Ok(())
    }
    /// Charge sample bytes and enforce the aggregate input-size budget.
    fn bytes(&mut self, count: usize) -> Result<()> {
        self.decoded = self
            .decoded
            .checked_add(count as u64)
            .ok_or("Alembic sample budget overflow")?;
        if self.decoded > MAX_INPUT_BYTES {
            return Err("Alembic samples exceed aggregate 512 MiB limit".into());
        }
        Ok(())
    }
}

/// Load first-sample static geometry from an Ogawa or HDF5 Alembic archive.
///
/// # Errors
/// Returns an error for unsupported storage versions or schemas, malformed records,
/// missing samples or references, invalid transforms or geometry, and exceeded
/// archive, sample or geometry budgets.
pub(super) fn load(path: &Path) -> Result<Scene> {
    let bytes = read_file(path)?;
    let root = if bytes.starts_with(b"Ogawa") {
        Ogawa::new(&bytes)?.root()?
    } else if bytes.starts_with(b"\x89HDF\r\n\x1a\n") {
        hdf_archive(bytes)?
    } else {
        return Err("unsupported Alembic archive; expected Ogawa or HDF5".into());
    };
    build_scene(&root)
}

/// Bounds-checked cursor over one Alembic metadata or property record.
struct Bytes<'a> {
    /// Bytes belonging to the current record.
    data: &'a [u8],
    /// Offset of the next unread byte.
    offset: usize,
}
impl<'a> Bytes<'a> {
    /// Create a cursor positioned at the start of a record.
    fn new(data: &'a [u8]) -> Self {
        Self { data, offset: 0 }
    }
    /// Consume an exact byte count, rejecting overflow or truncated records.
    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
        let end = self
            .offset
            .checked_add(n)
            .ok_or("Alembic offset overflow")?;
        let data = self
            .data
            .get(self.offset..end)
            .ok_or("truncated Alembic record")?;
        self.offset = end;
        Ok(data)
    }
    /// Read a little-endian unsigned value of the specified byte width.
    fn uint(&mut self, n: usize) -> Result<u64> {
        Ok(self
            .take(n)?
            .iter()
            .rev()
            .fold(0, |v, &b| (v << 8) | u64::from(b)))
    }
    /// Read a property size encoded using its one-, two- or four-byte size hint.
    fn hint(&mut self, hint: u32) -> Result<usize> {
        let width = match hint {
            0 => 1,
            1 => 2,
            2 => 4,
            _ => return Err("invalid Alembic property size hint".into()),
        };
        Ok(usize::try_from(self.uint(width)?)?)
    }
    /// Read a nonempty bounded UTF-8 name without embedded terminators.
    fn name(&mut self, len: usize) -> Result<String> {
        if len == 0 || len > 4096 {
            return Err("invalid Alembic name length".into());
        }
        let name = std::str::from_utf8(self.take(len)?)?;
        if name.contains('\0') {
            return Err("Alembic name contains NUL".into());
        }
        Ok(name.to_owned())
    }
    /// Whether the record has no remaining bytes.
    fn done(&self) -> bool {
        self.offset == self.data.len()
    }
}
/// Bounded Ogawa archive reader with metadata references and cycle detection.
struct Ogawa<'a> {
    /// Complete archive bytes.
    bytes: &'a [u8],
    /// Metadata entries indexed by their archive references.
    metadata: Vec<Metadata>,
    /// Root archive group child pointers.
    archive: Vec<u64>,
    /// Shared hierarchy and sample byte budgets.
    budget: Budget,
    /// Active group pointers for detecting recursive archive records.
    active: HashSet<u64>,
}
impl<'a> Ogawa<'a> {
    /// Validate the Ogawa header and initialize archive and metadata groups.
    #[allow(
        clippy::cast_possible_truncation,
        reason = "Metadata entry sizes are read from exactly one byte."
    )]
    fn new(bytes: &'a [u8]) -> Result<Self> {
        if bytes.get(..8) != Some(b"Ogawa\xff\0\x01") {
            return Err("unsupported or unclosed Ogawa archive; expected version1".into());
        }
        let mut reader = Self {
            bytes,
            metadata: vec![Metadata::new()],
            archive: Vec::new(),
            budget: Budget::default(),
            active: HashSet::new(),
        };
        let root = Bytes::new(bytes.get(8..16).ok_or("truncated Ogawa header")?).uint(8)?;
        let archive = reader.group(root)?;
        if archive.len() < 6 {
            return Err("invalid Alembic archive root".into());
        }
        let version = reader.data(archive[0])?;
        if version.len() != 4 || Bytes::new(version).uint(4)? > 0 {
            return Err("unsupported Alembic Ogawa storage version".into());
        }
        let release = reader.data(archive[1])?;
        if release.len() != 4 || Bytes::new(release).uint(4)? < 9999 {
            return Err("unsupported Alembic release version".into());
        }
        let mut indexed = Bytes::new(reader.data(archive[5])?);
        while !indexed.done() {
            let size = indexed.uint(1)? as usize;
            reader.metadata.push(metadata(indexed.take(size)?)?);
            if reader.metadata.len() > 256 {
                return Err("Alembic indexed metadata exceeds 256 entries".into());
            }
        }
        reader.archive = archive;
        Ok(reader)
    }
    /// Read a bounded Ogawa group's child pointers.
    fn group(&self, pointer: u64) -> Result<Vec<u64>> {
        if pointer & DATA != 0 {
            return Err("Alembic data record used as a group".into());
        }
        if pointer == 0 {
            return Ok(Vec::new());
        }
        let offset = usize::try_from(pointer)?;
        let mut b = Bytes::new(
            self.bytes
                .get(offset..)
                .ok_or("Ogawa group offset outside input")?,
        );
        let count = usize::try_from(b.uint(8)?)?;
        if count > 500_000 {
            return Err("Alembic group exceeds 500000 children".into());
        }
        let mut entries =
            Bytes::new(b.take(count.checked_mul(8).ok_or("Ogawa group size overflow")?)?);
        (0..count).map(|_| entries.uint(8)).collect()
    }
    /// Read a tagged Ogawa data block within the input bounds.
    fn data(&self, pointer: u64) -> Result<&'a [u8]> {
        if pointer & DATA == 0 {
            return Err("Alembic group record used as data".into());
        }
        let offset = usize::try_from(pointer & !DATA)?;
        if offset == 0 {
            return Ok(&[]);
        }
        let mut b = Bytes::new(
            self.bytes
                .get(offset..)
                .ok_or("Ogawa data offset outside input")?,
        );
        let size = usize::try_from(b.uint(8)?)?;
        b.take(size)
    }
    /// Resolve metadata either inline or by archive metadata index.
    fn meta(&self, index: usize, b: &mut Bytes<'_>, hint: Option<u32>) -> Result<Metadata> {
        if index == 255 {
            let size = if let Some(h) = hint {
                b.hint(h)?
            } else {
                usize::try_from(b.uint(4)?)?
            };
            metadata(b.take(size)?)
        } else {
            self.metadata
                .get(index)
                .cloned()
                .ok_or_else(|| "invalid Alembic metadata index".into())
        }
    }
    /// Decode the archive's top-level object hierarchy.
    fn root(mut self) -> Result<Object> {
        let md = metadata(self.data(self.archive[3])?)?;
        self.object(self.archive[2], "/".to_owned(), md, 0)
    }
    /// Decode an Ogawa object, its properties and child objects with cycle detection.
    #[allow(
        clippy::cast_possible_truncation,
        reason = "Metadata indices are read from exactly one byte."
    )]
    fn object(&mut self, pointer: u64, path: String, md: Metadata, depth: usize) -> Result<Object> {
        self.budget.node(depth)?;
        if pointer != 0 && !self.active.insert(pointer) {
            return Err("cyclic Alembic object records".into());
        }
        let group = self.group(pointer)?;
        let mut properties = Property::default();
        let mut children = Vec::new();
        if let Some(&p) = group.first() {
            properties = self.compound(p, String::new(), Metadata::new(), depth + 1)?;
        }
        if let Some(&headers) = group.last().filter(|&&p| p & DATA != 0) {
            let raw = self.data(headers)?;
            let mut b = Bytes::new(
                raw.get(
                    ..raw
                        .len()
                        .checked_sub(32)
                        .ok_or("Alembic object headers lack hashes")?,
                )
                .ok_or("invalid Alembic object headers")?,
            );
            let mut names = HashSet::new();
            let mut index = 1;
            while !b.done() {
                let len = usize::try_from(b.uint(4)?)?;
                let name = b.name(len)?;
                if name.contains('/') || !names.insert(name.clone()) {
                    return Err("invalid or duplicate Alembic object name".into());
                }
                let mi = b.uint(1)? as usize;
                let md = self.meta(mi, &mut b, None)?;
                let pointer = *group
                    .get(index)
                    .ok_or("Alembic object header count mismatch")?;
                children.push(self.object(
                    pointer,
                    format!("{}/{name}", path.trim_end_matches('/')),
                    md,
                    depth + 1,
                )?);
                index += 1;
            }
            if index + 1 != group.len() {
                return Err("Alembic child/header count mismatch".into());
            }
        } else if group.len() > 1 {
            return Err("Alembic object lacks child headers".into());
        }
        self.active.remove(&pointer);
        Ok(Object {
            path,
            metadata: md,
            properties,
            children,
        })
    }
    /// Decode compound property headers and bounded first-sample data recursively.
    #[allow(
        clippy::cast_possible_truncation,
        clippy::too_many_lines,
        reason = "Property header words are read from exactly four bytes; the bounded property decoder keeps header and sample validation together."
    )]
    fn compound(
        &mut self,
        pointer: u64,
        name: String,
        md: Metadata,
        depth: usize,
    ) -> Result<Property> {
        self.budget.node(depth)?;
        if pointer != 0 && !self.active.insert(pointer) {
            return Err("cyclic Alembic property records".into());
        }
        let group = self.group(pointer)?;
        let mut children = Vec::new();
        if let Some(&p) = group.last() {
            let mut b = Bytes::new(self.data(p)?);
            let mut index = 0;
            let mut names = HashSet::new();
            while !b.done() {
                let info = b.uint(4)? as u32;
                let kind = info & 3;
                let hint = (info >> 2) & 3;
                let pod = ((info >> 4) & 15) as u8;
                let extent = ((info >> 12) & 255) as usize;
                let mut samples = 0;
                if kind != 0 {
                    pod_width(pod)?;
                    if extent == 0 {
                        return Err("Alembic property has zero extent".into());
                    }
                    samples = b.hint(hint)?;
                    if info & 512 != 0 {
                        let first = b.hint(hint)?;
                        let last = b.hint(hint)?;
                        if first > last || last >= samples {
                            return Err("invalid Alembic sample repetition range".into());
                        }
                    }
                    if info & 256 != 0 {
                        b.hint(hint)?;
                    }
                }
                let len = b.hint(hint)?;
                let name = b.name(len)?;
                if !names.insert(name.clone()) {
                    return Err("duplicate Alembic property name".into());
                }
                let md = self.meta(((info >> 20) & 255) as usize, &mut b, Some(hint))?;
                let child = *group.get(index).ok_or("Alembic property count mismatch")?;
                let prop = if kind == 0 {
                    self.compound(child, name, md, depth + 1)?
                } else {
                    self.budget.node(depth + 1)?;
                    let records = self.group(child)?;
                    let sample = if samples == 0 {
                        None
                    } else {
                        let raw = self.data(
                            *records
                                .first()
                                .ok_or("Alembic sampled property has no data")?,
                        )?;
                        let raw = if raw.is_empty() && kind >= 2 {
                            raw
                        } else {
                            raw.get(16..).ok_or("Alembic sample lacks its data key")?
                        };
                        let width = pod_width(pod)?;
                        if pod < 12
                            && (!raw.len().is_multiple_of(width * extent)
                                || raw.len() / width > MAX_ITEMS)
                        {
                            return Err("invalid or oversized Alembic sample".into());
                        }
                        if kind == 1 && pod < 12 && raw.len() != width * extent {
                            return Err("Alembic scalar sample has wrong extent".into());
                        }
                        if kind >= 2 {
                            let dims = self.data(
                                *records
                                    .get(1)
                                    .ok_or("Alembic array sample lacks dimensions")?,
                            )?;
                            if !dims.is_empty() && pod < 12 {
                                let mut dims = Bytes::new(dims);
                                let mut count = 1u64;
                                while !dims.done() {
                                    count = count
                                        .checked_mul(dims.uint(8)?)
                                        .ok_or("Alembic dimensions overflow")?;
                                }
                                if count != u64::try_from(raw.len() / (width * extent))? {
                                    return Err(
                                        "Alembic array dimensions disagree with sample".into()
                                    );
                                }
                            }
                        }
                        self.budget.bytes(raw.len())?;
                        Some(Sample {
                            pod,
                            extent,
                            big_endian: false,
                            bytes: raw.to_vec(),
                        })
                    };
                    Property {
                        name,
                        metadata: md,
                        children: Vec::new(),
                        sample,
                    }
                };
                children.push(prop);
                index += 1;
            }
            if index + 1 != group.len() {
                return Err("Alembic property/header count mismatch".into());
            }
        }
        self.active.remove(&pointer);
        Ok(Property {
            name,
            metadata: md,
            children,
            sample: None,
        })
    }
}

/// Open a supported Alembic HDF5 storage version and decode its object hierarchy.
fn hdf_archive(bytes: Vec<u8>) -> Result<Object> {
    let file = Hdf5File::from_vec(bytes)?;
    let root = file.root_group()?;
    let version = root.attribute("abc_version")?.read_scalar::<i32>()?;
    if !(-8..=0).contains(&version) {
        return Err("unsupported Alembic HDF5 storage version".into());
    }
    hdf_object(
        &file,
        &file.group("/ABC")?,
        "/".to_owned(),
        &mut Budget::default(),
        0,
    )
}
/// Read optional HDF5 metadata from a named string attribute.
fn hdf_meta(attributes: &[Attribute], name: &str) -> Result<Metadata> {
    match attributes.iter().find(|a| a.name == name) {
        Some(a) => metadata(a.read_string()?.as_bytes()),
        None => Ok(Metadata::new()),
    }
}
/// Decode an HDF5 object group and its child object and property groups.
fn hdf_object(
    file: &Hdf5File,
    group: &Group,
    path: String,
    budget: &mut Budget,
    depth: usize,
) -> Result<Object> {
    budget.node(depth)?;
    let attrs = group.attributes()?;
    let metadata = hdf_meta(&attrs, ".prop.meta")?;
    let properties = if group.group(".prop").is_ok() {
        hdf_compound(
            file,
            &group.group(".prop")?,
            String::new(),
            Metadata::new(),
            budget,
            depth + 1,
        )?
    } else {
        Property::default()
    };
    let mut children = Vec::new();
    for child in group.groups()? {
        let name = child
            .name()
            .rsplit('/')
            .next()
            .ok_or("Alembic HDF5 child lacks a name")?;
        if name == ".prop" {
            continue;
        }
        children.push(hdf_object(
            file,
            &child,
            format!("{}/{name}", path.trim_end_matches('/')),
            budget,
            depth + 1,
        )?);
    }
    Ok(Object {
        path,
        metadata,
        properties,
        children,
    })
}
/// Determine the byte order of an HDF5 numeric component, including array wrappers.
fn byte_order(dtype: &Datatype) -> Result<bool> {
    match dtype {
        Datatype::FixedPoint { byte_order, .. } | Datatype::FloatingPoint { byte_order, .. } => {
            Ok(*byte_order == ByteOrder::BigEndian)
        }
        Datatype::Array { base, .. } | Datatype::Enum { base, .. } => byte_order(base),
        _ => Err("unsupported Alembic HDF5 numeric datatype".into()),
    }
}
/// Decode HDF5 compound headers and first scalar or array samples within shared budgets.
#[allow(
    clippy::case_sensitive_file_extension_comparisons,
    reason = "The Alembic .info suffix is a case-sensitive HDF5 attribute name, not a filename extension."
)]
fn hdf_compound(
    file: &Hdf5File,
    group: &Group,
    name: String,
    md: Metadata,
    budget: &mut Budget,
    depth: usize,
) -> Result<Property> {
    budget.node(depth)?;
    let attrs = group.attributes()?;
    let mut children = Vec::new();
    for attr in attrs.iter().filter(|a| a.name.ends_with(".info")) {
        let name = attr.name.strip_suffix(".info").unwrap().to_owned();
        if attr.num_elements()? > 5 {
            return Err("Alembic HDF5 property header exceeds five words".into());
        }
        let info = attr.read_1d::<u32>()?;
        let bits = *info.first().ok_or("empty Alembic HDF5 property header")?;
        let md = hdf_meta(&attrs, &format!("{name}.meta"))?;
        let kind = bits & 3;
        let prop = if kind == 0 {
            match group.group(&name) {
                Ok(child) => hdf_compound(file, &child, name, md, budget, depth + 1)?,
                Err(_) => Property {
                    name,
                    metadata: md,
                    ..Property::default()
                },
            }
        } else {
            budget.node(depth + 1)?;
            let pod = ((bits >> 2) & 15) as u8;
            let extent = ((bits >> 8) & 255) as usize;
            if extent == 0 {
                return Err("Alembic HDF5 sample has zero extent".into());
            }
            pod_width(pod)?;
            let sample_name = format!("{name}.smp0");
            let sample = if kind == 1 {
                attrs
                    .iter()
                    .find(|a| a.name == sample_name)
                    .map(|a| {
                        budget.bytes(a.raw_data.len())?;
                        let big_endian = if pod < 12 {
                            byte_order(&a.datatype)?
                        } else {
                            false
                        };
                        Ok::<_, crate::Error>(Sample {
                            pod,
                            extent,
                            big_endian,
                            bytes: if pod == 12 {
                                a.read_string()?.into_bytes()
                            } else {
                                a.raw_data.clone()
                            },
                        })
                    })
                    .transpose()?
            } else if let Ok(dataset) = group.dataset(&sample_name) {
                let dataset = file.adapt_dataset(dataset);
                let element = hdf5_reader::datatype_api::dtype_element_size(dataset.dtype())?;
                let total = usize::try_from(dataset.num_elements()?)?
                    .checked_mul(element)
                    .ok_or("Alembic HDF5 array byte size overflow")?;
                budget.bytes(total)?;
                let big_endian = if pod < 12 {
                    byte_order(dataset.dtype())?
                } else {
                    false
                };
                Some(Sample {
                    pod,
                    extent,
                    big_endian,
                    bytes: if pod == 12 {
                        dataset.read_string()?.into_bytes()
                    } else {
                        dataset.read_raw_bytes()?
                    },
                })
            } else {
                None
            };
            Property {
                name,
                metadata: md,
                children: Vec::new(),
                sample,
            }
        };
        children.push(prop);
    }
    Ok(Property {
        name,
        metadata: md,
        children,
        sample: None,
    })
}

/// Index archive objects and traverse their visible first-sample geometry.
fn build_scene(root: &Object) -> Result<Scene> {
    let mut objects = HashMap::new();
    index_objects(root, &mut objects);
    let mut scene = Scene::default();
    walk(
        root,
        Transform::IDENTITY,
        false,
        &objects,
        &mut HashSet::new(),
        0,
        &mut scene,
    )?;
    scene.validate()?;
    Ok(scene)
}
/// Index every decoded object by its archive path for instance resolution.
fn index_objects<'a>(object: &'a Object, index: &mut HashMap<&'a str, &'a Object>) {
    index.insert(&object.path, object);
    for child in &object.children {
        index_objects(child, index);
    }
}
/// Traverse object transforms, visibility, schemas and bounded archive instances.
fn walk(
    object: &Object,
    parent: Transform,
    hidden: bool,
    objects: &HashMap<&str, &Object>,
    active: &mut HashSet<String>,
    depth: usize,
    scene: &mut Scene,
) -> Result<()> {
    if depth > MAX_DEPTH || !active.insert(object.path.clone()) {
        return Err("cyclic or excessively deep Alembic instancing".into());
    }
    if object.metadata.get("isInstance").is_some_and(|v| v == "1") {
        let path = object.properties.required(".instanceSource")?.text()?;
        let source = objects
            .get(path)
            .ok_or("Alembic instance source does not exist")?;
        walk(source, parent, hidden, objects, active, depth + 1, scene)?;
        active.remove(&object.path);
        return Ok(());
    }
    let visibility = object
        .properties
        .child("visible")
        .map(Property::numbers)
        .transpose()?;
    let hidden = match visibility.as_deref() {
        Some([0.]) => true,
        Some([1.]) => false,
        Some([-1.]) | None => hidden,
        _ => return Err("invalid Alembic visibility sample".into()),
    };
    let schema = object.metadata.get("schema").map_or("", String::as_str);
    let mut world = parent;
    if schema.starts_with("AbcGeom_Xform_") || object.properties.child(".xform").is_some() {
        let p = object.properties.required(".xform")?;
        let local = xform(p)?;
        let inherits = p.child(".inherits").map(Property::numbers).transpose()?;
        world = match inherits.as_deref() {
            Some([0.]) => local,
            Some([1.]) | None => parent.then(local),
            _ => return Err("invalid Alembic transform inheritance sample".into()),
        };
    }
    if !hidden {
        let geom = object.properties.child(".geom");
        if schema.starts_with("AbcGeom_PolyMesh_") || schema.starts_with("AbcGeom_SubD_") {
            mesh(geom.ok_or("Alembic mesh lacks .geom")?, world, scene)?;
        } else if schema.starts_with("AbcGeom_Points_") {
            point_cloud(geom.ok_or("Alembic points lack .geom")?, world, scene)?;
        } else if schema.starts_with("AbcGeom_Curve_") {
            curves(geom.ok_or("Alembic curves lack .geom")?, world, scene)?;
        } else if !schema.is_empty()
            && !schema.starts_with("AbcGeom_Xform_")
            && !schema.starts_with("AbcGeom_Camera_")
            && !schema.starts_with("AbcGeom_FaceSet_")
            && !schema.starts_with("AbcMaterial_")
        {
            return Err(format!("unsupported Alembic geometry schema {schema}").into());
        } else if schema.is_empty()
            && (geom.is_some_and(|g| g.child("P").is_some())
                || object.metadata.contains_key("Usd:typeName"))
        {
            return Err("Alembic custom or incomplete geometry schemas are unsupported".into());
        }
    }
    for child in &object.children {
        walk(child, world, hidden, objects, active, depth + 1, scene)?;
    }
    active.remove(&object.path);
    geometry_limit(scene)
}
/// Compose the encoded Alembic transform operation stack and validate its channels.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::float_cmp,
    reason = "Transform opcodes are range-checked integral bytes; affine row entries require exact protocol constants."
)]
fn xform(p: &Property) -> Result<Transform> {
    let Some(ops) = p.child(".ops") else {
        if p.child(".vals").is_some() {
            return Err("Alembic transform has values but no operations".into());
        }
        return Ok(Transform::IDENTITY);
    };
    let ops = ops.numbers()?;
    let vals = p.required(".vals")?.numbers()?;
    let mut offset = 0;
    let mut result = Transform::IDENTITY;
    for op in ops {
        if !(0. ..=255.).contains(&op) || op.fract() != 0. {
            return Err("invalid Alembic transform operation encoding".into());
        }
        let kind = (op as u8) >> 4;
        let len = match kind {
            0 | 1 => 3,
            2 => 4,
            3 => 16,
            4..=6 => 1,
            _ => return Err("unsupported Alembic transform operation".into()),
        };
        let v = vals
            .get(offset..offset + len)
            .ok_or("Alembic transform has too few channels")?;
        offset += len;
        let m = match kind {
            0 => Transform([
                [v[0], 0., 0., 0.],
                [0., v[1], 0., 0.],
                [0., 0., v[2], 0.],
                [0., 0., 0., 1.],
            ]),
            1 => Transform([
                [1., 0., 0., 0.],
                [0., 1., 0., 0.],
                [0., 0., 1., 0.],
                [v[0], v[1], v[2], 1.],
            ]),
            2 => rotate(Vec3::new(v[0], v[1], v[2]), v[3])?,
            3 => Transform(std::array::from_fn(|c| {
                std::array::from_fn(|r| v[c * 4 + r])
            })),
            4..=6 => rotate(
                match kind {
                    4 => Vec3::new(1., 0., 0.),
                    5 => Vec3::new(0., 1., 0.),
                    _ => Vec3::new(0., 0., 1.),
                },
                v[0],
            )?,
            _ => unreachable!(),
        };
        if m.0.iter().flatten().any(|v| !v.is_finite())
            || m.0[0][3] != 0.
            || m.0[1][3] != 0.
            || m.0[2][3] != 0.
            || m.0[3][3] != 1.
        {
            return Err("Alembic transforms must be finite and affine".into());
        }
        result = result.then(m);
    }
    if offset != vals.len() {
        return Err("Alembic transform has unused channels".into());
    }
    if result.0.iter().flatten().any(|v| !v.is_finite()) {
        return Err("Alembic transform exceeds finite range".into());
    }
    Ok(result)
}
/// Build an axis-angle rotation from an angle in degrees, rejecting a zero axis.
fn rotate(axis: Vec3, degrees: f64) -> Result<Transform> {
    if axis.length() == 0. {
        return Err("Alembic rotation has a zero axis".into());
    }
    let axis = axis.normalized();
    let (sin, cos) = degrees.to_radians().sin_cos();
    let complement = 1. - cos;
    let (x, y, z) = (axis.x, axis.y, axis.z);
    Ok(Transform([
        [
            complement * x * x + cos,
            complement * x * y + sin * z,
            complement * x * z - sin * y,
            0.,
        ],
        [
            complement * x * y - sin * z,
            complement * y * y + cos,
            complement * y * z + sin * x,
            0.,
        ],
        [
            complement * x * z + sin * y,
            complement * y * z - sin * x,
            complement * z * z + cos,
            0.,
        ],
        [0., 0., 0., 1.],
    ]))
}
/// Read finite three-component position samples from the schema's P property.
fn positions(p: &Property) -> Result<Vec<Vec3>> {
    let p = p.required("P")?;
    if p.sample.as_ref().is_none_or(|s| s.extent != 3) {
        return Err("Alembic positions need extent three".into());
    }
    let values = p.numbers()?;
    if !values.len().is_multiple_of(3) {
        return Err("Alembic coordinates are not triples".into());
    }
    Ok(values
        .as_chunks::<3>()
        .0
        .iter()
        .map(|v| Vec3::new(v[0], v[1], v[2]))
        .collect())
}
/// Convert bounded nonnegative integral sample values into geometry indices.
#[allow(
    clippy::cast_precision_loss,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    reason = "Indices are finite nonnegative integers bounded by five million, which is represented exactly by f64."
)]
fn indices(p: &Property) -> Result<Vec<usize>> {
    p.numbers()?
        .into_iter()
        .map(|v| {
            if !(0. ..=MAX_ITEMS as f64).contains(&v) || v.fract() != 0. {
                return Err("invalid Alembic integer/index sample".into());
            }
            Ok(v as usize)
        })
        .collect()
}
/// Append transformed point samples with optional geometry colors.
fn point_cloud(p: &Property, world: Transform, scene: &mut Scene) -> Result<()> {
    let positions = positions(p)?;
    let colors = Colors::new(p)?;
    for (i, position) in positions.into_iter().enumerate() {
        scene.points.push(Point {
            position: world.apply(position),
            color: colors.as_ref().map(|c| c.color(&[i], i, i)).transpose()?,
        });
    }
    geometry_limit(scene)
}
/// Triangulate polygon samples, skipping declared hole faces and resolving colors.
fn mesh(p: &Property, world: Transform, scene: &mut Scene) -> Result<()> {
    let vertices = positions(p)?;
    let counts = indices(p.required(".faceCounts")?)?;
    let ids = indices(p.required(".faceIndices")?)?;
    let holes = p
        .child(".holes")
        .map(indices)
        .transpose()?
        .unwrap_or_default()
        .into_iter()
        .collect::<HashSet<_>>();
    let colors = Colors::new(p)?;
    let mut offset = 0;
    for (face, count) in counts.into_iter().enumerate() {
        if !(3..=65_536).contains(&count) {
            return Err("Alembic polygon needs 3..65536 vertices".into());
        }
        let indices = ids
            .get(offset..offset + count)
            .ok_or("Alembic face counts exceed the index array")?;
        let polygon = indices
            .iter()
            .map(|&i| {
                vertices
                    .get(i)
                    .copied()
                    .ok_or_else(|| "Alembic vertex index outside positions".into())
            })
            .collect::<Result<Vec<_>>>()?;
        let color = colors
            .as_ref()
            .map(|c| c.color(indices, face, offset))
            .transpose()?;
        if !holes.contains(&face) {
            for vertices in triangulate_polygon(&polygon)? {
                scene.triangles.push(Triangle {
                    vertices: vertices.map(|v| world.apply(v)),
                    color,
                });
            }
        }
        offset += count;
        geometry_limit(scene)?;
    }
    if offset != ids.len() {
        return Err("Alembic polygon indices contain unused entries".into());
    }
    Ok(())
}
/// Alembic RGB values with optional indices and geometry scope.
struct Colors {
    /// Decoded linear color components.
    values: Vec<Vec3>,
    /// Optional indirection from geometry color elements to values.
    indices: Option<Vec<usize>>,
    /// Constant, uniform, varying, vertex or face-varying scope token.
    scope: String,
}
impl Colors {
    /// Find a supported color geometry parameter and validate its layout and scope.
    fn new(p: &Property) -> Result<Option<Self>> {
        let params = p.child(".arbGeomParams").unwrap_or(p);
        let Some(color) = params.children.iter().find(|p| {
            matches!(p.name.as_str(), "Cs" | "Cd" | "displayColor")
                || matches!(
                    p.metadata.get("interpretation").map(String::as_str),
                    Some("rgb" | "rgba")
                )
        }) else {
            return Ok(None);
        };
        let values = color.child(".vals").unwrap_or(color);
        let sample = values
            .sample
            .as_ref()
            .ok_or("Alembic color has no values")?;
        if sample.extent != 3 && sample.extent != 4 {
            return Err("Alembic colors need RGB/RGBA extent".into());
        }
        let n = values.numbers()?;
        if !n.len().is_multiple_of(sample.extent) {
            return Err("Alembic color sample is misaligned".into());
        }
        let values = n
            .chunks_exact(sample.extent)
            .map(|v| Vec3::new(v[0], v[1], v[2]))
            .collect();
        let indices = color.child(".indices").map(indices).transpose()?;
        let scope = color
            .metadata
            .get("geoScope")
            .or_else(|| {
                color
                    .child(".vals")
                    .and_then(|p| p.metadata.get("geoScope"))
            })
            .map_or("con", String::as_str)
            .to_owned();
        if !matches!(scope.as_str(), "con" | "uni" | "var" | "vtx" | "fvr") {
            return Err("unsupported Alembic color geometry scope".into());
        }
        Ok(Some(Self {
            values,
            indices,
            scope,
        }))
    }
    /// Resolve and average the colors of a face or point under its geometry scope.
    #[allow(
        clippy::cast_precision_loss,
        reason = "The divisor is a bounded geometry element count, well within exact f64 integer precision."
    )]
    fn color(&self, ids: &[usize], face: usize, corner: usize) -> Result<[u8; 3]> {
        let mut sum = Vec3::default();
        for (offset, &vertex) in ids.iter().enumerate() {
            let i = match self.scope.as_str() {
                "con" => 0,
                "uni" => face,
                "fvr" => corner + offset,
                _ => vertex,
            };
            let i = if let Some(indices) = &self.indices {
                *indices
                    .get(i)
                    .ok_or("Alembic color index array is too short")?
            } else {
                i
            };
            sum = sum
                + *self
                    .values
                    .get(i)
                    .ok_or("Alembic color array is too short")?;
        }
        let c = sum / (ids.len() as f64);
        Ok([srgb(c.x), srgb(c.y), srgb(c.z)])
    }
}
/// Clamp a linear color component and encode it as an sRGB byte.
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    reason = "Color components are clamped and rounded to the inclusive byte range before conversion."
)]
fn srgb(v: f64) -> u8 {
    let v = v.clamp(0., 1.);
    ((if v <= 0.003_130_8 {
        v * 12.92
    } else {
        1.055 * v.powf(1. / 2.4) - 0.055
    }) * 255.)
        .round() as u8
}
/// Append first-sample linear or tessellated cubic curves under their declared basis.
#[allow(
    clippy::float_cmp,
    reason = "Curve kind and wrap are discrete schema tags decoded from numeric samples."
)]
fn curves(p: &Property, world: Transform, scene: &mut Scene) -> Result<()> {
    let positions = positions(p)?;
    let counts = indices(p.required("nVertices")?)?;
    let options = p.required("curveBasisAndType")?.numbers()?;
    let [kind, periodic, basis, ..] = options.as_slice() else {
        return Err("Alembic curves lack basis/type channels".into());
    };
    if (*kind != 0. && *kind != 1.) || (*periodic != 0. && *periodic != 1.) {
        return Err("Alembic variable-order curves are unsupported".into());
    }
    if p.child("w").is_some() {
        return Err("Alembic rational curves are unsupported".into());
    }
    let colors = Colors::new(p)?;
    let mut offset = 0;
    for (curve, count) in counts.into_iter().enumerate() {
        let v = positions
            .get(offset..offset + count)
            .ok_or("Alembic curve counts exceed positions")?;
        if count < 2 {
            return Err("Alembic curve needs at least two vertices".into());
        }
        let ids = (offset..offset + count).collect::<Vec<_>>();
        let color = colors
            .as_ref()
            .map(|c| c.color(&ids, curve, offset))
            .transpose()?;
        let periodic = *periodic == 1.;
        if *kind == 1. {
            for pair in v.windows(2) {
                scene.lines.push(Line {
                    vertices: [world.apply(pair[0]), world.apply(pair[1])],
                    color,
                });
            }
            if periodic {
                scene.lines.push(Line {
                    vertices: [world.apply(v[count - 1]), world.apply(v[0])],
                    color,
                });
            }
        } else {
            let step = match *basis {
                1. => 3,
                4. => 2,
                5. => 4,
                _ => 1,
            };
            if !matches!(*basis, 1. | 2. | 3. | 4. | 5.) || count < 4 {
                return Err("unsupported Alembic cubic curve basis/count".into());
            }
            let spans = if periodic {
                if !count.is_multiple_of(step) {
                    return Err("Alembic periodic Bezier count is not divisible by three".into());
                }
                count / step
            } else {
                if !(count - 4).is_multiple_of(step) {
                    return Err("Alembic cubic count does not match its basis step".into());
                }
                (count - 4) / step + 1
            };
            for span in 0..spans {
                let q = std::array::from_fn(|i| v[(span * step + i) % count]);
                let mut previous = cubic(q, *basis, 0.);
                for sample in 1..=24 {
                    let next = cubic(q, *basis, f64::from(sample) / 24.);
                    scene.lines.push(Line {
                        vertices: [world.apply(previous), world.apply(next)],
                        color,
                    });
                    previous = next;
                }
                geometry_limit(scene)?;
            }
        }
        offset += count;
        geometry_limit(scene)?;
    }
    if offset != positions.len() {
        return Err("Alembic curves contain unused positions".into());
    }
    Ok(())
}
/// Evaluate four curve controls at a parameter using the declared cubic basis.
fn cubic(q: [Vec3; 4], basis: f64, t: f64) -> Vec3 {
    let t2 = t * t;
    let t3 = t2 * t;
    let weights = match basis {
        1. => [
            (1. - t).powi(3),
            3. * t * (1. - t).powi(2),
            3. * t2 * (1. - t),
            t3,
        ],
        2. => [
            (-t3 + 3. * t2 - 3. * t + 1.) / 6.,
            (3. * t3 - 6. * t2 + 4.) / 6.,
            (-3. * t3 + 3. * t2 + 3. * t + 1.) / 6.,
            t3 / 6.,
        ],
        3. => [
            -0.5 * t3 + t2 - 0.5 * t,
            1.5 * t3 - 2.5 * t2 + 1.,
            -1.5 * t3 + 2. * t2 + 0.5 * t,
            0.5 * t3 - 0.5 * t2,
        ],
        4. => [
            2. * t3 - 3. * t2 + 1.,
            t3 - 2. * t2 + t,
            -2. * t3 + 3. * t2,
            t3 - t2,
        ],
        _ => [t3, t2, t, 1.],
    };
    q.into_iter()
        .zip(weights)
        .fold(Vec3::default(), |v, (q, w)| v + q * w)
}
/// Enforce the aggregate output point, line and triangle budget.
fn geometry_limit(scene: &Scene) -> Result<()> {
    if scene
        .triangles
        .len()
        .saturating_add(scene.points.len())
        .saturating_add(scene.lines.len())
        > MAX_ITEMS
    {
        return Err("Alembic scene exceeds five million elements".into());
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{
        fs,
        path::PathBuf,
        sync::atomic::{AtomicUsize, Ordering},
    };
    static NEXT: AtomicUsize = AtomicUsize::new(0);
    struct Fixture(PathBuf);
    impl Fixture {
        fn new(bytes: &[u8]) -> Self {
            let path = std::env::temp_dir().join(format!(
                "catwalk-alembic-{}-{}.abc",
                std::process::id(),
                NEXT.fetch_add(1, Ordering::Relaxed)
            ));
            fs::write(&path, bytes).unwrap();
            Self(path)
        }
    }
    impl Drop for Fixture {
        fn drop(&mut self) {
            let _ = fs::remove_file(&self.0);
        }
    }
    fn md(schema: &str) -> Metadata {
        HashMap::from([("schema".to_owned(), schema.to_owned())])
    }
    fn compound(name: &str, children: Vec<Property>) -> Property {
        Property {
            name: name.to_owned(),
            children,
            ..Property::default()
        }
    }
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "The authored test samples use small integral byte or i32 values."
    )]
    fn value(name: &str, extent: usize, values: &[f64]) -> Property {
        let (pod, bytes) = match name {
            ".ops" | "curveBasisAndType" | ".inherits" => {
                (1, values.iter().map(|&v| v as u8).collect())
            }
            ".faceCounts" | ".faceIndices" | ".indices" | ".holes" | "nVertices" => (
                6,
                values
                    .iter()
                    .flat_map(|&v| (v as i32).to_le_bytes())
                    .collect(),
            ),
            _ => (11, values.iter().flat_map(|v| v.to_le_bytes()).collect()),
        };
        Property {
            name: name.to_owned(),
            sample: Some(Sample {
                pod,
                extent,
                big_endian: false,
                bytes,
            }),
            ..Property::default()
        }
    }
    fn string(name: &str, text: &str) -> Property {
        let mut bytes = text.as_bytes().to_vec();
        bytes.push(0);
        Property {
            name: name.to_owned(),
            sample: Some(Sample {
                pod: 12,
                extent: 1,
                big_endian: false,
                bytes,
            }),
            ..Property::default()
        }
    }
    #[allow(
        clippy::cast_possible_truncation,
        reason = "The test archive uses small authored names, extents and metadata lengths."
    )]
    fn object(
        path: &str,
        schema: &str,
        properties: Vec<Property>,
        children: Vec<Object>,
    ) -> Object {
        Object {
            path: path.to_owned(),
            metadata: md(schema),
            properties: compound("", properties),
            children,
        }
    }
    fn triangle(path: &str) -> Object {
        object(
            path,
            "AbcGeom_PolyMesh_v1",
            vec![compound(
                ".geom",
                vec![
                    value("P", 3, &[0., 0., 0., 1., 0., 0., 0., 1., 0.]),
                    value(".faceCounts", 1, &[3.]),
                    value(".faceIndices", 1, &[0., 1., 2.]),
                ],
            )],
            Vec::new(),
        )
    }
    fn root(child: Object) -> Object {
        object("/", "", Vec::new(), vec![child])
    }
    fn xform(ops: &[f64], values: &[f64], inherits: bool) -> Property {
        compound(
            ".xform",
            vec![
                value(".ops", ops.len(), ops),
                value(".vals", values.len(), values),
                value(".inherits", 1, &[f64::from(inherits)]),
            ],
        )
    }
    fn close(actual: Vec3, expected: [f64; 3]) {
        assert!(
            (actual - Vec3::new(expected[0], expected[1], expected[2])).length() < 1e-9,
            "{actual:?} != {expected:?}"
        );
    }
    struct Writer(Vec<u8>);
    impl Writer {
        fn data(&mut self, data: &[u8]) -> u64 {
            let ptr = self.0.len() as u64;
            self.0.extend_from_slice(&(data.len() as u64).to_le_bytes());
            self.0.extend_from_slice(data);
            ptr | DATA
        }
        fn group(&mut self, children: &[u64]) -> u64 {
            if children.is_empty() {
                return 0;
            }
            let ptr = self.0.len() as u64;
            self.0
                .extend_from_slice(&(children.len() as u64).to_le_bytes());
            for child in children {
                self.0.extend_from_slice(&child.to_le_bytes());
            }
            ptr
        }
        #[allow(
            clippy::cast_possible_truncation,
            reason = "The test archive uses small authored names, extents and metadata lengths."
        )]
        fn property(&mut self, p: &Property) -> u64 {
            let mut children = Vec::new();
            let mut headers = Vec::new();
            for p in &p.children {
                let (kind, pod, extent, records) = if let Some(sample) = &p.sample {
                    let width = pod_width(sample.pod).unwrap();
                    let scalar = sample.pod >= 12 || sample.bytes.len() == width * sample.extent;
                    let kind = if scalar { 1 } else { 2 };
                    let mut data = vec![0; 16];
                    data.extend_from_slice(&sample.bytes);
                    let pointer = self.data(&data);
                    let mut records = vec![pointer];
                    if !scalar {
                        records.push(DATA);
                    }
                    if p.name == "P" {
                        let mut second = vec![0; 16];
                        second.extend(
                            sample
                                .bytes
                                .as_chunks::<8>()
                                .0
                                .iter()
                                .flat_map(|b| (f64::from_le_bytes(*b) + 100.).to_le_bytes()),
                        );
                        records.push(self.data(&second));
                        if !scalar {
                            records.push(DATA);
                        }
                    }
                    (kind, sample.pod, sample.extent, self.group(&records))
                } else {
                    (0, 0, 0, self.property(p))
                };
                children.push(records);
                let info = kind
                    | (2 << 2)
                    | (u32::from(pod) << 4)
                    | ((extent as u32) << 12)
                    | (255 << 20)
                    | if p.name == "P" {
                        0x200
                    } else if kind != 0 {
                        0x800
                    } else {
                        0
                    };
                headers.extend_from_slice(&info.to_le_bytes());
                if kind != 0 {
                    headers
                        .extend_from_slice(&if p.name == "P" { 2u32 } else { 1u32 }.to_le_bytes());
                    if p.name == "P" {
                        headers.extend_from_slice(&1u32.to_le_bytes());
                        headers.extend_from_slice(&1u32.to_le_bytes());
                    }
                }
                headers.extend_from_slice(&(p.name.len() as u32).to_le_bytes());
                headers.extend_from_slice(p.name.as_bytes());
                let metadata = p
                    .metadata
                    .iter()
                    .map(|(k, v)| format!("{k}={v}"))
                    .collect::<Vec<_>>()
                    .join(";");
                headers.extend_from_slice(&(metadata.len() as u32).to_le_bytes());
                headers.extend_from_slice(metadata.as_bytes());
            }
            if children.is_empty() {
                return 0;
            }
            children.push(self.data(&headers));
            self.group(&children)
        }
        #[allow(
            clippy::cast_possible_truncation,
            reason = "The authored archive uses short object names and bounded metadata lengths."
        )]
        fn object(&mut self, o: &Object) -> u64 {
            let mut children = vec![self.property(&o.properties)];
            let mut headers = Vec::new();
            for child in &o.children {
                children.push(self.object(child));
                let name = child.path.rsplit('/').next().unwrap();
                headers.extend_from_slice(&(name.len() as u32).to_le_bytes());
                headers.extend_from_slice(name.as_bytes());
                headers.push(255);
                let meta = child
                    .metadata
                    .iter()
                    .map(|(k, v)| format!("{k}={v}"))
                    .collect::<Vec<_>>()
                    .join(";");
                headers.extend_from_slice(&(meta.len() as u32).to_le_bytes());
                headers.extend_from_slice(meta.as_bytes());
            }
            headers.resize(headers.len() + 32, 0);
            children.push(self.data(&headers));
            self.group(&children)
        }
        fn archive(o: &Object) -> Vec<u8> {
            let mut w = Self(b"Ogawa\xff\0\x01\0\0\0\0\0\0\0\0".to_vec());
            let version = w.data(&0u32.to_le_bytes());
            let release = w.data(&10803u32.to_le_bytes());
            let object = w.object(o);
            let root = w.group(&[version, release, object, DATA, DATA, DATA]);
            w.0[8..16].copy_from_slice(&root.to_le_bytes());
            w.0
        }
    }

    #[test]
    fn actual_ogawa_records_read_earliest_geometry_sample() {
        let root = root(triangle("/mesh"));
        let bytes = Writer::archive(&root);
        let fixture = Fixture::new(&bytes);
        let scene = load(&fixture.0).unwrap();
        assert_eq!(scene.triangles.len(), 1);
        close(scene.triangles[0].vertices[1], [1., 0., 0.]);
        assert_eq!(scene.points.len(), 0);
    }
    #[test]
    fn hierarchical_transform_order_and_inheritance_reset() {
        let child = object(
            "/parent/child",
            "AbcGeom_Xform_v3",
            vec![xform(&[16., 96., 0.], &[2., 0., 0., 90., 2., 3., 1.], true)],
            vec![triangle("/parent/child/mesh")],
        );
        let reset = object(
            "/parent/reset",
            "AbcGeom_Xform_v3",
            vec![xform(&[16.], &[4., 5., 6.], false)],
            vec![triangle("/parent/reset/mesh")],
        );
        let parent = object(
            "/parent",
            "AbcGeom_Xform_v3",
            vec![xform(&[16.], &[10., 0., 0.], true)],
            vec![child, reset],
        );
        let scene = build_scene(&root(parent)).unwrap();
        close(scene.triangles[0].vertices[0], [12., 0., 0.]);
        close(scene.triangles[0].vertices[1], [12., 2., 0.]);
        close(scene.triangles[0].vertices[2], [9., 0., 0.]);
        close(scene.triangles[1].vertices[0], [4., 5., 6.]);
    }
    #[test]
    fn matrix_axis_angle_and_axis_rotations() {
        let matrix = xform(
            &[48.],
            &[
                1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 3., 4., 5., 1.,
            ],
            true,
        );
        close(
            super::xform(&matrix).unwrap().apply(Vec3::new(1., 2., 3.)),
            [4., 6., 8.],
        );
        let axis = xform(&[32.], &[0., 0., 2., 90.], true);
        close(
            super::xform(&axis).unwrap().apply(Vec3::new(1., 0., 0.)),
            [0., 1., 0.],
        );
        for (op, p, e) in [
            (64., [0., 1., 0.], [0., 0., 1.]),
            (80., [0., 0., 1.], [1., 0., 0.]),
            (96., [1., 0., 0.], [0., 1., 0.]),
        ] {
            close(
                super::xform(&xform(&[op], &[90.], true))
                    .unwrap()
                    .apply(Vec3::new(p[0], p[1], p[2])),
                e,
            );
        }
    }
    #[test]
    fn indexed_face_colors_and_subdivision_holes() {
        let mut color = compound(
            "Cs",
            vec![
                value(".vals", 3, &[1., 0., 0., 0., 1., 0.]),
                value(".indices", 1, &[0., 1.]),
            ],
        );
        color
            .metadata
            .insert("geoScope".to_owned(), "uni".to_owned());
        let geom = compound(
            ".geom",
            vec![
                value("P", 3, &[0., 0., 0., 1., 0., 0., 1., 1., 0., 0., 1., 0.]),
                value(".faceCounts", 1, &[3., 3.]),
                value(".faceIndices", 1, &[0., 1., 2., 0., 2., 3.]),
                value(".holes", 1, &[1.]),
                compound(".arbGeomParams", vec![color]),
            ],
        );
        let root = root(object("/subd", "AbcGeom_SubD_v1", vec![geom], Vec::new()));
        let scene = build_scene(&root).unwrap();
        assert_eq!(scene.triangles.len(), 1);
        assert_eq!(scene.triangles[0].color, Some([255, 0, 0]));
    }
    #[test]
    fn nested_instances_preserve_source_local_and_instance_parent_transforms() {
        let a = object(
            "/a",
            "AbcGeom_Xform_v3",
            vec![xform(&[16.], &[-2., 0., 0.], true)],
            vec![triangle("/a/mesh")],
        );
        let mut instance = object(
            "/b/i",
            "",
            vec![string(".instanceSource", "/a")],
            Vec::new(),
        );
        instance
            .metadata
            .insert("isInstance".to_owned(), "1".to_owned());
        let b = object(
            "/b",
            "AbcGeom_Xform_v3",
            vec![xform(&[16.], &[0., 5., 0.], true)],
            vec![instance],
        );
        let mut instance = object(
            "/c/i",
            "",
            vec![string(".instanceSource", "/b")],
            Vec::new(),
        );
        instance
            .metadata
            .insert("isInstance".to_owned(), "1".to_owned());
        let c = object(
            "/c",
            "AbcGeom_Xform_v3",
            vec![xform(&[16.], &[0., 0., 5.], true)],
            vec![instance],
        );
        let root = object("/", "", Vec::new(), vec![a, b, c]);
        let bytes = Writer::archive(&root);
        let fixture = Fixture::new(&bytes);
        let scene = load(&fixture.0).unwrap();
        assert_eq!(scene.triangles.len(), 3);
        close(scene.triangles[0].vertices[0], [-2., 0., 0.]);
        close(scene.triangles[1].vertices[0], [-2., 5., 0.]);
        close(scene.triangles[2].vertices[0], [-2., 5., 5.]);
    }
    #[test]
    fn point_cloud_colors_and_visibility() {
        let mut color = value("Cd", 3, &[0.25, 0., 0.]);
        color
            .metadata
            .insert("geoScope".to_owned(), "con".to_owned());
        let points = object(
            "/points",
            "AbcGeom_Points_v1",
            vec![compound(
                ".geom",
                vec![
                    value("P", 3, &[0., 0., 0., 1., 1., 1.]),
                    compound(".arbGeomParams", vec![color]),
                ],
            )],
            Vec::new(),
        );
        let mut hidden = triangle("/hidden");
        hidden.properties.children.push(value("visible", 1, &[0.]));
        let scene = build_scene(&object("/", "", Vec::new(), vec![points, hidden])).unwrap();
        assert_eq!(scene.points.len(), 2);
        assert!(scene.triangles.is_empty());
        assert_eq!(scene.points[0].color, Some([137, 0, 0]));
    }
    #[test]
    fn periodic_linear_and_sampled_cubic_curves() {
        let geom = compound(
            ".geom",
            vec![
                value("P", 3, &[0., 0., 0., 1., 0., 0., 1., 1., 0.]),
                value("nVertices", 1, &[3.]),
                value("curveBasisAndType", 4, &[1., 1., 0., 0.]),
            ],
        );
        let scene = build_scene(&root(object(
            "/curves",
            "AbcGeom_Curve_v2",
            vec![geom],
            Vec::new(),
        )))
        .unwrap();
        assert_eq!(scene.lines.len(), 3);
        close(scene.lines[2].vertices[1], [0., 0., 0.]);
        let geom = compound(
            ".geom",
            vec![
                value("P", 3, &[0., 0., 0., 0., 1., 0., 1., 1., 0., 1., 0., 0.]),
                value("nVertices", 1, &[4.]),
                value("curveBasisAndType", 4, &[0., 0., 1., 1.]),
            ],
        );
        let scene = build_scene(&root(object(
            "/curves",
            "AbcGeom_Curve_v2",
            vec![geom],
            Vec::new(),
        )))
        .unwrap();
        assert_eq!(scene.lines.len(), 24);
        close(scene.lines[0].vertices[0], [0., 0., 0.]);
        close(scene.lines[23].vertices[1], [1., 0., 0.]);
        close(scene.lines[11].vertices[1], [0.5, 0.75, 0.]);
    }
    #[test]
    fn typed_samples_big_endian_half_and_invalid_numbers() {
        let sample = Sample {
            pod: 10,
            extent: 3,
            big_endian: true,
            bytes: [1f32, 2., 3.]
                .iter()
                .flat_map(|v| v.to_be_bytes())
                .collect(),
        };
        assert_eq!(sample.numbers().unwrap(), vec![1., 2., 3.]);
        let sample = Sample {
            pod: 9,
            extent: 2,
            big_endian: false,
            bytes: [0x3c00u16, 0xc000u16]
                .iter()
                .flat_map(|v| v.to_le_bytes())
                .collect(),
        };
        assert_eq!(sample.numbers().unwrap(), vec![1., -2.]);
        let sample = Sample {
            pod: 11,
            extent: 1,
            big_endian: false,
            bytes: f64::NAN.to_le_bytes().to_vec(),
        };
        assert!(sample.numbers().is_err());
    }
    #[test]
    fn malformed_archives_and_unsupported_schemas_fail_cleanly() {
        let bytes = Writer::archive(&root(triangle("/mesh")));
        for len in [0, 5, 15, bytes.len() - 8] {
            assert!(Ogawa::new(&bytes[..len]).is_err());
        }
        let mut bytes = bytes.clone();
        bytes[5] = 0;
        assert!(Ogawa::new(&bytes).is_err());
        let mut bytes = bytes.clone();
        bytes[5] = 255;
        bytes[8..16].copy_from_slice(&u64::MAX.to_le_bytes());
        assert!(Ogawa::new(&bytes).is_err());
        let unsupported = root(object(
            "/patch",
            "AbcGeom_NuPatch_v1",
            Vec::new(),
            Vec::new(),
        ));
        assert!(
            build_scene(&unsupported)
                .unwrap_err()
                .to_string()
                .contains("unsupported")
        );
        let mut instance = object("/i", "", vec![string(".instanceSource", "/i")], Vec::new());
        instance
            .metadata
            .insert("isInstance".to_owned(), "1".to_owned());
        assert!(
            build_scene(&root(instance))
                .unwrap_err()
                .to_string()
                .contains("cyclic")
        );
        assert!(super::xform(&xform(&[16.], &[1.], true)).is_err());
    }

    #[test]
    fn filtered_hdf_properties_render_geometry_and_decode_fixed_and_vlen_strings() {
        use hdf5_writer::{AttributeBuilder, DatasetBuilder, Hdf5Builder, WriteOptions};
        let positions: Vec<f32> = (0..171)
            .flat_map(|index| {
                [
                    f32::from(i16::try_from(index - 80).unwrap()),
                    f32::from(i16::try_from(index * 7 % 13).unwrap()),
                    f32::from(i16::try_from(index / 11).unwrap()),
                ]
            })
            .collect();
        let text = format!("{}λ", "a".repeat(510));
        let points = DatasetBuilder::typed_data("ABC/.prop/.geom/P.smp0", vec![171, 3], &positions)
            .unwrap()
            .chunked(vec![128, 1]);
        let fixed = DatasetBuilder::fixed_string_data("ABC/.prop/fixed.smp0", vec![1], &[&text])
            .unwrap()
            .max_shape(vec![u64::MAX])
            .chunked(vec![1]);
        let variable =
            DatasetBuilder::vlen_string_data("ABC/.prop/variable.smp0", vec![1], &[&text])
                .unwrap()
                .max_shape(vec![u64::MAX])
                .chunked(vec![32]);
        let mut builder = Hdf5Builder::new()
            .attribute(AttributeBuilder::scalar("abc_version", -8i32).unwrap())
            .group_attribute(
                "ABC",
                AttributeBuilder::fixed_string(".prop.meta", "schema=AbcGeom_Points_v1"),
            )
            .group_attribute(
                "ABC/.prop",
                AttributeBuilder::vector(".geom.info", &[0u32]).unwrap(),
            )
            .group_attribute(
                "ABC/.prop/.geom",
                AttributeBuilder::vector("P.info", &[2u32 | (10 << 2) | (3 << 8)]).unwrap(),
            );
        for name in ["fixed", "variable"] {
            builder = builder.group_attribute(
                "ABC/.prop",
                AttributeBuilder::vector(format!("{name}.info"), &[2u32 | (12 << 2) | (1 << 8)])
                    .unwrap(),
            );
        }
        for dataset in [points, fixed, variable] {
            builder = builder.dataset(hdf_compressed(dataset));
        }
        let bytes = builder
            .into_plan()
            .unwrap()
            .encode(WriteOptions::default())
            .unwrap();
        let unmodified = hdf5_reader::Hdf5File::from_bytes(&bytes).unwrap();
        for path in [
            "ABC/.prop/.geom/P.smp0",
            "ABC/.prop/fixed.smp0",
            "ABC/.prop/variable.smp0",
        ] {
            assert!(unmodified.dataset(path).unwrap().read_raw_bytes().is_err());
        }
        let archive = hdf_archive(bytes).unwrap();
        for name in ["fixed", "variable"] {
            assert_eq!(
                archive.properties.required(name).unwrap().text().unwrap(),
                text
            );
        }
        let actual = build_scene(&archive).unwrap();
        let expected = Scene {
            points: positions
                .as_chunks::<3>()
                .0
                .iter()
                .map(|point| Point {
                    position: Vec3::new(
                        f64::from(point[0]),
                        f64::from(point[1]),
                        f64::from(point[2]),
                    ),
                    color: None,
                })
                .collect(),
            ..Scene::default()
        };
        assert_eq!(actual.points.len(), 171);
        for (actual, expected) in actual.points.iter().zip(&expected.points) {
            assert_eq!(actual.position, expected.position);
        }
        let options = crate::render::RenderOptions {
            width: 64,
            height: 64,
            transparent: true,
            ..Default::default()
        };
        assert_eq!(
            crate::render::render(&actual, &options).unwrap(),
            crate::render::render(&expected, &options).unwrap()
        );
    }

    /// Apply independent writer codecs to force the filtered Alembic dataset path.
    fn hdf_compressed(dataset: hdf5_writer::DatasetBuilder) -> hdf5_writer::DatasetBuilder {
        dataset
            .filter(hdf5_writer::FilterDescription {
                id: 1,
                name: None,
                client_data: vec![6],
            })
            .filter(hdf5_writer::FilterDescription {
                id: 3,
                name: None,
                client_data: vec![],
            })
    }
}