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
//! Ordered batches of independent sequential operations, using Rayon.
//!
//! Every successful item has exactly the sequential operation's meaningful
//! bytes, including float bits. There are no parallel reductions. Results stay
//! in input order, and an item's [`Error`] does not cancel other items. The outer
//! [`BatchResult`] error concerns only allocation of the result slots, before
//! any item runs. Panics follow Rayon's usual propagation rules.
//!
//! Each executing thread has a private [`Workspace`]. Scratch is cleared before
//! and after each item, so an earlier item's retained capacity cannot change a
//! later item's limit outcome. The supplied [`Limits`] apply independently to
//! each item. A LOD chain includes all its live output, scratch and cumulative
//! work in that budget. The batch result slots, caller inputs and Rayon's pool
//! infrastructure are excluded. There is no aggregate batch memory limit: all
//! successful outputs remain live until the caller drops them.
//!
//! [`encode_vertex_buffer_parallel`], [`decode_vertex_buffer_parallel`] and
//! [`build_meshlets_spatial_parallel`] instead split one large input over the
//! pool, with output byte-identical to the serial function for every pool size.
//!
//! Work uses the current Rayon pool (normally the global pool). Use
//! [`rayon::ThreadPool::install`] to select an existing pool; the crate does not
//! explicitly create pools. Rayon lazily initializes the global pool on first
//! use if none was configured; initialization failure panics inside Rayon,
//! rather than returning a per-item [`Error`]. Native threads are required for
//! parallel execution.
//!
//! ```
//! use meshoptimizer_rs::{parallel::{encode_buffers_batch, EncodeInput}, codec::IndexEncoding, Limits};
//! let indices = [0, 1, 2, 2, 1, 3];
//! let views = [EncodeInput::Triangles { indices: &indices, encoding: IndexEncoding::DEFAULT }];
//! let outputs = encode_buffers_batch(&views, Limits::default())?;
//! assert!(outputs[0].is_ok());
//! # Ok::<(), meshoptimizer_rs::Error>(())
//! ```
//!
//! ```
//! use meshoptimizer_rs::{parallel::{build_meshlets_batch, MeshletInput, MeshletBuilder},
//!     Limits, MeshletSettings, Positions};
//! let positions = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.]];
//! let indices = [0, 1, 2];
//! let inputs = [MeshletInput { indices: &indices, positions: Positions::from_packed(&positions),
//!     settings: MeshletSettings::default(), builder: MeshletBuilder::Scan }];
//! let pool = rayon::ThreadPoolBuilder::new().num_threads(2).build()?;
//! let outputs = pool.install(|| build_meshlets_batch(&inputs, Limits::default()))?;
//! assert_eq!(outputs[0].as_ref().unwrap().meshlets.len(), 1);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use crate::codec::{self, BufferView, IndexEncoding, VertexEncoding};
use crate::workspace::checked_bytes;
use crate::{
    Attributes, Error, Limits, MeshletSettings, Meshlets, MeshletsGeneric, Positions,
    SimplifiedMesh, SimplifiedMeshGeneric, SimplifySettings, VertexFlags, Workspace,
};
use alloc::vec::Vec;
use core::mem::size_of;
use rayon::prelude::*;
use std::cell::RefCell;

/// Ordered per-item results, or a result-slot allocation error before execution.
pub type BatchResult<T> = Result<Vec<Result<T, Error>>, Error>;

std::thread_local! {
    static WORKSPACE: RefCell<Workspace> = RefCell::new(Workspace::default());
}

fn slots<T>(count: usize) -> BatchResult<T> {
    checked_bytes(count, size_of::<Result<T, Error>>())?;
    let mut result = Vec::new();
    result
        .try_reserve_exact(count)
        .map_err(|_| Error::AllocationFailed)?;
    result.resize_with(count, || Err(Error::AllocationFailed));
    Ok(result)
}

fn item<T>(
    limits: Limits,
    run: impl FnOnce(&mut Workspace) -> Result<T, Error>,
) -> Result<T, Error> {
    WORKSPACE.with(|cell| {
        let mut workspace = cell.borrow_mut();
        workspace.set_limits(limits);
        let result = run(&mut workspace);
        workspace.clear();
        result
    })
}

fn batch<I: Sync, T: Send>(
    inputs: &[I],
    limits: Limits,
    run: impl Fn(&I, &mut Workspace) -> Result<T, Error> + Sync,
) -> BatchResult<T> {
    let mut result = slots(inputs.len())?;
    result
        .par_iter_mut()
        .zip(inputs.par_iter())
        .for_each(|(out, input)| {
            *out = item(limits, |workspace| run(input, workspace));
        });
    Ok(result)
}
#[cfg(feature = "clusterlod")]
fn batch_mut<I: Send, T: Send>(
    inputs: &mut [I],
    limits: Limits,
    run: impl Fn(&mut I, &mut Workspace) -> Result<T, Error> + Sync,
) -> BatchResult<T> {
    let mut result = slots(inputs.len())?;
    result
        .par_iter_mut()
        .zip(inputs.par_iter_mut())
        .for_each(|(out, input)| {
            *out = item(limits, |workspace| run(input, workspace));
        });
    Ok(result)
}

