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
// Translation of meshoptimizer 1.3 src/vcacheoptimizer.cpp; see LICENSE.
use crate::budget::Budget;
use crate::workspace::{checked_bytes, output, topology, Work};
use crate::{Error, Workspace};
use alloc::vec::Vec;

const CACHE: [f32; 17] = [
    0., 0.779, 0.791, 0.789, 0.981, 0.843, 0.726, 0.847, 0.882, 0.867, 0.799, 0.642, 0.613, 0.600,
    0.568, 0.372, 0.234,
];
const LIVE: [f32; 9] = [0., 0.995, 0.713, 0.450, 0.404, 0.059, 0.005, 0.147, 0.006];
const STRIP_CACHE: [f32; 17] = [
    0., 1., 1., 1., 0.453, 0.561, 0.490, 0.459, 0.179, 0.526, 0., 0.227, 0.184, 0.490, 0.112,
    0.050, 0.131,
];
const STRIP_LIVE: [f32; 9] = [0., 0.956, 0.786, 0.577, 0.558, 0.618, 0.549, 0.499, 0.489];
/// Caller-defined vertex-cache scores; an opt-in extension not in C++ meshoptimizer.
///
/// Cache score zero is for a vertex outside the cache; entries 1 through 16
/// correspond to most to least recently used. Live-valence scores cover 0 through
/// 8 remaining triangle references; larger valences use entry 8. The cache size
/// and valence clamp cannot be changed. [`Default`] reproduces the standard table.
#[derive(Clone, Debug, PartialEq)]
pub struct VertexScoreTable {
    cache: [f32; 17],
    live: [f32; 9],
}

impl VertexScoreTable {
    /// Copy and validate exactly 17 cache scores and 9 live-valence scores.
    /// Construction allocates no heap storage and needs no workspace.
    ///
    /// # Errors
    /// `InvalidParameter` if either length differs or any score is non-finite.
    pub fn new(cache: &[f32], live: &[f32]) -> Result<Self, Error> {
        if cache.len() != 17 || live.len() != 9 || !cache.iter().chain(live).all(|s| s.is_finite())
        {
            return Err(Error::InvalidParameter);
        }
        let mut table = Self::default();
        table.cache.copy_from_slice(cache);
        table.live.copy_from_slice(live);
        Ok(table)
    }

    /// Cache-position scores, including the outside-cache score at zero.
    pub fn cache_scores(&self) -> &[f32; 17] {
        &self.cache
    }

    /// Live-valence scores; valences above eight use the final entry.
    pub fn live_scores(&self) -> &[f32; 9] {
        &self.live
    }
}

impl Default for VertexScoreTable {
    fn default() -> Self {
        Self {
            cache: CACHE,
            live: LIVE,
        }
    }
}

trait Scores {
    fn score(&self, position: usize, live: u32) -> f32;
}

struct Preset<const STRIP: bool>;

impl<const STRIP: bool> Scores for Preset<STRIP> {
    fn score(&self, position: usize, live: u32) -> f32 {
        if STRIP {
            STRIP_CACHE[position] + STRIP_LIVE[live.min(8) as usize]
        } else {
            CACHE[position] + LIVE[live.min(8) as usize]
        }
    }
}

impl Scores for VertexScoreTable {
    fn score(&self, position: usize, live: u32) -> f32 {
        self.cache[position] + self.live[live.min(8) as usize]
    }
}

/// Reorder triangles with caller-defined scores; not in C++ meshoptimizer.
///
/// Uses the same workspace limits, topology validation and triangle preservation
/// as [`optimize_vertex_cache`]. The default table gives identical output.
/// Tuned tables must be validated on the target hardware; no improvement is
/// guaranteed.
///
/// A triangle score is the sum of its three vertex scores. After each emitted
/// triangle, the vertices of the cache are rescored in cache order, and each
/// change in a vertex score is added to the score of every unemitted triangle
/// that uses it. The next triangle is whichever updated triangle first reaches
/// the largest positive running score during this pass, so a transient maximum
/// reached before a later vertex lowers the same triangle's score can win.
/// This is upstream's incremental selection, and tables are applied through the
/// same procedure as the default table. When no updated triangle scores above
/// zero, the next unemitted triangle in input order follows. A table whose sums
/// are never positive therefore keeps the input order. Extreme finite scores can overflow the summed scores, which
/// degrades the ordering but never drops or duplicates a triangle.
///
/// ```
/// use meshoptimizer_rs::{optimize_vertex_cache_with_table, VertexScoreTable, Workspace};
/// let defaults = VertexScoreTable::default();
/// let mut cache = *defaults.cache_scores();
/// cache[1] = 1.0;
/// let table = VertexScoreTable::new(&cache, defaults.live_scores())?;
/// let result = optimize_vertex_cache_with_table(&[0, 1, 2], 3, &table,
///                                               &mut Workspace::default())?;
/// assert_eq!(result, [0, 1, 2]);
/// # Ok::<(), meshoptimizer_rs::Error>(())
/// ```
///
/// # Errors
/// Same errors as [`optimize_vertex_cache`].
#[inline]
pub fn optimize_vertex_cache_with_table_generic<I: crate::Index>(
    indices: &[I],
    vertex_count: usize,
    table: &VertexScoreTable,
    workspace: &mut Workspace,
) -> Result<Vec<I>, Error> {
    I::with_input(indices, workspace, |indices, workspace| {
        optimize_vertex_cache_with_table_u32(indices, vertex_count, table, workspace)
            .and_then(|value| crate::index::Convert::<I>::convert(value, workspace))
    })
}

