meshoptimizer-rs 0.2.20

Rust port of meshoptimizer 1.3 with byte-identical output. Covers mesh simplification, meshlets, cluster LOD, vertex/index compression analysis, remeshing and optional parallel batch APIs and audited SIMD codecs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
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
//! MDAG 2: a chunked cluster-LOD container whose resident prefix opens without
//! reading any page. Not in C++ meshoptimizer.
//!
//! A file is `header | chunk table | resident chunks | pages`. The resident
//! prefix holds the group, node, page and dependency tables and the refinement
//! relation (each cluster's refined group); pages hold the clusters in the disk
//! form of [`page`] and are fetched and transcoded one at a
//! time. Groups are stored coarse-first, so a page's dependencies always have
//! smaller page indices and every prefix of the page table that contains the
//! pinned pages is a valid residency set.
//!
//! [`Reader::open`] validates the resident prefix only, including the exact
//! parent counts and dependency lists implied by the refinement relation;
//! [`Reader::transcode_page`] validates one page against it; [`Reader::read_all`]
//! does both for a whole file. Every byte is untrusted: failures are typed
//! [`Error`]s, nothing recurses, and allocations are bounded by the input
//! length. Opening costs `O(n log n)` in the prefix length `n` (the logarithm
//! is a sort of each page's distinct parent groups); transcoding a page is
//! linear in its size.
//!
//! Wire specification: `docs/DAG_FORMAT.md`, section "MDAG 2".
use super::Error;
use crate::clusterlod::bounds_math::{containing_radius, enclosing_sphere};
use crate::clusterlod::page::{self, PageView, QuantGrid};
use crate::clusterlod::LodBounds;
use crate::Workspace;
use alloc::vec::Vec;
use core::ops::Range;

#[cfg(feature = "clusterlod")]
#[path = "dag_format_v2_write.rs"]
mod writer;
#[cfg(feature = "clusterlod")]
pub use writer::{
    build_key, write, KeyInputs, Source, WriteOptions, WriteReport, BUILDER_REVISION,
    DEFAULT_NODE_WIDTH,
};

#[path = "far_field.rs"]
mod far_field;
pub use far_field::{FarField, FAR_FIELD_BYTES};

/// Major version written and accepted.
pub const MAJOR: u32 = 2;
/// Minor version written: the newest chunk set this crate knows. Readers
/// accept any minor; it is informational.
pub const MINOR: u32 = 1;
/// Header length in bytes.
pub const HEADER_BYTES: usize = 64;
/// Chunk table entry length in bytes.
pub const CHUNK_ENTRY_BYTES: usize = 16;
/// Alignment of every chunk offset and of the resident length.
pub const CHUNK_ALIGN: usize = 16;
/// Largest accepted chunk count.
pub const MAX_CHUNKS: usize = 64;
/// Largest accepted DAG level count.
pub const MAX_LEVELS: u32 = 64;
/// Smallest page capacity in bytes of the memory form.
pub const MIN_PAGE_CAPACITY: usize = 4096;
/// Largest page capacity in bytes of the memory form.
pub const MAX_PAGE_CAPACITY: usize = 1 << 20;
/// Default page capacity, 128 KiB of memory form.
pub const DEFAULT_PAGE_CAPACITY: usize = 128 * 1024;
/// Largest resident prefix and largest page disk form in bytes: each must fit
/// one storage-buffer binding of the smallest common limit (128 MiB).
pub const MAX_BUFFER_VIEW_BYTES: usize = 128 << 20;
/// Default limit on clusters per page. About 200 clusters of the measured
/// average size (`docs/PAGE_FORMAT.md`) fill a default page, so it rarely binds.
pub const DEFAULT_MAX_PAGE_CLUSTERS: usize = 256;
/// Chunk flag: a reader that does not know the tag must reject the file.
pub const CHUNK_REQUIRED: u32 = 1;
/// Page flag: the page is pinned (always resident).
pub const PAGE_PINNED: u32 = 1;

/// `MESH`: one 112-byte record of counts, bounds and the position grid.
pub const TAG_MESH: [u8; 4] = *b"MESH";
/// `GRPS`: one 48-byte record per group, coarse-first.
pub const TAG_GROUPS: [u8; 4] = *b"GRPS";
/// `NODE`: one 32-byte record per culling-hierarchy node.
pub const TAG_NODES: [u8; 4] = *b"NODE";
/// `PAGE`: one 48-byte record per page.
pub const TAG_PAGES: [u8; 4] = *b"PAGE";
/// `PDEP`: page dependency lists, one `u32` page index per entry.
pub const TAG_DEPENDENCIES: [u8; 4] = *b"PDEP";
/// `ATTR`: the vertex attribute layout (16 bytes plus 16 per channel).
pub const TAG_ATTRIBUTES: [u8; 4] = *b"ATTR";
/// `MATS`: required when material tables are used; slot count and three reserved words.
pub const TAG_MATERIALS: [u8; 4] = *b"MATS";
/// `CSPH`: one 16-byte culling sphere per cluster (the tight sphere of the
/// cluster's page descriptor), so culling works while pages are absent.
pub const TAG_CLUSTER_SPHERES: [u8; 4] = *b"CSPH";
/// `CREF`: one `i32` per cluster, the group it was simplified from (its page
/// descriptor's refined group, `-1` for source geometry), so the parent
/// relation, parent counts and page dependencies are checkable without pages.
pub const TAG_CLUSTER_REFINED: [u8; 4] = *b"CREF";
/// Reserved optional tag: per-node axis-aligned boxes.
pub const TAG_NODE_BOXES: [u8; 4] = *b"NAAB";
/// Optional validated 64-byte far-field (impostor) record.
pub const TAG_FAR_FIELD: [u8; 4] = *b"FARF";
/// Reserved optional tag: source vertex identifiers kept in pages.
pub const TAG_SOURCE_IDS: [u8; 4] = *b"SRCI";

/// `MESH` record length.
pub const MESH_BYTES: usize = 112;
/// `GRPS` record length.
pub const GROUP_BYTES: usize = 48;
/// `NODE` record length.
pub const NODE_BYTES: usize = 32;
/// `PAGE` record length.
pub const PAGE_BYTES: usize = 48;
/// `PDEP` entry length.
pub const DEPENDENCY_BYTES: usize = 4;
/// `ATTR` header length.
pub const ATTRIBUTE_HEADER_BYTES: usize = 16;
/// `ATTR` channel record length.
pub const ATTRIBUTE_CHANNEL_BYTES: usize = 16;
/// `CSPH` record length.
pub const CLUSTER_SPHERE_BYTES: usize = 16;
/// `CREF` record length.
pub const CLUSTER_REFINED_BYTES: usize = 4;
/// Byte range of the resident hash in the header; the hash covers the whole
/// resident prefix with these bytes read as zero.
pub const RESIDENT_HASH_FIELD: Range<usize> = 40..48;

const REQUIRED: [[u8; 4]; 8] = [
    TAG_MESH,
    TAG_GROUPS,
    TAG_NODES,
    TAG_PAGES,
    TAG_DEPENDENCIES,
    TAG_ATTRIBUTES,
    TAG_CLUSTER_SPHERES,
    TAG_CLUSTER_REFINED,
];
const UNSET: u8 = u8::MAX;

const P1: u64 = 0x9E37_79B1_85EB_CA87;
const P2: u64 = 0xC2B2_AE3D_27D4_EB4F;
const P3: u64 = 0x1656_67B1_9E37_79F9;
const P4: u64 = 0x85EB_CA77_C2B2_AE63;
const P5: u64 = 0x27D4_EB2F_1656_67C5;

fn xxh_round(acc: u64, lane: u64) -> u64 {
    acc.wrapping_add(lane.wrapping_mul(P2))
        .rotate_left(31)
        .wrapping_mul(P1)
}
fn xxh_merge(acc: u64, v: u64) -> u64 {
    (acc ^ xxh_round(0, v)).wrapping_mul(P1).wrapping_add(P4)
}