/// Optional attributes and flags used at every level of a LOD chain.
#[derive(Clone, Copy, Debug)]
pub struct LodAttributes<'a> {
    /// Attribute records for the unchanged full vertex array.
    pub attributes: Attributes<'a>,
    /// One weight per component.
    pub weights: &'a [f32],
    /// Optional per-vertex simplifier flags.
    pub vertex_flags: Option<&'a [VertexFlags]>,
}

/// One chain. Each level simplifies the preceding level's topology.
#[derive(Clone, Copy, Debug)]
pub struct LodChainInputGeneric<'a, I: crate::Index = u32> {
    /// Original triangle topology.
    pub indices: &'a [I],
    /// Full vertex positions; returned indices keep their original references.
    pub positions: Positions<'a>,
    /// Per-level settings, in execution order. Targets are index counts relative
    /// to that level's input. Error values are returned unchanged, not accumulated.
    pub levels: &'a [SimplifySettings],
    /// None selects plain simplification; Some selects attribute simplification.
    pub attributes: Option<LodAttributes<'a>>,
}

/// Sequential reference for [`simplify_lod_chains_batch`].
///
/// Calls [`crate::simplify`] or [`crate::simplify_with_attributes`] in level
/// order. No cache optimization, compaction or error adjustment is added.
/// Empty settings produce an empty chain without validating unused mesh data.
/// A failed level drops the entire chain. The workspace reports cumulative work
/// (including one visit per level) and peak live storage for the whole chain.
///
/// ```
/// use meshoptimizer_rs::{parallel::{simplify_lod_chain, LodChainInput}, Positions,
///     SimplifySettings, SimplifyOptions, Workspace};
/// let p = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.]];
/// let indices = [0, 1, 2];
/// let levels = [SimplifySettings { target_index_count: 3, target_error: 0.01,
///     options: SimplifyOptions::EMPTY }];
/// let chain = simplify_lod_chain(&LodChainInput { indices: &indices,
///     positions: Positions::from_packed(&p), levels: &levels, attributes: None },
///     &mut Workspace::default())?;
/// assert_eq!(chain[0].indices, indices);
/// # Ok::<(), meshoptimizer_rs::Error>(())
/// ```
///
/// # Errors
/// Same errors as [`crate::simplify_with_attributes`]. Limits apply to cumulative work and peak live storage for the chain.
pub fn simplify_lod_chain_generic<I: crate::Index>(
    input: &LodChainInputGeneric<'_, I>,
    workspace: &mut Workspace,
) -> Result<Vec<SimplifiedMeshGeneric<I>>, Error> {
    let mut work = workspace.begin();
    let result = (|| {
        let limits = workspace.limits();
        workspace.release_unused();
        let mut levels = crate::budget::Budget::new(workspace)
            .reserved::<SimplifiedMeshGeneric<I>>(input.levels.len())?;
        let mut live = checked_bytes(levels.capacity(), size_of::<SimplifiedMeshGeneric<I>>())?;
        let mut spent = 0u64;
        for &settings in input.levels {
            work.add(1)?;
            spent = spent.checked_add(1).ok_or(Error::SizeOverflow)?;
            let mut child = Workspace::new(Limits {
                max_bytes: limits
                    .max_bytes
                    .checked_sub(live)
                    .ok_or(Error::LimitExceeded)?,
                max_work: limits
                    .max_work
                    .checked_sub(spent)
                    .ok_or(Error::LimitExceeded)?,
            });
            let indices = levels.last().map_or(input.indices, |level| &level.indices);
            let result = match input.attributes {
                None => crate::simplify_generic(indices, input.positions, settings, &mut child),
                Some(a) => crate::simplify_with_attributes_generic(
                    indices,
                    input.positions,
                    a.attributes,
                    a.weights,
                    a.vertex_flags,
                    settings,
                    &mut child,
                ),
            };
            work.add_processing(child.usage().work)?;
            spent = spent
                .checked_add(child.usage().work)
                .ok_or(Error::SizeOverflow)?;
            workspace.charge_owned(
                live.checked_add(child.usage().bytes)
                    .ok_or(Error::SizeOverflow)?,
            )?;
            let level = result?;
            live = live
                .checked_add(checked_bytes(level.indices.capacity(), size_of::<I>())?)
                .ok_or(Error::SizeOverflow)?;
            levels.push(level);
        }
        Ok(levels)
    })();
    workspace.finish(&work);
    result
}

