draco-oxide 0.1.0-alpha.9

draco-oxide is a rust rewrite of Google's draco mesh compression library.
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
//! Geometry extraction from glTF accessors.

use serde_json::Value;

/// Errors from reading geometry out of glTF accessors.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// The referenced accessor index does not exist.
    #[error("Accessor {0} not found")]
    AccessorNotFound(u64),
    /// The referenced buffer view index does not exist.
    #[error("BufferView {0} not found")]
    BufferViewNotFound(u64),
    /// The accessor has no buffer view to read from.
    #[error("Accessor {0} has no bufferView (may be Draco-compressed)")]
    NoBufferView(u64),
    /// The buffer view references a buffer index that is not available.
    #[error("Buffer index {0} out of range")]
    BufferOutOfRange(u64),
    /// A read would extend past the end of the binary buffer.
    #[error("Buffer read out of bounds: offset {offset}, size {size}, buffer len {buffer_len}")]
    OutOfBounds {
        offset: usize,
        size: usize,
        buffer_len: usize,
    },
    /// The accessor uses a componentType code that is not supported.
    #[error("Unsupported component type: {0}")]
    UnsupportedComponentType(u32),
    /// The accessor uses a type string that is not supported.
    #[error("Unsupported accessor type: {0}")]
    UnsupportedAccessorType(String),
    /// A required accessor or buffer view field is missing from the JSON.
    #[error("Missing required field: {0}")]
    MissingField(String),
}

/// A glTF accessor component type, with the discriminant equal to the glTF
/// componentType code.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComponentType {
    /// Signed 8-bit integer.
    Byte = 5120,
    /// Unsigned 8-bit integer.
    UnsignedByte = 5121,
    /// Signed 16-bit integer.
    Short = 5122,
    /// Unsigned 16-bit integer.
    UnsignedShort = 5123,
    /// Unsigned 32-bit integer.
    UnsignedInt = 5125,
    /// 32-bit IEEE float.
    Float = 5126,
}

impl ComponentType {
    /// Converts a glTF componentType code to a [`ComponentType`].
    pub fn from_u32(value: u32) -> Result<Self, Error> {
        match value {
            5120 => Ok(Self::Byte),
            5121 => Ok(Self::UnsignedByte),
            5122 => Ok(Self::Short),
            5123 => Ok(Self::UnsignedShort),
            5125 => Ok(Self::UnsignedInt),
            5126 => Ok(Self::Float),
            _ => Err(Error::UnsupportedComponentType(value)),
        }
    }

    /// The size of one component of this type in bytes.
    pub fn byte_size(self) -> usize {
        match self {
            Self::Byte | Self::UnsignedByte => 1,
            Self::Short | Self::UnsignedShort => 2,
            Self::UnsignedInt | Self::Float => 4,
        }
    }
}

/// The fields of a glTF accessor needed to read its data.
#[derive(Debug, Clone)]
pub struct AccessorInfo {
    /// Index of the buffer view the accessor reads from.
    pub buffer_view_idx: u64,
    /// Byte offset of the accessor within its buffer view.
    pub byte_offset: usize,
    /// Component type of the accessor's elements.
    pub component_type: ComponentType,
    /// Number of elements in the accessor.
    pub count: usize,
    /// The glTF accessor type string ("SCALAR", "VEC3", ...).
    pub accessor_type: String,
}

/// The fields of a glTF buffer view needed to read its data.
#[derive(Debug, Clone)]
pub struct BufferViewInfo {
    /// Index of the buffer the view reads from.
    pub buffer_idx: u64,
    /// Byte offset of the view within its buffer.
    pub byte_offset: usize,
    /// Length of the view in bytes.
    pub byte_length: usize,
    /// Byte stride between elements, if the view is interleaved.
    pub byte_stride: Option<usize>,
}