/// Streaming XXH64 (the 64-bit xxHash of Yann Collet), implemented in the crate.
/// Used for page, resident and build-key hashes; it detects corruption, not
/// tampering. Not in C++ meshoptimizer.
#[derive(Clone, Debug)]
pub struct Xxh64 {
    seed: u64,
    lanes: [u64; 4],
    buffer: [u8; 32],
    buffered: usize,
    total: u64,
}

impl Xxh64 {
    /// A hasher with `seed`.
    pub const fn new(seed: u64) -> Self {
        Self {
            seed,
            lanes: [
                seed.wrapping_add(P1).wrapping_add(P2),
                seed.wrapping_add(P2),
                seed,
                seed.wrapping_sub(P1),
            ],
            buffer: [0; 32],
            buffered: 0,
            total: 0,
        }
    }

    fn stripe(&mut self, stripe: &[u8; 32]) {
        for (lane, bytes) in self.lanes.iter_mut().zip(stripe.as_chunks::<8>().0) {
            *lane = xxh_round(*lane, u64::from_le_bytes(*bytes));
        }
    }

    /// Append `data`.
    pub fn update(&mut self, mut data: &[u8]) {
        self.total = self.total.wrapping_add(data.len() as u64);
        if self.buffered > 0 {
            let take = (32 - self.buffered).min(data.len());
            let (head, rest) = data.split_at(take);
            self.buffer[self.buffered..self.buffered + take].copy_from_slice(head);
            self.buffered += take;
            data = rest;
            if self.buffered < 32 {
                return;
            }
            let stripe = self.buffer;
            self.stripe(&stripe);
            self.buffered = 0;
        }
        let (stripes, rest) = data.as_chunks::<32>();
        for stripe in stripes {
            self.stripe(stripe);
        }
        self.buffer[..rest.len()].copy_from_slice(rest);
        self.buffered = rest.len();
    }

    /// The hash of everything appended so far.
    pub fn finish(&self) -> u64 {
        let [v1, v2, v3, v4] = self.lanes;
        let mut h = if self.total >= 32 {
            let h = v1
                .rotate_left(1)
                .wrapping_add(v2.rotate_left(7))
                .wrapping_add(v3.rotate_left(12))
                .wrapping_add(v4.rotate_left(18));
            xxh_merge(xxh_merge(xxh_merge(xxh_merge(h, v1), v2), v3), v4)
        } else {
            self.seed.wrapping_add(P5)
        };
        h = h.wrapping_add(self.total);
        let (eights, mut tail) = self.buffer[..self.buffered].as_chunks::<8>();
        for e in eights {
            h ^= xxh_round(0, u64::from_le_bytes(*e));
            h = h.rotate_left(27).wrapping_mul(P1).wrapping_add(P4);
        }
        if let Some((four, rest)) = tail.split_first_chunk::<4>() {
            h ^= u64::from(u32::from_le_bytes(*four)).wrapping_mul(P1);
            h = h.rotate_left(23).wrapping_mul(P2).wrapping_add(P3);
            tail = rest;
        }
        for &b in tail {
            h ^= u64::from(b).wrapping_mul(P5);
            h = h.rotate_left(11).wrapping_mul(P1);
        }
        h ^= h >> 33;
        h = h.wrapping_mul(P2);
        h ^= h >> 29;
        h = h.wrapping_mul(P3);
        h ^ (h >> 32)
    }
}

/// XXH64 of `data` with `seed`; see [`Xxh64`]. Not in C++ meshoptimizer.
pub fn xxh64(data: &[u8], seed: u64) -> u64 {
    let mut h = Xxh64::new(seed);
    h.update(data);
    h.finish()
}

/// Resident hash of `prefix` (the first [`resident_len`] bytes of a file):
/// XXH64 (seed 0) of all of it, header included, with the bytes of
/// [`RESIDENT_HASH_FIELD`] read as zero. `None` if `prefix` is shorter than
/// the header. Not in C++ meshoptimizer.
pub fn prefix_hash(prefix: &[u8]) -> Option<u64> {
    let head = prefix.get(..RESIDENT_HASH_FIELD.start)?;
    let tail = prefix.get(RESIDENT_HASH_FIELD.end..)?;
    if prefix.len() < HEADER_BYTES {
        return None;
    }
    let mut h = Xxh64::new(0);
    h.update(head);
    h.update(&[0; 8]);
    h.update(tail);
    Some(h.finish())
}

/// Attribute layout hash: the low 32 bits of XXH64 (seed 0) over the `ATTR`
/// channel records. Pages and `MESH` repeat it.
pub(crate) fn attribute_layout_hash(channels: &[u8]) -> u32 {
    xxh64(channels, 0) as u32
}

fn size(v: u32) -> Result<usize, Error> {
    usize::try_from(v).map_err(|_| Error::Limit)
}
fn add(a: usize, b: usize) -> Result<usize, Error> {
    a.checked_add(b).ok_or(Error::Limit)
}
fn mul(a: usize, b: usize) -> Result<usize, Error> {
    a.checked_mul(b).ok_or(Error::Limit)
}
fn le32(b: &[u8], at: usize) -> Result<u32, Error> {
    let w = b
        .get(at..add(at, 4)?)
        .and_then(|w| w.first_chunk::<4>())
        .ok_or(Error::Invalid)?;
    Ok(u32::from_le_bytes(*w))
}
fn le64(b: &[u8], at: usize) -> Result<u64, Error> {
    Ok(u64::from(le32(b, at)?) | u64::from(le32(b, add(at, 4)?)?) << 32)
}
fn fl(b: &[u8], at: usize) -> Result<f32, Error> {
    Ok(f32::from_bits(le32(b, at)?))
}
fn vec3(b: &[u8], at: usize) -> Result<[f32; 3], Error> {
    Ok([fl(b, at)?, fl(b, at + 4)?, fl(b, at + 8)?])
}
fn finite3(v: [f32; 3]) -> bool {
    v.iter().all(|x| x.is_finite())
}
fn filled<T: Clone>(n: usize, value: T) -> Result<Vec<T>, Error> {
    let mut v = Vec::new();
    v.try_reserve_exact(n).map_err(|_| Error::Allocation)?;
    v.resize(n, value);
    Ok(v)
}
fn sphere_ok(center: [f32; 3], radius: f32, error: f32) -> bool {
    finite3(center) && radius.is_finite() && radius >= 0.0 && error.is_finite() && error >= 0.0
}

/// Length of the resident prefix, read from the first [`HEADER_BYTES`] bytes
/// alone, so a runtime can fetch exactly the bytes [`Reader::open`] needs.
/// Not in C++ meshoptimizer.
///
/// # Errors
/// `Invalid` for a short or malformed header; `Unsupported` for another major
/// version; `Limit` for more than [`MAX_CHUNKS`] chunks or a prefix above
/// [`MAX_BUFFER_VIEW_BYTES`].
pub fn resident_len(header: &[u8]) -> Result<usize, Error> {
    let h = header.get(..HEADER_BYTES).ok_or(Error::Invalid)?;
    if h.get(..4) != Some(b"MDAG".as_slice()) {
        return Err(Error::Invalid);
    }
    if le32(h, 4)? != MAJOR {
        return Err(Error::Unsupported);
    }
    let chunks = size(le32(h, 12)?)?;
    if chunks > MAX_CHUNKS || size(le32(h, 24)?)? > MAX_BUFFER_VIEW_BYTES {
        return Err(Error::Limit);
    }
    let len = size(le32(h, 24)?)?;
    if !len.is_multiple_of(CHUNK_ALIGN) || len < HEADER_BYTES + chunks * CHUNK_ENTRY_BYTES {
        return Err(Error::Invalid);
    }
    Ok(len)
}

/// Page format parameters from the header, chosen by the writer, so a runtime
/// can size page slots and per-page tables before reading any page.
/// Not in C++ meshoptimizer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PageLimits {
    /// Page capacity in bytes of the memory form: a power of two from
    /// [`MIN_PAGE_CAPACITY`] to [`MAX_PAGE_CAPACITY`].
    pub page_capacity: usize,
    /// Most clusters in one page.
    pub max_clusters: usize,
    /// Most vertices in one cluster, at most 256.
    pub max_vertices: usize,
    /// Most triangles in one cluster, at most 256.
    pub max_triangles: usize,
}

