meshoptimizer-rs 0.2.13

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
# Using meshoptimizer-rs

These recipes use triangle lists of `u32` indices and borrowed vertex views.
`Positions::from_packed` borrows XYZ records (`&[[f32; 3]]`). For interleaved
floats, strides and offsets count `f32` components; for byte views they count
bytes and the byte order is explicit. Indices refer to the full position array.

## Non-packed positions

```text
pub fn from_interleaved(
    data: &[f32],
    count: usize,
    stride: usize,
    offset: usize,
) -> Result<Positions<'_>, Error>

pub fn from_bytes(
    data: &[u8],
    count: usize,
    stride: usize,
    offset: usize,
    order: ByteOrder,
) -> Result<Positions<'_>, Error>
```

Both are `Positions` constructors. For `from_interleaved`, `stride` (3 to 64) and
`offset` count `f32` components. For `from_bytes`, they count bytes: `stride` is a
multiple of four from 12 to 256, and `order` is `ByteOrder::LittleEndian` or
`ByteOrder::BigEndian`. `count` is the number of vertices. Both return
`InvalidLayout` if the layout or buffer length is invalid. The views borrow
`data` and copy nothing.

```rust
use meshoptimizer_rs::{
    simplify, ByteOrder, Positions, SimplifyOptions, SimplifySettings, Workspace,
};

let indices = [0, 1, 2, 2, 1, 3];
let settings = SimplifySettings {
    target_index_count: 3,
    target_error: 0.01,
    options: SimplifyOptions::EMPTY,
};
let mut workspace = Workspace::default();

// x, y, z, u, v per vertex: stride 5 floats, XYZ at offset 0.
let floats = [
    0., 0., 0., 0., 0.,
    1., 0., 0., 1., 0.,
    0., 1., 0., 0., 1.,
    1., 1., 0., 1., 1.,
];
let view = Positions::from_interleaved(&floats, 4, 5, 0)?;
simplify(&indices, view, settings, &mut workspace)?;

// The same vertices as big-endian bytes: stride 20 bytes, XYZ at byte offset 0.
let bytes: Vec<u8> = floats.iter().flat_map(|v| v.to_be_bytes()).collect();
let view = Positions::from_bytes(&bytes, 4, 20, 0, ByteOrder::BigEndian)?;
simplify(&indices, view, settings, &mut workspace)?;
# Ok::<(), meshoptimizer_rs::Error>(())
```

## Simplify one mesh

```text
pub fn simplify(
    indices: &[u32],
    positions: Positions<'_>,
    settings: SimplifySettings,
    workspace: &mut Workspace,
) -> Result<SimplifiedMesh, Error>
```

Returns `SimplifiedMesh { indices, error }`. Indices still refer to the original
vertices; there is no implicit welding, fetch compaction or cache optimization.
The target counts indices, not triangles, and is a goal rather than a guarantee.
By default `error` is relative to the mesh extent; `ERROR_ABSOLUTE` selects position units.
`target_error` must be finite and nonnegative; all supplied positions must be finite.

```rust
use meshoptimizer_rs::{simplify, Positions, SimplifyOptions, SimplifySettings, Workspace};

let positions = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [1., 1., 0.]];
let indices = [0, 1, 2, 2, 1, 3];
let settings = SimplifySettings {
    target_index_count: 3,
    target_error: 0.01,
    options: SimplifyOptions::EMPTY,
};
let mut workspace = Workspace::default();
let lod = simplify(&indices, Positions::from_packed(&positions), settings, &mut workspace)?;
assert!(lod.indices.len() <= indices.len());
# Ok::<(), meshoptimizer_rs::Error>(())
```

Errors: `InvalidTopology` for incomplete triangles, `IndexOutOfBounds` for invalid
references, `InvalidParameter` for invalid settings (including
`target_index_count > indices.len()`) or non-finite positions,
`NumericalFailure` for non-finite calculations, and the resource errors below.
Use `SimplifyOptions::from_bits` to validate raw options (`UnknownFlags` on rejection).

## Per-mesh LOD chain

```text
pub fn simplify_scale(positions: Positions<'_>) -> Result<f32, Error>

pub fn simplify(
    indices: &[u32],
    positions: Positions<'_>,
    settings: SimplifySettings,
    workspace: &mut Workspace,
) -> Result<SimplifiedMesh, Error>

pub fn optimize_vertex_cache(
    indices: &[u32],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<Vec<u32>, Error>

pub fn optimize_overdraw(
    indices: &[u32],
    positions: Positions<'_>,
    threshold: f32,
    workspace: &mut Workspace,
) -> Result<Vec<u32>, Error>
```