/// Simplify independent LOD chains in parallel, returning one result per chain.
/// Levels within each chain retain the sequential reference's order and budget.
///
/// # Errors
/// Outer `SizeOverflow` or `AllocationFailed` if result-slot allocation fails;
/// per-item errors are those of [`simplify_lod_chain`] and do not cancel other items.
///
/// # Panics
/// Panics if Rayon cannot initialize its thread pool or a worker panics.
pub fn simplify_lod_chains_batch_generic<I: crate::Index>(
    inputs: &[LodChainInputGeneric<'_, I>],
    limits: Limits,
) -> BatchResult<Vec<SimplifiedMeshGeneric<I>>> {
    batch(inputs, limits, simplify_lod_chain_generic)
}

/// An independent buffer to encode. Configuration is local to each descriptor.
#[derive(Clone, Copy, Debug)]
pub enum EncodeInputGeneric<'a, I: crate::Index = u32> {
    /// Initialized vertex bytes, including supplied padding.
    Vertices {
        /// Exact count times stride bytes.
        vertices: &'a [u8],
        /// Number of vertex records.
        count: usize,
        /// Record stride in bytes.
        stride: usize,
        /// Format version and compression level.
        encoding: VertexEncoding,
    },
    /// Triangle-list indices.
    Triangles {
        /// Topology in the selected index width.
        indices: &'a [I],
        /// Format version.
        encoding: IndexEncoding,
    },
    /// General index sequence.
    Sequence {
        /// Values in the selected index width.
        indices: &'a [I],
        /// Format version.
        encoding: IndexEncoding,
    },
}
impl<I: crate::Index> EncodeInputGeneric<'_, I> {
    /// Encode this descriptor through the corresponding sequential codec API.
    ///
    /// # Errors
    /// The selected [`crate::codec`] encoder's errors: `InvalidLayout`, `InvalidTopology`,
    /// `SizeOverflow`, `LimitExceeded` or `AllocationFailed`, for invalid input or exhausted resources.
    pub fn encode_generic(self, workspace: &mut Workspace) -> Result<Vec<u8>, Error> {
        match self {
            Self::Vertices {
                vertices,
                count,
                stride,
                encoding,
            } => codec::encode_vertex_buffer(vertices, count, stride, encoding, workspace),
            Self::Triangles { indices, encoding } => {
                codec::encode_index_buffer_generic(indices, encoding, workspace)
            }
            Self::Sequence { indices, encoding } => {
                codec::encode_index_sequence_generic(indices, encoding, workspace)
            }
        }
    }
}

/// Encode vertex, triangle and sequence buffers in input order.
///
/// # Errors
/// Outer `SizeOverflow` or `AllocationFailed` if result-slot allocation fails;
/// per-item errors are those of [`EncodeInput::encode`] and do not cancel other items.
///
/// # Panics
/// Panics if Rayon cannot initialize its thread pool or a worker panics.
pub fn encode_buffers_batch_generic<I: crate::Index>(
    inputs: &[EncodeInputGeneric<'_, I>],
    limits: Limits,
) -> BatchResult<Vec<u8>> {
    batch(inputs, limits, |input, workspace| {
        input.encode_generic(workspace)
    })
}

/// One checked EXT buffer view and its compressed bytes.
#[derive(Clone, Copy, Debug)]
pub struct DecodeInput<'a> {
    /// Mode, filter, count and stride; construct through [`BufferView::new`].
    pub view: BufferView,
    /// Compressed source bytes.
    pub source: &'a [u8],
}

/// Decode complete independent EXT views through [`BufferView::decode`].
///
/// # Errors
/// Outer `SizeOverflow` or `AllocationFailed` if result-slot allocation fails;
/// per-item errors are those of [`crate::codec::BufferView::decode`] and do not cancel other items.
///
/// # Panics
/// Panics if Rayon cannot initialize its thread pool or a worker panics.
pub fn decode_buffer_views_batch(
    inputs: &[DecodeInput<'_>],
    limits: Limits,
) -> BatchResult<Vec<u8>> {
    batch(inputs, limits, |input, workspace| {
        input.view.decode(input.source, workspace)
    })
}

/// Sequential builder selection for a meshlet batch item.
#[derive(Clone, Copy, Debug)]
pub enum MeshletBuilder {
    /// Consume triangles in source order; only the position count is used.
    Scan,
    /// Standard connectivity and cone-aware builder.
    Standard {
        /// Cone score weight.
        cone_weight: f32,
    },
    /// Flexible connectivity builder.
    Flex {
        /// Minimum triangles per meshlet.
        min_triangles: usize,
        /// Cone score weight.
        cone_weight: f32,
        /// Spatial split factor.
        split_factor: f32,
    },
    /// Surface-area heuristic spatial builder.
    Spatial {
        /// Minimum triangles per meshlet.
        min_triangles: usize,
        /// Fill weight.
        fill_weight: f32,
    },
}

/// Mesh and builder settings for one independent clustering operation.
#[derive(Clone, Copy, Debug)]
pub struct MeshletInputGeneric<'a, I: crate::Index = u32> {
    /// Triangle topology.
    pub indices: &'a [I],
    /// Full vertex positions.
    pub positions: Positions<'a>,
    /// Maximum vertices and triangles per meshlet.
    pub settings: MeshletSettings,
    /// Sequential algorithm and its parameters.
    pub builder: MeshletBuilder,
}
impl<I: crate::Index> MeshletInputGeneric<'_, I> {
    /// Run this descriptor through the selected sequential meshlet builder.
    ///
    /// # Errors
    /// Same errors as [`crate::build_meshlets`]. The selected builder validates its own parameters.
    pub fn build_generic(self, workspace: &mut Workspace) -> Result<MeshletsGeneric<I>, Error> {
        let Self {
            indices,
            positions,
            settings,
            builder,
        } = self;
        match builder {
            MeshletBuilder::Scan => {
                crate::build_meshlets_scan_generic(indices, positions.len(), settings, workspace)
            }
            MeshletBuilder::Standard { cone_weight } => {
                crate::build_meshlets_generic(indices, positions, settings, cone_weight, workspace)
            }
            MeshletBuilder::Flex {
                min_triangles,
                cone_weight,
                split_factor,
            } => crate::build_meshlets_flex_generic(
                indices,
                positions,
                settings,
                min_triangles,
                cone_weight,
                split_factor,
                workspace,
            ),
            MeshletBuilder::Spatial {
                min_triangles,
                fill_weight,
            } => crate::build_meshlets_spatial_generic(
                indices,
                positions,
                settings,
                min_triangles,
                fill_weight,
                workspace,
            ),
        }
    }
}