impl PageLimits {
    /// Most clusters a page of `page_capacity` bytes can physically hold.
    pub const fn cluster_bound(page_capacity: usize) -> usize {
        (page_capacity / 4).saturating_sub(page::PAGE_HEADER_WORDS) / page::CLUSTER_WORDS
    }
    fn valid(&self) -> bool {
        self.page_capacity.is_power_of_two()
            && (MIN_PAGE_CAPACITY..=MAX_PAGE_CAPACITY).contains(&self.page_capacity)
            && (1..=Self::cluster_bound(self.page_capacity)).contains(&self.max_clusters)
            && (1..=page::MAX_CLUSTER_VERTICES).contains(&self.max_vertices)
            && (1..=page::MAX_CLUSTER_TRIANGLES).contains(&self.max_triangles)
    }
}

/// Whole-mesh record (`MESH`). Not in C++ meshoptimizer.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct MeshInfo {
    /// Number of DAG levels; group depths are below it.
    pub level_count: u32,
    /// Node count of the longest root-to-leaf path of the culling hierarchy.
    pub bvh_depth: u32,
    /// Largest child count of a hierarchy node.
    pub node_width: u32,
    /// Group count.
    pub group_count: u32,
    /// Cluster count.
    pub cluster_count: u32,
    /// Hierarchy node count.
    pub node_count: u32,
    /// Page count.
    pub page_count: u32,
    /// Number of pinned pages, a prefix of the page table.
    pub pinned_page_count: u32,
    /// Triangles over all clusters of all levels.
    pub dag_triangles: u64,
    /// Triangles of the source-geometry clusters.
    pub leaf_triangles: u64,
    /// Minimum corner of the box containing every decoded vertex of every level.
    pub aabb_min: [f32; 3],
    /// Maximum corner of that box.
    pub aabb_max: [f32; 3],
    /// Center of a sphere containing every decoded vertex.
    pub sphere_center: [f32; 3],
    /// Radius of that sphere.
    pub sphere_radius: f32,
    /// Position grid of every page.
    pub grid: QuantGrid,
    /// Largest distance between a source position and its decoded position,
    /// [`QuantGrid::max_displacement`]; already included in every finite group error.
    pub max_displacement: f32,
    /// Attribute layout hash, repeated in every page header.
    pub attribute_layout_hash: u32,
    /// Number of material slots; every cluster's slot is below it.
    pub material_count: u32,
}

/// Group record (`GRPS`). Not in C++ meshoptimizer.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct GroupRecord {
    /// LOD sphere center.
    pub center: [f32; 3],
    /// LOD sphere radius; the sphere contains every decoded vertex of the group
    /// and the LOD sphere of every group its clusters were simplified from.
    pub radius: f32,
    /// Group error, at least that of every refined group; parentless groups
    /// usually carry `f32::MAX`.
    pub error: f32,
    /// DAG level; non-increasing over the table.
    pub depth: u32,
    /// First cluster.
    pub first_cluster: u32,
    /// Cluster count, at least one.
    pub cluster_count: u32,
    /// First page holding one of its clusters.
    pub first_page: u32,
    /// Number of consecutive pages holding its clusters.
    pub page_count: u32,
    /// Number of distinct groups whose clusters were simplified from this one
    /// (checked against `CREF` by [`Reader::open`]); zero for parentless
    /// groups, which are pinned.
    pub parent_count: u32,
}

impl GroupRecord {
    /// Pages holding this group's clusters.
    pub fn pages(&self) -> Range<u32> {
        self.first_page..self.first_page.saturating_add(self.page_count)
    }
    /// This group's clusters.
    pub fn clusters(&self) -> Range<u32> {
        self.first_cluster..self.first_cluster.saturating_add(self.cluster_count)
    }
}

/// Culling-hierarchy node record (`NODE`). Not in C++ meshoptimizer.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct NodeRecord {
    /// Sphere center.
    pub center: [f32; 3],
    /// Sphere radius, containing every child's sphere (or the group's).
    pub radius: f32,
    /// Error, at least every child's (or the group's).
    pub error: f32,
    /// Group of a leaf, or -1 for an internal node.
    pub group: i32,
    /// First child; children follow their parent in the table.
    pub child_offset: u32,
    /// Child count; zero for leaves.
    pub child_count: u32,
}

/// Page record (`PAGE`). Not in C++ meshoptimizer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PageRecord {
    /// Byte offset of the disk form from the start of the file.
    pub disk_offset: u64,
    /// Byte length of the disk form.
    pub disk_length: u32,
    /// Words of the memory form, at most the page capacity.
    pub memory_words: u32,
    /// First cluster.
    pub first_cluster: u32,
    /// Cluster count, at least one.
    pub cluster_count: u32,
    /// First `PDEP` entry.
    pub first_dependency: u32,
    /// Number of `PDEP` entries.
    pub dependency_count: u32,
    /// XXH64 (seed 0) of the disk form.
    pub hash: u64,
    /// The page is pinned.
    pub pinned: bool,
}

impl PageRecord {
    /// Byte range of the disk form in the file.
    pub fn disk_range(&self) -> Range<u64> {
        self.disk_offset..self.disk_offset.saturating_add(u64::from(self.disk_length))
    }
}

/// Dependencies of one page, ascending. Not in C++ meshoptimizer.
#[derive(Clone, Debug)]
pub struct Dependencies<'a>(core::slice::Iter<'a, [u8; 4]>);

impl Iterator for Dependencies<'_> {
    type Item = u32;
    fn next(&mut self) -> Option<u32> {
        self.0.next().map(|b| u32::from_le_bytes(*b))
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}
impl ExactSizeIterator for Dependencies<'_> {}

fn parse_group(b: &[u8]) -> Result<GroupRecord, Error> {
    Ok(GroupRecord {
        center: vec3(b, 0)?,
        radius: fl(b, 12)?,
        error: fl(b, 16)?,
        depth: le32(b, 20)?,
        first_cluster: le32(b, 24)?,
        cluster_count: le32(b, 28)?,
        first_page: le32(b, 32)?,
        page_count: le32(b, 36)?,
        parent_count: le32(b, 40)?,
    })
}
fn parse_node(b: &[u8]) -> Result<NodeRecord, Error> {
    Ok(NodeRecord {
        center: vec3(b, 0)?,
        radius: fl(b, 12)?,
        error: fl(b, 16)?,
        group: le32(b, 20)? as i32,
        child_offset: le32(b, 24)?,
        child_count: le32(b, 28)?,
    })
}
fn parse_page(b: &[u8]) -> Result<PageRecord, Error> {
    Ok(PageRecord {
        disk_offset: le64(b, 0)?,
        disk_length: le32(b, 8)?,
        memory_words: le32(b, 12)?,
        first_cluster: le32(b, 16)?,
        cluster_count: le32(b, 20)?,
        first_dependency: le32(b, 24)?,
        dependency_count: le32(b, 28)?,
        hash: le64(b, 32)?,
        pinned: le32(b, 40)? & PAGE_PINNED != 0,
    })
}

/// Distinct parents of every group in compressed rows (`offsets` has
/// `group_count + 1` entries), from `(owner, refined)` per cluster in cluster
/// order. Owners must be non-decreasing; parents come out ascending.
pub(crate) fn parent_lists(
    group_count: usize,
    links: &[(u32, i32)],
) -> Result<(Vec<u32>, Vec<u32>), Error> {
    let mut offsets = filled(add(group_count, 1)?, 0u32)?;
    let mut last = filled(group_count, u32::MAX)?;
    for &(owner, refined) in links {
        if refined < 0 {
            continue;
        }
        let q = refined as usize;
        let slot = last.get_mut(q).ok_or(Error::Invalid)?;
        if *slot != owner {
            *slot = owner;
            offsets[q + 1] += 1;
        }
    }
    for q in 0..group_count {
        offsets[q + 1] += offsets[q];
    }
    let mut parents = filled(size(offsets[group_count])?, 0u32)?;
    let mut fill = filled(group_count, 0u32)?;
    fill.copy_from_slice(&offsets[..group_count]);
    last.fill(u32::MAX);
    for &(owner, refined) in links {
        if refined < 0 {
            continue;
        }
        let q = refined as usize;
        if last[q] != owner {
            last[q] = owner;
            parents[fill[q] as usize] = owner;
            fill[q] += 1;
        }
    }
    Ok((offsets, parents))
}