fn optimize_vertex_cache_with_table_u32(
    indices: &[u32],
    vertex_count: usize,
    table: &VertexScoreTable,
    workspace: &mut Workspace,
) -> Result<Vec<u32>, Error> {
    let mut work = workspace.begin();
    let result = (|| {
        topology(indices, vertex_count, &mut work)?;
        prepare(
            indices.len(),
            vertex_count,
            checked_bytes(indices.len(), 4)?,
            workspace,
        )?;
        let mut destination = output(indices.len())?;
        kernel(
            &mut destination,
            indices,
            vertex_count,
            workspace,
            &mut work,
            table,
        )?;
        Ok(destination)
    })();
    workspace.finish(&work);
    result
}

/// Write caller-defined cache ordering; not in C++ meshoptimizer.
///
/// The unused destination tail is untouched. Validation and reservation precede
/// writes; work exhaustion can partially modify the used prefix. Caller-owned
/// destination storage is excluded from workspace byte limits.
///
/// # Errors
/// Same errors as [`optimize_vertex_cache_with_table`], plus `BufferTooSmall`
/// if the destination is shorter than the input.
#[inline]
pub fn optimize_vertex_cache_with_table_into_generic<I: crate::Index>(
    destination: &mut [I],
    indices: &[I],
    vertex_count: usize,
    table: &VertexScoreTable,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    I::with_input(indices, workspace, |indices, workspace| {
        I::with_mut(destination, workspace, |destination, workspace| {
            optimize_vertex_cache_with_table_into_u32(
                destination,
                indices,
                vertex_count,
                table,
                workspace,
            )
        })
    })
}

fn optimize_vertex_cache_with_table_into_u32(
    destination: &mut [u32],
    indices: &[u32],
    vertex_count: usize,
    table: &VertexScoreTable,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    let mut work = workspace.begin();
    let result = (|| {
        topology(indices, vertex_count, &mut work)?;
        if destination.len() < indices.len() {
            return Err(Error::BufferTooSmall);
        }
        prepare(indices.len(), vertex_count, 0, workspace)?;
        kernel(
            destination,
            indices,
            vertex_count,
            workspace,
            &mut work,
            table,
        )
    })();
    workspace.finish(&work);
    result
}

