meshoptimizer-rs 0.2.8

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
// meshoptimizer 1.3 scalar decoder, MIT, Arseny Kapoulkine.
// Byte-group parsing also reuses the Moss dc4af42a decoder (MIT).
use crate::Error;
use alloc::vec::Vec;

// All sinks expose initialized, checked block slices. The allocating sink
// initializes each block just before reconstruction, keeping those writes hot
// instead of clearing the entire output in a separate memory pass. Its caller
// reserves the complete output first, so extending the length cannot allocate.
pub(super) trait Destination {
    fn block(&mut self, start: usize, end: usize) -> &mut [u8];
    fn finish_block(&mut self) {}
}
impl Destination for [u8] {
    #[inline]
    fn block(&mut self, start: usize, end: usize) -> &mut [u8] {
        &mut self[start..end]
    }
}
impl Destination for Vec<u8> {
    #[inline]
    fn block(&mut self, start: usize, end: usize) -> &mut [u8] {
        debug_assert!(end <= self.capacity());
        self.resize(end, 0);
        &mut self[start..end]
    }
}

// A bounded, initialized staging block for large owned stride-four streams.
// Decoding writes every live byte before finish_block appends it to reserved
// output. It avoids repeatedly extending and zeroing the owned destination.
pub(super) struct StreamingDestination<'a> {
    output: &'a mut Vec<u8>,
    scratch: [u8; 1024],
    used: usize,
}
impl<'a> StreamingDestination<'a> {
    pub(super) fn new(output: &'a mut Vec<u8>) -> Self {
        Self {
            output,
            scratch: [0; 1024],
            used: 0,
        }
    }
}
impl Destination for StreamingDestination<'_> {
    #[inline]
    fn block(&mut self, start: usize, end: usize) -> &mut [u8] {
        debug_assert_eq!(start, self.output.len());
        debug_assert!(end <= self.output.capacity());
        self.used = end - start;
        &mut self.scratch[..self.used]
    }
    #[inline]
    fn finish_block(&mut self) {
        self.output.extend_from_slice(&self.scratch[..self.used]);
    }
}