/// Page dependency lists computed from the parent relation, one page at a time
/// in page order. The dependencies of page `p` are every page of every parent
/// of every group with clusters in `p`, excluding `p`, sorted and unique.
///
/// Work is linear up to a sort: group page spans are ordered (groups partition
/// the clusters in order, pages too), so a page touched only by the group that
/// also alone touched the previous page has the previous page's list; every
/// other page collects the distinct parents of its groups once (a marker per
/// group), sorts them and emits each one's span, which comes out ascending with
/// duplicates only where consecutive spans meet. A group is collected for at
/// most three pages (its first, second and last), and emission stops past the
/// caller's limit, so hostile tables cannot inflate the work.
pub(crate) struct DependencyLists<'t> {
    offsets: &'t [u32],
    parents: &'t [u32],
    mark: Vec<u32>,
    distinct: Vec<u32>,
    out: Vec<u32>,
    previous: Option<(u32, Range<u32>)>,
}

impl<'t> DependencyLists<'t> {
    /// Lists over the parent table of [`parent_lists`].
    pub(crate) fn new(offsets: &'t [u32], parents: &'t [u32]) -> Result<Self, Error> {
        let groups = offsets.len().saturating_sub(1);
        Ok(Self {
            offsets,
            parents,
            mark: filled(groups, u32::MAX)?,
            distinct: Vec::new(),
            out: Vec::new(),
            previous: None,
        })
    }

    /// Dependencies of `page`, whose clusters belong to `groups`; pages must be
    /// visited in increasing order. `Invalid` if the list would exceed `limit`
    /// entries or the spans are not ordered.
    pub(crate) fn next(
        &mut self,
        page: u32,
        groups: Range<u32>,
        pages_of: impl Fn(u32) -> Result<Range<u32>, Error>,
        limit: usize,
    ) -> Result<&[u32], Error> {
        let single = groups.len() == 1;
        let continues = single
            && self
                .previous
                .as_ref()
                .is_some_and(|(p, g)| p.checked_add(1) == Some(page) && *g == groups);
        self.previous = Some((page, groups.clone()));
        if continues {
            // Only the group that alone touched the previous page touches this
            // one, so no parent of it touches either page: same list.
            return if self.out.len() > limit {
                Err(Error::Invalid)
            } else {
                Ok(&self.out)
            };
        }
        self.out.clear();
        self.distinct.clear();
        for q in groups {
            let q = q as usize;
            let row = self.offsets.get(q..q + 2).ok_or(Error::Invalid)?;
            let list = self
                .parents
                .get(row[0] as usize..row[1] as usize)
                .ok_or(Error::Invalid)?;
            for &parent in list {
                let m = self.mark.get_mut(parent as usize).ok_or(Error::Invalid)?;
                if *m != page {
                    *m = page;
                    self.distinct
                        .try_reserve(1)
                        .map_err(|_| Error::Allocation)?;
                    self.distinct.push(parent);
                }
            }
        }
        self.distinct.sort_unstable();
        for &parent in &self.distinct {
            for d in pages_of(parent)? {
                match self.out.last() {
                    _ if d == page => continue,
                    Some(&last) if d == last => continue,
                    Some(&last) if d < last => return Err(Error::Invalid),
                    _ => {}
                }
                if self.out.len() >= limit {
                    return Err(Error::Invalid);
                }
                self.out.try_reserve(1).map_err(|_| Error::Allocation)?;
                self.out.push(d);
            }
        }
        Ok(&self.out)
    }
}

#[derive(Clone, Copy, Debug)]
struct Chunk {
    tag: [u8; 4],
    flags: u32,
    offset: usize,
    len: usize,
}

fn chunk_entry(bytes: &[u8], i: usize) -> Result<Chunk, Error> {
    let e = add(HEADER_BYTES, mul(i, CHUNK_ENTRY_BYTES)?)?;
    let tag = *bytes
        .get(e..add(e, 4)?)
        .and_then(|t| t.first_chunk::<4>())
        .ok_or(Error::Invalid)?;
    Ok(Chunk {
        tag,
        flags: le32(bytes, e + 4)?,
        offset: size(le32(bytes, e + 8)?)?,
        len: size(le32(bytes, e + 12)?)?,
    })
}

/// Validated resident prefix of an MDAG 2 file, borrowing its bytes.
/// Not in C++ meshoptimizer.
#[derive(Clone, Copy, Debug)]
pub struct Reader<'a> {
    bytes: &'a [u8],
    resident_len: usize,
    minor: u32,
    limits: PageLimits,
    build_key: u64,
    resident_hash: u64,
    mesh: MeshInfo,
    chunk_count: usize,
    groups_at: usize,
    nodes_at: usize,
    pages_at: usize,
    deps_at: usize,
    dep_count: usize,
    spheres_at: usize,
    refined_at: usize,
    attributes_at: usize,
    attribute_count: usize,
    materials_declared: bool,
    root: LodBounds,
}

/// Cluster ranges of the parentless groups of an MDAG 2 file, see
/// [`Reader::root_clusters`]. Not in C++ meshoptimizer.
#[derive(Clone, Debug)]
pub struct RootClusters<'a> {
    reader: Reader<'a>,
    next: usize,
}

impl Iterator for RootClusters<'_> {
    type Item = Range<u32>;
    fn next(&mut self) -> Option<Range<u32>> {
        let count = self.reader.mesh.group_count as usize;
        let parentless = |g: usize| {
            self.reader
                .group(g)
                .ok()
                .filter(|r| r.parent_count == 0)
                .map(|r| r.clusters())
        };
        let (first, mut range) = (self.next..count).find_map(|g| parentless(g).map(|r| (g, r)))?;
        let mut g = first + 1;
        while let Some(r) = parentless(g) {
            range.end = r.end;
            g += 1;
        }
        self.next = g;
        Some(range)
    }
}