/// Reads the accessor at `accessor_idx` from the glTF JSON.
pub fn get_accessor_info(json: &Value, accessor_idx: u64) -> Result<AccessorInfo, Error> {
    let accessor = json
        .get("accessors")
        .and_then(|a| a.get(accessor_idx as usize))
        .ok_or(Error::AccessorNotFound(accessor_idx))?;

    let buffer_view_idx = accessor
        .get("bufferView")
        .and_then(|v| v.as_u64())
        .ok_or(Error::NoBufferView(accessor_idx))?;

    let byte_offset = accessor
        .get("byteOffset")
        .and_then(|v| v.as_u64())
        .unwrap_or(0) as usize;
    let component_type_raw = accessor
        .get("componentType")
        .and_then(|v| v.as_u64())
        .ok_or_else(|| Error::MissingField("accessor.componentType".into()))?
        as u32;
    let component_type = ComponentType::from_u32(component_type_raw)?;
    let count = accessor
        .get("count")
        .and_then(|v| v.as_u64())
        .ok_or_else(|| Error::MissingField("accessor.count".into()))? as usize;
    let accessor_type = accessor
        .get("type")
        .and_then(|v| v.as_str())
        .ok_or_else(|| Error::MissingField("accessor.type".into()))?
        .to_string();

    Ok(AccessorInfo {
        buffer_view_idx,
        byte_offset,
        component_type,
        count,
        accessor_type,
    })
}

/// Reads the buffer view at `buffer_view_idx` from the glTF JSON.
pub fn get_buffer_view_info(json: &Value, buffer_view_idx: u64) -> Result<BufferViewInfo, Error> {
    let bv = json
        .get("bufferViews")
        .and_then(|b| b.get(buffer_view_idx as usize))
        .ok_or(Error::BufferViewNotFound(buffer_view_idx))?;

    let buffer_idx = bv
        .get("buffer")
        .and_then(|v| v.as_u64())
        .ok_or_else(|| Error::MissingField("bufferView.buffer".into()))?;
    let byte_offset = bv.get("byteOffset").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
    let byte_length =
        bv.get("byteLength")
            .and_then(|v| v.as_u64())
            .ok_or_else(|| Error::MissingField("bufferView.byteLength".into()))? as usize;
    let byte_stride = bv
        .get("byteStride")
        .and_then(|v| v.as_u64())
        .map(|v| v as usize);

    Ok(BufferViewInfo {
        buffer_idx,
        byte_offset,
        byte_length,
        byte_stride,
    })
}

fn component_count(accessor_type: &str) -> Result<usize, Error> {
    match accessor_type {
        "SCALAR" => Ok(1),
        "VEC2" => Ok(2),
        "VEC3" => Ok(3),
        "VEC4" => Ok(4),
        "MAT2" => Ok(4),
        "MAT3" => Ok(9),
        "MAT4" => Ok(16),
        _ => Err(Error::UnsupportedAccessorType(accessor_type.to_string())),
    }
}

/// Reads an accessor's data as a flat `f32` vector, converting each component
/// from its stored type.
pub fn read_accessor_as_f32(
    json: &Value,
    buffer: &[u8],
    accessor_idx: u64,
) -> Result<Vec<f32>, Error> {
    let accessor = get_accessor_info(json, accessor_idx)?;
    let buffer_view = get_buffer_view_info(json, accessor.buffer_view_idx)?;

    if buffer_view.buffer_idx != 0 {
        return Err(Error::BufferOutOfRange(buffer_view.buffer_idx));
    }

    let num_components = component_count(&accessor.accessor_type)?;
    let element_size = accessor.component_type.byte_size() * num_components;
    let stride = buffer_view.byte_stride.unwrap_or(element_size);
    let base_offset = buffer_view.byte_offset + accessor.byte_offset;
    let total_floats = accessor.count * num_components;

    // Fast path: tightly-packed f32 data can be copied directly
    if accessor.component_type == ComponentType::Float && stride == element_size {
        let total_bytes = total_floats * 4;
        if base_offset + total_bytes > buffer.len() {
            return Err(Error::OutOfBounds {
                offset: base_offset,
                size: total_bytes,
                buffer_len: buffer.len(),
            });
        }
        let mut result = vec![0.0f32; total_floats];
        // Safety: copying raw LE bytes into f32 slice; both are 4-byte aligned in the Vec
        let dst =
            unsafe { std::slice::from_raw_parts_mut(result.as_mut_ptr() as *mut u8, total_bytes) };
        dst.copy_from_slice(&buffer[base_offset..base_offset + total_bytes]);
        return Ok(result);
    }

    let mut result = Vec::with_capacity(total_floats);

    for i in 0..accessor.count {
        let element_offset = base_offset + i * stride;
        for c in 0..num_components {
            let offset = element_offset + c * accessor.component_type.byte_size();
            let value = read_component_as_f32(buffer, offset, accessor.component_type)?;
            result.push(value);
        }
    }

    Ok(result)
}