#[inline]
fn packed<const BITS: u32>(data: &[u8; 24], out: &mut [u8; 16]) -> usize {
    let header = (BITS * 2) as usize;
    let literals: &[u8; 16] = data[header..header + 16].try_into().unwrap();
    let mut literal = 0;
    let escape = (1u8 << BITS) - 1;
    for (i, slot) in out.iter_mut().enumerate() {
        let byte = data[i / (8 / BITS as usize)];
        let shift = if BITS == 1 {
            i as u32 % 8
        } else {
            8 - BITS - (i as u32 % (8 / BITS)) * BITS
        };
        let value = (byte >> shift) & escape;
        *slot = if value == escape {
            // Sixteen output slots consume at most sixteen literals. Before
            // an escape read the cursor is therefore <= 15; the mask exposes
            // that bound to codegen without a per-escape bounds check.
            let v = literals[literal & 15];
            literal += 1;
            v
        } else {
            value
        };
    }
    header + literal
}
#[inline]
fn group(data: &[u8], pos: usize, out: &mut [u8; 16], bits: u32) -> Result<usize, Error> {
    // Upstream's 24-byte lookahead becomes one checked slice per group.
    let source: &[u8; 24] = data
        .get(pos..pos + 24)
        .ok_or(Error::InvalidStream)?
        .try_into()
        .map_err(|_| Error::InvalidStream)?;
    #[cfg(feature = "simd")]
    if let Some(used) = super::simd::group(source, out, bits) {
        return Ok(pos + used);
    }
    let used = match bits {
        0 => {
            out.fill(0);
            0
        }
        1 => packed::<1>(source, out),
        2 => packed::<2>(source, out),
        4 => packed::<4>(source, out),
        8 => {
            out.copy_from_slice(&source[..16]);
            16
        }
        _ => return Err(Error::InvalidStream),
    };
    Ok(pos + used)
}
pub(super) fn decode_deltas<const WIDTH: usize, const XOR: bool>(
    buffer: &[u8],
    target: &mut [u8],
    count: usize,
    stride: usize,
    last: &[u8],
    rot: u32,
) {
    #[cfg(feature = "simd")]
    if WIDTH == 1 && !XOR && super::simd::deltas8(buffer, target, count, stride, last) {
        return;
    }
    scalar_deltas::<WIDTH, XOR>(buffer, target, count, stride, last, rot, 0);
}
// Shared canonical short/tail path. `start` skips the already reconstructed
// complete records while plane spacing remains the original block count.
#[allow(clippy::too_many_arguments)]
pub(super) fn scalar_deltas<const WIDTH: usize, const XOR: bool>(
    buffer: &[u8],
    target: &mut [u8],
    count: usize,
    stride: usize,
    last: &[u8],
    rot: u32,
    start: usize,
) {
    if WIDTH == 1 && !XOR {
        // Four byte planes share the same records. Zip their checked slices
        // once, instead of repeating the strided destination walk and source
        // indexing for each component. Narrow wrapping addition preserves the
        // original u32 reconstruction modulo the stored byte.
        let (a, rest) = buffer.split_at(count);
        let (b, rest) = rest.split_at(count);
        let (c, d) = rest.split_at(count);
        #[cfg(all(target_arch = "wasm32", not(feature = "simd")))]
        match stride {
            48 => {
                strided_bytes::<48>(
                    target,
                    [&a[start..], &b[start..], &c[start..], &d[start..]],
                    last,
                );
                return;
            }
            64 => {
                strided_bytes::<64>(
                    target,
                    [&a[start..], &b[start..], &c[start..], &d[start..]],
                    last,
                );
                return;
            }
            _ => {}
        }
        let mut previous: [u8; 4] = last[..4].try_into().unwrap();
        for ((((record, &a), &b), &c), &d) in target
            .chunks_mut(stride)
            .zip(&a[start..])
            .zip(&b[start..])
            .zip(&c[start..])
            .zip(&d[start..])
        {
            for (p, v) in previous.iter_mut().zip([a, b, c, d]) {
                let delta = (v >> 1) ^ 0u8.wrapping_sub(v & 1);
                *p = p.wrapping_add(delta);
            }
            record[..4].copy_from_slice(&previous);
        }
        return;
    }
    for component in (0..4).step_by(WIDTH) {
        let mut previous = 0u32;
        for j in 0..WIDTH {
            previous |= u32::from(last[component + j]) << (8 * j);
        }
        let c0 = &buffer[component * count..(component + 1) * count];
        let c1 = if WIDTH >= 2 {
            &buffer[(component + 1) * count..(component + 2) * count]
        } else {
            c0
        };
        let c2 = if WIDTH == 4 {
            &buffer[(component + 2) * count..(component + 3) * count]
        } else {
            c0
        };
        let c3 = if WIDTH == 4 {
            &buffer[(component + 3) * count..(component + 4) * count]
        } else {
            c0
        };
        for (i, record) in target.chunks_mut(stride).enumerate() {
            let mut value = u32::from(c0[start + i]);
            if WIDTH >= 2 {
                value |= u32::from(c1[start + i]) << 8;
            }
            if WIDTH == 4 {
                value |= u32::from(c2[start + i]) << 16 | u32::from(c3[start + i]) << 24;
            }
            value = if XOR {
                value.rotate_left(rot) ^ previous
            } else {
                ((value >> 1) ^ 0u32.wrapping_sub(value & 1)).wrapping_add(previous)
            };
            let record = &mut record[..4];
            for j in 0..WIDTH {
                record[component + j] = (value >> (8 * j)) as u8;
            }
            previous = value;
        }
    }
}
// Common scalar WASM attribute layouts. Full records carry a static bound,
// leaving only one checked short final record instead of one check per record.
#[cfg(all(target_arch = "wasm32", not(feature = "simd")))]
fn strided_bytes<const STRIDE: usize>(target: &mut [u8], planes: [&[u8]; 4], last: &[u8]) {
    #[inline(always)]
    fn add(previous: &mut [u8; 4], values: [u8; 4]) {
        for (p, v) in previous.iter_mut().zip(values) {
            *p = p.wrapping_add((v >> 1) ^ 0u8.wrapping_sub(v & 1));
        }
    }
    let mut previous: [u8; 4] = last[..4].try_into().unwrap();
    let (records, tail) = target.as_chunks_mut::<STRIDE>();
    let mut source = planes[0]
        .iter()
        .zip(planes[1])
        .zip(planes[2])
        .zip(planes[3]);
    for (record, (((&a, &b), &c), &d)) in records.iter_mut().zip(source.by_ref()) {
        add(&mut previous, [a, b, c, d]);
        record[..4].copy_from_slice(&previous);
    }
    if let Some((((&a, &b), &c), &d)) = source.next() {
        add(&mut previous, [a, b, c, d]);
        tail[..4].copy_from_slice(&previous);
    }
}