impl<'a> Reader<'a> {
    /// Open from the resident prefix: `bytes` must hold at least
    /// [`resident_len`] bytes; pages are not read. Validates the header, chunk
    /// table and every resident table (rules 1-5 of `docs/DAG_FORMAT.md`),
    /// including exact parent counts and dependency lists, so every page set
    /// that holds the pinned pages and is closed under dependencies is a valid
    /// residency set before any page is read. Allocates scratch proportional
    /// to the node, group, cluster and page counts, which are bounded by the
    /// prefix length.
    ///
    /// # Errors
    /// `Invalid` for a truncated or inconsistent prefix (including a resident
    /// hash mismatch); `Unsupported` for another major version, an unknown
    /// required chunk, unknown chunk flags or attribute encodings;
    /// `Limit` for oversized counts; `Allocation` if scratch allocation fails.
    pub fn open(bytes: &'a [u8]) -> Result<Self, Error> {
        let resident_len = resident_len(bytes)?;
        let prefix = bytes.get(..resident_len).ok_or(Error::Invalid)?;
        let limits = PageLimits {
            page_capacity: size(le32(prefix, 20)?)?,
            max_clusters: size(le32(prefix, 28)?)?,
            max_vertices: size(le32(prefix, 48)?)?,
            max_triangles: size(le32(prefix, 52)?)?,
        };
        if !limits.valid() || prefix[56..HEADER_BYTES].iter().any(|&b| b != 0) {
            return Err(Error::Invalid);
        }
        let resident_hash = le64(prefix, RESIDENT_HASH_FIELD.start)?;
        if prefix_hash(prefix) != Some(resident_hash) {
            return Err(Error::Invalid);
        }
        let chunk_count = size(le32(prefix, 12)?)?;
        let mut known = [None::<(usize, usize)>; REQUIRED.len()];
        let mut materials_at = None;
        let mut cursor = HEADER_BYTES + chunk_count * CHUNK_ENTRY_BYTES;
        for i in 0..chunk_count {
            let Chunk {
                tag,
                flags,
                offset,
                len,
            } = chunk_entry(prefix, i)?;
            let end = add(offset, len)?;
            let duplicate = (0..i).any(|j| chunk_entry(prefix, j).is_ok_and(|c| c.tag == tag));
            if !tag.iter().all(u8::is_ascii_graphic)
                || !offset.is_multiple_of(CHUNK_ALIGN)
                || offset < cursor
                || end > resident_len
                || duplicate
            {
                return Err(Error::Invalid);
            }
            if flags & !CHUNK_REQUIRED != 0 {
                return Err(Error::Unsupported);
            }
            if prefix[cursor..offset].iter().any(|&b| b != 0) {
                return Err(Error::Invalid);
            }
            cursor = end;
            match REQUIRED.iter().position(|&t| t == tag) {
                Some(k) if flags & CHUNK_REQUIRED != 0 => known[k] = Some((offset, len)),
                Some(_) => return Err(Error::Invalid),
                None if tag == TAG_MATERIALS => {
                    if flags != CHUNK_REQUIRED {
                        return Err(Error::Invalid);
                    }
                    materials_at = Some((offset, len));
                }
                None if tag == TAG_FAR_FIELD => {
                    if flags != 0 {
                        return Err(Error::Invalid);
                    }
                    FarField::decode(&prefix[offset..end])?;
                }
                None if flags & CHUNK_REQUIRED != 0 => return Err(Error::Unsupported),
                None => {}
            }
        }
        if prefix[cursor..].iter().any(|&b| b != 0) {
            return Err(Error::Invalid);
        }
        let mut at = [(0usize, 0usize); REQUIRED.len()];
        for (slot, k) in at.iter_mut().zip(known) {
            *slot = k.ok_or(Error::Invalid)?;
        }
        let [mesh_at, groups_at, nodes_at, pages_at, deps_at, attr_at, spheres_at, refined_at] = at;
        let mesh = parse_mesh(prefix, mesh_at, le32(prefix, 16)?)?;
        if let Some((offset, len)) = materials_at {
            if len != 16
                || le32(prefix, offset)? != mesh.material_count
                || (1..4).any(|k| le32(prefix, offset + k * 4) != Ok(0))
            {
                return Err(Error::Invalid);
            }
        }
        let lengths = [
            (groups_at.1, GROUP_BYTES, mesh.group_count),
            (nodes_at.1, NODE_BYTES, mesh.node_count),
            (pages_at.1, PAGE_BYTES, mesh.page_count),
            (spheres_at.1, CLUSTER_SPHERE_BYTES, mesh.cluster_count),
            (refined_at.1, CLUSTER_REFINED_BYTES, mesh.cluster_count),
        ];
        for (len, record, count) in lengths {
            if len != mul(record, size(count)?)? {
                return Err(Error::Invalid);
            }
        }
        if !deps_at.1.is_multiple_of(DEPENDENCY_BYTES) {
            return Err(Error::Invalid);
        }
        let attr = &prefix[attr_at.0..attr_at.0 + attr_at.1];
        let channels = size(le32(attr, 0)?)?;
        if channels > super::super::attributes::MAX_CHANNELS {
            return Err(Error::Limit);
        }
        if attr.len() != ATTRIBUTE_HEADER_BYTES + channels * ATTRIBUTE_CHANNEL_BYTES
            || le32(attr, 8)? != 0
            || le32(attr, 12)? != 0
            || le32(attr, 4)? != attribute_layout_hash(&attr[ATTRIBUTE_HEADER_BYTES..])
            || le32(attr, 4)? != mesh.attribute_layout_hash
        {
            return Err(Error::Invalid);
        }
        for k in 0..channels {
            let at = ATTRIBUTE_HEADER_BYTES + k * ATTRIBUTE_CHANNEL_BYTES;
            let ch = super::super::attributes::Channel::parse([
                le32(attr, at)?,
                le32(attr, at + 4)?,
                le32(attr, at + 8)?,
                le32(attr, at + 12)?,
            ])?;
            for j in 0..k {
                if le32(attr, ATTRIBUTE_HEADER_BYTES + j * ATTRIBUTE_CHANNEL_BYTES)? == ch.tag {
                    return Err(Error::Invalid);
                }
            }
        }
        let reader = Self {
            bytes,
            resident_len,
            minor: le32(prefix, 8)?,
            limits,
            build_key: le64(prefix, 32)?,
            resident_hash,
            mesh,
            chunk_count,
            groups_at: groups_at.0,
            nodes_at: nodes_at.0,
            pages_at: pages_at.0,
            deps_at: deps_at.0,
            dep_count: deps_at.1 / DEPENDENCY_BYTES,
            spheres_at: spheres_at.0,
            refined_at: refined_at.0,
            attributes_at: attr_at.0 + ATTRIBUTE_HEADER_BYTES,
            attribute_count: channels,
            materials_declared: materials_at.is_some(),
            root: LodBounds::default(),
        };
        for c in 0..mesh.cluster_count as usize {
            let (center, radius) = reader.cluster_sphere(c)?;
            if !sphere_ok(center, radius, 0.0) {
                return Err(Error::Invalid);
            }
        }
        reader.validate_pages()?;
        reader.validate_groups()?;
        reader.validate_nodes()?;
        reader.validate_links()?;
        let mut reader = reader;
        reader.root = reader.compute_root()?;
        Ok(reader)
    }