/// Reorder triangles using upstream `meshopt_optimizeVertexCache` (standard variant).
///
/// Returns exactly as many indices as supplied, preserving triangle corner
/// order and vertex references. Empty input is valid. No geometry is welded
/// or compacted. Output and scratch count toward the workspace byte limit.
///
/// # Errors
/// `InvalidTopology` for incomplete triangles or `IndexOutOfBounds` for invalid vertex references.
/// `SizeOverflow` for size overflow, `LimitExceeded` for exhausted limits, or `AllocationFailed` for failed reservation.
#[inline]
pub fn optimize_vertex_cache_generic<I: crate::Index>(
    indices: &[I],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<Vec<I>, Error> {
    I::with_input(indices, workspace, |indices, workspace| {
        optimize_vertex_cache_u32(indices, vertex_count, workspace)
            .and_then(|value| crate::index::Convert::<I>::convert(value, workspace))
    })
}

fn optimize_vertex_cache_u32(
    indices: &[u32],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<Vec<u32>, Error> {
    let mut work = workspace.begin();
    let result = (|| {
        topology(indices, vertex_count, &mut work)?;
        prepare(
            indices.len(),
            vertex_count,
            checked_bytes(indices.len(), 4)?,
            workspace,
        )?;
        let mut destination = output(indices.len())?;
        kernel(
            &mut destination,
            indices,
            vertex_count,
            workspace,
            &mut work,
            &Preset::<false>,
        )?;
        Ok(destination)
    })();
    workspace.finish(&work);
    result
}

/// Write upstream standard cache ordering to the used prefix of `destination`.
///
/// The unused tail is untouched. Validation and reservation precede writes.
/// Counted-work exhaustion during optimization can leave the used prefix
/// partially modified. Caller-owned destination storage is excluded from limits.
///
/// # Errors
/// Same errors as [`optimize_vertex_cache`]. `BufferTooSmall` if the destination is shorter than the input.
#[inline]
pub fn optimize_vertex_cache_into_generic<I: crate::Index>(
    destination: &mut [I],
    indices: &[I],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    I::with_input(indices, workspace, |indices, workspace| {
        I::with_mut(destination, workspace, |destination, workspace| {
            optimize_vertex_cache_into_u32(destination, indices, vertex_count, workspace)
        })
    })
}

fn optimize_vertex_cache_into_u32(
    destination: &mut [u32],
    indices: &[u32],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    let mut work = workspace.begin();
    let result = (|| {
        topology(indices, vertex_count, &mut work)?;
        if destination.len() < indices.len() {
            return Err(Error::BufferTooSmall);
        }
        prepare(indices.len(), vertex_count, 0, workspace)?;
        kernel(
            destination,
            indices,
            vertex_count,
            workspace,
            &mut work,
            &Preset::<false>,
        )
    })();
    workspace.finish(&work);
    result
}

/// Destructively apply upstream standard cache ordering, leaving input unchanged on error.
/// A fallibly allocated temporary output counts toward the byte limit.
///
/// # Errors
/// Same errors as [`optimize_vertex_cache`].
#[inline]
pub fn optimize_vertex_cache_in_place_generic<I: crate::Index>(
    indices: &mut [I],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    I::with_mut(indices, workspace, |indices, workspace| {
        optimize_vertex_cache_in_place_u32(indices, vertex_count, workspace)
    })
}

fn optimize_vertex_cache_in_place_u32(
    indices: &mut [u32],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    let result = optimize_vertex_cache_generic(indices, vertex_count, workspace)?;
    indices.copy_from_slice(&result);
    Ok(())
}

fn prepare(n: usize, v: usize, out: usize, ws: &mut Workspace) -> Result<(), Error> {
    ws.acquire(crate::workspace::ScratchFamily::Cache);
    if n == 0 {
        return ws.prepare([0; 4], out);
    }
    let faces = n / 3;
    ws.prepare_cache([n, faces, faces, 0], v, out)
}

fn kernel<S: Scores>(
    dest: &mut [u32],
    indices: &[u32],
    v: usize,
    ws: &mut Workspace,
    work: &mut Work,
    scores: &S,
) -> Result<(), Error> {
    if indices.is_empty() {
        return Ok(());
    }
    let faces = indices.len() / 3;
    let vertices = &mut ws.vertices[..v];
    let adjacency = &mut ws.integers[..indices.len()];
    let triangle_scores = &mut ws.floats[..faces];
    let emitted = &mut ws.flags[..faces];
    let triangles = indices.as_chunks::<3>().0;
    let destination = dest[..indices.len()].as_chunks_mut::<3>().0;
    assert_eq!(triangles.len(), triangle_scores.len());
    assert_eq!(triangles.len(), emitted.len());
    work.add(v)?;
    for vertex in vertices.iter_mut() {
        vertex.live = 0;
    }
    work.scan(indices.iter().copied(), |index| {
        vertices[index as usize].live += 1;
        Ok(())
    })?;
    let mut offset = 0;
    work.scan(vertices.iter_mut(), |vertex| {
        vertex.offset = offset;
        offset += vertex.live;
        Ok(())
    })?;
    if work.precharge(indices.len(), 1)? {
        for (i, triangle) in triangles.iter().enumerate() {
            for &index in triangle {
                let vertex = &mut vertices[index as usize];
                adjacency[vertex.offset as usize] = i as u32;
                vertex.offset += 1;
            }
        }
    } else {
        for (i, triangle) in indices.as_chunks::<3>().0.iter().enumerate() {
            for &index in triangle {
                work.add(1)?;
                let j = index as usize;
                let vertex = &mut vertices[j];
                adjacency[vertex.offset as usize] = i as u32;
                vertex.offset += 1;
            }
        }
    }
    let mut max_live = 0usize;
    work.scan(vertices.iter_mut(), |vertex| {
        max_live = max_live.max(vertex.live as usize);
        vertex.offset -= vertex.live;
        vertex.score = scores.score(0, vertex.live);
        Ok(())
    })?;
    work.add(faces)?;
    emitted.fill(0);
    work.scan(
        triangle_scores[..faces].iter_mut().zip(triangles),
        |(s, triangle)| {
            *s = vertices[triangle[0] as usize].score
                + vertices[triangle[1] as usize].score
                + vertices[triangle[2] as usize].score;
            Ok(())
        },
    )?;
    // Per emission: one face, <=16 old cache entries, three removal searches
    // of <=max_live entries, <=19 score visits each scanning <=max_live. The
    // cursor advances <=faces-1 times and stops on <=faces-1 selections.
    let bound = max_live
        .checked_mul(22)
        .and_then(|n| n.checked_add(38))
        .and_then(|n| faces.checked_mul(n));
    if let Some(bound) = bound.filter(|&n| work.covers(n) == Ok(true)) {
        // Prepay the proven whole-kernel bound, then refund the unvisited part
        // so the charged total equals the limited path's visit-by-visit count.
        work.add(bound)?;
        let visits = cache_loop_covered(
            destination,
            triangles,
            vertices,
            adjacency,
            triangle_scores,
            emitted,
            scores,
        );
        debug_assert!(visits <= bound, "cache work bound overrun");
        work.refund_cache(bound.saturating_sub(visits));
        Ok(())
    } else {
        cache_loop_limited(
            destination,
            triangles,
            vertices,
            adjacency,
            triangle_scores,
            emitted,
            work,
            scores,
        )
    }
}

/// Merge the previous cache behind the emitted triangle, as upstream does, and
/// carry each kept entry's live bit to its new position.
///
/// Upstream copies each old entry and advances unless it equals a triangle
/// vertex. Here the old entries equal to a triangle vertex form a mask from
/// fixed-width comparisons. Without a match all 16 slots are copied at once;
/// otherwise the copy advances past matched slots, so every kept entry ends at
/// the same position as upstream's. Slots past `count` hold stale values that
/// the mask excludes and no later step reads.
///
/// `live` has bit `k` set when old entry `k` still has unemitted triangles.
/// Returns the merged length and the carried live bits, both below 19.
#[inline(always)]
fn merge(
    next: &mut [u32; 32],
    old: &[u32; 32],
    count: usize,
    mut live: u32,
    [a, b, c]: [u32; 3],
) -> (usize, u32) {
    let mut matched = 0u32;
    for (k, &index) in old[..16].iter().enumerate() {
        matched |= u32::from((index == a) | (index == b) | (index == c)) << k;
    }
    matched &= (1u32 << count.min(16)) - 1;
    if matched == 0 {
        next[3..19].copy_from_slice(&old[..16]);
    } else {
        let mut write = 3;
        for (k, &index) in old[..16].iter().enumerate() {
            next[write & 31] = index;
            write += (!matched >> k & 1) as usize;
        }
        let mut pending = matched;
        while pending != 0 {
            // Highest matched slot first keeps lower bit positions valid.
            let slot = 31 - pending.leading_zeros();
            pending &= !(1 << slot);
            let below = (1u32 << slot) - 1;
            live = (live & below) | (live >> 1 & !below);
        }
    }
    (3 + count.min(16) - matched.count_ones() as usize, live << 3)
}

/// Covered path of the cache optimizer: no budget checks, returns the exact
/// number of visits the limited path charges one by one.
///
/// Same traversal, float operations and selection as [`cache_loop_limited`].
/// A vertex's live count only falls when its triangle is emitted, and the
/// emitted triangle's vertices always land at cache positions 0..3, so a live
/// bit per cache position is exact: fresh for those three, carried for the
/// rest. Rescoring then visits the set bits in position order and skips
/// exhausted vertices without loading them; upstream loads and skips them.
#[inline(never)]
#[allow(clippy::too_many_arguments)]
fn cache_loop_covered<S: Scores>(
    destination: &mut [[u32; 3]],
    triangles: &[[u32; 3]],
    vertices: &mut [crate::workspace::CacheVertex],
    adjacency: &mut [u32],
    triangle_scores: &mut [f32],
    emitted: &mut [u8],
    scores: &S,
) -> usize {
    let faces = triangles.len();
    assert_eq!(faces, triangle_scores.len());
    assert_eq!(faces, emitted.len());
    let mut cache_storage = [0u32; 32];
    let mut next_storage = [0u32; 32];
    // Upstream exchanges pointers, not the contents of its two cache arrays.
    let mut cache = &mut cache_storage;
    let mut next = &mut next_storage;
    let mut cache_count = 0;
    let mut live = 0u32;
    let mut current = 0usize;
    let mut cursor = 1usize;
    let mut emitted_count = 0;
    let mut visits = 0usize;
    while current != usize::MAX {
        visits += 1;
        let triangle = triangles[current];
        destination[emitted_count] = triangle;
        emitted_count += 1;
        emitted[current] = 1;
        triangle_scores[current] = 0.;
        next[..3].copy_from_slice(&triangle);
        visits += cache_count;
        let (write, carried) = merge(next, cache, cache_count, live, triangle);
        core::mem::swap(&mut cache, &mut next);
        cache_count = write.min(16);
        let current_id = current as u32;
        for index in triangle {
            let vertex = &mut vertices[index as usize];
            let start = vertex.offset as usize;
            let count = vertex.live as usize;
            let adjacent = &mut adjacency[start..start + count];
            match adjacent.iter().position(|&tri| tri == current_id) {
                Some(i) => {
                    visits += i + 1;
                    adjacent[i] = adjacent[count - 1];
                    vertex.live -= 1;
                }
                None => visits += count,
            }
        }
        let [a, b, c] = triangle;
        let fresh = u32::from(vertices[a as usize].live != 0)
            | u32::from(vertices[b as usize].live != 0) << 1
            | u32::from(vertices[c as usize].live != 0) << 2;
        let mut pending = carried | fresh;
        live = pending & 0xffff;
        // Every cache entry is a visit, exhausted or not.
        visits += write;
        let mut best = usize::MAX;
        let mut best_score = 0.;
        while pending != 0 {
            let i = pending.trailing_zeros() as usize;
            pending &= pending - 1;
            let vertex = &mut vertices[cache[i & 31] as usize];
            let s = scores.score(if i >= 16 { 0 } else { i + 1 }, vertex.live);
            let diff = s - vertex.score;
            vertex.score = s;
            let start = vertex.offset as usize;
            let count = vertex.live as usize;
            visits += count;
            for &tri in &adjacency[start..start + count] {
                let tri = tri as usize;
                let s = triangle_scores[tri] + diff;
                if best_score < s {
                    best = tri;
                    best_score = s;
                }
                triangle_scores[tri] = s;
            }
        }
        current = best;
        if current == usize::MAX {
            while cursor < faces {
                visits += 1;
                if emitted[cursor] == 0 {
                    current = cursor;
                    break;
                }
                cursor += 1;
            }
        }
    }
    visits
}

/// Limited path: charges every visit before its observable mutation, so
/// exhaustion stops at exactly the same point as a visit-by-visit meter.
#[inline(never)]
#[allow(clippy::too_many_arguments)]
fn cache_loop_limited<S: Scores>(
    destination: &mut [[u32; 3]],
    triangles: &[[u32; 3]],
    vertices: &mut [crate::workspace::CacheVertex],
    adjacency: &mut [u32],
    triangle_scores: &mut [f32],
    emitted: &mut [u8],
    work: &mut Work,
    scores: &S,
) -> Result<(), Error> {
    let faces = triangles.len();
    assert_eq!(triangles.len(), triangle_scores.len());
    assert_eq!(triangles.len(), emitted.len());
    let mut cache_storage = [0u32; 20];
    let mut next_storage = [0u32; 20];
    // Upstream exchanges pointers, not the contents of its two cache arrays.
    let mut cache = &mut cache_storage;
    let mut next = &mut next_storage;
    let mut cache_count = 0;
    let mut current = 0usize;
    let mut cursor = 1usize;
    let mut emitted_count = 0;
    while current != usize::MAX {
        work.add(1)?;
        let triangle = &triangles[current];
        destination[emitted_count].copy_from_slice(triangle);
        emitted_count += 1;
        emitted[current] = 1;
        triangle_scores[current] = 0.;
        next[..3].copy_from_slice(triangle);
        let mut write = 3;
        assert!(cache_count <= 16);
        work.scan(cache[..cache_count].iter().copied(), |index| {
            next[write] = index;
            write += usize::from(!triangle.contains(&index));
            Ok(())
        })?;
        core::mem::swap(&mut cache, &mut next);
        cache_count = write.min(16);
        for &index in triangle {
            let j = index as usize;
            let vertex = &mut vertices[j];
            let start = vertex.offset as usize;
            let count = vertex.live as usize;
            let adjacent = &mut adjacency[start..start + count];
            let found = work.search(count, |i| adjacent[i] == current as u32)?;
            if let Some(i) = found {
                adjacent[i] = adjacent[count - 1];
                vertex.live -= 1;
            }
        }
        let mut best = usize::MAX;
        let mut best_score = 0.;
        // One checked visit per cache entry, before the entry's mutation.
        for (i, &index) in cache[..write].iter().enumerate() {
            work.add(1)?;
            let j = index as usize;
            let vertex = &mut vertices[j];
            if vertex.live == 0 {
                continue;
            }
            let s = scores.score(if i >= 16 { 0 } else { i + 1 }, vertex.live);
            let diff = s - vertex.score;
            vertex.score = s;
            work.scan(
                adjacency[vertex.offset as usize..vertex.offset as usize + vertex.live as usize]
                    .iter()
                    .copied(),
                |tri| {
                    let tri = tri as usize;
                    let s = triangle_scores[tri] + diff;
                    if best_score < s {
                        best = tri;
                        best_score = s;
                    }
                    triangle_scores[tri] = s;
                    Ok(())
                },
            )?;
        }
        current = best;
        if current == usize::MAX {
            while cursor < faces {
                work.add(1)?;
                if emitted[cursor] == 0 {
                    current = cursor;
                    break;
                }
                cursor += 1;
            }
        }
    }
    Ok(())
}

/// Optimize cache ordering using upstream's strip-oriented score table.
///
/// # Errors
/// Same errors as [`optimize_vertex_cache`].
#[inline]
pub fn optimize_vertex_cache_strip_generic<I: crate::Index>(
    indices: &[I],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<Vec<I>, Error> {
    I::with_input(indices, workspace, |indices, workspace| {
        optimize_vertex_cache_strip_u32(indices, vertex_count, workspace)
            .and_then(|value| crate::index::Convert::<I>::convert(value, workspace))
    })
}

fn optimize_vertex_cache_strip_u32(
    indices: &[u32],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<Vec<u32>, Error> {
    let mut work = workspace.begin();
    let result = (|| {
        topology(indices, vertex_count, &mut work)?;
        prepare(
            indices.len(),
            vertex_count,
            checked_bytes(indices.len(), 4)?,
            workspace,
        )?;
        let mut destination = output(indices.len())?;
        kernel(
            &mut destination,
            indices,
            vertex_count,
            workspace,
            &mut work,
            &Preset::<true>,
        )?;
        Ok(destination)
    })();
    workspace.finish(&work);
    result
}
/// Write strip-oriented cache ordering; work exhaustion may partially modify
/// the used prefix. The unused destination tail is untouched.
///
/// # Errors
/// Same errors as [`optimize_vertex_cache_strip`]. `BufferTooSmall` if the destination is shorter than the input.
#[inline]
pub fn optimize_vertex_cache_strip_into_generic<I: crate::Index>(
    destination: &mut [I],
    indices: &[I],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    I::with_input(indices, workspace, |indices, workspace| {
        I::with_mut(destination, workspace, |destination, workspace| {
            optimize_vertex_cache_strip_into_u32(destination, indices, vertex_count, workspace)
        })
    })
}

fn optimize_vertex_cache_strip_into_u32(
    destination: &mut [u32],
    indices: &[u32],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    let mut work = workspace.begin();
    let result = (|| {
        topology(indices, vertex_count, &mut work)?;
        if destination.len() < indices.len() {
            return Err(Error::BufferTooSmall);
        }
        prepare(indices.len(), vertex_count, 0, workspace)?;
        kernel(
            destination,
            indices,
            vertex_count,
            workspace,
            &mut work,
            &Preset::<true>,
        )
    })();
    workspace.finish(&work);
    result
}
/// Destructively apply strip-oriented ordering, preserving indices on error.
///
/// # Errors
/// Same errors as [`optimize_vertex_cache_strip`].
#[inline]
pub fn optimize_vertex_cache_strip_in_place_generic<I: crate::Index>(
    indices: &mut [I],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    I::with_mut(indices, workspace, |indices, workspace| {
        optimize_vertex_cache_strip_in_place_u32(indices, vertex_count, workspace)
    })
}

fn optimize_vertex_cache_strip_in_place_u32(
    indices: &mut [u32],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    let result = optimize_vertex_cache_strip_generic(indices, vertex_count, workspace)?;
    indices.copy_from_slice(&result);
    Ok(())
}
/// Optimize using upstream's FIFO cache heuristic. Cache size is at least three.
///
/// # Errors
/// Same errors as [`optimize_vertex_cache`]. `InvalidParameter` if the cache size is below three.
#[inline]
pub fn optimize_vertex_cache_fifo_generic<I: crate::Index>(
    indices: &[I],
    vertex_count: usize,
    cache_size: u32,
    workspace: &mut Workspace,
) -> Result<Vec<I>, Error> {
    I::with_input(indices, workspace, |indices, workspace| {
        optimize_vertex_cache_fifo_u32(indices, vertex_count, cache_size, workspace)
            .and_then(|value| crate::index::Convert::<I>::convert(value, workspace))
    })
}

fn optimize_vertex_cache_fifo_u32(
    indices: &[u32],
    vertex_count: usize,
    cache_size: u32,
    workspace: &mut Workspace,
) -> Result<Vec<u32>, Error> {
    let mut work = workspace.begin();
    let result = (|| {
        topology(indices, vertex_count, &mut work)?;
        if cache_size < 3 {
            return Err(Error::InvalidParameter);
        }
        workspace.acquire(crate::workspace::ScratchFamily::Cache);
        let mut budget = Budget::new(workspace);
        let mut out = budget.filled(indices.len(), 0u32)?;
        fifo(
            &mut out,
            indices,
            vertex_count,
            cache_size,
            &mut budget,
            &mut work,
        )?;
        Ok(out)
    })();
    workspace.finish(&work);
    result
}
/// Write FIFO cache ordering; work exhaustion may partially modify the prefix.
///
/// # Errors
/// Same errors as [`optimize_vertex_cache_fifo`]. `BufferTooSmall` if the destination is shorter than the input.
#[inline]
pub fn optimize_vertex_cache_fifo_into_generic<I: crate::Index>(
    destination: &mut [I],
    indices: &[I],
    vertex_count: usize,
    cache_size: u32,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    I::with_input(indices, workspace, |indices, workspace| {
        I::with_mut(destination, workspace, |destination, workspace| {
            optimize_vertex_cache_fifo_into_u32(
                destination,
                indices,
                vertex_count,
                cache_size,
                workspace,
            )
        })
    })
}

fn optimize_vertex_cache_fifo_into_u32(
    destination: &mut [u32],
    indices: &[u32],
    vertex_count: usize,
    cache_size: u32,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    let mut work = workspace.begin();
    let result = (|| {
        topology(indices, vertex_count, &mut work)?;
        if cache_size < 3 {
            return Err(Error::InvalidParameter);
        }
        if destination.len() < indices.len() {
            return Err(Error::BufferTooSmall);
        }
        workspace.acquire(crate::workspace::ScratchFamily::Cache);
        fifo(
            destination,
            indices,
            vertex_count,
            cache_size,
            &mut Budget::new(workspace),
            &mut work,
        )
    })();
    workspace.finish(&work);
    result
}
/// Destructively apply FIFO ordering, preserving indices on error.
///
/// # Errors
/// Same errors as [`optimize_vertex_cache_fifo`].
#[inline]
pub fn optimize_vertex_cache_fifo_in_place_generic<I: crate::Index>(
    indices: &mut [I],
    vertex_count: usize,
    cache_size: u32,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    I::with_mut(indices, workspace, |indices, workspace| {
        optimize_vertex_cache_fifo_in_place_u32(indices, vertex_count, cache_size, workspace)
    })
}

fn optimize_vertex_cache_fifo_in_place_u32(
    indices: &mut [u32],
    vertex_count: usize,
    cache_size: u32,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    let result = optimize_vertex_cache_fifo_generic(indices, vertex_count, cache_size, workspace)?;
    indices.copy_from_slice(&result);
    Ok(())
}
fn fifo(
    out: &mut [u32],
    indices: &[u32],
    v: usize,
    cache_size: u32,
    budget: &mut Budget<'_>,
    work: &mut Work,
) -> Result<(), Error> {
    if indices.is_empty() {
        return Ok(());
    }
    let length = v
        .checked_mul(4)
        .and_then(|n| indices.len().checked_mul(2).and_then(|m| n.checked_add(m)))
        .ok_or(Error::SizeOverflow)?;
    let owned = budget.bytes();
    let ws = &mut *budget.ws;
    let old_integer_len = ws.integers.len();
    let old_flag_len = ws.flags.len();
    ws.prepare([length, 0, indices.len() / 3, 0], owned)?;
    // prepare initializes every newly extended element to zero. Only retained
    // active elements can contain state from an earlier operation.
    ws.integers[..old_integer_len.min(v)].fill(0);
    let old_hot = old_integer_len.saturating_sub(v * 2).min(v * 2);
    ws.integers[v * 2..v * 2 + old_hot].fill(0);
    ws.flags[..old_flag_len.min(indices.len() / 3)].fill(0);
    let (counts, rest) = ws.integers[..length].split_at_mut(v);
    let (offsets, rest) = rest.split_at_mut(v);
    let (hot, rest) = rest.split_at_mut(v * 2);
    let hot = hot.as_chunks_mut::<2>().0;
    let (adjacency, dead) = rest.split_at_mut(indices.len());
    let emitted = &mut ws.flags[..indices.len() / 3];
    let charged = work.precharge(indices.len(), 1)?;
    for &i in indices {
        if !charged {
            work.add(1)?;
        }
        counts[i as usize] += 1;
    }
    let mut offset = 0;
    let charged = work.precharge(v, 1)?;
    for (dst, &count) in offsets.iter_mut().zip(counts.iter()) {
        if !charged {
            work.add(1)?;
        }
        *dst = offset;
        offset += count;
    }
    let triangles = indices.as_chunks::<3>().0;
    if work.precharge(indices.len(), 1)? {
        // The triangle id is shared by its three corners. Iterating records
        // avoids dividing an index-stream offset for every adjacency entry.
        for (i, triangle) in triangles.iter().enumerate() {
            for &j in triangle {
                adjacency[offsets[j as usize] as usize] = i as u32;
                offsets[j as usize] += 1;
            }
        }
    } else {
        for (i, &j) in indices.iter().enumerate() {
            work.add(1)?;
            adjacency[offsets[j as usize] as usize] = (i / 3) as u32;
            offsets[j as usize] += 1;
        }
    }
    let charged = work.precharge(v, 1)?;
    for ((offset, &count), hot) in offsets.iter_mut().zip(counts.iter()).zip(hot.iter_mut()) {
        if !charged {
            work.add(1)?;
        }
        *offset -= count;
        hot[0] = count;
    }
    let mut current = 0u32;
    let mut timestamp = cache_size.wrapping_add(1);
    let mut cursor = 1usize;
    let mut top = 0usize;
    let mut write = 0usize;
    let destination = out[..indices.len()].as_chunks_mut::<3>().0;
    while current != u32::MAX {
        work.add(1)?;
        let begin = top;
        let j = current as usize;
        let adjacent = &adjacency[offsets[j] as usize..(offsets[j] + counts[j]) as usize];
        let charged = work.precharge(adjacent.len(), 1)?;
        for &triangle in adjacent {
            if !charged {
                work.add(1)?;
            }
            let t = triangle as usize;
            if emitted[t] != 0 {
                continue;
            }
            let tri = &triangles[t];
            destination[write].copy_from_slice(tri);
            write += 1;
            dead[top..top + 3].copy_from_slice(tri);
            top += 3;
            for &index in tri {
                let vertex = &mut hot[index as usize];
                vertex[0] -= 1;
                if timestamp.wrapping_sub(vertex[1]) > cache_size {
                    vertex[1] = timestamp;
                    timestamp = timestamp.wrapping_add(1);
                }
            }
            emitted[t] = 1;
        }
        current = u32::MAX;
        let mut best = -1i32;
        let candidates = &dead[begin..top];
        let charged = work.precharge(candidates.len(), 1)?;
        for &candidate in candidates {
            if !charged {
                work.add(1)?;
            }
            let vertex = hot[candidate as usize];
            if vertex[0] != 0 {
                let age = timestamp.wrapping_sub(vertex[1]);
                let priority = if vertex[0].wrapping_mul(2).wrapping_add(age) <= cache_size {
                    age as i32
                } else {
                    0
                };
                if priority > best {
                    current = candidate;
                    best = priority;
                }
            }
        }
        if current == u32::MAX {
            work.search(top, |_| {
                top -= 1;
                let vertex = dead[top];
                if hot[vertex as usize][0] > 0 {
                    current = vertex;
                    true
                } else {
                    false
                }
            })?;
            if current == u32::MAX {
                work.search(v - cursor, |_| {
                    if hot[cursor][0] > 0 {
                        current = cursor as u32;
                        true
                    } else {
                        cursor += 1;
                        false
                    }
                })?;
            }
        }
    }
    Ok(())
}

/// The source-compatible u32 entry point; see [`optimize_vertex_cache_with_table_generic`] for selectable index widths.
#[inline]
pub fn optimize_vertex_cache_with_table(
    indices: &[u32],
    vertex_count: usize,
    table: &VertexScoreTable,
    workspace: &mut Workspace,
) -> Result<Vec<u32>, Error> {
    optimize_vertex_cache_with_table_generic::<u32>(indices, vertex_count, table, workspace)
}

/// The source-compatible u32 entry point; see [`optimize_vertex_cache_with_table_into_generic`] for selectable index widths.
#[inline]
pub fn optimize_vertex_cache_with_table_into(
    destination: &mut [u32],
    indices: &[u32],
    vertex_count: usize,
    table: &VertexScoreTable,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    optimize_vertex_cache_with_table_into_generic::<u32>(
        destination,
        indices,
        vertex_count,
        table,
        workspace,
    )
}

/// The source-compatible u32 entry point; see [`optimize_vertex_cache_generic`] for selectable index widths.
#[inline]
pub fn optimize_vertex_cache(
    indices: &[u32],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<Vec<u32>, Error> {
    optimize_vertex_cache_generic::<u32>(indices, vertex_count, workspace)
}

/// The source-compatible u32 entry point; see [`optimize_vertex_cache_into_generic`] for selectable index widths.
#[inline]
pub fn optimize_vertex_cache_into(
    destination: &mut [u32],
    indices: &[u32],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    optimize_vertex_cache_into_generic::<u32>(destination, indices, vertex_count, workspace)
}

/// The source-compatible u32 entry point; see [`optimize_vertex_cache_in_place_generic`] for selectable index widths.
#[inline]
pub fn optimize_vertex_cache_in_place(
    indices: &mut [u32],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    optimize_vertex_cache_in_place_generic::<u32>(indices, vertex_count, workspace)
}

/// The source-compatible u32 entry point; see [`optimize_vertex_cache_strip_generic`] for selectable index widths.
#[inline]
pub fn optimize_vertex_cache_strip(
    indices: &[u32],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<Vec<u32>, Error> {
    optimize_vertex_cache_strip_generic::<u32>(indices, vertex_count, workspace)
}

/// The source-compatible u32 entry point; see [`optimize_vertex_cache_strip_into_generic`] for selectable index widths.
#[inline]
pub fn optimize_vertex_cache_strip_into(
    destination: &mut [u32],
    indices: &[u32],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    optimize_vertex_cache_strip_into_generic::<u32>(destination, indices, vertex_count, workspace)
}

/// The source-compatible u32 entry point; see [`optimize_vertex_cache_strip_in_place_generic`] for selectable index widths.
#[inline]
pub fn optimize_vertex_cache_strip_in_place(
    indices: &mut [u32],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    optimize_vertex_cache_strip_in_place_generic::<u32>(indices, vertex_count, workspace)
}

/// The source-compatible u32 entry point; see [`optimize_vertex_cache_fifo_generic`] for selectable index widths.
#[inline]
pub fn optimize_vertex_cache_fifo(
    indices: &[u32],
    vertex_count: usize,
    cache_size: u32,
    workspace: &mut Workspace,
) -> Result<Vec<u32>, Error> {
    optimize_vertex_cache_fifo_generic::<u32>(indices, vertex_count, cache_size, workspace)
}

/// The source-compatible u32 entry point; see [`optimize_vertex_cache_fifo_into_generic`] for selectable index widths.
#[inline]
pub fn optimize_vertex_cache_fifo_into(
    destination: &mut [u32],
    indices: &[u32],
    vertex_count: usize,
    cache_size: u32,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    optimize_vertex_cache_fifo_into_generic::<u32>(
        destination,
        indices,
        vertex_count,
        cache_size,
        workspace,
    )
}

/// The source-compatible u32 entry point; see [`optimize_vertex_cache_fifo_in_place_generic`] for selectable index widths.
#[inline]
pub fn optimize_vertex_cache_fifo_in_place(
    indices: &mut [u32],
    vertex_count: usize,
    cache_size: u32,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    optimize_vertex_cache_fifo_in_place_generic::<u32>(indices, vertex_count, cache_size, workspace)
}