/// Reads a scalar accessor's data as a `u32` vector, converting each value
/// from its stored type.
pub fn read_accessor_as_u32(
    json: &Value,
    buffer: &[u8],
    accessor_idx: u64,
) -> Result<Vec<u32>, Error> {
    let accessor = get_accessor_info(json, accessor_idx)?;
    let buffer_view = get_buffer_view_info(json, accessor.buffer_view_idx)?;

    if buffer_view.buffer_idx != 0 {
        return Err(Error::BufferOutOfRange(buffer_view.buffer_idx));
    }

    let element_size = accessor.component_type.byte_size();
    let stride = buffer_view.byte_stride.unwrap_or(element_size);
    let base_offset = buffer_view.byte_offset + accessor.byte_offset;

    let mut result = Vec::with_capacity(accessor.count);

    for i in 0..accessor.count {
        let offset = base_offset + i * stride;
        let value = read_component_as_u32(buffer, offset, accessor.component_type)?;
        result.push(value);
    }

    Ok(result)
}

fn read_component_as_f32(buffer: &[u8], offset: usize, ct: ComponentType) -> Result<f32, Error> {
    let size = ct.byte_size();
    if offset + size > buffer.len() {
        return Err(Error::OutOfBounds {
            offset,
            size,
            buffer_len: buffer.len(),
        });
    }

    Ok(match ct {
        ComponentType::Byte => buffer[offset] as i8 as f32,
        ComponentType::UnsignedByte => buffer[offset] as f32,
        ComponentType::Short => i16::from_le_bytes([buffer[offset], buffer[offset + 1]]) as f32,
        ComponentType::UnsignedShort => {
            u16::from_le_bytes([buffer[offset], buffer[offset + 1]]) as f32
        }
        ComponentType::UnsignedInt => u32::from_le_bytes([
            buffer[offset],
            buffer[offset + 1],
            buffer[offset + 2],
            buffer[offset + 3],
        ]) as f32,
        ComponentType::Float => f32::from_le_bytes([
            buffer[offset],
            buffer[offset + 1],
            buffer[offset + 2],
            buffer[offset + 3],
        ]),
    })
}

fn read_component_as_u32(buffer: &[u8], offset: usize, ct: ComponentType) -> Result<u32, Error> {
    let size = ct.byte_size();
    if offset + size > buffer.len() {
        return Err(Error::OutOfBounds {
            offset,
            size,
            buffer_len: buffer.len(),
        });
    }

    Ok(match ct {
        ComponentType::Byte => buffer[offset] as i8 as u32,
        ComponentType::UnsignedByte => buffer[offset] as u32,
        ComponentType::Short => i16::from_le_bytes([buffer[offset], buffer[offset + 1]]) as u32,
        ComponentType::UnsignedShort => {
            u16::from_le_bytes([buffer[offset], buffer[offset + 1]]) as u32
        }
        ComponentType::UnsignedInt => u32::from_le_bytes([
            buffer[offset],
            buffer[offset + 1],
            buffer[offset + 2],
            buffer[offset + 3],
        ]),
        ComponentType::Float => f32::from_le_bytes([
            buffer[offset],
            buffer[offset + 1],
            buffer[offset + 2],
            buffer[offset + 3],
        ]) as u32,
    })
}

/// Reads an accessor's data as 3-component `f32` vectors.
pub fn read_accessor_as_vec3(
    json: &Value,
    buffer: &[u8],
    accessor_idx: u64,
) -> Result<Vec<[f32; 3]>, Error> {
    read_accessor_as_array::<3>(json, buffer, accessor_idx)
}