    /// Producers of the clusters of parentless groups, once per cluster.
    fn root_producers(&self) -> impl Iterator<Item = GroupRecord> + Clone + '_ {
        RootClusters {
            reader: *self,
            next: 0,
        }
        .flatten()
        .filter_map(|c| usize::try_from(self.cluster_refined(c as usize).ok()?).ok())
        .filter_map(|q| self.group(q).ok())
    }

    /// `E_root` and `S` (see [`Self::root_error`]); runs after validation, so
    /// every record read here exists and is finite.
    fn compute_root(&self) -> Result<LodBounds, Error> {
        let producers = self.root_producers();
        let error = producers.clone().map(|q| q.error).fold(0.0f32, f32::max);
        let none = producers.clone().next().is_none();
        let (center, radius) = match enclosing_sphere(producers.map(|q| (q.center, q.radius))) {
            Some(s) => s,
            None if none => ([0.0; 3], 0.0),
            None => return Err(Error::Invalid),
        };
        Ok(LodBounds {
            center,
            radius,
            error,
        })
    }

    /// `E_root`: the largest error among the groups that produced a cluster of
    /// a parentless group (zero when none did), computed once by
    /// [`Self::open`] from `GRPS` and `CREF`. With [`Self::root_sphere`] it is
    /// the instance fast-path bound: `clusterlod::cut::is_root_cut` on the two
    /// tells a runtime, without testing any group, that the cut of a view is
    /// the root cut ([`Self::root_clusters`]). Parentless groups' own records
    /// are not part of the bound.
    pub fn root_error(&self) -> f32 {
        self.root.error
    }

    /// `S`: `[x, y, z, radius]` of a sphere containing the LOD sphere of every
    /// group counted by [`Self::root_error`], in the mesh frame; zero when there
    /// is none. Computed once by [`Self::open`]. The `MESH` sphere bounds
    /// decoded vertices, not LOD spheres, and is not a substitute.
    pub fn root_sphere(&self) -> [f32; 4] {
        let c = self.root.center;
        [c[0], c[1], c[2], self.root.radius]
    }

    /// The root cut: clusters of the parentless groups, as ascending,
    /// non-overlapping ranges (adjacent groups merged). They lie in pinned
    /// pages. The ranges are not one prefix in general: a group whose
    /// simplification got stuck is parentless at a finer level, so its clusters
    /// follow coarser groups that do have parents.
    pub fn root_clusters(&self) -> RootClusters<'a> {
        RootClusters {
            reader: *self,
            next: 0,
        }
    }

    /// Streaming priority bounds, one per page: the error is the largest error
    /// of the groups with a cluster on the page and the sphere contains their
    /// LOD spheres. A cluster on page `p` is drawn only if its group refines
    /// or is parentless, so when this bound projects at or below the
    /// threshold (`clusterlod::cut::is_root_cut` with it), no group on the
    /// page refines and the page is not needed by the cut unless it holds a
    /// parentless group, which is pinned. Pages holding a parentless group
    /// usually carry `f32::MAX`. Writes `out[..page_count]` and reads only the
    /// resident prefix.
    ///
    /// # Errors
    /// `Limit` if `out` is shorter than the page count.
    pub fn page_priority_bounds(&self, out: &mut [LodBounds]) -> Result<(), Error> {
        let (pages, groups) = (self.mesh.page_count, self.mesh.group_count as usize);
        let out = out.get_mut(..pages as usize).ok_or(Error::Limit)?;
        // Group page spans are ordered like the clusters they hold, so the
        // groups touching page `p` are one run starting at `lo`.
        let mut lo = 0usize;
        for (p, bound) in (0..pages).zip(out.iter_mut()) {
            while lo < groups && self.group(lo)?.pages().end <= p {
                lo += 1;
            }
            let touching = (lo..groups)
                .map_while(|g| self.group(g).ok())
                .take_while(|r| r.first_page <= p);
            let error = touching.clone().map(|r| r.error).fold(0.0f32, f32::max);
            let (center, radius) =
                enclosing_sphere(touching.map(|r| (r.center, r.radius))).ok_or(Error::Invalid)?;
            *bound = LodBounds {
                center,
                radius,
                error,
            };
        }
        Ok(())
    }

    /// Rule 6: the refinement relation (`CREF`) against groups, parent counts
    /// and page dependencies. Runs after rules 2 and 4, so group and page
    /// ranges partition the clusters in order.
    fn validate_links(&self) -> Result<(), Error> {
        let group_count = self.mesh.group_count as usize;
        let mut links = Vec::new();
        links
            .try_reserve_exact(self.mesh.cluster_count as usize)
            .map_err(|_| Error::Allocation)?;
        for g in 0..group_count {
            for c in self.group(g)?.clusters() {
                let q = self.cluster_refined(c as usize)?;
                if q < -1 || (q >= 0 && (q as usize <= g || q as usize >= group_count)) {
                    return Err(Error::Invalid);
                }
                links.push((g as u32, q));
            }
        }
        let (offsets, parents) = parent_lists(group_count, &links)?;
        for q in 0..group_count {
            let child = self.group(q)?;
            let row = offsets.get(q..q + 2).ok_or(Error::Invalid)?;
            if child.parent_count != row[1] - row[0] {
                return Err(Error::Invalid);
            }
            for &p in parents
                .get(row[0] as usize..row[1] as usize)
                .ok_or(Error::Invalid)?
            {
                // Monotonicity of the link: the cut rules compare these.
                let owner = self.group(p as usize)?;
                if child.depth >= owner.depth
                    || child.error > owner.error
                    || containing_radius(owner.center, child.center, child.radius)
                        > f64::from(owner.radius)
                {
                    return Err(Error::Invalid);
                }
            }
        }
        let mut lists = DependencyLists::new(&offsets, &parents)?;
        for p in 0..self.mesh.page_count as usize {
            let r = self.page(p)?;
            let first = links.get(r.first_cluster as usize).ok_or(Error::Invalid)?.0;
            let last = r.first_cluster as usize + r.cluster_count as usize - 1;
            let last = links.get(last).ok_or(Error::Invalid)?.0;
            let declared = self.dependencies(p)?;
            let expected = lists.next(
                p as u32,
                first..last + 1,
                |g| Ok(self.group(g as usize)?.pages()),
                declared.len(),
            )?;
            if !declared.eq(expected.iter().copied()) {
                return Err(Error::Invalid);
            }
        }
        Ok(())
    }

    /// Rule 4: pages.
    fn validate_pages(&self) -> Result<(), Error> {
        let mut disk_end = self.resident_len as u64;
        let (mut clusters, mut deps, mut pinned) = (0usize, 0usize, 0u32);
        let mut unpinned_seen = false;
        for p in 0..self.mesh.page_count as usize {
            let b = self.record(self.pages_at, PAGE_BYTES, p)?;
            let r = parse_page(b)?;
            let cc = size(r.cluster_count)?;
            let min_words = add(page::PAGE_HEADER_WORDS, mul(cc, page::CLUSTER_WORDS)?)?;
            let disk_end_p = r
                .disk_offset
                .checked_add(u64::from(r.disk_length))
                .ok_or(Error::Limit)?;
            if le32(b, 44)? != 0
                || le32(b, 40)? & !PAGE_PINNED != 0
                || r.disk_offset < disk_end
                || cc == 0
                || cc > self.limits.max_clusters
                || size(r.first_cluster)? != clusters
                || size(r.memory_words)? < min_words
                || mul(size(r.memory_words)?, 4)? > self.limits.page_capacity
                || u64::from(r.disk_length) < mul(cc, 64)? as u64
                || size(r.disk_length)? > MAX_BUFFER_VIEW_BYTES
                || size(r.first_dependency)? != deps
                || r.dependency_count as usize > p
            {
                return Err(Error::Invalid);
            }
            disk_end = disk_end_p;
            clusters = add(clusters, cc)?;
            deps = add(deps, size(r.dependency_count)?)?;
            if deps > self.dep_count {
                return Err(Error::Invalid);
            }
            let mut previous = None;
            for d in self.dependencies(p)? {
                // Sorted, unique and below the page: acyclic by one comparison,
                // and a pinned page (a prefix) depends only on pinned pages.
                if d as usize >= p || previous.is_some_and(|v| d <= v) {
                    return Err(Error::Invalid);
                }
                previous = Some(d);
            }
            if r.pinned {
                if unpinned_seen {
                    return Err(Error::Invalid);
                }
                pinned += 1;
            } else {
                unpinned_seen = true;
            }
        }
        if clusters != self.mesh.cluster_count as usize
            || deps != self.dep_count
            || pinned != self.mesh.pinned_page_count
        {
            return Err(Error::Invalid);
        }
        Ok(())
    }

    /// Rule 2: groups.
    fn validate_groups(&self) -> Result<(), Error> {
        let mut clusters = 0usize;
        let mut previous_depth = u32::MAX;
        let pages = self.mesh.page_count;
        for g in 0..self.mesh.group_count as usize {
            let b = self.record(self.groups_at, GROUP_BYTES, g)?;
            let r = parse_group(b)?;
            let span_end = r
                .first_page
                .checked_add(r.page_count)
                .ok_or(Error::Invalid)?;
            if le32(b, 44)? != 0
                || !sphere_ok(r.center, r.radius, r.error)
                || r.error < self.mesh.max_displacement
                || r.depth >= self.mesh.level_count
                || r.depth > previous_depth
                || r.cluster_count == 0
                || size(r.first_cluster)? != clusters
                || r.page_count == 0
                || span_end > pages
                || r.parent_count as usize > g
                || (r.parent_count == 0 && span_end > self.mesh.pinned_page_count)
            {
                return Err(Error::Invalid);
            }
            previous_depth = r.depth;
            clusters = add(clusters, size(r.cluster_count)?)?;
            // The span is exactly the pages that hold one of the group's clusters.
            let first = self.page(r.first_page as usize)?;
            let last = self.page(span_end as usize - 1)?;
            let last_cluster = r
                .first_cluster
                .checked_add(r.cluster_count - 1)
                .ok_or(Error::Invalid)?;
            let holds = |p: &PageRecord, c: u32| {
                p.first_cluster <= c && c - p.first_cluster < p.cluster_count
            };
            if !holds(&first, r.first_cluster) || !holds(&last, last_cluster) {
                return Err(Error::Invalid);
            }
        }
        if clusters != self.mesh.cluster_count as usize {
            return Err(Error::Invalid);
        }
        Ok(())
    }

    /// Rule 3: the culling hierarchy is a forest with one root per level,
    /// children after their parent, every group in exactly one leaf, and bounds
    /// that contain their children's.
    fn validate_nodes(&self) -> Result<(), Error> {
        let n = self.mesh.node_count as usize;
        let levels = self.mesh.level_count as usize;
        let mut level = filled(n, UNSET)?;
        let mut depth = filled(n, 0u32)?;
        let mut seen = filled(self.mesh.group_count as usize, false)?;
        if n < levels {
            return Err(Error::Invalid);
        }
        for (i, (l, d)) in level.iter_mut().zip(&mut depth).take(levels).enumerate() {
            *l = i as u8;
            *d = 1;
        }
        let mut longest = 0u32;
        let mut leaves = 0usize;
        for i in 0..n {
            let r = self.node(i)?;
            if level[i] == UNSET || !sphere_ok(r.center, r.radius, r.error) {
                return Err(Error::Invalid);
            }
            let contains = |center: [f32; 3], radius: f32, error: f32| {
                containing_radius(r.center, center, radius) <= f64::from(r.radius)
                    && error <= r.error
            };
            if r.group >= 0 {
                let g = r.group as usize;
                let group = self.group(g)?;
                if r.child_offset != 0
                    || r.child_count != 0
                    || seen[g]
                    || group.depth != u32::from(level[i])
                    || !contains(group.center, group.radius, group.error)
                {
                    return Err(Error::Invalid);
                }
                seen[g] = true;
                leaves += 1;
                longest = longest.max(depth[i]);
                continue;
            }
            let first = size(r.child_offset)?;
            let end = add(first, size(r.child_count)?)?;
            if r.group != -1
                || r.child_count == 0
                || r.child_count > self.mesh.node_width
                || first <= i
                || end > n
            {
                return Err(Error::Invalid);
            }
            for k in first..end {
                let child = self.node(k)?;
                if level[k] != UNSET || !contains(child.center, child.radius, child.error) {
                    return Err(Error::Invalid);
                }
                level[k] = level[i];
                depth[k] = depth[i] + 1;
            }
        }
        if leaves != seen.len() || longest != self.mesh.bvh_depth {
            return Err(Error::Invalid);
        }
        Ok(())
    }

    fn record(&self, at: usize, record: usize, index: usize) -> Result<&'a [u8], Error> {
        let start = add(at, mul(record, index)?)?;
        self.bytes
            .get(start..add(start, record)?)
            .ok_or(Error::Invalid)
    }

    /// Length of the resident prefix in bytes.
    pub fn resident_len(&self) -> usize {
        self.resident_len
    }
    /// Minor version of the writer (informational).
    pub fn minor(&self) -> u32 {
        self.minor
    }
    /// Page capacity in bytes of the memory form.
    pub fn page_capacity(&self) -> usize {
        self.limits.page_capacity
    }
    /// Page format parameters from the header.
    pub fn page_limits(&self) -> PageLimits {
        self.limits
    }

    /// Culling sphere (center, radius) of cluster `c`, readable while its page
    /// is absent; it equals the tight sphere of the cluster's page descriptor
    /// and contains every decoded vertex of the cluster.
    ///
    /// # Errors
    /// `Invalid` if `c` is out of range.
    pub fn cluster_sphere(&self, c: usize) -> Result<([f32; 3], f32), Error> {
        if c >= self.mesh.cluster_count as usize {
            return Err(Error::Invalid);
        }
        let b = self.record(self.spheres_at, CLUSTER_SPHERE_BYTES, c)?;
        Ok((vec3(b, 0)?, fl(b, 12)?))
    }
    /// Build key the writer recorded (zero when none was given).
    pub fn build_key(&self) -> u64 {
        self.build_key
    }
    /// Resident hash: XXH64 (seed 0) of the whole resident prefix, header
    /// included, with the hash field read as zero (see [`prefix_hash`]).
    pub fn resident_hash(&self) -> u64 {
        self.resident_hash
    }
    /// The `MESH` record.
    pub fn mesh(&self) -> MeshInfo {
        self.mesh
    }

    /// Group `g` (coarse-first order).
    ///
    /// # Errors
    /// `Invalid` if `g` is out of range.
    pub fn group(&self, g: usize) -> Result<GroupRecord, Error> {
        if g >= self.mesh.group_count as usize {
            return Err(Error::Invalid);
        }
        parse_group(self.record(self.groups_at, GROUP_BYTES, g)?)
    }

    /// Hierarchy node `n`; nodes `0..level_count` are the per-level roots.
    ///
    /// # Errors
    /// `Invalid` if `n` is out of range.
    pub fn node(&self, n: usize) -> Result<NodeRecord, Error> {
        if n >= self.mesh.node_count as usize {
            return Err(Error::Invalid);
        }
        parse_node(self.record(self.nodes_at, NODE_BYTES, n)?)
    }

    /// Page `p`.
    ///
    /// # Errors
    /// `Invalid` if `p` is out of range.
    pub fn page(&self, p: usize) -> Result<PageRecord, Error> {
        if p >= self.mesh.page_count as usize {
            return Err(Error::Invalid);
        }
        parse_page(self.record(self.pages_at, PAGE_BYTES, p)?)
    }

    /// Pages that page `p` depends on, ascending; load them before `p` and
    /// evict `p` before them.
    ///
    /// # Errors
    /// `Invalid` if `p` is out of range.
    pub fn dependencies(&self, p: usize) -> Result<Dependencies<'a>, Error> {
        let r = self.page(p)?;
        let start = add(
            self.deps_at,
            mul(size(r.first_dependency)?, DEPENDENCY_BYTES)?,
        )?;
        let end = add(start, mul(size(r.dependency_count)?, DEPENDENCY_BYTES)?)?;
        let b = self.bytes.get(start..end).ok_or(Error::Invalid)?;
        Ok(Dependencies(b.as_chunks::<4>().0.iter()))
    }

    /// Refined group of cluster `c` (`CREF`): the group it was simplified
    /// from, or -1 for source geometry. Readable while its page is absent.
    ///
    /// # Errors
    /// `Invalid` if `c` is out of range.
    pub fn cluster_refined(&self, c: usize) -> Result<i32, Error> {
        if c >= self.mesh.cluster_count as usize {
            return Err(Error::Invalid);
        }
        Ok(le32(self.record(self.refined_at, CLUSTER_REFINED_BYTES, c)?, 0)? as i32)
    }

    /// Validated optional impostor handoff metadata.
    pub fn far_field(&self) -> Option<FarField> {
        self.chunk(TAG_FAR_FIELD)
            .and_then(|b| FarField::decode(b).ok())
    }

    /// Bytes of the first chunk tagged `tag`, including optional chunks this
    /// version skips (such as the reserved [`TAG_NODE_BOXES`], [`TAG_FAR_FIELD`]
    /// and [`TAG_SOURCE_IDS`]).
    pub fn chunk(&self, tag: [u8; 4]) -> Option<&'a [u8]> {
        let c = (0..self.chunk_count)
            .filter_map(|i| chunk_entry(self.bytes, i).ok())
            .find(|c| c.tag == tag)?;
        self.bytes.get(c.offset..c.offset.checked_add(c.len)?)
    }

    /// Validate the disk form of page `p` (rules 7-10) and write its memory form
    /// into `out`, which needs [`PageRecord::memory_words`] words. Returns a view
    /// of the written words. Uses no heap allocation; codec work is charged to
    /// `workspace`. Work is linear in the page's disk and memory size: each
    /// cluster is compared with constant-size resident records (`CSPH`, `CREF`,
    /// its group) and each decoded vertex with three spheres and a box.
    ///
    /// # Errors
    /// `Invalid` for a length, hash or content mismatch; `Limit` if `out` is too
    /// short; `Unsupported` or `Codec` for codec failures.
    pub fn transcode_page<'o>(
        &self,
        p: usize,
        disk: &[u8],
        out: &'o mut [u32],
        workspace: &mut Workspace,
    ) -> Result<PageView<'o>, Error> {
        let r = self.page(p)?;
        if disk.len() as u64 != u64::from(r.disk_length) || xxh64(disk, 0) != r.hash {
            return Err(Error::Invalid);
        }
        if out.len() < r.memory_words as usize {
            return Err(Error::Limit);
        }
        let grid = self.mesh.grid;
        let m = page::transcode_page(disk, grid, out, workspace)?;
        let out: &'o [u32] = out;
        if m != r.memory_words as usize {
            return Err(Error::Invalid);
        }
        let view = PageView::new(&out[..m], grid)?;
        if view.cluster_count() != r.cluster_count as usize
            || view.attribute_layout_hash() != self.mesh.attribute_layout_hash
        {
            return Err(Error::Invalid);
        }
        self.validate_page_clusters(p, &r, &view)?;
        Ok(view)
    }

    /// Number of declared attribute channels.
    pub fn attribute_count(&self) -> usize {
        self.attribute_count
    }
    /// Read a validated ATTR channel declaration.
    /// # Errors
    /// Invalid channel index.
    pub fn attribute_channel(&self, k: usize) -> Result<super::super::attributes::Channel, Error> {
        if k >= self.attribute_count {
            return Err(Error::Invalid);
        }
        let at = self.attributes_at + k * ATTRIBUTE_CHANNEL_BYTES;
        super::super::attributes::Channel::parse([
            le32(self.bytes, at)?,
            le32(self.bytes, at + 4)?,
            le32(self.bytes, at + 8)?,
            le32(self.bytes, at + 12)?,
        ])
    }
    /// Rules 8 and 9 for the clusters of one transcoded page.
    fn validate_page_clusters(
        &self,
        p: usize,
        r: &PageRecord,
        view: &PageView<'_>,
    ) -> Result<(), Error> {
        let page_id = p as u32;
        let mut owner = self.group_of_cluster(r.first_cluster)?;
        let mut owner_group = self.group(owner)?;
        let mut positions = [[0f32; 3]; page::MAX_CLUSTER_VERTICES];
        let (lo, hi) = (self.mesh.aabb_min, self.mesh.aabb_max);
        let (mesh_center, mesh_radius) = (self.mesh.sphere_center, self.mesh.sphere_radius);
        for k in 0..view.cluster_count() {
            let c = r.first_cluster + k as u32;
            while c - owner_group.first_cluster >= owner_group.cluster_count {
                owner += 1;
                owner_group = self.group(owner)?;
            }
            let d = view.cluster(k)?;
            let (center, radius) = self.cluster_sphere(c as usize)?;
            let same_sphere = center.map(f32::to_bits) == d.center.map(f32::to_bits)
                && radius.to_bits() == d.radius.to_bits();
            if d.group as usize != owner
                || !owner_group.pages().contains(&page_id)
                || d.refined != self.cluster_refined(c as usize)?
                || (!d.single_material && !self.materials_declared)
                || (d.single_material && d.material >= self.mesh.material_count)
                || d.vertex_count as usize > self.limits.max_vertices
                || d.triangle_count as usize > self.limits.max_triangles
                || !same_sphere
            {
                return Err(Error::Invalid);
            }
            let block = view.attributes(k)?;
            if block.map_or(0, |b| b.channel_count()) != self.attribute_count {
                return Err(Error::Invalid);
            }
            if let Some(block) = block {
                for j in 0..self.attribute_count {
                    if block.channel(j)? != self.attribute_channel(j)? {
                        return Err(Error::Invalid);
                    }
                }
            }
            for t in 0..d.triangle_count as usize {
                if u32::from(view.triangle_material(k, t)?) >= self.mesh.material_count {
                    return Err(Error::Invalid);
                }
            }
            let n = view.decode_positions(k, &mut positions)?;
            for v in &positions[..n] {
                let inside = (0..3).all(|i| lo[i] <= v[i] && v[i] <= hi[i]);
                if !inside
                    || containing_radius(owner_group.center, *v, 0.0)
                        > f64::from(owner_group.radius)
                    || containing_radius(mesh_center, *v, 0.0) > f64::from(mesh_radius)
                {
                    return Err(Error::Invalid);
                }
            }
        }
        Ok(())
    }

    /// Group holding cluster `c` (groups partition the clusters in order).
    fn group_of_cluster(&self, c: u32) -> Result<usize, Error> {
        let (mut lo, mut hi) = (0usize, self.mesh.group_count as usize);
        while hi - lo > 1 {
            let mid = lo + (hi - lo) / 2;
            if self.group(mid)?.first_cluster <= c {
                lo = mid;
            } else {
                hi = mid;
            }
        }
        if self.group(lo)?.clusters().contains(&c) {
            Ok(lo)
        } else {
            Err(Error::Invalid)
        }
    }

    /// Open a whole file and validate every page as [`Self::transcode_page`]
    /// does, plus the cross-page facts a single page cannot show: triangle
    /// totals and that the last page ends the file. For tools and fuzzing.
    /// Scratch is that of [`Self::open`] plus one page of the memory form, so
    /// it is linear in the file length.
    ///
    /// # Errors
    /// As [`Self::open`] and [`Self::transcode_page`].
    pub fn read_all(file: &'a [u8], workspace: &mut Workspace) -> Result<Self, Error> {
        let r = Self::open(file)?;
        let mesh = r.mesh;
        let clusters = mesh.cluster_count as usize;
        if mul(clusters, 64)? > file.len() {
            return Err(Error::Invalid);
        }
        let mut words = filled(r.limits.page_capacity / 4, 0u32)?;
        let mut end = r.resident_len as u64;
        let (mut dag, mut leaf) = (0u64, 0u64);
        for p in 0..mesh.page_count as usize {
            let range = r.page(p)?.disk_range();
            let disk = usize::try_from(range.start)
                .ok()
                .zip(usize::try_from(range.end).ok())
                .and_then(|(s, e)| file.get(s..e))
                .ok_or(Error::Invalid)?;
            end = range.end;
            let view = r.transcode_page(p, disk, &mut words, workspace)?;
            for k in 0..view.cluster_count() {
                let d = view.cluster(k)?;
                let t = u64::from(d.triangle_count);
                dag += t;
                if d.refined < 0 {
                    leaf += t;
                }
            }
        }
        if end != file.len() as u64 || dag != mesh.dag_triangles || leaf != mesh.leaf_triangles {
            return Err(Error::Invalid);
        }
        Ok(r)
    }
}

