meshoptimizer_rs/lib.rs
1//! A Rust port of [meshoptimizer](https://github.com/zeux/meshoptimizer) 1.3.
2//!
3//! Every ported function produces byte-identical output to meshoptimizer 1.3
4//! (scalar build). Differential runs against the C++ library, seeded sweeps,
5//! fuzzing and a wasm32 identity check prove this on the recorded inputs.
6//!
7//! The crate is safe Rust except for one module, `codec::simd`, which holds the SIMD kernels for vertex decoding, EXT filters, meshlet decoding and spatial meshlet box sweeps. 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](https://github.com/Tavrin/meshoptimizer-rs/blob/main/src/codec/simd/SAFETY.md).
8//!
9//! The crate needs no C++ toolchain.
10//! It supports `no_std` with `alloc`. Invalid input returns a typed [`Error`]
11//! instead of undefined behaviour. A reusable [`Workspace`] holds scratch
12//! memory, makes every allocation fallible and enforces per-call memory and
13//! work [`Limits`].
14//!
15//! This is an independent project. It is not affiliated with meshoptimizer or
16//! its author. Coverage, measured performance and the parity records are in the
17//! [README](https://github.com/Tavrin/meshoptimizer-rs#readme).
18//!
19//! Coverage includes vertex processing, simplification, meshlets, codecs,
20//! analyzers, opacity maps, tangents, normals, remeshing, parallel batches
21//! and SIMD decoding.
22//! Cluster-LOD building requires `clusterlod`; DAG serialization is always available.
23//! Batches require `parallel` and `std`.
24//! Normal generation and remeshing require `experimental`.
25//!
26//! # Index widths
27//!
28//! Existing names keep their u32 signatures. Add `_generic` to index-processing
29//! function and width-aware method names to select the sealed [`Index`] trait
30//! (`u16` or `u32`). For example, [`optimize_vertex_cache_generic`] accepts
31//! `&[u16]` and returns `Vec<u16>`. Output-only calls take a type argument,
32//! such as `simplify_points_generic::<u16>`. Narrowing returns
33//! [`Error::IndexOverflow`] instead of truncating.
34//! Width-aware structs use a `Generic` suffix, such as [`MeshletsGeneric`].
35//! Original struct names remain concrete u32 forms.
36//! Existing byte-oriented codec layouts retain their upstream conversion rules;
37//! the typed index APIs check narrowing.
38//! See the [16-bit recipe](guide#16-bit-vertex-indices).
39//!
40//! # Recipes
41//!
42//! - [Non-packed positions](guide#non-packed-positions).
43//! - [Simplify one mesh](guide#simplify-one-mesh).
44//! - [Per-mesh LOD chain](guide#per-mesh-lod-chain).
45//! - [Meshlets with bounds](guide#meshlets-with-bounds).
46//! - [Vertex and index encode and decode](guide#vertex-and-index-encode-and-decode).
47//! - [Streaming index sequences](guide#streaming-index-sequences) (an extension, not in C++ meshoptimizer).
48//! - [Untrusted input with Limits](guide#untrusted-input-with-limits).
49//! - [Parallel workers](guide#parallel-workers).
50//! - [Lower peak memory with Retention::Lean](guide#lower-peak-memory-with-retentionlean).
51//! - [Mesh repair](guide#mesh-repair) (an extension, not in C++ meshoptimizer).
52//!
53//! - [LOD quality and switch distances](guide#lod-quality-and-switch-distances) (not in C++ meshoptimizer).
54//! - [Hidden-surface removal](guide#hidden-surface-removal) (an extension, not in C++ meshoptimizer).
55//! - [Alpha-cutout card trimming](guide#alpha-cutout-card-trimming) (an extension, not in C++ meshoptimizer).
56//! - [Cluster LOD DAG files](guide#cluster-lod-dag-files) (an extension, not in C++ meshoptimizer).
57//! - [Parallel vertex codec and spatial meshlets](guide#parallel-vertex-codec-and-spatial-meshlets-for-one-large-mesh) (an extension, not in C++ meshoptimizer).
58//! - [Character LODs](guide#character-lods) (an extension, not in C++ meshoptimizer).
59//! - [One-call asset pipeline](guide#one-call-asset-pipeline) (an extension, not in C++ meshoptimizer).
60//! - [Incremental vertex and triangle decoding](guide#incremental-vertex-and-triangle-decoding) (an extension, not in C++ meshoptimizer).
61//!
62//! # Simplify a mesh
63//!
64//! ```
65//! use meshoptimizer_rs::{simplify, Positions, SimplifyOptions, SimplifySettings, Workspace};
66//!
67//! 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]];
68//! let indices = [0, 1, 2, 2, 1, 3];
69//! let mut workspace = Workspace::default();
70//!
71//! let settings = SimplifySettings {
72//! target_index_count: 3,
73//! target_error: 0.01,
74//! options: SimplifyOptions::EMPTY,
75//! };
76//! let lod = simplify(&indices, Positions::from_packed(&positions), settings, &mut workspace)?;
77//! println!("{} indices, relative error {}", lod.indices.len(), lod.error);
78//! # Ok::<(), meshoptimizer_rs::Error>(())
79//! ```
80//!
81//! # Optimize for the vertex cache, then for overdraw
82//!
83//! ```
84//! use meshoptimizer_rs::{optimize_overdraw, optimize_vertex_cache, Positions, Workspace};
85//!
86//! 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]];
87//! let indices = [0, 1, 2, 2, 1, 3];
88//! let mut workspace = Workspace::default();
89//!
90//! let cached = optimize_vertex_cache(&indices, positions.len(), &mut workspace)?;
91//! let ordered = optimize_overdraw(&cached, Positions::from_packed(&positions), 1.05, &mut workspace)?;
92//! assert_eq!(ordered.len(), indices.len());
93//! # Ok::<(), meshoptimizer_rs::Error>(())
94//! ```
95//!
96//! # Build meshlets
97//!
98//! ```
99//! use meshoptimizer_rs::{build_meshlets, MeshletSettings, Positions, Workspace};
100//!
101//! 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]];
102//! let indices = [0, 1, 2, 2, 1, 3];
103//! let mut workspace = Workspace::default();
104//!
105//! // 64 vertices and 124 triangles per meshlet; cone weight 0.25.
106//! let built = build_meshlets(
107//! &indices,
108//! Positions::from_packed(&positions),
109//! MeshletSettings::default(),
110//! 0.25,
111//! &mut workspace,
112//! )?;
113//! for meshlet in &built.meshlets {
114//! let start = meshlet.vertex_offset as usize;
115//! let vertices = &built.vertices[start..start + meshlet.vertex_count as usize];
116//! println!("{} triangles over vertices {:?}", meshlet.triangle_count, vertices);
117//! }
118//! # Ok::<(), meshoptimizer_rs::Error>(())
119//! ```
120//!
121//! # Compress vertex and index buffers
122//!
123//! The [`codec`] module reads and writes the `EXT_meshopt_compression` formats.
124//! Buffers are little-endian bytes. The format version and level are set per
125//! call instead of through global setters.
126//!
127//! ```
128//! use meshoptimizer_rs::codec::{
129//! decode_index_buffer, decode_vertex_buffer, encode_index_buffer, encode_vertex_buffer,
130//! IndexEncoding, VertexEncoding,
131//! };
132//! use meshoptimizer_rs::Workspace;
133//!
134//! 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]];
135//! let indices = [0, 1, 2, 2, 1, 3];
136//! let mut workspace = Workspace::default();
137//!
138//! let vertex_bytes: Vec<u8> = positions.iter().flatten().flat_map(|v| v.to_le_bytes()).collect();
139//! let packed = encode_vertex_buffer(&vertex_bytes, 4, 12, VertexEncoding::DEFAULT, &mut workspace)?;
140//! assert_eq!(decode_vertex_buffer(4, 12, &packed, &mut workspace)?, vertex_bytes);
141//!
142//! let packed = encode_index_buffer(&indices, IndexEncoding::DEFAULT, &mut workspace)?;
143//! let decoded = decode_index_buffer(indices.len(), 4, &packed, &mut workspace)?; // u32 bytes
144//! assert_eq!(decoded.len(), indices.len() * 4);
145//! # Ok::<(), meshoptimizer_rs::Error>(())
146//! ```
147//!
148//! # Features
149//!
150//! - `std` (default): implements `std::error::Error` for [`Error`]. Disable
151//! default features for `no_std`; an allocator is still required.
152//! - `clusterlod`: the cluster-LOD builder from upstream's `demo/clusterlod.h`.
153//! DAG serialization and flat record types are always available.
154//! It reproduces the pinned demo exactly; it is not a stable upstream API.
155//! - `experimental`: upstream functions and options marked experimental.
156//! - `parallel`: ordered Rayon batch APIs for independent meshes and buffer
157//! views, plus parallel vertex encode/decode and spatial meshlet building
158//! for one large input; enables `std`. See the `parallel` module for limits
159//! and error semantics.
160#![deny(unsafe_code)]
161#![cfg_attr(not(feature = "simd"), forbid(unsafe_code))]
162#![deny(
163 unsafe_op_in_unsafe_fn,
164 clippy::undocumented_unsafe_blocks,
165 clippy::multiple_unsafe_ops_per_block,
166 clippy::missing_safety_doc
167)]
168#![cfg_attr(not(feature = "std"), no_std)]
169#![deny(missing_docs)]
170
171extern crate alloc;
172
173/// Compiles and runs every `rust` block in the README as a doctest.
174#[cfg(doctest)]
175#[doc = include_str!("../README.md")]
176pub struct ReadmeDoctests;
177
178/// Compiles and runs the migration guide examples as doctests.
179#[cfg(doctest)]
180#[doc = include_str!("../docs/MIGRATING_FROM_MESHOPT.md")]
181pub struct MigrationDoctests;
182
183/// Task recipes with complete, checked examples.
184pub mod guide {
185 #![doc = include_str!("../docs/USING.md")]
186}
187
188mod budget;
189mod hidden;
190pub use hidden::{
191 remove_hidden_triangles, remove_hidden_triangles_generic, remove_hidden_triangles_into,
192 remove_hidden_triangles_into_generic, HiddenOptions, HiddenReport, HiddenViews, VisibleMesh,
193 VisibleMeshGeneric,
194};
195mod cutout;
196pub use cutout::{
197 trim_alpha_cards, trim_alpha_cards_generic, AlphaMask, AlphaWrap, CardTrimOptions,
198 CardTrimReport, TrimmedCards, TrimmedCardsGeneric,
199};
200
201mod impostor;
202pub use impostor::{
203 bake_impostor, bake_impostor_generic, impostor_switch_distance, ImpostorAlbedo, ImpostorAtlas,
204 ImpostorBlend, ImpostorBounds, ImpostorFrame, ImpostorGrid, ImpostorLayout, ImpostorOptions,
205 ImpostorReconstruct, ImpostorReport, ImpostorSwitch,
206};
207mod analyze;
208mod cache;
209pub mod codec;
210mod error;
211mod index;
212pub use index::Index;
213mod input;
214mod math;
215mod mesh_analysis;
216#[cfg(feature = "experimental")]
217mod normal;
218mod opacity;
219mod overdraw;
220mod quantize;
221mod remap;
222mod repair;
223mod sanitize;
224pub use repair::{
225 fill_holes, fill_holes_bound, fill_holes_generic, fill_holes_into, fill_holes_into_generic,
226 orient_faces, orient_faces_bound, orient_faces_generic, orient_faces_into,
227 orient_faces_into_generic, split_non_manifold_vertices, split_non_manifold_vertices_generic,
228 stitch_cracks, stitch_cracks_generic, weld_vertices, weld_vertices_bound, weld_vertices_into,
229 weld_vertices_into_generic, FillHolesReport, FilledMesh, FilledMeshGeneric, HoleLoop,
230 OrientReport, OrientedMesh, OrientedMeshGeneric, SplitVerticesReport, StitchReport,
231 TopologyRepairGeneric, WeldPolicy, WeldReport, WeldedVertices,
232};
233
234mod character;
235pub use character::{
236 build_character_lod_chain, simplify_character, CharacterInputs, CharacterLodChain,
237 CharacterLodMethod, CharacterLodSelection, CharacterOptions, CharacterSkin,
238};
239
240mod lod_quality;
241pub use lod_quality::{
242 measure_lod_chain_quality, measure_lod_chain_quality_generic, measure_lod_quality,
243 measure_lod_quality_generic, LodCamera, LodDistance, LodNormalDeviation, LodQuality,
244 LodQualityLevel, LodQualityMesh, LodQualityMeshGeneric, LodQualityOptions,
245};
246mod lod_chain;
247mod raster;
248#[cfg(feature = "experimental")]
249mod remesh;
250pub use lod_chain::{
251 build_lod_chain, build_lod_chain_generic, LodChain, LodChainAttributes, LodChainError,
252 LodChainGeneric, LodChainOptions, LodErrors, LodLevel, LodLevelGeneric, LodTargets,
253};
254mod simplify;
255mod strip;
256mod tangent;
257mod vertex_layout;
258mod workspace;
259pub use simplify::{
260 simplify, simplify_generic, simplify_into, simplify_into_generic, simplify_points,
261 simplify_points_generic, simplify_points_into, simplify_points_into_generic, simplify_prune,
262 simplify_prune_generic, simplify_prune_into, simplify_prune_into_generic, simplify_scale,
263 simplify_sloppy, simplify_sloppy_generic, simplify_sloppy_into, simplify_sloppy_into_generic,
264 simplify_with_attributes, simplify_with_attributes_generic, simplify_with_attributes_into,
265 simplify_with_attributes_into_generic, simplify_with_update, simplify_with_update_generic,
266 SimplifiedMesh, SimplifiedMeshGeneric, SimplifyOptions, SimplifyResult, SimplifySettings,
267};
268pub use vertex_layout::{VertexFieldSnapshot, VertexLayout, VertexLayoutError};
269
270pub use analyze::{
271 analyze_vertex_cache, analyze_vertex_cache_generic, analyze_vertex_fetch,
272 analyze_vertex_fetch_generic, VertexCacheStatistics, VertexFetchStatistics,
273};
274pub use cache::{
275 optimize_vertex_cache, optimize_vertex_cache_fifo, optimize_vertex_cache_fifo_generic,
276 optimize_vertex_cache_fifo_in_place, optimize_vertex_cache_fifo_in_place_generic,
277 optimize_vertex_cache_fifo_into, optimize_vertex_cache_fifo_into_generic,
278 optimize_vertex_cache_generic, optimize_vertex_cache_in_place,
279 optimize_vertex_cache_in_place_generic, optimize_vertex_cache_into,
280 optimize_vertex_cache_into_generic, optimize_vertex_cache_strip,
281 optimize_vertex_cache_strip_generic, optimize_vertex_cache_strip_in_place,
282 optimize_vertex_cache_strip_in_place_generic, optimize_vertex_cache_strip_into,
283 optimize_vertex_cache_strip_into_generic, optimize_vertex_cache_with_table,
284 optimize_vertex_cache_with_table_generic, optimize_vertex_cache_with_table_into,
285 optimize_vertex_cache_with_table_into_generic, VertexScoreTable,
286};
287pub use error::Error;
288pub use input::{
289 validate_vertex_flags, Attributes, AttributesMut, ByteOrder, Positions, PositionsMut,
290 VertexFlags,
291};
292pub use mesh_analysis::{
293 analyze_mesh, analyze_mesh_generic, AnalysisLists, AnalyzeOptions, BoundaryComponent,
294 MeshAnalysis,
295};
296pub use overdraw::{
297 optimize_overdraw, optimize_overdraw_generic, optimize_overdraw_in_place,
298 optimize_overdraw_in_place_generic, optimize_overdraw_into, optimize_overdraw_into_generic,
299};
300pub use quantize::{
301 compute_position_exponent, dequantize_half, quantize_float, quantize_half, quantize_snorm,
302 quantize_unorm,
303};
304pub use remap::*;
305pub use sanitize::{
306 sanitize, sanitize_bound, sanitize_generic, sanitize_into, sanitize_into_generic,
307 SanitizeOptions, SanitizeReport, SanitizedMesh, SanitizedMeshGeneric,
308};
309
310#[cfg(feature = "experimental")]
311pub use normal::{
312 generate_normals, generate_normals_generic, generate_normals_into,
313 generate_normals_into_generic,
314};
315pub use opacity::{
316 opacity_map_compact, opacity_map_entry_size, opacity_map_measure, opacity_map_measure_generic,
317 opacity_map_measure_into, opacity_map_measure_into_generic, opacity_map_rasterize,
318 opacity_map_rasterize_into, OpacityMapMeasure,
319};
320pub use raster::{
321 analyze_coverage, analyze_coverage_generic, analyze_overdraw, analyze_overdraw_generic,
322 CoverageStatistics, OverdrawStatistics,
323};
324#[cfg(feature = "experimental")]
325pub use remesh::{
326 remesh, remesh_bound, remesh_bound_generic, remesh_generic, remesh_into, remesh_into_generic,
327 REMESH_SHELL, REMESH_SOLVE,
328};
329pub use strip::{
330 stripify, stripify_bound, stripify_generic, stripify_into, stripify_into_generic, unstripify,
331 unstripify_bound, unstripify_generic, unstripify_into, unstripify_into_generic,
332};
333pub use tangent::{
334 generate_tangents, generate_tangents_generic, generate_tangents_into,
335 generate_tangents_into_generic, TANGENT_COMPATIBLE, TANGENT_ZERO_FALLBACK,
336};
337pub use workspace::{Limits, Retention, Usage, Workspace};
338
339mod meshlet;
340mod meshlet_spatial;
341mod meshlet_util;
342mod processing;
343mod spatial;
344pub use meshlet::*;
345pub use meshlet_util::*;
346pub use spatial::*;
347
348mod partition;
349pub use partition::*;
350
351#[cfg(feature = "clusterlod")]
352pub mod clusterlod;
353#[cfg(not(feature = "clusterlod"))]
354#[path = "clusterlod/format_only.rs"]
355pub mod clusterlod;
356#[cfg(feature = "parallel")]
357pub mod parallel;
358/// Explicit destructive spelling for caller-buffer fetch optimization.
359/// This is the same checked operation as `optimize_vertex_fetch_into`.
360pub use remap::optimize_vertex_fetch_into as optimize_vertex_fetch_in_place;
361/// Explicit destructive spelling for update simplification with mutable views.
362/// This is the same checked operation as `simplify_with_update`.
363pub use simplify::simplify_with_update as simplify_with_update_in_place;
364
365/// Selectable index-width fetch optimization.
366pub use remap::optimize_vertex_fetch_into_generic as optimize_vertex_fetch_in_place_generic;
367/// Selectable index-width update simplification.
368pub use simplify::simplify_with_update_generic as simplify_with_update_in_place_generic;
369
370mod pipeline;
371pub use pipeline::{
372 process_mesh, ProcessError, ProcessLevel, ProcessOptions, ProcessReport, ProcessSkin,
373 ProcessStage, ProcessStageReport, ProcessedMesh,
374};
375
376#[cfg(feature = "clusterlod")]
377pub use pipeline::ProcessClusters;