/// Reads an accessor's data as 2-component `f32` vectors.
pub fn read_accessor_as_vec2(
    json: &Value,
    buffer: &[u8],
    accessor_idx: u64,
) -> Result<Vec<[f32; 2]>, Error> {
    read_accessor_as_array::<2>(json, buffer, accessor_idx)
}

/// Reads an accessor's data as 4-component `f32` vectors.
pub fn read_accessor_as_vec4(
    json: &Value,
    buffer: &[u8],
    accessor_idx: u64,
) -> Result<Vec<[f32; 4]>, Error> {
    read_accessor_as_array::<4>(json, buffer, accessor_idx)
}

fn read_accessor_as_array<const N: usize>(
    json: &Value,
    buffer: &[u8],
    accessor_idx: u64,
) -> Result<Vec<[f32; N]>, Error> {
    let accessor = get_accessor_info(json, accessor_idx)?;
    let buffer_view = get_buffer_view_info(json, accessor.buffer_view_idx)?;

    if buffer_view.buffer_idx != 0 {
        return Err(Error::BufferOutOfRange(buffer_view.buffer_idx));
    }

    let element_size = accessor.component_type.byte_size() * N;
    let stride = buffer_view.byte_stride.unwrap_or(element_size);
    let base_offset = buffer_view.byte_offset + accessor.byte_offset;

    // Fast path: tightly-packed f32 data can be reinterpreted directly
    if accessor.component_type == ComponentType::Float && stride == element_size {
        let total_bytes = accessor.count * N * 4;
        if base_offset + total_bytes > buffer.len() {
            return Err(Error::OutOfBounds {
                offset: base_offset,
                size: total_bytes,
                buffer_len: buffer.len(),
            });
        }
        let mut result = vec![[0.0f32; N]; accessor.count];
        let dst =
            unsafe { std::slice::from_raw_parts_mut(result.as_mut_ptr() as *mut u8, total_bytes) };
        dst.copy_from_slice(&buffer[base_offset..base_offset + total_bytes]);
        return Ok(result);
    }

    // Slow path: per-component conversion
    let mut result = Vec::with_capacity(accessor.count);
    for i in 0..accessor.count {
        let element_offset = base_offset + i * stride;
        let mut arr = [0.0f32; N];
        for (c, slot) in arr.iter_mut().enumerate() {
            let offset = element_offset + c * accessor.component_type.byte_size();
            *slot = read_component_as_f32(buffer, offset, accessor.component_type)?;
        }
        result.push(arr);
    }

    Ok(result)
}

/// Reads a scalar accessor's data as an `f32` vector, converting each value
/// from its stored type.
pub fn read_accessor_as_scalar_f32(
    json: &Value,
    buffer: &[u8],
    accessor_idx: u64,
) -> Result<Vec<f32>, Error> {
    let accessor = get_accessor_info(json, accessor_idx)?;
    let buffer_view = get_buffer_view_info(json, accessor.buffer_view_idx)?;

    if buffer_view.buffer_idx != 0 {
        return Err(Error::BufferOutOfRange(buffer_view.buffer_idx));
    }

    let element_size = accessor.component_type.byte_size();
    let stride = buffer_view.byte_stride.unwrap_or(element_size);
    let base_offset = buffer_view.byte_offset + accessor.byte_offset;

    let mut result = Vec::with_capacity(accessor.count);

    for i in 0..accessor.count {
        let offset = base_offset + i * stride;
        let value = read_component_as_f32(buffer, offset, accessor.component_type)?;
        result.push(value);
    }

    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_read_vec3() {
        let json = json!({
            "accessors": [{ "bufferView": 0, "byteOffset": 0, "componentType": 5126, "count": 3, "type": "VEC3" }],
            "bufferViews": [{ "buffer": 0, "byteOffset": 0, "byteLength": 36 }]
        });

        let mut buffer = Vec::new();
        for v in [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] {
            buffer.extend_from_slice(&v.to_le_bytes());
        }

        let positions = read_accessor_as_vec3(&json, &buffer, 0).unwrap();
        assert_eq!(positions.len(), 3);
        assert_eq!(positions[0], [1.0, 2.0, 3.0]);
        assert_eq!(positions[1], [4.0, 5.0, 6.0]);
    }
}