/// Rule 5: the `MESH` record.
fn parse_mesh(prefix: &[u8], (at, len): (usize, usize), pages: u32) -> Result<MeshInfo, Error> {
    if len != MESH_BYTES {
        return Err(Error::Invalid);
    }
    let b = &prefix[at..at + len];
    let w = |i: usize| le32(b, i * 4);
    let grid = QuantGrid::new(w(22)? as i32).map_err(|_| Error::Invalid)?;
    let m = MeshInfo {
        level_count: w(0)?,
        bvh_depth: w(1)?,
        node_width: w(2)?,
        group_count: w(3)?,
        cluster_count: w(4)?,
        node_count: w(5)?,
        page_count: w(6)?,
        pinned_page_count: w(7)?,
        dag_triangles: le64(b, 32)?,
        leaf_triangles: le64(b, 40)?,
        aabb_min: vec3(b, 48)?,
        aabb_max: vec3(b, 60)?,
        sphere_center: vec3(b, 72)?,
        sphere_radius: fl(b, 84)?,
        grid,
        max_displacement: fl(b, 92)?,
        attribute_layout_hash: w(24)?,
        material_count: w(25)?,
    };
    let empty = m.group_count == 0;
    let ok = m.page_count == pages
        && m.level_count <= MAX_LEVELS
        && m.node_width >= 2
        && (m.level_count == 0) == empty
        && if empty {
            m.cluster_count == 0 && m.node_count == 0 && m.page_count == 0 && m.bvh_depth == 0
        } else {
            m.cluster_count >= m.group_count && m.page_count >= 1
        }
        && m.material_count <= 65536
        && (empty || m.material_count > 0)
        && m.pinned_page_count <= m.page_count
        && m.leaf_triangles <= m.dag_triangles
        && finite3(m.aabb_min)
        && finite3(m.aabb_max)
        && (0..3).all(|i| m.aabb_min[i] <= m.aabb_max[i])
        && finite3(m.sphere_center)
        && m.sphere_radius.is_finite()
        && m.sphere_radius >= 0.0
        && m.max_displacement.to_bits() == grid.max_displacement().to_bits()
        && w(26)? == 0
        && w(27)? == 0;
    if ok {
        Ok(m)
    } else {
        Err(Error::Invalid)
    }
}