Keep the full vertex array for every level. Each target below simplifies the
previous level's topology, then orders it for the vertex cache and overdraw.
`scale` is the largest axis extent; multiply a relative error by it to get
position units. Each level's error is relative to that level's input, not an
accumulated bound against the original mesh. The optimizers return reordered
`Vec<u32>` triangle lists. Reuse one workspace for the whole chain: it keeps
scratch capacity between calls, so later calls skip reallocating.

```rust
use meshoptimizer_rs::{
    optimize_overdraw, optimize_vertex_cache, simplify, simplify_scale, Error,
    Positions, SimplifyOptions, SimplifySettings, Workspace,
};

fn main() -> Result<(), Error> {
    let positions = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [1., 1., 0.]];
    let indices = [0, 1, 2, 2, 1, 3];
    let view = Positions::from_packed(&positions);
    let mut workspace = Workspace::default();
    let scale = simplify_scale(view)?;
    let mut current = indices.to_vec();
    for target_index_count in [6, 3, 0] {
        let settings = SimplifySettings {
            target_index_count,
            target_error: 0.01,
            options: SimplifyOptions::EMPTY,
        };
        let lod = simplify(&current, view, settings, &mut workspace)?;
        let cached = optimize_vertex_cache(&lod.indices, positions.len(), &mut workspace)?;
        current = optimize_overdraw(&cached, view, 1.05, &mut workspace)?;
        println!("{} indices, absolute error {}", current.len(), lod.error * scale);
    }
    Ok(())
}
```

Errors: simplification's errors above; `simplify_scale` returns `InvalidParameter`
for non-finite positions and `NumericalFailure` for an overflowing extent.
Cache ordering checks topology and indices; overdraw also rejects a non-finite
threshold with `InvalidParameter` and non-finite geometry/calculations with
`NumericalFailure`. Both optimizers can return the resource errors below.

## Meshlets with bounds

```text
pub fn build_meshlets(
    indices: &[u32],
    p: Positions<'_>,
    s: MeshletSettings,
    cone_weight: f32,
    workspace: &mut Workspace,
) -> Result<Meshlets, Error>
```

```text
pub fn new(positions: Positions<'a>) -> Self // BoundsPositions<'a>
```

```text
pub fn compute_meshlet_bounds_with_positions(
    vertices: &[u32],
    triangles: &[u8],
    p: BoundsPositions<'_>,
    workspace: &mut Workspace,
) -> Result<Bounds, Error>
```

`build_meshlets` returns `Meshlets`: descriptors, original vertex references and
three local `u8` indices per triangle. Descriptor triangle offsets are byte
offsets, with no padding between meshlets. Bounds return a sphere and normal cone
in `Bounds`. Cache the full position validation once with `BoundsPositions` when
querying many meshlets; failures are stored and reported by the bounds operation.

`MeshletSettings::default()` is `max_vertices: 64`, `max_triangles: 124`. Valid
ranges are 3 to 256 vertices and 1 to 512 triangles; anything else returns
`InvalidParameter`. `cone_weight` (finite, 0.0 to 1.0) makes the builder prefer
triangles that face the same way, which helps cone culling; 0.0 ignores facing.
The example uses 0.25.

```rust
use meshoptimizer_rs::{
    build_meshlets, compute_meshlet_bounds_with_positions, BoundsPositions, Error,
    MeshletSettings, Positions, Workspace,
};

fn main() -> Result<(), Error> {
    let positions = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [1., 1., 0.]];
    let indices = [0, 1, 2, 2, 1, 3];
    let view = Positions::from_packed(&positions);
    let mut workspace = Workspace::default();
    let built = build_meshlets(&indices, view, MeshletSettings::default(), 0.25, &mut workspace)?;
    let positions = BoundsPositions::new(view);
    for m in &built.meshlets {
        let v = m.vertex_offset as usize;
        let t = m.triangle_offset as usize;
        let bounds = compute_meshlet_bounds_with_positions(
            &built.vertices[v..v + m.vertex_count as usize],
            &built.triangles[t..t + m.triangle_count as usize * 3],
            positions,
            &mut workspace,
        )?;
        println!("center {:?}, radius {}", bounds.center, bounds.radius);
    }
    Ok(())
}
```

Errors: `InvalidTopology`, `IndexOutOfBounds`, `InvalidParameter` for unsupported
meshlet sizes or builder settings, `NumericalFailure` for non-finite geometry or
calculations, and the resource errors below. Bounds also validate meshlet-local
indices and supported vertex/triangle counts. `BoundsPositions::new` defers errors.

## Vertex and index encode and decode