/// Build meshlets for independent meshes, preserving descriptors and packed bytes.
///
/// # Errors
/// Outer `SizeOverflow` or `AllocationFailed` if result-slot allocation fails;
/// per-item errors are those of [`MeshletInput::build`] and do not cancel other items.
///
/// # Panics
/// Panics if Rayon cannot initialize its thread pool or a worker panics.
pub fn build_meshlets_batch_generic<I: crate::Index>(
    inputs: &[MeshletInputGeneric<'_, I>],
    limits: Limits,
) -> BatchResult<MeshletsGeneric<I>> {
    batch(inputs, limits, |input, workspace| {
        input.build_generic(workspace)
    })
}

/// One independent cluster-LOD build, including its exclusive mutable positions.
#[cfg(feature = "clusterlod")]
pub struct ClusterLodInputGeneric<'a, I: crate::Index = u32> {
    /// Complete pinned-demo configuration.
    pub config: crate::clusterlod::Config,
    /// Mesh input; dilation can mutate positions even when this item fails.
    pub mesh: crate::clusterlod::MeshGeneric<'a, I>,
}

/// Build independent cluster-LOD DAGs in parallel using [`crate::clusterlod::build`].
///
/// Each mesh retains the demo's group/cluster order and refinement identifiers.
/// Dilation has the same partial-mutation contract as the sequential builder.
/// Groups within a mesh stay sequential: shared dilation and later refinement
/// consume earlier results. Parallelism is across meshes with disjoint positions.
///
/// # Errors
/// Outer `SizeOverflow` or `AllocationFailed` if result-slot allocation fails;
/// per-item errors are those of [`crate::clusterlod::build`] and do not cancel other items.
///
/// # Panics
/// Panics if Rayon cannot initialize its thread pool or a worker panics.
#[cfg(feature = "clusterlod")]
pub fn build_cluster_lod_batch_generic<I: crate::Index>(
    inputs: &mut [ClusterLodInputGeneric<'_, I>],
    limits: Limits,
) -> BatchResult<Vec<crate::clusterlod::GroupOutputGeneric<I>>> {
    let mut result = slots(inputs.len())?;
    result
        .par_iter_mut()
        .zip(inputs.par_iter_mut())
        .for_each(|(out, input)| {
            *out = item(limits, |workspace| {
                crate::clusterlod::build_generic(
                    input.config,
                    crate::clusterlod::MeshGeneric {
                        indices: input.mesh.indices,
                        positions: &mut *input.mesh.positions,
                        attributes: input.mesh.attributes,
                        vertex_lock: input.mesh.vertex_lock,
                        attribute_weights: input.mesh.attribute_weights,
                        attribute_protect_mask: input.mesh.attribute_protect_mask,
                    },
                    workspace,
                )
            });
        });
    Ok(result)
}

/// One independent cluster-LOD spatial forest.
#[cfg(feature = "clusterlod")]
#[derive(Clone, Copy, Debug)]
pub struct ClusterHierarchyInput<'a> {
    /// Groups in sequential callback order.
    pub groups: &'a [crate::clusterlod::Group],
    /// Maximum children per node, at least two.
    pub node_width: usize,
    /// Number of nonempty DAG levels.
    pub level_count: usize,
}

