Expand description
A Rust port of meshoptimizer 1.3.
Every ported function produces byte-identical output to meshoptimizer 1.3 (scalar build). Differential runs against the C++ library, seeded sweeps, fuzzing and a wasm32 identity check prove this on the recorded inputs.
The crate is safe Rust except for one module, codec::simd, which holds the SIMD kernels for vertex decoding, EXT filters and meshlet decoding. Every unsafe block there has a written safety argument, and every SIMD path must produce the same bytes as the scalar safe-Rust path, which is the reference and the fallback. Build with default-features = false (adding std if needed) to compile no unsafe code; output is identical. Cargo feature unification applies: if any other crate in the dependency graph enables simd, the module is compiled for the whole graph. Simplification, optimization, index decoding and all encoders contain no unsafe in either configuration. See the safety audit.
The crate needs no C++ toolchain.
It supports no_std with alloc. Invalid input returns a typed Error
instead of undefined behaviour. A reusable Workspace holds scratch
memory, makes every allocation fallible and enforces per-call memory and
work Limits.
This is an independent project. It is not affiliated with meshoptimizer or its author. Coverage, measured performance and the parity records are in the README.
Coverage includes vertex processing, simplification, meshlets, codecs,
analyzers, opacity maps, tangents, normals, remeshing, parallel batches
and SIMD decoding.
Cluster-LOD requires clusterlod; batches require parallel and std.
Normal generation and remeshing require experimental.
§Recipes
- Non-packed positions.
- Simplify one mesh.
- Per-mesh LOD chain.
- Meshlets with bounds.
- Vertex and index encode and decode.
- Untrusted input with Limits.
- Parallel workers.
- Lower peak memory with Retention::Lean.
§Simplify a mesh
use meshoptimizer_rs::{simplify, Positions, SimplifyOptions, SimplifySettings, Workspace};
let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0]];
let indices = [0, 1, 2, 2, 1, 3];
let mut workspace = Workspace::default();
let settings = SimplifySettings {
target_index_count: 3,
target_error: 0.01,
options: SimplifyOptions::EMPTY,
};
let lod = simplify(&indices, Positions::from_packed(&positions), settings, &mut workspace)?;
println!("{} indices, relative error {}", lod.indices.len(), lod.error);§Optimize for the vertex cache, then for overdraw
use meshoptimizer_rs::{optimize_overdraw, optimize_vertex_cache, Positions, Workspace};
let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0]];
let indices = [0, 1, 2, 2, 1, 3];
let mut workspace = Workspace::default();
let cached = optimize_vertex_cache(&indices, positions.len(), &mut workspace)?;
let ordered = optimize_overdraw(&cached, Positions::from_packed(&positions), 1.05, &mut workspace)?;
assert_eq!(ordered.len(), indices.len());§Build meshlets
use meshoptimizer_rs::{build_meshlets, MeshletSettings, Positions, Workspace};
let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0]];
let indices = [0, 1, 2, 2, 1, 3];
let mut workspace = Workspace::default();
// 64 vertices and 124 triangles per meshlet; cone weight 0.25.
let built = build_meshlets(
&indices,
Positions::from_packed(&positions),
MeshletSettings::default(),
0.25,
&mut workspace,
)?;
for meshlet in &built.meshlets {
let start = meshlet.vertex_offset as usize;
let vertices = &built.vertices[start..start + meshlet.vertex_count as usize];
println!("{} triangles over vertices {:?}", meshlet.triangle_count, vertices);
}§Compress vertex and index buffers
The codec module reads and writes the EXT_meshopt_compression formats.
Buffers are little-endian bytes. The format version and level are set per
call instead of through global setters.
use meshoptimizer_rs::codec::{
decode_index_buffer, decode_vertex_buffer, encode_index_buffer, encode_vertex_buffer,
IndexEncoding, VertexEncoding,
};
use meshoptimizer_rs::Workspace;
let positions: [[f32; 3]; 4] = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0]];
let indices = [0, 1, 2, 2, 1, 3];
let mut workspace = Workspace::default();
let vertex_bytes: Vec<u8> = positions.iter().flatten().flat_map(|v| v.to_le_bytes()).collect();
let packed = encode_vertex_buffer(&vertex_bytes, 4, 12, VertexEncoding::DEFAULT, &mut workspace)?;
assert_eq!(decode_vertex_buffer(4, 12, &packed, &mut workspace)?, vertex_bytes);
let packed = encode_index_buffer(&indices, IndexEncoding::DEFAULT, &mut workspace)?;
let decoded = decode_index_buffer(indices.len(), 4, &packed, &mut workspace)?; // u32 bytes
assert_eq!(decoded.len(), indices.len() * 4);§Features
std(default): implementsstd::error::ErrorforError. Disable default features forno_std; an allocator is still required.clusterlod: the cluster-LOD builder from upstream’sdemo/clusterlod.h. It reproduces the pinned demo exactly; it is not a stable upstream API.experimental: upstream functions and options marked experimental.parallel: ordered Rayon batch APIs for independent meshes and buffer views; enablesstd. See theparallelmodule for limits and error semantics.
Modules§
- clusterlod
- Pure-Rust port of the pinned upstream
demo/clusterlod.h(MIT, Arseny Kapoulkine). - codec
- meshoptimizer 1.3 codecs, with explicit little-endian byte buffers.
- guide
- Task recipes with complete, checked examples.
- parallel
- Ordered batches of independent sequential operations, using Rayon.
Structs§
- Attributes
- Checked borrowed attribute view with at most 32 components per vertex.
- Attributes
Mut - Checked mutable attribute components for destructive update simplification.
- Bounds
- Meaningful fields of
meshopt_Bounds, without native padding. - Bounds
Positions - A borrowed positions view whose bounds-validation scan is cached once.
- Coverage
Statistics - Result of
meshopt_analyzeCoverage. - Fetch
Indices - Borrowed fetch-remap input with its index-validation result cached once.
- Fetched
Mesh - Fetch-ordered initialized vertex bytes and rewritten indices.
- Limits
- Per-call limits for crate-owned heap storage and counted work.
- Local
Meshlet - Meshlet-local topology with first-visit vertex references.
- Meshlet
- Current 1.3 descriptor: triangle offsets are consecutive byte offsets, without padding.
- Meshlet
Settings - Limits used by all meshlet builders.
- Meshlet
Sizes - Used prefixes after caller-buffer meshlet construction.
- Meshlets
- Complete tightly packed meshlet output.
- Opacity
MapMeasure - Output of upstream
meshopt_opacityMapMeasure. - Overdraw
Statistics - Result of
meshopt_analyzeOverdraw. - Partitions
- Cluster-to-partition assignments in upstream order.
- Positions
- Checked borrowed XYZ view, preserving all supplied vertices, including unused ones.
- Positions
Mut - Checked mutable positions for destructive update simplification.
- Provoking
Mesh - Unique first-corner indices and source vertices for provoking-vertex rendering.
- Simplified
Mesh - Simplified topology referencing the original vertex array.
- Simplify
Options - Stable simplification options supported by this port.
- Simplify
Result - Caller-buffer simplification result.
- Simplify
Settings - Parameters for edge-collapse simplification.
- Usage
- Resource measurements for the most recent algorithm call.
- Vertex
Cache Statistics - Result of upstream
meshopt_analyzeVertexCache. - Vertex
Fetch Statistics - Result of upstream
meshopt_analyzeVertexFetch. - Vertex
Flags - Independent upstream simplification vertex flags; unknown bits are rejected.
- Vertex
Remap - A compact vertex numbering; unused vertices retain
u32::MAX. - Vertex
Stream - Initialized byte records used as binary equality keys. Supplied padding is part of equality; no typed object is reinterpreted as bytes.
- Workspace
- Reusable fallibly allocated scratch storage and per-call resource limits.
Enums§
- Byte
Order - Explicit byte order of floating-point components in byte-backed views.
- Error
- Checked input, resource, allocation, or numerical failure.
- Retention
- Policy for retaining reusable algorithm scratch between calls.
Constants§
- REMESH_
SHELL - Produce a two-sided surface shell.
- REMESH_
SOLVE - Solve the output positions using accumulated quadrics.
- TANGENT_
COMPATIBLE - Preserve MikkTSpace weighting instead of upstream’s area-weighted default.
- TANGENT_
ZERO_ FALLBACK - Emit zero tangents for isolated degenerate faces.
Functions§
- analyze_
coverage - Analyze projected coverage on three axes with the upstream rasterizer.
- analyze_
overdraw - Analyze raster overdraw with upstream’s 256-pixel viewport model.
- analyze_
vertex_ cache - Analyze a triangle list using upstream’s simplified FIFO transform cache.
- analyze_
vertex_ fetch - Analyze index order with upstream’s direct-mapped 128 KiB fetch-cache model.
- build_
meshlets meshopt_buildMeshlets: connectivity and cone-aware meshlets.- build_
meshlets_ bound meshopt_buildMeshletsBound: conservative descriptor capacity, with checked arithmetic.- build_
meshlets_ flex meshopt_buildMeshletsFlex: variable triangle counts and optional spatial splits.- build_
meshlets_ flex_ into - Caller-buffer flexible builder; a late failure may modify output prefixes.
- build_
meshlets_ into - Caller-buffer standard builder; a late failure may modify output prefixes.
- build_
meshlets_ scan meshopt_buildMeshletsScan: consume triangles in input order.- build_
meshlets_ scan_ into - Caller-buffer scan builder; a late work-limit failure may modify output prefixes.
- build_
meshlets_ spatial meshopt_buildMeshletsSpatial: surface-area heuristic meshlets for ray tracing.- build_
meshlets_ spatial_ into - Caller-buffer spatial builder; a late failure may modify output prefixes.
- compute_
cluster_ bounds meshopt_computeClusterBounds: sphere and conservative normal cone.- compute_
cluster_ bounds_ with_ positions - Compute cluster bounds using a cached positions-validation scan.
- compute_
meshlet_ bounds meshopt_computeMeshletBounds: bounds of byte-local triangles.- compute_
meshlet_ bounds_ with_ positions - Compute meshlet bounds using a cached positions-validation scan.
- compute_
position_ exponent - Compute the exponent of a conservative signed position grid.
Bounds must be finite and ordered;
min_expis at least -126 andmax_bitsis 2 through 24. Overflowing scaled bounds return an error. - compute_
sphere_ bounds meshopt_computeSphereBounds. Optional radii use a checked one-component view.- dequantize_
half - Expand a half value; flush half subnormals, preserve signed zero and NaN payloads.
- extract_
meshlet_ indices meshopt_extractMeshletIndices: preserve first-visit vertex order.- extract_
meshlet_ indices_ into - Caller-buffer extraction. Errors leave both destinations unchanged; tails are preserved.
- filter_
index_ buffer - Remove binary-degenerate and duplicate triangles; preserve surviving source corners and winding. Rotated duplicates are removed; reversed winding stays.
- filter_
index_ buffer_ into - Caller-buffer filtering. The tail is preserved; work exhaustion can leave partial output.
- filter_
index_ buffer_ multi - Multi-stream triangle filtering.
- filter_
index_ buffer_ multi_ into - Caller-buffer multi-stream filtering; late work exhaustion can leave partial output.
- generate_
adjacency_ index_ buffer - Generate six adjacency indices per triangle using binary position welding.
- generate_
adjacency_ index_ buffer_ into - Caller-buffer adjacency; requires twice input-length capacity. Late work exhaustion can leave partial output.
- generate_
normals - Experimental upstream
meshopt_generateNormals, exposed only withexperimental.Noneindices denote an unindexed triangle list. - generate_
normals_ into - Caller-buffer form of the experimental normal generator. The destination is unchanged if validation or allocation fails.
- generate_
position_ remap - Map each position to its first numerically equal vertex. Signed zeros weld; NaNs do not compare equal. The output refers to original indices.
- generate_
position_ remap_ into - Caller-buffer numerical position remap. The tail is preserved; work exhaustion can leave partial output.
- generate_
provoking_ index_ buffer - Generate a unique first-corner vertex for each triangle, with the same wrapping eight-bit valence heuristic and cyclic rotations as upstream.
- generate_
provoking_ index_ buffer_ into - Write provoking topology and used reorder prefix. Requires vertex-count plus triangle-count reorder capacity; work exhaustion can partially modify both outputs.
- generate_
shadow_ index_ buffer - Replace triangle references with first referenced binary-equal vertices.
- generate_
shadow_ index_ buffer_ into - Caller-buffer shadow indices; late work exhaustion can leave partial output.
- generate_
shadow_ index_ buffer_ multi - Multi-stream shadow indices, preserving original vertex numbering.
- generate_
shadow_ index_ buffer_ multi_ into - Caller-buffer multi-stream shadow indices; late work exhaustion can leave partial output.
- generate_
tangents - Generate per-corner XYZ plus handedness, matching
meshopt_generateTangents.Noneindices denote an unindexed triangle list. Normals and UVs are packed. - generate_
tangents_ into - Caller-buffer form of
meshopt_generateTangents; writes one vector per corner. The destination is unchanged if validation or allocation fails. - generate_
tessellation_ index_ buffer - Generate twelve tessellation indices per triangle using binary position welding.
- generate_
tessellation_ index_ buffer_ into - Caller-buffer tessellation; requires four times input-length capacity. Late work exhaustion can leave partial output.
- generate_
vertex_ remap - Generate compact numbering from tightly packed binary keys.
Nonevisits every vertex in original order; indexed input need not be a triangle list. - generate_
vertex_ remap_ custom - Generate compact numbering with a callback invoked only for numerically equal positions, in exactly upstream’s hash-probe order. Signed zeros weld.
- generate_
vertex_ remap_ custom_ into - Caller-buffer custom numbering with exact callback traversal. Work exhaustion can leave partial output.
- generate_
vertex_ remap_ into - Single-stream caller-buffer compact numbering.
- generate_
vertex_ remap_ multi - Generate compact numbering from one through sixteen initialized key streams.
- generate_
vertex_ remap_ multi_ into - Generate compact numbering into caller storage. The tail is untouched; work exhaustion may leave the used prefix partially modified.
- opacity_
map_ compact - Compact OMM data in place, as upstream
meshopt_opacityMapCompactdoes. - opacity_
map_ entry_ size - Packed byte count for one micromap, corresponding to
meshopt_opacityMapEntrySize. - opacity_
map_ measure - Deduplicate triangles by quantized UV and choose adaptive OMM levels.
- opacity_
map_ measure_ into - Caller-buffer form of
meshopt_opacityMapMeasure; returns unique entry count. The three destinations are unchanged when validation fails. - opacity_
map_ rasterize - Rasterize one upstream opacity entry using an alpha-channel byte view.
- opacity_
map_ rasterize_ into - Caller-buffer form of
meshopt_opacityMapRasterize. Returns the number of bytes written and preserves the destination on error. - optimize_
meshlet - Allocating
meshopt_optimizeMeshlet(level zero). - optimize_
meshlet_ in_ place - Atomic destructive
meshopt_optimizeMeshlet(level zero). - optimize_
meshlet_ into - Caller-buffer level-zero meshlet optimization, preserving unused tails.
- optimize_
meshlet_ level - Allocating
meshopt_optimizeMeshletLevel; unused vertex suffix stays unchanged. - optimize_
meshlet_ level_ in_ place meshopt_optimizeMeshletLevel: atomic destructive variant, levels 0 through 9.- optimize_
meshlet_ level_ into - Caller-buffer meshlet optimization. Errors leave destinations unchanged; suffixes beyond the supplied vertex and triangle lengths are preserved.
- optimize_
overdraw - Reorder cache-optimized triangles using upstream
meshopt_optimizeOverdraw. - optimize_
overdraw_ in_ place - Destructively apply upstream overdraw ordering, leaving input unchanged on error. A fallibly allocated temporary output counts toward the byte limit.
- optimize_
overdraw_ into - Write upstream overdraw ordering to the used prefix of a caller buffer.
- optimize_
vertex_ cache - Reorder triangles using upstream
meshopt_optimizeVertexCache(standard variant). - optimize_
vertex_ cache_ fifo - Optimize using upstream’s FIFO cache heuristic. Cache size is at least three.
- optimize_
vertex_ cache_ fifo_ in_ place - Destructively apply FIFO ordering, preserving indices on error.
- optimize_
vertex_ cache_ fifo_ into - Write FIFO cache ordering; work exhaustion may partially modify the prefix.
- optimize_
vertex_ cache_ in_ place - Destructively apply upstream standard cache ordering, leaving input unchanged on error. A fallibly allocated temporary output counts toward the byte limit.
- optimize_
vertex_ cache_ into - Write upstream standard cache ordering to the used prefix of
destination. - optimize_
vertex_ cache_ strip - Optimize cache ordering using upstream’s strip-oriented score table.
- optimize_
vertex_ cache_ strip_ in_ place - Destructively apply strip-oriented ordering, preserving indices on error.
- optimize_
vertex_ cache_ strip_ into - Write strip-oriented cache ordering; work exhaustion may partially modify the used prefix. The unused destination tail is untouched.
- optimize_
vertex_ fetch - Allocate first-use vertex bytes and rewritten arbitrary indices.
- optimize_
vertex_ fetch_ in_ place - Explicit destructive spelling for caller-buffer fetch optimization.
This is the same checked operation as
optimize_vertex_fetch_into. Write fetch-ordered bytes while rewriting indices in place. Validation and allocation precede writes; counted-work exhaustion may modify both buffers. - optimize_
vertex_ fetch_ into - Write fetch-ordered bytes while rewriting indices in place. Validation and allocation precede writes; counted-work exhaustion may modify both buffers.
- optimize_
vertex_ fetch_ remap - Generate first-use fetch numbering for an arbitrary index sequence.
- optimize_
vertex_ fetch_ remap_ into - Fetch numbering into caller storage. Unused vertices are
u32::MAX; work exhaustion may partially modify the used prefix. - optimize_
vertex_ fetch_ remap_ with_ indices - Generate first-use fetch numbering using cached index validation.
- optimize_
vertex_ fetch_ remap_ with_ indices_ into - Generate fetch numbering into caller storage using cached validation.
- partition_
clusters meshopt_partitionClusters. Clusters may contain arbitrary index lists; empty clusters are invalid. Positions are optional; without them only connected clusters merge.- partition_
clusters_ into - Caller-buffer cluster partitioning; a late failure may modify the used prefix.
- quantize_
float - Round to 0 through 23 mantissa bits. Preserve infinity and NaN payloads; flush all exponent-zero values, including negative zero, to positive zero.
- quantize_
half - Convert to upstream’s half representation, flushing subnormals and canonicalizing NaNs to signed quiet NaNs.
- quantize_
snorm - Quantize to a signed normalized integer with 1 through 31 bits. Infinities clamp; NaN follows upstream comparisons and becomes the minimum.
- quantize_
unorm - Quantize to an unsigned normalized integer with 0 through 30 bits. Infinities clamp; NaN follows upstream comparisons and becomes zero.
- remap_
index_ buffer - Allocate remapped indices.
- remap_
index_ buffer_ into - Remap arbitrary index sequences.
Noneremaps all vertices in order; references to the unused sentinel are rejected before writes. - remap_
vertex_ buffer - Allocate remapped tightly packed bytes, zero-initializing unmapped records.
- remap_
vertex_ buffer_ into - Remap initialized vertex bytes into caller storage. Repeated destinations use the last source record, matching upstream; unmapped records are untouched. Validation precedes writes; work exhaustion may leave partial output.
- remesh
- Allocate the upper bound, remesh, and return three vertices per output triangle.
- remesh_
bound - Return the upstream triangle-count upper bound with no output allocation.
- remesh_
into - Write up to
destination.len()/3triangles and return the full triangle count. A short destination receives a prefix, matching upstream’s partial-write rule. - simplify
- Allocate meshopt_simplify’s result, preserving upstream ordering and error bits. No welding, fetch compaction or cache optimization is applied to the result.
- simplify_
into - Write meshopt_simplify’s result into a caller buffer of at least input length. The tail after the input length is preserved. A late resource or numerical error may modify the input-length prefix; use the allocating API for atomicity.
- simplify_
points - Simplify points to original vertex indices using grid reservoirs. Optional colors are checked three-component views; all supplied values must be finite.
- simplify_
points_ into - Caller-buffer point reduction. Requires target-count capacity; work exhaustion may partially modify output.
- simplify_
prune - Remove disconnected components whose bounding-sphere radius is at most the relative error. Position welding is numerical, including signed zeros; unused positions affect bounds.
- simplify_
prune_ into - Caller-buffer component pruning. Requires input-length capacity; work exhaustion may partially modify output.
- simplify_
scale - Return meshopt_simplifyScale’s maximum axis extent, without an epsilon clamp. Empty and coincident positions return zero; non-finite inputs and overflowing extents return an error. This operation allocates no memory.
- simplify_
sloppy - Grid-based sloppy triangle simplification. Only
LOCKflags are accepted; target error and returned error are relative to the full position extent. - simplify_
sloppy_ into - Caller-buffer sloppy simplification. Requires input-length capacity; work exhaustion may partially modify output.
- simplify_
with_ attributes - Allocate meshopt_simplifyWithAttributes’s result. All three vertex flags are supported; weights must be finite and nonnegative, with one per component. Zero-weight components do not contribute to error. All supplied values must be finite, including unused vertices and zero-weight components.
- simplify_
with_ attributes_ into - Caller-buffer attribute simplification, with the same contracts as
simplify_with_attributesand the mutation guarantee ofsimplify_into. - simplify_
with_ update - Destructively simplify indices and solve surviving positions and weighted attributes. Late work or numerical failures may modify the index prefix; position and attribute writes start only after solving completes. Unused vertices, externally locked vertices and zero-weight attributes are preserved.
- simplify_
with_ update_ in_ place - Explicit destructive spelling for update simplification with mutable views.
This is the same checked operation as
simplify_with_update. Destructively simplify indices and solve surviving positions and weighted attributes. Late work or numerical failures may modify the index prefix; position and attribute writes start only after solving completes. Unused vertices, externally locked vertices and zero-weight attributes are preserved. - spatial_
cluster_ points meshopt_spatialClusterPoints: new-to-old permutation in fixed-size clusters.- spatial_
cluster_ points_ into - Caller-buffer point clustering; the unused tail is preserved.
- spatial_
sort_ remap meshopt_spatialSortRemap: old-to-new Morton remap.- spatial_
sort_ remap_ into - Caller-buffer Morton remap; the unused tail is preserved.
- spatial_
sort_ triangles meshopt_spatialSortTriangles: reorder complete triangles by centroid Morton order.- spatial_
sort_ triangles_ in_ place - Atomic in-place spatial triangle sorting.
- spatial_
sort_ triangles_ into - Caller-buffer spatial triangle sorting; the unused tail is preserved.
- stripify
- Convert triangles to an exact upstream strip. A nonzero
restart_indexenables restarts. - stripify_
bound - Worst-case output index count for
meshopt_stripify. - stripify_
into - Caller-buffer form of
meshopt_stripify; destination needs the bound capacity. - unstripify
- Convert a strip to triangles, skipping degenerate triangles as upstream does.
- unstripify_
bound - Worst-case output index count for
meshopt_unstripify. - unstripify_
into - Caller-buffer form of
meshopt_unstripify; destination needs the bound capacity. - validate_
vertex_ flags - Validate that optional vertex flags have exactly one entry per vertex.