```text
pub fn encode_vertex_buffer(
    vertices: &[u8],
    count: usize,
    stride: usize,
    encoding: VertexEncoding,
    workspace: &mut Workspace,
) -> Result<Vec<u8>, Error>

pub fn decode_vertex_buffer(
    count: usize,
    stride: usize,
    source: &[u8],
    workspace: &mut Workspace,
) -> Result<Vec<u8>, Error>

pub fn encode_index_buffer(
    indices: &[u32],
    encoding: IndexEncoding,
    workspace: &mut Workspace,
) -> Result<Vec<u8>, Error>

pub fn decode_index_buffer(
    count: usize,
    stride: usize,
    source: &[u8],
    workspace: &mut Workspace,
) -> Result<Vec<u8>, Error>
```

Vertex input is `count * stride` initialized bytes; stride is a positive multiple
of four, at most 256. This recipe serializes packed XYZ as little-endian floats.
Index encoding takes a `u32` triangle list. Decoding returns little-endian bytes:
index stride 2 gives `u16` bytes and stride 4 gives `u32` bytes. At stride 2,
indices above 65535 wrap (upstream's truncating `u16` conversion); use stride 4
for such meshes. Counts and strides
come from your container format; encoded streams do not supply them for you.
Each allocating codec returns a `Vec<u8>`. Triangle encoding may rotate corners
within each triangle, preserving winding; decoded index order reflects those rotations.

```rust
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]; 3] = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.]];
let indices = [0u32, 1, 2];
let vertices: Vec<u8> = positions.iter().flatten().flat_map(|v| v.to_le_bytes()).collect();
let mut workspace = Workspace::default();
let encoded = encode_vertex_buffer(&vertices, 3, 12, VertexEncoding::DEFAULT, &mut workspace)?;
assert_eq!(decode_vertex_buffer(3, 12, &encoded, &mut workspace)?, vertices);
let encoded = encode_index_buffer(&indices, IndexEncoding::DEFAULT, &mut workspace)?;
let decoded = decode_index_buffer(3, 4, &encoded, &mut workspace)?;
let expected: Vec<u8> = indices.iter().flat_map(|v| v.to_le_bytes()).collect();
assert_eq!(decoded, expected);
# Ok::<(), meshoptimizer_rs::Error>(())
```

Errors: `InvalidLayout` for invalid vertex/index strides or vertex byte lengths,
`InvalidTopology` for incomplete triangles, `InvalidStream` for malformed data,
`UnsupportedVersion` for unsupported codec versions, and the resource errors below.
Encoding constructors validate versions and levels (`InvalidParameter` for an
unsupported vertex level), so an invalid encoding configuration cannot be built.

## Untrusted input with Limits

```text
pub fn new(limits: Limits) -> Self // Workspace
```

```text
pub fn decode_vertex_buffer(
    count: usize,
    stride: usize,
    source: &[u8],
    workspace: &mut Workspace,
) -> Result<Vec<u8>, Error>
```

The default `Limits` allow 1 GiB of crate-owned output plus retained scratch
capacity and 2^34 counted record visits per call. Caller buffers, allocator overhead,
stack storage and the application's retained outputs are outside this accounting.
Choose smaller limits for the request, and check transport sizes and decoded size
before allocating caller buffers. There is no wall-clock timeout in `Limits`.

```rust
use meshoptimizer_rs::{codec::decode_vertex_buffer, Error, Limits, Workspace};

fn main() -> Result<(), Error> {
    // Check transport sizes before buffering a request or creating its views.
    let source = [0u8; 4]; // Deliberately malformed stream supplied by a client.
    let count = 3usize;
    let stride = 12usize;
    let limits = Limits { max_bytes: 64 << 20, max_work: 1 << 20 };
    if source.len() > limits.max_bytes || count > limits.max_bytes / stride {
        return Err(Error::LimitExceeded);
    }
    let mut workspace = Workspace::new(limits);
    match decode_vertex_buffer(count, stride, &source, &mut workspace) {
        Ok(bytes) => println!("{} decoded bytes", bytes.len()),
        Err(Error::InvalidStream) => println!("rejected malformed input"),
        Err(error) => return Err(error),
    }
    Ok(())
}
```

Returns decoded bytes or an error; this example treats `InvalidStream` as a
malformed client stream to reject, not a failure. Decoding can also return `InvalidLayout`, `UnsupportedVersion`,
`SizeOverflow`, `LimitExceeded` or `AllocationFailed`. `Workspace::new` is infallible.
`BoundsPositions::new` and `simplify_scale` have no workspace budget: bound input
sizes before calling them on untrusted data.

## Parallel workers

Each worker calls `simplify` (signature above) on a shared immutable XYZ array
and triangle list, and owns its workspace and returned mesh. The following uses standard threads and needs no `parallel` feature.

```rust
use meshoptimizer_rs::{simplify, Error, Positions, SimplifyOptions, SimplifySettings, Workspace};

let positions = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [1., 1., 0.]];
let indices = [0, 1, 2, 2, 1, 3];
let results = std::thread::scope(|scope| {
    let mut workers = Vec::new();
    for target_index_count in [6, 3] {
        let (positions, indices) = (&positions, &indices);
        workers.push(scope.spawn(move || {
            let mut workspace = Workspace::default();
            let settings = SimplifySettings {
                target_index_count, target_error: 0.01, options: SimplifyOptions::EMPTY,
            };
            // Reuse this workspace for further jobs handled by this worker.
            simplify(indices, Positions::from_packed(positions), settings, &mut workspace)
        }));
    }
    workers.into_iter().map(|worker| worker.join().expect("worker panicked"))
        .collect::<Result<Vec<_>, Error>>()
})?;
assert_eq!(results.len(), 2);
# Ok::<(), Error>(())
```

Returns one `SimplifiedMesh` per worker. With the `parallel` feature,
[`simplify_lod_chains_batch`](https://docs.rs/meshoptimizer-rs/latest/meshoptimizer_rs/parallel/fn.simplify_lod_chains_batch.html)
provides ordered per-mesh chains using Rayon. It panics if Rayon cannot start or
a worker panics. Its outer error is result-slot
`SizeOverflow` or `AllocationFailed`; item errors stay in input order and do not
cancel other items. Limits apply separately to each item, with no aggregate cap.

## Lower peak memory with Retention::Lean

```text
pub fn set_retention(&mut self, retention: Retention) // Workspace
```

Use the same position and index layouts as simplification. `set_retention` returns
`()` and cannot fail. With `Retention::Lean`, the workspace keeps less scratch
between calls, so peak memory is lower. Later calls have to reallocate that
scratch, so they are slower. It applies to simplify, vertex-cache and overdraw
calls; other operations keep their scratch.

```rust
use meshoptimizer_rs::{simplify, Positions, Retention, SimplifyOptions, SimplifySettings, Workspace};

let positions = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [1., 1., 0.]];
let indices = [0, 1, 2, 2, 1, 3];
let mut workspace = Workspace::default();
workspace.set_retention(Retention::Lean);
let lod = simplify(&indices, Positions::from_packed(&positions), SimplifySettings {
    target_index_count: 3, target_error: 0.01, options: SimplifyOptions::EMPTY,
}, &mut workspace)?;
assert!(lod.indices.len() <= indices.len());
# Ok::<(), meshoptimizer_rs::Error>(())
```

Returns the same simplification result and errors as the first recipe. Lean is
opt-in: it lowers peak memory, but later calls reallocate scratch and run slower.
See the measured [memory and time results](https://github.com/Tavrin/meshoptimizer-rs/blob/main/docs/PERFORMANCE.md).

## Resource errors

Workspace operations can return `SizeOverflow` when size arithmetic or platform
allocation bounds overflow, `LimitExceeded` when the per-call bytes or counted work
exceed `Limits`, and `AllocationFailed` when fallible reservation fails.
Caller-buffer `_into` forms also return `BufferTooSmall` for insufficient capacity;
a late error may leave a used prefix modified. The `_into` functions are
`simplify_into`, `optimize_vertex_cache_into`, `optimize_overdraw_into` and
`build_meshlets_into`, among others.

## Gotchas

- **Indices:** `u32` only. Pass the full position count as `vertex_count`, not the number of vertices a LOD uses. An index at or beyond that count returns `IndexOutOfBounds`.
- **Simplify target:** `target_index_count` larger than `indices.len()` returns `InvalidParameter`.
- **Index decode at stride 2:** indices above 65535 wrap (upstream's truncating `u16` conversion). Use stride 4 for meshes with more than 65536 vertices.
- **Position layout:** use `Positions::from_packed(&[[f32; 3]])` when you can; it is the fastest layout. Other layouts work but read more slowly.
- **Workspace reuse:** use one `Workspace` per worker thread and reuse it across calls; see [Per-mesh LOD chain]#per-mesh-lod-chain.
- **Retention::Lean:** lowers peak memory at the cost of time; the default is `Retention::Reuse`.
- **Default Limits:** 1 GiB of crate-owned storage and 2^34 counted visits per call; set smaller `max_bytes` and `max_work` for untrusted input and check caller allocations separately.
- **Byte-identical output:** results match C++ meshoptimizer 1.3 (scalar build); recorded differential inputs and exceptions are described in the README.
- **Semver policy:** 0.2.x patch releases are drop-in, with no API break and the same output.