/// Build independent spatial forests using [`crate::clusterlod::build_hierarchy`].
///
/// Small batches (at most 256 total groups and 2048 group-by-level visits) run
/// sequentially on the calling thread to avoid dispatch overhead. Larger batches
/// use the current Rayon pool. Ordering, workspace reset and per-item limits are
/// identical on both paths. This cutoff is a workload heuristic, not a speed guarantee.
///
/// # Errors
/// Outer `SizeOverflow` or `AllocationFailed` if result-slot allocation fails;
/// per-item errors are those of [`crate::clusterlod::build_hierarchy`] and do not cancel other items.
///
/// # Panics
/// Panics if Rayon cannot initialize its thread pool or a worker panics.
#[cfg(feature = "clusterlod")]
pub fn build_cluster_hierarchies_batch(
    inputs: &[ClusterHierarchyInput<'_>],
    limits: Limits,
) -> BatchResult<Vec<crate::clusterlod::Node>> {
    // D158: the measured 231-group/1848-visit family does not amortize
    // Rayon dispatch. Saturate this heuristic; validation stays per item.
    let (groups, visits) = inputs.iter().fold((0usize, 0usize), |(groups, visits), i| {
        (
            groups.saturating_add(i.groups.len()),
            visits.saturating_add(i.groups.len().saturating_mul(i.level_count.max(1))),
        )
    });
    let run = |input: &ClusterHierarchyInput<'_>, workspace: &mut Workspace| {
        crate::clusterlod::build_hierarchy(
            input.groups,
            input.node_width,
            input.level_count,
            workspace,
        )
    };
    if groups <= 256 && visits <= 2048 {
        let mut result = slots(inputs.len())?;
        for (out, input) in result.iter_mut().zip(inputs) {
            *out = item(limits, |workspace| run(input, workspace));
        }
        Ok(result)
    } else {
        batch(inputs, limits, run)
    }
}

/// One canonical caller-buffer DAG build, including exclusive positions and output.
#[cfg(feature = "clusterlod")]
pub struct DagBuildInputGeneric<'a, I: crate::Index = u32> {
    /// Complete pinned-demo configuration.
    pub config: crate::clusterlod::Config,
    /// Mesh input; dilation may mutate positions even on failure.
    pub mesh: crate::clusterlod::MeshGeneric<'a, I>,
    /// Maximum children per spatial node, at least two.
    pub node_width: usize,
    /// Caller storage; publish only successful returned prefixes.
    pub destination: crate::clusterlod::DagBuffersGeneric<'a, I>,
}