fn bytes(data: &[u8], mut pos: usize, out: &mut [u8], bits: &[u32]) -> Result<usize, Error> {
    #[cfg(feature = "simd")]
    if let Some(result) = super::simd::bytes(data, pos, out, bits) {
        return result;
    }
    let header = pos;
    let headers = (out.len() / 16).div_ceil(4);
    if data.len().saturating_sub(pos) < headers {
        return Err(Error::InvalidStream);
    }
    pos += headers;
    for (i, out) in out.as_chunks_mut::<16>().0.iter_mut().enumerate() {
        if data.len().saturating_sub(pos) < 24 {
            return Err(Error::InvalidStream);
        }
        let selector = (data[header + i / 4] >> (2 * (i % 4))) & 3;
        pos = group(data, pos, out, bits[selector as usize])?;
    }
    Ok(pos)
}
pub(super) fn decode<D: Destination + ?Sized>(
    output: &mut D,
    count: usize,
    stride: usize,
    data: &[u8],
) -> Result<(), Error> {
    #[cfg(feature = "simd")]
    if let Some(result) = super::simd::vertex(output, count, stride, data) {
        return result;
    }
    let version = super::decode_vertex_version(data)?;
    let tail = stride + if version == 0 { 0 } else { stride / 4 };
    let padded = tail.max(if version == 0 { 32 } else { 24 });
    if data.len() < 1 + padded {
        return Err(Error::InvalidStream);
    }
    let start = data.len() - tail;
    let channels = &data[start + stride..];
    let mut last = [0u8; 256];
    last[..stride].copy_from_slice(&data[start..start + stride]);
    let block_size = ((8192 / stride) & !15).min(256);
    let mut pos = 1;
    let mut deltas = [0u8; 1024];
    let mut offset = 0;
    while offset < count {
        let block = block_size.min(count - offset);
        let aligned = block.div_ceil(16) * 16;
        let controls = if version == 0 {
            &[][..]
        } else {
            let c = data
                .get(pos..pos + stride / 4)
                .ok_or(Error::InvalidStream)?;
            pos += stride / 4;
            c
        };
        // Each bounded block fits 8 KiB. Write directly into its checked
        // destination slice, avoiding zeroing/copying an extra stack block.
        let block_output = output.block(offset * stride, (offset + block) * stride);
        for k in (0..stride).step_by(4) {
            let control = if version == 0 { 0 } else { controls[k / 4] };
            for j in 0..4 {
                let ctrl = (control >> (j * 2)) & 3;
                let out = &mut deltas[j * block..j * block + aligned];
                match ctrl {
                    3 => {
                        out[..block].copy_from_slice(
                            data.get(pos..pos + block).ok_or(Error::InvalidStream)?,
                        );
                        pos += block;
                    }
                    2 => out[..block].fill(0),
                    _ => {
                        pos = bytes(
                            data,
                            pos,
                            out,
                            if version == 0 {
                                &[0, 2, 4, 8]
                            } else if ctrl == 0 {
                                &[0, 1, 2, 4]
                            } else {
                                &[1, 2, 4, 8]
                            },
                        )?
                    }
                }
            }
            let channel = if version == 0 { 0 } else { channels[k / 4] };
            let target = &mut block_output[k..];
            // k is a four-byte-aligned channel group; only complete records
            // belong to this group. Extend the target to keep chunk strides
            // complete without touching bytes beyond this group's four bytes.
            let target_len = (block - 1) * stride + 4;
            let target = &mut target[..target_len];
            match channel & 3 {
                0 => decode_deltas::<1, false>(
                    &deltas[..block * 4],
                    target,
                    block,
                    stride,
                    &last[k..k + 4],
                    0,
                ),
                1 => decode_deltas::<2, false>(
                    &deltas[..block * 4],
                    target,
                    block,
                    stride,
                    &last[k..k + 4],
                    0,
                ),
                2 => decode_deltas::<4, true>(
                    &deltas[..block * 4],
                    target,
                    block,
                    stride,
                    &last[k..k + 4],
                    (32 - u32::from(channel >> 4)) & 31,
                ),
                _ => return Err(Error::InvalidStream),
            }
        }
        last[..stride].copy_from_slice(&block_output[(block - 1) * stride..]);
        output.finish_block();
        offset += block;
    }
    if data.len().checked_sub(pos) != Some(padded) {
        return Err(Error::InvalidStream);
    }
    Ok(())
}

#[cfg(test)]
mod streaming_tests {
    use super::*;
    use crate::{
        codec::{encode_vertex_buffer, VertexEncoding},
        Workspace,
    };
    use alloc::vec;

    #[test]
    fn staged_vertex_destination_matches_initialized_reference() {
        let counts: &[usize] = if cfg!(miri) {
            &[17, 257]
        } else {
            &[0, 1, 15, 16, 17, 255, 256, 257, 513]
        };
        let levels: &[u8] = if cfg!(miri) {
            &[0, 2, 3]
        } else {
            &[0, 1, 2, 3, 9]
        };
        for &count in counts {
            let data: Vec<u8> = (0..count * 4).map(|j| (j * 37 + j / 4) as u8).collect();
            for version in [0, 1] {
                for &level in levels {
                    let source = encode_vertex_buffer(
                        &data,
                        count,
                        4,
                        VertexEncoding::new(version, level).unwrap(),
                        &mut Workspace::default(),
                    )
                    .unwrap();
                    let mut staged = Vec::new();
                    staged.try_reserve_exact(data.len()).unwrap();
                    decode(
                        &mut StreamingDestination::new(&mut staged),
                        count,
                        4,
                        &source,
                    )
                    .unwrap();
                    let mut initialized = vec![0; data.len()];
                    decode(&mut initialized[..], count, 4, &source).unwrap();
                    assert_eq!(staged, data);
                    assert_eq!(staged, initialized);
                    assert_eq!(staged.capacity(), data.len());
                    let mut bad = source.clone();
                    bad.push(0);
                    let mut output = Vec::with_capacity(data.len());
                    assert_eq!(
                        decode(&mut StreamingDestination::new(&mut output), count, 4, &bad),
                        Err(Error::InvalidStream)
                    );
                }
            }
        }
    }
}