/// Build independent DAGs into caller buffers, retaining ordered item results.
///
/// Slot allocation fails before any mesh executes. Item errors do not cancel
/// peers. Each worker uses one workspace; each item shares its limits across
/// construction, flattening and hierarchy. Caller buffers, result slots and
/// Rayon infrastructure are excluded; there is no aggregate memory guarantee.
/// Late errors can write output prefixes and mutate positions through dilation.
///
/// # Errors
/// Outer `SizeOverflow` or `AllocationFailed` if result-slot allocation fails;
/// per-item errors are those of [`crate::clusterlod::build_dag_into`] and do not cancel other items.
///
/// # Panics
/// Panics if Rayon cannot initialize its thread pool or a worker panics.
#[cfg(feature = "clusterlod")]
pub fn build_dags_batch_into_generic<I: crate::Index>(
    inputs: &mut [DagBuildInputGeneric<'_, I>],
    limits: Limits,
) -> BatchResult<crate::clusterlod::DagCounts> {
    let mut result = slots(inputs.len())?;
    result
        .par_iter_mut()
        .zip(inputs.par_iter_mut())
        .for_each(|(out, input)| {
            *out = item(limits, |workspace| {
                crate::clusterlod::build_dag_into_generic(
                    input.config,
                    crate::clusterlod::MeshGeneric {
                        indices: input.mesh.indices,
                        positions: &mut *input.mesh.positions,
                        attributes: input.mesh.attributes,
                        vertex_lock: input.mesh.vertex_lock,
                        attribute_weights: input.mesh.attribute_weights,
                        attribute_protect_mask: input.mesh.attribute_protect_mask,
                    },
                    input.node_width,
                    crate::clusterlod::DagBuffersGeneric {
                        vertex_source: &mut *input.destination.vertex_source,
                        vertex_positions: &mut *input.destination.vertex_positions,
                        indices: &mut *input.destination.indices,
                        clusters: &mut *input.destination.clusters,
                        groups: &mut *input.destination.groups,
                        nodes: &mut *input.destination.nodes,
                    },
                    workspace,
                )
            });
        });
    Ok(result)
}

/// The source-compatible u32 entry point; see [`simplify_lod_chain_generic`] for selectable index widths.
#[inline]
pub fn simplify_lod_chain(
    input: &LodChainInput<'_>,
    workspace: &mut Workspace,
) -> Result<Vec<SimplifiedMesh>, Error> {
    simplify_lod_chain_generic::<u32>(&(*input).into(), workspace)
        .map(|values| values.into_iter().map(Into::into).collect())
}

/// Encode one large vertex buffer on the current Rayon pool. Not in C++ meshoptimizer.
///
/// The bytes equal [`codec::encode_vertex_buffer`] for every pool size: the
/// format's block bodies depend only on the input and the per-channel
/// estimates, so runs of blocks and the estimators run concurrently and the
/// results concatenate in order. A pool of one worker, or a buffer of fewer
/// than eight blocks, takes the serial path unchanged. Limits are accounted as
/// in the serial encoder (the worst-case bound); the transient per-run buffers
/// are not additionally accounted.
///
/// # Errors
/// Those of [`codec::encode_vertex_buffer`].
///
/// # Panics
/// Panics if Rayon cannot initialize its thread pool or a worker panics.
pub fn encode_vertex_buffer_parallel(
    vertices: &[u8],
    count: usize,
    stride: usize,
    encoding: VertexEncoding,
    workspace: &mut Workspace,
) -> Result<Vec<u8>, Error> {
    codec::encode_vertex_buffer_parallel(vertices, count, stride, encoding, workspace)
}

/// Decode one large vertex buffer on the current Rayon pool. Not in C++ meshoptimizer.
///
/// The output and the error equal [`codec::decode_vertex_buffer`] for every
/// pool size. Each block starts from the previous block's last vertex, but a
/// decoded block is linear in that vertex (every channel is a prefix sum or
/// prefix xor), so runs of blocks decode from a zero baseline concurrently
/// after a serial scan of the group selectors, and their true baselines are
/// chained and applied afterwards. A malformed stream is judged by the serial
/// decoder. The scan of the group headers is serial and costs about a third of
/// a serial decode, so the serial decoder runs instead (never slower) when the
/// pool has fewer than four workers, the output is under 48 MiB (32 MiB for
/// strides of 8 or less, which are highly compressible), or it has fewer than
/// eight blocks. The output buffer is zero-initialized lazily, so its pages are first touched
/// by the workers.
///
/// # Errors
/// Those of [`codec::decode_vertex_buffer`].
///
/// # Panics
/// Panics if Rayon cannot initialize its thread pool or a worker panics.
pub fn decode_vertex_buffer_parallel(
    count: usize,
    stride: usize,
    source: &[u8],
    workspace: &mut Workspace,
) -> Result<Vec<u8>, Error> {
    codec::decode_vertex_buffer_parallel(count, stride, source, workspace)
}

/// Build SAH-spatial meshlets for one large mesh on the current Rayon pool. Not in C++ meshoptimizer.
///
/// The meshlets, vertices, triangles and counted work equal
/// [`crate::build_meshlets_spatial_generic`]'s for every pool size: the box,
/// sort and recursive cut stages run concurrently on independent subtrees, and
/// the final meshlet emission, which is a serial scan, runs in the fixed
/// triangle order. Scan and flex builders keep an open meshlet across the whole
/// triangle sequence, so no exactly equal parallel form exists for them.
///
/// Only a workspace with `max_bytes == usize::MAX` and `max_work == u64::MAX`
/// uses the concurrent path, as in cluster LOD, because per-worker scratch is
/// not counted. Any other workspace, or a one-worker pool, runs the serial
/// builder. [`Workspace::usage`] work matches serial; its bytes count only the
/// serial algorithm's storage and exclude concurrent scratch.
///
/// # Errors
/// Those of [`crate::build_meshlets_spatial_generic`].
///
/// # Panics
/// Panics if Rayon cannot initialize its thread pool or a worker panics.
#[inline]
pub fn build_meshlets_spatial_parallel_generic<I: crate::Index>(
    indices: &[I],
    p: Positions<'_>,
    s: MeshletSettings,
    min_triangles: usize,
    fill_weight: f32,
    workspace: &mut Workspace,
) -> Result<MeshletsGeneric<I>, Error> {
    crate::meshlet::build_meshlets_spatial_parallel_generic(
        indices,
        p,
        s,
        min_triangles,
        fill_weight,
        workspace,
    )
}

/// The source-compatible u32 entry point; see [`build_meshlets_spatial_parallel_generic`] for selectable index widths.
///
/// # Errors
/// Those of [`crate::build_meshlets_spatial`].
///
/// # Panics
/// Panics if Rayon cannot initialize its thread pool or a worker panics.
#[inline]
pub fn build_meshlets_spatial_parallel(
    indices: &[u32],
    p: Positions<'_>,
    s: MeshletSettings,
    min_triangles: usize,
    fill_weight: f32,
    workspace: &mut Workspace,
) -> Result<Meshlets, Error> {
    build_meshlets_spatial_parallel_generic::<u32>(
        indices,
        p,
        s,
        min_triangles,
        fill_weight,
        workspace,
    )
    .map(Into::into)
}

/// The source-compatible u32 entry point; see [`simplify_lod_chains_batch_generic`] for selectable index widths.
#[inline]
pub fn simplify_lod_chains_batch(
    inputs: &[LodChainInput<'_>],
    limits: Limits,
) -> BatchResult<Vec<SimplifiedMesh>> {
    batch(inputs, limits, simplify_lod_chain)
}

/// The source-compatible u32 entry point; see [`encode_buffers_batch_generic`] for selectable index widths.
#[inline]
pub fn encode_buffers_batch(inputs: &[EncodeInput<'_>], limits: Limits) -> BatchResult<Vec<u8>> {
    batch(inputs, limits, |input, workspace| input.encode(workspace))
}

/// The source-compatible u32 entry point; see [`build_meshlets_batch_generic`] for selectable index widths.
#[inline]
pub fn build_meshlets_batch(inputs: &[MeshletInput<'_>], limits: Limits) -> BatchResult<Meshlets> {
    batch(inputs, limits, |input, workspace| input.build(workspace))
}

/// The source-compatible u32 entry point; see [`build_cluster_lod_batch_generic`] for selectable index widths.
#[cfg(feature = "clusterlod")]
#[inline]
pub fn build_cluster_lod_batch(
    inputs: &mut [ClusterLodInput<'_>],
    limits: Limits,
) -> BatchResult<Vec<crate::clusterlod::GroupOutput>> {
    batch_mut(inputs, limits, |input, workspace| {
        crate::clusterlod::build(
            input.config,
            crate::clusterlod::Mesh {
                indices: input.mesh.indices,
                positions: input.mesh.positions,
                attributes: input.mesh.attributes,
                vertex_lock: input.mesh.vertex_lock,
                attribute_weights: input.mesh.attribute_weights,
                attribute_protect_mask: input.mesh.attribute_protect_mask,
            },
            workspace,
        )
    })
}

/// The source-compatible u32 entry point; see [`build_dags_batch_into_generic`] for selectable index widths.
#[cfg(feature = "clusterlod")]
#[inline]
pub fn build_dags_batch_into(
    inputs: &mut [DagBuildInput<'_>],
    limits: Limits,
) -> BatchResult<crate::clusterlod::DagCounts> {
    batch_mut(inputs, limits, |input, workspace| {
        crate::clusterlod::build_dag_into(
            input.config,
            crate::clusterlod::Mesh {
                indices: input.mesh.indices,
                positions: input.mesh.positions,
                attributes: input.mesh.attributes,
                vertex_lock: input.mesh.vertex_lock,
                attribute_weights: input.mesh.attribute_weights,
                attribute_protect_mask: input.mesh.attribute_protect_mask,
            },
            input.node_width,
            crate::clusterlod::DagBuffers {
                vertex_source: input.destination.vertex_source,
                vertex_positions: input.destination.vertex_positions,
                indices: input.destination.indices,
                clusters: input.destination.clusters,
                groups: input.destination.groups,
                nodes: input.destination.nodes,
            },
            workspace,
        )
    })
}

impl MeshletInput<'_> {
    /// Source-compatible u32 operation.
    #[inline]
    pub fn build(self, workspace: &mut Workspace) -> Result<Meshlets, Error> {
        MeshletInputGeneric::from(self)
            .build_generic(workspace)
            .map(Into::into)
    }
}

/// The source-compatible u32 form of [`LodChainInputGeneric`].
/// One chain. Each level simplifies the preceding level's topology.
#[derive(Clone, Copy, Debug)]
pub struct LodChainInput<'a> {
    /// Original triangle topology.
    pub indices: &'a [u32],
    /// Full vertex positions; returned indices keep their original references.
    pub positions: Positions<'a>,
    /// Per-level settings, in execution order. Targets are index counts relative
    /// to that level's input. Error values are returned unchanged, not accumulated.
    pub levels: &'a [SimplifySettings],
    /// None selects plain simplification; Some selects attribute simplification.
    pub attributes: Option<LodAttributes<'a>>,
}
impl<'a> From<LodChainInputGeneric<'a, u32>> for LodChainInput<'a> {
    #[inline]
    fn from(value: LodChainInputGeneric<'a, u32>) -> Self {
        Self {
            indices: value.indices,
            positions: value.positions,
            levels: value.levels,
            attributes: value.attributes,
        }
    }
}

impl<'a> From<LodChainInput<'a>> for LodChainInputGeneric<'a, u32> {
    #[inline]
    fn from(value: LodChainInput<'a>) -> Self {
        Self {
            indices: value.indices,
            positions: value.positions,
            levels: value.levels,
            attributes: value.attributes,
        }
    }
}

/// The source-compatible u32 form of [`MeshletInputGeneric`].
/// Mesh and builder settings for one independent clustering operation.
#[derive(Clone, Copy, Debug)]
pub struct MeshletInput<'a> {
    /// Triangle topology.
    pub indices: &'a [u32],
    /// Full vertex positions.
    pub positions: Positions<'a>,
    /// Maximum vertices and triangles per meshlet.
    pub settings: MeshletSettings,
    /// Sequential algorithm and its parameters.
    pub builder: MeshletBuilder,
}
impl<'a> From<MeshletInputGeneric<'a, u32>> for MeshletInput<'a> {
    #[inline]
    fn from(value: MeshletInputGeneric<'a, u32>) -> Self {
        Self {
            indices: value.indices,
            positions: value.positions,
            settings: value.settings,
            builder: value.builder,
        }
    }
}

impl<'a> From<MeshletInput<'a>> for MeshletInputGeneric<'a, u32> {
    #[inline]
    fn from(value: MeshletInput<'a>) -> Self {
        Self {
            indices: value.indices,
            positions: value.positions,
            settings: value.settings,
            builder: value.builder,
        }
    }
}

/// The source-compatible u32 form of [`ClusterLodInputGeneric`].
/// One independent cluster-LOD build, including its exclusive mutable positions.
#[cfg(feature = "clusterlod")]
pub struct ClusterLodInput<'a> {
    /// Complete pinned-demo configuration.
    pub config: crate::clusterlod::Config,
    /// Mesh input; dilation can mutate positions even when this item fails.
    pub mesh: crate::clusterlod::Mesh<'a>,
}
#[cfg(feature = "clusterlod")]
impl<'a> From<ClusterLodInputGeneric<'a, u32>> for ClusterLodInput<'a> {
    #[inline]
    fn from(value: ClusterLodInputGeneric<'a, u32>) -> Self {
        Self {
            config: value.config,
            mesh: value.mesh.into(),
        }
    }
}

#[cfg(feature = "clusterlod")]
impl<'a> From<ClusterLodInput<'a>> for ClusterLodInputGeneric<'a, u32> {
    #[inline]
    fn from(value: ClusterLodInput<'a>) -> Self {
        Self {
            config: value.config,
            mesh: value.mesh.into(),
        }
    }
}

/// The source-compatible u32 form of [`DagBuildInputGeneric`].
/// One canonical caller-buffer DAG build, including exclusive positions and output.
#[cfg(feature = "clusterlod")]
pub struct DagBuildInput<'a> {
    /// Complete pinned-demo configuration.
    pub config: crate::clusterlod::Config,
    /// Mesh input; dilation may mutate positions even on failure.
    pub mesh: crate::clusterlod::Mesh<'a>,
    /// Maximum children per spatial node, at least two.
    pub node_width: usize,
    /// Caller storage; publish only successful returned prefixes.
    pub destination: crate::clusterlod::DagBuffers<'a>,
}
#[cfg(feature = "clusterlod")]
impl<'a> From<DagBuildInputGeneric<'a, u32>> for DagBuildInput<'a> {
    #[inline]
    fn from(value: DagBuildInputGeneric<'a, u32>) -> Self {
        Self {
            config: value.config,
            mesh: value.mesh.into(),
            node_width: value.node_width,
            destination: value.destination.into(),
        }
    }
}

#[cfg(feature = "clusterlod")]
impl<'a> From<DagBuildInput<'a>> for DagBuildInputGeneric<'a, u32> {
    #[inline]
    fn from(value: DagBuildInput<'a>) -> Self {
        Self {
            config: value.config,
            mesh: value.mesh.into(),
            node_width: value.node_width,
            destination: value.destination.into(),
        }
    }
}

/// An independent u32 buffer to encode; the source-compatible descriptor.
#[derive(Clone, Copy, Debug)]
pub enum EncodeInput<'a> {
    /// Initialized vertex bytes, including supplied padding.
    Vertices {
        /// Exact count times stride bytes.
        vertices: &'a [u8],
        /// Number of vertex records.
        count: usize,
        /// Record stride in bytes.
        stride: usize,
        /// Format version and compression level.
        encoding: VertexEncoding,
    },
    /// Triangle-list indices.
    Triangles {
        /// Topology in u32 form.
        indices: &'a [u32],
        /// Format version.
        encoding: IndexEncoding,
    },
    /// General index sequence.
    Sequence {
        /// Values in u32 form.
        indices: &'a [u32],
        /// Format version.
        encoding: IndexEncoding,
    },
}

impl EncodeInput<'_> {
    /// Encode this u32 descriptor through the shared generic implementation.
    pub fn encode(self, workspace: &mut Workspace) -> Result<Vec<u8>, Error> {
        let generic = match self {
            Self::Vertices {
                vertices,
                count,
                stride,
                encoding,
            } => EncodeInputGeneric::Vertices {
                vertices,
                count,
                stride,
                encoding,
            },
            Self::Triangles { indices, encoding } => {
                EncodeInputGeneric::Triangles { indices, encoding }
            }
            Self::Sequence { indices, encoding } => {
                EncodeInputGeneric::Sequence { indices, encoding }
            }
        };
        generic.encode_generic(workspace)
    }
}