Skip to main content

euv_core/game/engine3d/gltf/
fn.rs

1use super::*;
2
3/// Returns the number of scalar components per element for a glTF 2.0 accessor `type` string.
4///
5/// # Arguments
6///
7/// - `&str` - Accessor `type` string (`SCALAR`, `VEC2`, `VEC3`, `VEC4`, `MAT2`, `MAT3`, `MAT4`).
8///
9/// # Returns
10///
11/// - `usize` - Component count per element (`0` if unrecognized).
12#[must_use]
13fn gltf_type_components(type_str: &str) -> usize {
14    match type_str {
15        ACC_TYPE_SCALAR => 1,
16        ACC_TYPE_VEC2 => 2,
17        ACC_TYPE_VEC3 => 3,
18        ACC_TYPE_VEC4 | ACC_TYPE_MAT2 => 4,
19        ACC_TYPE_MAT3 => 9,
20        ACC_TYPE_MAT4 => 16,
21        _ => 0,
22    }
23}
24
25/// Returns byte size per scalar component for a glTF 2.0 `componentType` code.
26///
27/// # Arguments
28///
29/// - `u32` - glTF `componentType` code (`5120..=5126`).
30///
31/// # Returns
32///
33/// - `usize` - Component byte width (`0` if unsupported).
34#[must_use]
35fn gltf_component_byte_size(comp_type: u32) -> usize {
36    match comp_type {
37        GLTF_COMP_I8 | GLTF_COMP_U8 => 1,
38        GLTF_COMP_I16 | GLTF_COMP_U16 => 2,
39        GLTF_COMP_U32 | GLTF_COMP_F32 => 4,
40        _ => 0,
41    }
42}
43
44/// Reads a single scalar component from `bytes` at `offset` as `f32`, applying glTF normalization when `normalized` is set.
45///
46/// # Arguments
47///
48/// - `&[u8]` - Backing binary buffer slice.
49/// - `usize` - Byte offset of the scalar component.
50/// - `u32` - glTF `componentType` code.
51/// - `bool` - Whether integer values are normalized (`KHR_mesh_quantization` / `COLOR_0` / `WEIGHTS_0`).
52///
53/// # Returns
54///
55/// - `Result<f32, String>` - Decoded floating-point component or bounds error.
56fn read_gltf_scalar_f32(
57    bytes: &[u8],
58    offset: usize,
59    comp_type: u32,
60    normalized: bool,
61) -> Result<f32, String> {
62    let size: usize = gltf_component_byte_size(comp_type);
63    if size == 0 || offset.saturating_add(size) > bytes.len() {
64        return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
65    }
66    let val: f32 = match comp_type {
67        GLTF_COMP_I8 => {
68            let raw: f32 = f32::from(bytes[offset] as i8);
69            if normalized {
70                (raw / 127.0).max(-1.0)
71            } else {
72                raw
73            }
74        }
75        GLTF_COMP_U8 => {
76            let raw: f32 = f32::from(bytes[offset]);
77            if normalized { raw / 255.0 } else { raw }
78        }
79        GLTF_COMP_I16 => {
80            let raw: f32 = f32::from(i16::from_le_bytes([bytes[offset], bytes[offset + 1]]));
81            if normalized {
82                (raw / 32_767.0).max(-1.0)
83            } else {
84                raw
85            }
86        }
87        GLTF_COMP_U16 => {
88            let raw: f32 = f32::from(u16::from_le_bytes([bytes[offset], bytes[offset + 1]]));
89            if normalized { raw / 65_535.0 } else { raw }
90        }
91        GLTF_COMP_U32 => u32::from_le_bytes([
92            bytes[offset],
93            bytes[offset + 1],
94            bytes[offset + 2],
95            bytes[offset + 3],
96        ]) as f32,
97        GLTF_COMP_F32 => f32::from_le_bytes([
98            bytes[offset],
99            bytes[offset + 1],
100            bytes[offset + 2],
101            bytes[offset + 3],
102        ]),
103        _ => return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string()),
104    };
105    Ok(val)
106}
107
108/// Reads an unsigned integer index from `bytes` at `offset` for `u8`, `u16`, or `u32` glTF component types.
109///
110/// # Arguments
111///
112/// - `&[u8]` - Backing binary buffer slice.
113/// - `usize` - Byte offset.
114/// - `u32` - glTF `componentType` code.
115///
116/// # Returns
117///
118/// - `Result<u32, String>` - Decoded unsigned integer or bounds error.
119fn read_gltf_scalar_u32(bytes: &[u8], offset: usize, comp_type: u32) -> Result<u32, String> {
120    let size: usize = gltf_component_byte_size(comp_type);
121    if size == 0 || offset.saturating_add(size) > bytes.len() {
122        return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
123    }
124    match comp_type {
125        GLTF_COMP_U8 => Ok(u32::from(bytes[offset])),
126        GLTF_COMP_U16 => Ok(u32::from(u16::from_le_bytes([
127            bytes[offset],
128            bytes[offset + 1],
129        ]))),
130        GLTF_COMP_U32 => Ok(u32::from_le_bytes([
131            bytes[offset],
132            bytes[offset + 1],
133            bytes[offset + 2],
134            bytes[offset + 3],
135        ])),
136        GLTF_COMP_I16 => Ok(i16::from_le_bytes([bytes[offset], bytes[offset + 1]]).max(0) as u32),
137        GLTF_COMP_I8 => Ok((bytes[offset] as i8).max(0) as u32),
138        _ => Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string()),
139    }
140}
141
142/// Resolves a `bufferViews[view_idx]` byte slice and optional `byteStride`.
143///
144/// # Arguments
145///
146/// - `&Value` - Root glTF JSON object.
147/// - `&'a [Vec<u8>]` - Loaded raw buffer blobs.
148/// - `usize` - Index into `bufferViews`.
149///
150/// # Returns
151///
152/// - `Result<(&'a [u8], Option<usize>), String>` - Validated slice and optional stride.
153fn resolve_buffer_view<'a>(
154    root: &Value,
155    buffers: &'a [Vec<u8>],
156    view_idx: usize,
157) -> Result<(&'a [u8], Option<usize>), String> {
158    let view: &Value = root
159        .get(KEY_BUFFER_VIEWS)
160        .and_then(Value::as_array)
161        .and_then(|arr: &Vec<Value>| arr.get(view_idx))
162        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
163    let buf_idx: usize = view
164        .get(KEY_BUFFER)
165        .and_then(Value::as_u64)
166        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as usize;
167    let byte_offset: usize = view
168        .get(KEY_BYTE_OFFSET)
169        .and_then(Value::as_u64)
170        .unwrap_or(0) as usize;
171    let byte_length: usize = view
172        .get(KEY_BYTE_LENGTH)
173        .and_then(Value::as_u64)
174        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as usize;
175    let byte_stride: Option<usize> = view
176        .get(KEY_BYTE_STRIDE)
177        .and_then(Value::as_u64)
178        .map(|val: u64| val as usize);
179    let buf: &[u8] = buffers
180        .get(buf_idx)
181        .map(Vec::as_slice)
182        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
183    let end: usize = byte_offset.saturating_add(byte_length);
184    if end > buf.len() {
185        return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
186    }
187    Ok((&buf[byte_offset..end], byte_stride))
188}
189
190/// Decodes a glTF 2.0 accessor (including `KHR_mesh_quantization` and `sparse` overrides) into flat `f32` values and component count.
191///
192/// # Arguments
193///
194/// - `&Value` - Root glTF JSON object.
195/// - `&[Vec<u8>]` - Loaded raw buffer blobs.
196/// - `usize` - Index into `accessors`.
197///
198/// # Returns
199///
200/// - `Result<(Vec<f32>, usize, usize), String>` - Tuple `(flat_floats, element_count, components_per_element)`.
201fn decode_accessor_f32(
202    root: &Value,
203    buffers: &[Vec<u8>],
204    accessor_idx: usize,
205) -> Result<(Vec<f32>, usize, usize), String> {
206    let acc: &Value = root
207        .get(KEY_ACCESSORS)
208        .and_then(Value::as_array)
209        .and_then(|arr: &Vec<Value>| arr.get(accessor_idx))
210        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
211    let comp_type: u32 = acc
212        .get(KEY_COMPONENT_TYPE)
213        .and_then(Value::as_u64)
214        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as u32;
215    let count: usize = acc
216        .get(KEY_COUNT)
217        .and_then(Value::as_u64)
218        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as usize;
219    let type_str: &str = acc
220        .get(KEY_TYPE)
221        .and_then(Value::as_str)
222        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
223    let comps: usize = gltf_type_components(type_str);
224    let comp_size: usize = gltf_component_byte_size(comp_type);
225    if comps == 0 || comp_size == 0 {
226        return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
227    }
228    let normalized: bool = acc
229        .get(KEY_NORMALIZED)
230        .and_then(Value::as_bool)
231        .unwrap_or(false);
232    let mut out: Vec<f32> = vec![0.0; count.saturating_mul(comps)];
233    if let Some(view_idx) = acc.get(KEY_BUFFER_VIEW).and_then(Value::as_u64) {
234        let (view_slice, stride_opt): (&[u8], Option<usize>) =
235            resolve_buffer_view(root, buffers, view_idx as usize)?;
236        let acc_off: usize = acc
237            .get(KEY_BYTE_OFFSET)
238            .and_then(Value::as_u64)
239            .unwrap_or(0) as usize;
240        let elem_bytes: usize = comps * comp_size;
241        let stride: usize = stride_opt.unwrap_or(elem_bytes).max(elem_bytes);
242        for elem_idx in 0..count {
243            let base: usize = acc_off.saturating_add(elem_idx.saturating_mul(stride));
244            for c_idx in 0..comps {
245                let off: usize = base.saturating_add(c_idx.saturating_mul(comp_size));
246                out[elem_idx * comps + c_idx] =
247                    read_gltf_scalar_f32(view_slice, off, comp_type, normalized)?;
248            }
249        }
250    }
251    if let Some(sparse) = acc.get(KEY_SPARSE) {
252        let sparse_count: usize =
253            sparse.get(KEY_COUNT).and_then(Value::as_u64).unwrap_or(0) as usize;
254        if sparse_count > 0 {
255            let idx_obj: &Value = sparse
256                .get(KEY_INDICES)
257                .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
258            let val_obj: &Value = sparse
259                .get(KEY_VALUES)
260                .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
261            let idx_view_id: usize = idx_obj
262                .get(KEY_BUFFER_VIEW)
263                .and_then(Value::as_u64)
264                .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?
265                as usize;
266            let idx_off: usize = idx_obj
267                .get(KEY_BYTE_OFFSET)
268                .and_then(Value::as_u64)
269                .unwrap_or(0) as usize;
270            let idx_comp_type: u32 = idx_obj
271                .get(KEY_COMPONENT_TYPE)
272                .and_then(Value::as_u64)
273                .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?
274                as u32;
275            let idx_step: usize = gltf_component_byte_size(idx_comp_type);
276            let val_view_id: usize = val_obj
277                .get(KEY_BUFFER_VIEW)
278                .and_then(Value::as_u64)
279                .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?
280                as usize;
281            let val_off: usize = val_obj
282                .get(KEY_BYTE_OFFSET)
283                .and_then(Value::as_u64)
284                .unwrap_or(0) as usize;
285            let (idx_slice, _): (&[u8], Option<usize>) =
286                resolve_buffer_view(root, buffers, idx_view_id)?;
287            let (val_slice, _): (&[u8], Option<usize>) =
288                resolve_buffer_view(root, buffers, val_view_id)?;
289            let val_elem_bytes: usize = comps * comp_size;
290            for sparse_i in 0..sparse_count {
291                let target_idx: usize = read_gltf_scalar_u32(
292                    idx_slice,
293                    idx_off.saturating_add(sparse_i.saturating_mul(idx_step)),
294                    idx_comp_type,
295                )? as usize;
296                if target_idx >= count {
297                    return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
298                }
299                let src_base: usize =
300                    val_off.saturating_add(sparse_i.saturating_mul(val_elem_bytes));
301                for c_idx in 0..comps {
302                    let off: usize = src_base.saturating_add(c_idx.saturating_mul(comp_size));
303                    out[target_idx * comps + c_idx] =
304                        read_gltf_scalar_f32(val_slice, off, comp_type, normalized)?;
305                }
306            }
307        }
308    }
309    Ok((out, count, comps))
310}
311
312/// Decodes a glTF 2.0 scalar or vector unsigned-integer accessor (indices or `JOINTS_n`).
313///
314/// # Arguments
315///
316/// - `&Value` - Root glTF JSON object.
317/// - `&[Vec<u8>]` - Loaded raw buffer blobs.
318/// - `usize` - Index into `accessors`.
319///
320/// # Returns
321///
322/// - `Result<(Vec<u32>, usize, usize), String>` - Tuple `(flat_u32, element_count, components_per_element)`.
323fn decode_accessor_u32(
324    root: &Value,
325    buffers: &[Vec<u8>],
326    accessor_idx: usize,
327) -> Result<(Vec<u32>, usize, usize), String> {
328    let acc: &Value = root
329        .get(KEY_ACCESSORS)
330        .and_then(Value::as_array)
331        .and_then(|arr: &Vec<Value>| arr.get(accessor_idx))
332        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
333    let comp_type: u32 = acc
334        .get(KEY_COMPONENT_TYPE)
335        .and_then(Value::as_u64)
336        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as u32;
337    let count: usize = acc
338        .get(KEY_COUNT)
339        .and_then(Value::as_u64)
340        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as usize;
341    let type_str: &str = acc
342        .get(KEY_TYPE)
343        .and_then(Value::as_str)
344        .ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
345    let comps: usize = gltf_type_components(type_str);
346    let comp_size: usize = gltf_component_byte_size(comp_type);
347    if comps == 0 || comp_size == 0 {
348        return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
349    }
350    let mut out: Vec<u32> = vec![0u32; count.saturating_mul(comps)];
351    if let Some(view_idx) = acc.get(KEY_BUFFER_VIEW).and_then(Value::as_u64) {
352        let (view_slice, stride_opt): (&[u8], Option<usize>) =
353            resolve_buffer_view(root, buffers, view_idx as usize)?;
354        let acc_off: usize = acc
355            .get(KEY_BYTE_OFFSET)
356            .and_then(Value::as_u64)
357            .unwrap_or(0) as usize;
358        let elem_bytes: usize = comps * comp_size;
359        let stride: usize = stride_opt.unwrap_or(elem_bytes).max(elem_bytes);
360        for elem_idx in 0..count {
361            let base: usize = acc_off.saturating_add(elem_idx.saturating_mul(stride));
362            for c_idx in 0..comps {
363                let off: usize = base.saturating_add(c_idx.saturating_mul(comp_size));
364                out[elem_idx * comps + c_idx] = read_gltf_scalar_u32(view_slice, off, comp_type)?;
365            }
366        }
367    }
368    Ok((out, count, comps))
369}
370
371/// Decodes a `data:...;base64,...` URI into raw bytes.
372///
373/// # Arguments
374///
375/// - `&str` - RFC 2397 data URI string.
376///
377/// # Returns
378///
379/// - `Result<Vec<u8>, String>` - Decoded payload bytes or error.
380fn decode_data_uri(uri: &str) -> Result<Vec<u8>, String> {
381    let marker_pos: usize = uri
382        .find(GLTF_BASE64_MARKER)
383        .ok_or_else(|| ERR_GLTF_URI_RESOLVE.to_string())?;
384    let b64_str: &str = &uri[(marker_pos + GLTF_BASE64_MARKER.len())..];
385    decode_base64(b64_str)
386}
387
388/// Reads an optional JSON array of `f32` values into a fixed-size `[f32; 2]`.
389///
390/// # Arguments
391///
392/// - `Option<&Value>` - Optional JSON array value.
393/// - `[f32; 2]` - Default fallback values.
394///
395/// # Returns
396///
397/// - `[f32; 2]` - Parsed 2-element float array.
398#[must_use]
399fn json_f32_2(value: Option<&Value>, default: [f32; 2]) -> [f32; 2] {
400    let Some(arr) = value.and_then(Value::as_array) else {
401        return default;
402    };
403    if arr.len() < 2 {
404        return default;
405    }
406    [
407        arr[0].as_f64().unwrap_or(f64::from(default[0])) as f32,
408        arr[1].as_f64().unwrap_or(f64::from(default[1])) as f32,
409    ]
410}
411
412/// Reads an optional JSON array of `f32` values into a fixed-size `[f32; 3]`.
413///
414/// # Arguments
415///
416/// - `Option<&Value>` - Optional JSON array value.
417/// - `[f32; 3]` - Default fallback values.
418///
419/// # Returns
420///
421/// - `[f32; 3]` - Parsed 3-element float array.
422#[must_use]
423fn json_f32_3(value: Option<&Value>, default: [f32; 3]) -> [f32; 3] {
424    let Some(arr) = value.and_then(Value::as_array) else {
425        return default;
426    };
427    if arr.len() < 3 {
428        return default;
429    }
430    [
431        arr[0].as_f64().unwrap_or(f64::from(default[0])) as f32,
432        arr[1].as_f64().unwrap_or(f64::from(default[1])) as f32,
433        arr[2].as_f64().unwrap_or(f64::from(default[2])) as f32,
434    ]
435}
436
437/// Reads an optional JSON array of `f32` values into a fixed-size `[f32; 4]`.
438///
439/// # Arguments
440///
441/// - `Option<&Value>` - Optional JSON array value.
442/// - `[f32; 4]` - Default fallback values.
443///
444/// # Returns
445///
446/// - `[f32; 4]` - Parsed 4-element float array.
447#[must_use]
448fn json_f32_4(value: Option<&Value>, default: [f32; 4]) -> [f32; 4] {
449    let Some(arr) = value.and_then(Value::as_array) else {
450        return default;
451    };
452    if arr.len() < 4 {
453        return default;
454    }
455    [
456        arr[0].as_f64().unwrap_or(f64::from(default[0])) as f32,
457        arr[1].as_f64().unwrap_or(f64::from(default[1])) as f32,
458        arr[2].as_f64().unwrap_or(f64::from(default[2])) as f32,
459        arr[3].as_f64().unwrap_or(f64::from(default[3])) as f32,
460    ]
461}
462
463/// Parses a glTF textureInfo object including `KHR_texture_transform` overrides.
464///
465/// # Arguments
466///
467/// - `Option<&Value>` - Optional texture info JSON object.
468///
469/// # Returns
470///
471/// - `Option<TextureSlot3D>` - Parsed texture slot when `index` is present.
472#[must_use]
473fn parse_texture_slot(info_opt: Option<&Value>) -> Option<TextureSlot3D> {
474    let info: &Value = info_opt?;
475    let tex_index: u32 = info.get(KEY_INDEX).and_then(Value::as_u64)? as u32;
476    let mut tex_coord: u8 = info.get(KEY_TEX_COORD).and_then(Value::as_u64).unwrap_or(0) as u8;
477    let mut transform: TextureTransform3D = TextureTransform3D::default();
478    if let Some(tt) = info
479        .get(KEY_EXTENSIONS)
480        .and_then(|ext: &Value| ext.get(GLTF_EXT_TEX_TRANSFORM))
481    {
482        let offset_arr: [f32; 2] = json_f32_2(tt.get(KEY_OFFSET), [0.0, 0.0]);
483        let rotation: f32 = tt.get(KEY_ROTATION).and_then(Value::as_f64).unwrap_or(0.0) as f32;
484        let scale_arr: [f32; 2] = json_f32_2(tt.get(KEY_SCALE), [1.0, 1.0]);
485        if let Some(override_uv) = tt.get(KEY_TEX_COORD).and_then(Value::as_u64) {
486            tex_coord = override_uv as u8;
487        }
488        transform = TextureTransform3D::from_trs(
489            Vec2::from_array(offset_arr),
490            rotation,
491            Vec2::from_array(scale_arr),
492        );
493    }
494    Some(TextureSlot3D {
495        texture_index: tex_index,
496        tex_coord,
497        transform,
498    })
499}
500
501/// Parses a single glTF 2.0 material entry into a 1:1 `PrincipledMaterial3D` with all KHR PBR extensions.
502///
503/// # Arguments
504///
505/// - `&Value` - Material JSON object.
506/// - `usize` - Material index used for default fallback naming.
507///
508/// # Returns
509///
510/// - `PrincipledMaterial3D` - Populated Principled BSDF material.
511#[must_use]
512fn parse_principled_material(mat_val: &Value, mat_idx: usize) -> PrincipledMaterial3D {
513    let mut mat: PrincipledMaterial3D = PrincipledMaterial3D::default();
514    let name: String = mat_val
515        .get(KEY_NAME)
516        .and_then(Value::as_str)
517        .map(str::to_string)
518        .unwrap_or_else(|| format!("material_{mat_idx}"));
519    mat.set_name(name);
520    if let Some(pbr) = mat_val.get(KEY_PBR_MR) {
521        mat.set_base_color_factor(json_f32_4(
522            pbr.get(KEY_BASE_COLOR_FACTOR),
523            [1.0, 1.0, 1.0, 1.0],
524        ));
525        mat.set_base_color_texture(parse_texture_slot(pbr.get(KEY_BASE_COLOR_TEX)));
526        let metallic: f32 = pbr
527            .get(KEY_METALLIC_FACTOR)
528            .and_then(Value::as_f64)
529            .unwrap_or(1.0) as f32;
530        let roughness: f32 = pbr
531            .get(KEY_ROUGHNESS_FACTOR)
532            .and_then(Value::as_f64)
533            .unwrap_or(1.0) as f32;
534        mat.set_metallic_factor(metallic.clamp(0.0, 1.0));
535        mat.set_roughness_factor(roughness.clamp(0.04, 1.0));
536        mat.set_metallic_roughness_texture(parse_texture_slot(pbr.get(KEY_MR_TEX)));
537    }
538    if let Some(norm_obj) = mat_val.get(KEY_NORMAL_TEX) {
539        mat.set_normal_texture(parse_texture_slot(Some(norm_obj)));
540        let scale: f32 = norm_obj
541            .get(KEY_SCALE)
542            .and_then(Value::as_f64)
543            .unwrap_or(1.0) as f32;
544        mat.set_normal_scale(scale);
545    }
546    if let Some(occ_obj) = mat_val.get(KEY_OCCLUSION_TEX) {
547        mat.set_occlusion_texture(parse_texture_slot(Some(occ_obj)));
548        let strength: f32 = occ_obj
549            .get(KEY_STRENGTH)
550            .and_then(Value::as_f64)
551            .unwrap_or(1.0) as f32;
552        mat.set_occlusion_strength(strength.clamp(0.0, 1.0));
553    }
554    mat.set_emissive_factor(json_f32_3(
555        mat_val.get(KEY_EMISSIVE_FACTOR),
556        [0.0, 0.0, 0.0],
557    ));
558    mat.set_emissive_texture(parse_texture_slot(mat_val.get(KEY_EMISSIVE_TEX)));
559    if let Some(alpha_str) = mat_val.get(KEY_ALPHA_MODE).and_then(Value::as_str) {
560        let mode: AlphaMode3D = if alpha_str == ALPHA_MODE_MASK {
561            AlphaMode3D::Mask
562        } else if alpha_str == ALPHA_MODE_BLEND {
563            AlphaMode3D::Blend
564        } else {
565            AlphaMode3D::Opaque
566        };
567        mat.set_alpha_mode(mode);
568    }
569    if let Some(cutoff) = mat_val.get(KEY_ALPHA_CUTOFF).and_then(Value::as_f64) {
570        mat.set_alpha_cutoff(cutoff as f32);
571    }
572    if let Some(ds) = mat_val.get(KEY_DOUBLE_SIDED).and_then(Value::as_bool) {
573        mat.set_double_sided(ds);
574    }
575    if let Some(ext) = mat_val.get(KEY_EXTENSIONS) {
576        if let Some(em_ext) = ext.get(GLTF_EXT_EMISSIVE_STRENGTH)
577            && let Some(val) = em_ext.get(KEY_EMISSIVE_STRENGTH).and_then(Value::as_f64)
578        {
579            mat.set_emissive_strength((val as f32).max(0.0));
580        }
581        if let Some(ior_ext) = ext.get(GLTF_EXT_IOR)
582            && let Some(val) = ior_ext.get("ior").and_then(Value::as_f64)
583        {
584            mat.set_ior((val as f32).max(1.0));
585        }
586        if let Some(spec_ext) = ext.get(GLTF_EXT_SPECULAR) {
587            if let Some(sf) = spec_ext.get(KEY_SPECULAR_FACTOR).and_then(Value::as_f64) {
588                mat.set_specular_factor((sf as f32).clamp(0.0, 1.0));
589            }
590            mat.set_specular_color_factor(json_f32_3(
591                spec_ext.get(KEY_SPECULAR_COLOR_FACTOR),
592                [1.0, 1.0, 1.0],
593            ));
594            mat.set_specular_texture(parse_texture_slot(spec_ext.get(KEY_SPECULAR_TEX)));
595            mat.set_specular_color_texture(parse_texture_slot(
596                spec_ext.get(KEY_SPECULAR_COLOR_TEX),
597            ));
598        }
599        if let Some(cc_ext) = ext.get(GLTF_EXT_CLEARCOAT) {
600            if let Some(cf) = cc_ext.get(KEY_CLEARCOAT_FACTOR).and_then(Value::as_f64) {
601                mat.set_clearcoat_factor((cf as f32).clamp(0.0, 1.0));
602            }
603            if let Some(cr) = cc_ext.get(KEY_CLEARCOAT_ROUGHNESS).and_then(Value::as_f64) {
604                mat.set_clearcoat_roughness_factor((cr as f32).clamp(0.0, 1.0));
605            }
606            mat.set_clearcoat_texture(parse_texture_slot(cc_ext.get(KEY_CLEARCOAT_TEX)));
607            mat.set_clearcoat_roughness_texture(parse_texture_slot(
608                cc_ext.get(KEY_CLEARCOAT_ROUGH_TEX),
609            ));
610            mat.set_clearcoat_normal_texture(parse_texture_slot(
611                cc_ext.get(KEY_CLEARCOAT_NORM_TEX),
612            ));
613        }
614        if let Some(tr_ext) = ext.get(GLTF_EXT_TRANSMISSION) {
615            if let Some(tf) = tr_ext.get(KEY_TRANSMISSION_FACTOR).and_then(Value::as_f64) {
616                mat.set_transmission_factor((tf as f32).clamp(0.0, 1.0));
617            }
618            mat.set_transmission_texture(parse_texture_slot(tr_ext.get(KEY_TRANSMISSION_TEX)));
619        }
620        if let Some(vol_ext) = ext.get(GLTF_EXT_VOLUME) {
621            if let Some(th) = vol_ext.get(KEY_THICKNESS_FACTOR).and_then(Value::as_f64) {
622                mat.set_thickness_factor((th as f32).max(0.0));
623            }
624            if let Some(ad) = vol_ext.get(KEY_ATTENUATION_DIST).and_then(Value::as_f64) {
625                mat.set_attenuation_distance((ad as f32).max(1e-4));
626            }
627            mat.set_attenuation_color(json_f32_3(
628                vol_ext.get(KEY_ATTENUATION_COLOR),
629                [1.0, 1.0, 1.0],
630            ));
631        }
632        if let Some(sh_ext) = ext.get(GLTF_EXT_SHEEN) {
633            mat.set_sheen_color_factor(json_f32_3(sh_ext.get(KEY_SHEEN_COLOR), [0.0, 0.0, 0.0]));
634            if let Some(sr) = sh_ext.get(KEY_SHEEN_ROUGHNESS).and_then(Value::as_f64) {
635                mat.set_sheen_roughness_factor((sr as f32).clamp(0.0, 1.0));
636            }
637            mat.set_sheen_color_texture(parse_texture_slot(sh_ext.get(KEY_SHEEN_COLOR_TEX)));
638            mat.set_sheen_roughness_texture(parse_texture_slot(sh_ext.get(KEY_SHEEN_ROUGH_TEX)));
639        }
640        if ext.get(GLTF_EXT_UNLIT).is_some() {
641            mat.set_unlit(true);
642        }
643    }
644    mat
645}
646
647/// Converts primitive vertex index stream into triangle triplets respecting glTF `TRIANGLES`, `TRIANGLE_STRIP`, or `TRIANGLE_FAN`.
648///
649/// # Arguments
650///
651/// - `&[u32]` - Raw vertex index list.
652/// - `u32` - glTF primitive mode constant (`4`, `5`, or `6`).
653///
654/// # Returns
655///
656/// - `Vec<[u32; 3]>` - Triangle index triplets.
657#[must_use]
658fn assemble_primitive_triangles(raw_indices: &[u32], mode: u32) -> Vec<[u32; 3]> {
659    let mut tris: Vec<[u32; 3]> = Vec::new();
660    match mode {
661        GLTF_MODE_TRIANGLE_STRIP => {
662            if raw_indices.len() >= 3 {
663                tris.reserve(raw_indices.len() - 2);
664                for idx in 0..(raw_indices.len() - 2) {
665                    let i0: u32 = raw_indices[idx];
666                    let i1: u32 = raw_indices[idx + 1];
667                    let i2: u32 = raw_indices[idx + 2];
668                    if i0 == i1 || i1 == i2 || i0 == i2 {
669                        continue;
670                    }
671                    if (idx & 1) == 0 {
672                        tris.push([i0, i1, i2]);
673                    } else {
674                        tris.push([i1, i0, i2]);
675                    }
676                }
677            }
678        }
679        GLTF_MODE_TRIANGLE_FAN => {
680            if raw_indices.len() >= 3 {
681                tris.reserve(raw_indices.len() - 2);
682                let anchor: u32 = raw_indices[0];
683                for idx in 1..(raw_indices.len() - 1) {
684                    tris.push([anchor, raw_indices[idx], raw_indices[idx + 1]]);
685                }
686            }
687        }
688        _ => {
689            tris.reserve(raw_indices.len() / 3);
690            for tri in raw_indices.as_chunks::<3>().0 {
691                tris.push(*tri);
692            }
693        }
694    }
695    tris
696}
697
698/// Parses a single glTF 2.0 JSON document together with optional GLB binary buffer chunk and URI resolver.
699///
700/// # Arguments
701///
702/// - `&str` - UTF-8 glTF 2.0 JSON document text.
703/// - `Option<&[u8]>` - Optional GLB `BIN\0` chunk backing `buffers[0]`.
704/// - `Option<&dyn GltfBufferResolver>` - Optional external buffer/image URI resolver.
705///
706/// # Returns
707///
708/// - `Result<ImportedScene3D, String>` - Fully parsed scene bundle or diagnostic error.
709pub fn parse_gltf_document(
710    json_source: &str,
711    glb_bin_chunk: Option<&[u8]>,
712    resolver: Option<&dyn GltfBufferResolver>,
713) -> Result<ImportedScene3D, String> {
714    let root: Value = from_str::<Value>(json_source)
715        .ok()
716        .ok_or_else(|| ERR_GLTF_PARSE.to_string())?;
717    let generator: String = root
718        .get(KEY_ASSET)
719        .and_then(|asset: &Value| asset.get(KEY_GENERATOR))
720        .and_then(Value::as_str)
721        .unwrap_or(GLTF_DEFAULT_SCENE_NAME)
722        .to_string();
723    let default_scene_idx: usize =
724        root.get(KEY_SCENE).and_then(Value::as_u64).unwrap_or(0) as usize;
725    let scene_name: String = root
726        .get(KEY_SCENES)
727        .and_then(Value::as_array)
728        .and_then(|arr: &Vec<Value>| arr.get(default_scene_idx))
729        .and_then(|sc: &Value| sc.get(KEY_NAME))
730        .and_then(Value::as_str)
731        .map(str::to_string)
732        .unwrap_or_else(|| generator.clone());
733    let mut buffers: Vec<Vec<u8>> = Vec::new();
734    if let Some(bufs_arr) = root.get(KEY_BUFFERS).and_then(Value::as_array) {
735        for (buf_idx, buf_val) in bufs_arr.iter().enumerate() {
736            if let Some(uri) = buf_val.get("uri").and_then(Value::as_str) {
737                if uri.starts_with(GLTF_DATA_URI_PREFIX) {
738                    buffers.push(decode_data_uri(uri)?);
739                } else if let Some(res) = resolver {
740                    buffers.push(res.resolve_buffer(uri)?);
741                } else {
742                    return Err(ERR_GLTF_URI_RESOLVE.to_string());
743                }
744            } else if buf_idx == 0
745                && let Some(bin) = glb_bin_chunk
746            {
747                buffers.push(bin.to_vec());
748            } else {
749                buffers.push(Vec::new());
750            }
751        }
752    } else if let Some(bin) = glb_bin_chunk {
753        buffers.push(bin.to_vec());
754    }
755    let mut materials: Vec<PrincipledMaterial3D> = Vec::new();
756    if let Some(mats_arr) = root.get(KEY_MATERIALS).and_then(Value::as_array) {
757        for (mat_idx, mat_val) in mats_arr.iter().enumerate() {
758            materials.push(parse_principled_material(mat_val, mat_idx));
759        }
760    }
761    let mut tex_spaces: HashMap<u32, TextureColorSpace> = HashMap::new();
762    for mat in materials.iter() {
763        if let Some(slot) = mat.try_get_base_color_texture() {
764            let _: Option<TextureColorSpace> =
765                tex_spaces.insert(slot.get_texture_index(), TextureColorSpace::Srgb);
766        }
767        if let Some(slot) = mat.try_get_emissive_texture() {
768            let _: Option<TextureColorSpace> =
769                tex_spaces.insert(slot.get_texture_index(), TextureColorSpace::Srgb);
770        }
771        if let Some(slot) = mat.try_get_sheen_color_texture() {
772            let _: Option<TextureColorSpace> =
773                tex_spaces.insert(slot.get_texture_index(), TextureColorSpace::Srgb);
774        }
775        if let Some(slot) = mat.try_get_normal_texture() {
776            let _: Option<TextureColorSpace> =
777                tex_spaces.insert(slot.get_texture_index(), TextureColorSpace::NormalTangent);
778        }
779        if let Some(slot) = mat.try_get_clearcoat_normal_texture() {
780            let _: Option<TextureColorSpace> =
781                tex_spaces.insert(slot.get_texture_index(), TextureColorSpace::NormalTangent);
782        }
783        for slot in [
784            mat.try_get_metallic_roughness_texture(),
785            mat.try_get_occlusion_texture(),
786            mat.try_get_clearcoat_texture(),
787            mat.try_get_clearcoat_roughness_texture(),
788            mat.try_get_transmission_texture(),
789            mat.try_get_specular_texture(),
790            mat.try_get_sheen_roughness_texture(),
791        ]
792        .into_iter()
793        .flatten()
794        {
795            let _: &mut TextureColorSpace = tex_spaces
796                .entry(slot.get_texture_index())
797                .or_insert(TextureColorSpace::Linear);
798        }
799    }
800    let mut samplers: Vec<TextureSampler3D> = Vec::new();
801    if let Some(samps_arr) = root.get(KEY_SAMPLERS).and_then(Value::as_array) {
802        for samp_val in samps_arr.iter() {
803            let mag: TextureFilterMode = samp_val
804                .get(KEY_MAG_FILTER)
805                .and_then(Value::as_u64)
806                .map(|code: u64| TextureFilterMode::from_gltf_code(code as u32))
807                .unwrap_or(TextureFilterMode::Linear);
808            let min: TextureFilterMode = samp_val
809                .get(KEY_MIN_FILTER)
810                .and_then(Value::as_u64)
811                .map(|code: u64| TextureFilterMode::from_gltf_code(code as u32))
812                .unwrap_or(TextureFilterMode::LinearMipmapLinear);
813            let wrap_s: TextureWrapMode = samp_val
814                .get(KEY_WRAP_S)
815                .and_then(Value::as_u64)
816                .map(|code: u64| TextureWrapMode::from_gltf_code(code as u32))
817                .unwrap_or(TextureWrapMode::Repeat);
818            let wrap_t: TextureWrapMode = samp_val
819                .get(KEY_WRAP_T)
820                .and_then(Value::as_u64)
821                .map(|code: u64| TextureWrapMode::from_gltf_code(code as u32))
822                .unwrap_or(TextureWrapMode::Repeat);
823            samplers.push(TextureSampler3D::new(mag, min, wrap_s, wrap_t));
824        }
825    }
826    let mut raw_images: Vec<(String, Vec<u8>)> = Vec::new();
827    if let Some(imgs_arr) = root.get(KEY_IMAGES).and_then(Value::as_array) {
828        for (img_idx, img_val) in imgs_arr.iter().enumerate() {
829            let img_name: String = img_val
830                .get(KEY_NAME)
831                .and_then(Value::as_str)
832                .map(str::to_string)
833                .unwrap_or_else(|| format!("image_{img_idx}"));
834            let img_bytes: Vec<u8> =
835                if let Some(view_idx) = img_val.get(KEY_BUFFER_VIEW).and_then(Value::as_u64) {
836                    let (slice, _): (&[u8], Option<usize>) =
837                        resolve_buffer_view(&root, &buffers, view_idx as usize)?;
838                    slice.to_vec()
839                } else if let Some(uri) = img_val.get("uri").and_then(Value::as_str) {
840                    if uri.starts_with(GLTF_DATA_URI_PREFIX) {
841                        decode_data_uri(uri)?
842                    } else if let Some(res) = resolver {
843                        res.resolve_image(uri)?
844                    } else {
845                        Vec::new()
846                    }
847                } else {
848                    Vec::new()
849                };
850            raw_images.push((img_name, img_bytes));
851        }
852    }
853    let mut textures: Vec<Texture2D3D> = Vec::new();
854    if let Some(texs_arr) = root.get(KEY_TEXTURES).and_then(Value::as_array) {
855        for (tex_idx, tex_val) in texs_arr.iter().enumerate() {
856            let color_space: TextureColorSpace = tex_spaces
857                .get(&(tex_idx as u32))
858                .copied()
859                .unwrap_or(TextureColorSpace::Srgb);
860            let sampler: TextureSampler3D = tex_val
861                .get(KEY_SAMPLER)
862                .and_then(Value::as_u64)
863                .and_then(|s_idx: u64| samplers.get(s_idx as usize).copied())
864                .unwrap_or_default();
865            let tex_name: String = tex_val
866                .get(KEY_NAME)
867                .and_then(Value::as_str)
868                .map(str::to_string)
869                .unwrap_or_else(|| format!("texture_{tex_idx}"));
870            let mut decoded_tex: Texture2D3D = if let Some(src_idx) =
871                tex_val.get(KEY_SOURCE).and_then(Value::as_u64)
872                && let Some((img_name, img_bytes)) = raw_images.get(src_idx as usize)
873                && !img_bytes.is_empty()
874            {
875                let label: &str = if tex_val.get(KEY_NAME).is_some() {
876                    &tex_name
877                } else {
878                    img_name
879                };
880                Texture2D3D::from_encoded_bytes(label, img_bytes, color_space, true)?
881            } else {
882                Texture2D3D::from_rgba8(
883                    &tex_name,
884                    1,
885                    1,
886                    vec![255, 255, 255, 255],
887                    color_space,
888                    false,
889                )?
890            };
891            decoded_tex.set_sampler(sampler);
892            textures.push(decoded_tex);
893        }
894    }
895    let mut meshes: Vec<Mesh3D> = Vec::new();
896    let mut gltf_mesh_to_first_prim: Vec<usize> = Vec::new();
897    if let Some(meshes_arr) = root.get(KEY_MESHES).and_then(Value::as_array) {
898        for (mesh_idx, mesh_val) in meshes_arr.iter().enumerate() {
899            gltf_mesh_to_first_prim.push(meshes.len());
900            let mesh_name: String = mesh_val
901                .get(KEY_NAME)
902                .and_then(Value::as_str)
903                .map(str::to_string)
904                .unwrap_or_else(|| format!("{scene_name}_mesh_{mesh_idx}"));
905            let target_names: Vec<String> = mesh_val
906                .get(KEY_EXTRAS)
907                .and_then(|ext: &Value| ext.get(KEY_TARGET_NAMES))
908                .and_then(Value::as_array)
909                .map(|arr: &Vec<Value>| {
910                    arr.iter()
911                        .filter_map(|item: &Value| item.as_str().map(str::to_string))
912                        .collect()
913                })
914                .unwrap_or_default();
915            let Some(prims) = mesh_val.get(KEY_PRIMITIVES).and_then(Value::as_array) else {
916                continue;
917            };
918            for (prim_idx, prim) in prims.iter().enumerate() {
919                let prim_name: String = if prims.len() == 1 {
920                    mesh_name.clone()
921                } else {
922                    format!("{mesh_name}_prim_{prim_idx}")
923                };
924                let mat_opt: Option<u32> = prim
925                    .get(KEY_MATERIAL)
926                    .and_then(Value::as_u64)
927                    .map(|idx: u64| idx as u32);
928                let legacy_mat: PbrMaterial = mat_opt
929                    .and_then(|idx: u32| materials.get(idx as usize))
930                    .or_else(|| materials.first())
931                    .map(PrincipledMaterial3D::to_legacy_pbr)
932                    .unwrap_or_default();
933                if let Some(attrs) = prim.get(KEY_ATTRIBUTES).and_then(Value::as_object) {
934                    let Some(pos_acc_idx) = attrs.get(ATTR_POSITION).and_then(Value::as_u64) else {
935                        continue;
936                    };
937                    let (pos_floats, vert_count, pos_comps): (Vec<f32>, usize, usize) =
938                        decode_accessor_f32(&root, &buffers, pos_acc_idx as usize)?;
939                    if pos_comps < 3 || vert_count == 0 {
940                        continue;
941                    }
942                    let mut vertices: Vec<Vertex3D> = Vec::with_capacity(vert_count);
943                    for v_idx in 0..vert_count {
944                        let base: usize = v_idx * pos_comps;
945                        vertices.push(Vertex3D::new(
946                            Vec3::new(pos_floats[base], pos_floats[base + 1], pos_floats[base + 2]),
947                            Vec3::new(0.0, 1.0, 0.0),
948                        ));
949                    }
950                    let has_normals: bool = if let Some(n_acc) =
951                        attrs.get(ATTR_NORMAL).and_then(Value::as_u64)
952                    {
953                        let (n_floats, n_count, n_comps): (Vec<f32>, usize, usize) =
954                            decode_accessor_f32(&root, &buffers, n_acc as usize)?;
955                        if n_comps >= 3 && n_count >= vert_count {
956                            for (v_idx, vertex) in vertices.iter_mut().enumerate().take(vert_count)
957                            {
958                                let base: usize = v_idx * n_comps;
959                                vertex.set_normal(
960                                    Vec3::new(
961                                        n_floats[base],
962                                        n_floats[base + 1],
963                                        n_floats[base + 2],
964                                    )
965                                    .normalize(),
966                                );
967                            }
968                            true
969                        } else {
970                            false
971                        }
972                    } else {
973                        false
974                    };
975                    let has_tangents: bool = if let Some(t_acc) =
976                        attrs.get(ATTR_TANGENT).and_then(Value::as_u64)
977                    {
978                        let (t_floats, t_count, t_comps): (Vec<f32>, usize, usize) =
979                            decode_accessor_f32(&root, &buffers, t_acc as usize)?;
980                        if t_comps >= 4 && t_count >= vert_count {
981                            for (v_idx, vertex) in vertices.iter_mut().enumerate().take(vert_count)
982                            {
983                                let base: usize = v_idx * t_comps;
984                                vertex.set_tangent([
985                                    t_floats[base],
986                                    t_floats[base + 1],
987                                    t_floats[base + 2],
988                                    t_floats[base + 3],
989                                ]);
990                                let next_flags: u32 = vertex.get_flags() | 4;
991                                vertex.set_flags(next_flags);
992                            }
993                            true
994                        } else {
995                            false
996                        }
997                    } else {
998                        false
999                    };
1000                    if let Some(uv0_acc) = attrs.get(ATTR_TEXCOORD_0).and_then(Value::as_u64) {
1001                        let (uv_floats, uv_count, uv_comps): (Vec<f32>, usize, usize) =
1002                            decode_accessor_f32(&root, &buffers, uv0_acc as usize)?;
1003                        if uv_comps >= 2 && uv_count >= vert_count {
1004                            for (v_idx, vertex) in vertices.iter_mut().enumerate().take(vert_count)
1005                            {
1006                                let base: usize = v_idx * uv_comps;
1007                                vertex.set_uv0([uv_floats[base], uv_floats[base + 1]]);
1008                                let next_flags: u32 = vertex.get_flags() | 1;
1009                                vertex.set_flags(next_flags);
1010                            }
1011                        }
1012                    }
1013                    if let Some(uv1_acc) = attrs.get(ATTR_TEXCOORD_1).and_then(Value::as_u64) {
1014                        let (uv_floats, uv_count, uv_comps): (Vec<f32>, usize, usize) =
1015                            decode_accessor_f32(&root, &buffers, uv1_acc as usize)?;
1016                        if uv_comps >= 2 && uv_count >= vert_count {
1017                            for (v_idx, vertex) in vertices.iter_mut().enumerate().take(vert_count)
1018                            {
1019                                let base: usize = v_idx * uv_comps;
1020                                vertex.set_uv1([uv_floats[base], uv_floats[base + 1]]);
1021                                let next_flags: u32 = vertex.get_flags() | 2;
1022                                vertex.set_flags(next_flags);
1023                            }
1024                        }
1025                    }
1026                    if let Some(col_acc) = attrs.get(ATTR_COLOR_0).and_then(Value::as_u64) {
1027                        let (c_floats, c_count, c_comps): (Vec<f32>, usize, usize) =
1028                            decode_accessor_f32(&root, &buffers, col_acc as usize)?;
1029                        if c_comps >= 3 && c_count >= vert_count {
1030                            for (v_idx, vertex) in vertices.iter_mut().enumerate().take(vert_count)
1031                            {
1032                                let base: usize = v_idx * c_comps;
1033                                let r_u8: u8 =
1034                                    (c_floats[base].clamp(0.0, 1.0) * 255.0).round() as u8;
1035                                let g_u8: u8 =
1036                                    (c_floats[base + 1].clamp(0.0, 1.0) * 255.0).round() as u8;
1037                                let b_u8: u8 =
1038                                    (c_floats[base + 2].clamp(0.0, 1.0) * 255.0).round() as u8;
1039                                let a_u8: u8 = if c_comps >= 4 {
1040                                    (c_floats[base + 3].clamp(0.0, 1.0) * 255.0).round() as u8
1041                                } else {
1042                                    255
1043                                };
1044                                vertex.set_color0([r_u8, g_u8, b_u8, a_u8]);
1045                                let next_flags: u32 = vertex.get_flags() | 8;
1046                                vertex.set_flags(next_flags);
1047                            }
1048                        }
1049                    }
1050                    let mut skin_influences: Vec<MeshSkinInfluence3D> = Vec::new();
1051                    if let Some(j0_acc) = attrs.get(ATTR_JOINTS_0).and_then(Value::as_u64)
1052                        && let Some(w0_acc) = attrs.get(ATTR_WEIGHTS_0).and_then(Value::as_u64)
1053                    {
1054                        let (j0_vals, j0_cnt, j0_c): (Vec<u32>, usize, usize) =
1055                            decode_accessor_u32(&root, &buffers, j0_acc as usize)?;
1056                        let (w0_vals, w0_cnt, w0_c): (Vec<f32>, usize, usize) =
1057                            decode_accessor_f32(&root, &buffers, w0_acc as usize)?;
1058                        let j1_data: Option<(Vec<u32>, usize, usize)> = attrs
1059                            .get(ATTR_JOINTS_1)
1060                            .and_then(Value::as_u64)
1061                            .and_then(|id: u64| {
1062                                decode_accessor_u32(&root, &buffers, id as usize).ok()
1063                            });
1064                        let w1_data: Option<(Vec<f32>, usize, usize)> =
1065                            attrs.get(ATTR_WEIGHTS_1).and_then(Value::as_u64).and_then(
1066                                |id: u64| decode_accessor_f32(&root, &buffers, id as usize).ok(),
1067                            );
1068                        if j0_c >= 4 && w0_c >= 4 && j0_cnt >= vert_count && w0_cnt >= vert_count {
1069                            skin_influences.reserve(vert_count);
1070                            for v_idx in 0..vert_count {
1071                                let jb: usize = v_idx * j0_c;
1072                                let wb: usize = v_idx * w0_c;
1073                                let joints_0: [u16; 4] = [
1074                                    j0_vals[jb] as u16,
1075                                    j0_vals[jb + 1] as u16,
1076                                    j0_vals[jb + 2] as u16,
1077                                    j0_vals[jb + 3] as u16,
1078                                ];
1079                                let mut weights_0: [f32; 4] = [
1080                                    w0_vals[wb].max(0.0),
1081                                    w0_vals[wb + 1].max(0.0),
1082                                    w0_vals[wb + 2].max(0.0),
1083                                    w0_vals[wb + 3].max(0.0),
1084                                ];
1085                                let mut joints_1: [u16; 4] = [0u16; 4];
1086                                let mut weights_1: [f32; 4] = [0.0; 4];
1087                                if let (Some((j1v, j1cnt, j1c)), Some((w1v, w1cnt, w1c))) =
1088                                    (&j1_data, &w1_data)
1089                                    && *j1c >= 4
1090                                    && *w1c >= 4
1091                                    && *j1cnt >= vert_count
1092                                    && *w1cnt >= vert_count
1093                                {
1094                                    let j1b: usize = v_idx * (*j1c);
1095                                    let w1b: usize = v_idx * (*w1c);
1096                                    joints_1 = [
1097                                        j1v[j1b] as u16,
1098                                        j1v[j1b + 1] as u16,
1099                                        j1v[j1b + 2] as u16,
1100                                        j1v[j1b + 3] as u16,
1101                                    ];
1102                                    weights_1 = [
1103                                        w1v[w1b].max(0.0),
1104                                        w1v[w1b + 1].max(0.0),
1105                                        w1v[w1b + 2].max(0.0),
1106                                        w1v[w1b + 3].max(0.0),
1107                                    ];
1108                                }
1109                                let sum_w: f32 = weights_0[0]
1110                                    + weights_0[1]
1111                                    + weights_0[2]
1112                                    + weights_0[3]
1113                                    + weights_1[0]
1114                                    + weights_1[1]
1115                                    + weights_1[2]
1116                                    + weights_1[3];
1117                                if sum_w > 1e-6 {
1118                                    let inv_w: f32 = 1.0 / sum_w;
1119                                    for lane in 0..4usize {
1120                                        weights_0[lane] *= inv_w;
1121                                        weights_1[lane] *= inv_w;
1122                                    }
1123                                }
1124                                skin_influences.push(MeshSkinInfluence3D::new(
1125                                    joints_0, weights_0, joints_1, weights_1,
1126                                ));
1127                            }
1128                        }
1129                    }
1130                    let mut morph_targets: Vec<MorphTarget3D> = Vec::new();
1131                    if let Some(targets_arr) = prim.get(KEY_TARGETS).and_then(Value::as_array) {
1132                        for (t_idx, target_val) in targets_arr.iter().enumerate() {
1133                            let target_name: String = target_names
1134                                .get(t_idx)
1135                                .cloned()
1136                                .unwrap_or_else(|| format!("shape_key_{t_idx}"));
1137                            let mut delta_positions: Vec<[f32; 3]> = Vec::new();
1138                            if let Some(dp_acc) =
1139                                target_val.get(ATTR_POSITION).and_then(Value::as_u64)
1140                            {
1141                                let (dp, cnt, comps): (Vec<f32>, usize, usize) =
1142                                    decode_accessor_f32(&root, &buffers, dp_acc as usize)?;
1143                                if comps >= 3 {
1144                                    delta_positions.reserve(cnt);
1145                                    for i in 0..cnt {
1146                                        let b: usize = i * comps;
1147                                        delta_positions.push([dp[b], dp[b + 1], dp[b + 2]]);
1148                                    }
1149                                }
1150                            }
1151                            let mut delta_normals: Vec<[f32; 3]> = Vec::new();
1152                            if let Some(dn_acc) =
1153                                target_val.get(ATTR_NORMAL).and_then(Value::as_u64)
1154                            {
1155                                let (dn, cnt, comps): (Vec<f32>, usize, usize) =
1156                                    decode_accessor_f32(&root, &buffers, dn_acc as usize)?;
1157                                if comps >= 3 {
1158                                    delta_normals.reserve(cnt);
1159                                    for i in 0..cnt {
1160                                        let b: usize = i * comps;
1161                                        delta_normals.push([dn[b], dn[b + 1], dn[b + 2]]);
1162                                    }
1163                                }
1164                            }
1165                            let mut delta_tangents: Vec<[f32; 3]> = Vec::new();
1166                            if let Some(dt_acc) =
1167                                target_val.get(ATTR_TANGENT).and_then(Value::as_u64)
1168                            {
1169                                let (dt, cnt, comps): (Vec<f32>, usize, usize) =
1170                                    decode_accessor_f32(&root, &buffers, dt_acc as usize)?;
1171                                if comps >= 3 {
1172                                    delta_tangents.reserve(cnt);
1173                                    for i in 0..cnt {
1174                                        let b: usize = i * comps;
1175                                        delta_tangents.push([dt[b], dt[b + 1], dt[b + 2]]);
1176                                    }
1177                                }
1178                            }
1179                            morph_targets.push(MorphTarget3D {
1180                                name: target_name,
1181                                delta_positions,
1182                                delta_normals,
1183                                delta_tangents,
1184                            });
1185                        }
1186                    }
1187                    let raw_indices: Vec<u32> =
1188                        if let Some(idx_acc) = prim.get(KEY_INDICES).and_then(Value::as_u64) {
1189                            let (vals, _, _): (Vec<u32>, usize, usize) =
1190                                decode_accessor_u32(&root, &buffers, idx_acc as usize)?;
1191                            vals
1192                        } else {
1193                            (0..(vert_count as u32)).collect()
1194                        };
1195                    let mode: u32 = prim
1196                        .get(KEY_MODE)
1197                        .and_then(Value::as_u64)
1198                        .unwrap_or(u64::from(GLTF_MODE_TRIANGLES))
1199                        as u32;
1200                    let tris: Vec<[u32; 3]> = assemble_primitive_triangles(&raw_indices, mode);
1201                    if !tris.is_empty() {
1202                        let mut built: Mesh3D =
1203                            Mesh3D::from_parts(prim_name, vertices, tris, legacy_mat);
1204                        if !has_normals {
1205                            built.compute_smooth_normals();
1206                        }
1207                        if !has_tangents {
1208                            built.compute_lengyel_tangents();
1209                        }
1210                        built.set_skin_influences(skin_influences);
1211                        built.set_morph_targets(morph_targets);
1212                        built.set_material_index(mat_opt);
1213                        meshes.push(built);
1214                    }
1215                } else {
1216                    let extras: &Value = prim.get(KEY_EXTRAS).unwrap_or(prim);
1217                    let pos_vals: Vec<f32> = extras
1218                        .get(KEY_LEGACY_POSITIONS)
1219                        .and_then(Value::as_array)
1220                        .map(|arr: &Vec<Value>| {
1221                            arr.iter()
1222                                .filter_map(|item: &Value| item.as_f64().map(|val: f64| val as f32))
1223                                .collect()
1224                        })
1225                        .unwrap_or_default();
1226                    let idx_vals: Vec<u32> = extras
1227                        .get(KEY_INDICES)
1228                        .and_then(Value::as_array)
1229                        .map(|arr: &Vec<Value>| {
1230                            arr.iter()
1231                                .filter_map(|item: &Value| item.as_u64().map(|val: u64| val as u32))
1232                                .collect()
1233                        })
1234                        .unwrap_or_default();
1235                    let raw_pts: Vec<Vec3> = pos_vals
1236                        .as_chunks::<3>()
1237                        .0
1238                        .iter()
1239                        .map(|chunk: &[f32; 3]| Vec3::new(chunk[0], chunk[1], chunk[2]))
1240                        .collect();
1241                    let mut verts: Vec<Vertex3D> = Vec::new();
1242                    let mut tris: Vec<[u32; 3]> = Vec::new();
1243                    for tri in idx_vals.as_chunks::<3>().0 {
1244                        let (i0, i1, i2): (usize, usize, usize) =
1245                            (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1246                        if i0 < raw_pts.len() && i1 < raw_pts.len() && i2 < raw_pts.len() {
1247                            let p0: Vec3 = raw_pts[i0];
1248                            let p1: Vec3 = raw_pts[i1];
1249                            let p2: Vec3 = raw_pts[i2];
1250                            let face_n: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
1251                            let base: u32 = verts.len() as u32;
1252                            verts.push(Vertex3D::new(p0, face_n));
1253                            verts.push(Vertex3D::new(p1, face_n));
1254                            verts.push(Vertex3D::new(p2, face_n));
1255                            tris.push([base, base + 1, base + 2]);
1256                        }
1257                    }
1258                    if !tris.is_empty() {
1259                        let mut built: Mesh3D =
1260                            Mesh3D::from_parts(prim_name, verts, tris, legacy_mat);
1261                        built.set_material_index(mat_opt);
1262                        meshes.push(built);
1263                    }
1264                }
1265            }
1266        }
1267    }
1268    let mut skins: Vec<ImportedSkin3D> = Vec::new();
1269    if let Some(skins_arr) = root.get(KEY_SKINS).and_then(Value::as_array) {
1270        for (skin_idx, skin_val) in skins_arr.iter().enumerate() {
1271            let name: String = skin_val
1272                .get(KEY_NAME)
1273                .and_then(Value::as_str)
1274                .map(str::to_string)
1275                .unwrap_or_else(|| format!("skin_{skin_idx}"));
1276            let joints: Vec<u32> = skin_val
1277                .get(KEY_JOINTS)
1278                .and_then(Value::as_array)
1279                .map(|arr: &Vec<Value>| {
1280                    arr.iter()
1281                        .filter_map(|item: &Value| item.as_u64().map(|id: u64| id as u32))
1282                        .collect()
1283                })
1284                .unwrap_or_default();
1285            let skeleton_root: Option<u32> = skin_val
1286                .get(KEY_SKELETON)
1287                .and_then(Value::as_u64)
1288                .map(|id: u64| id as u32);
1289            let mut inverse_bind_matrices: Vec<Mat4> = Vec::with_capacity(joints.len());
1290            if let Some(ibm_acc) = skin_val.get(KEY_INV_BIND_MATRICES).and_then(Value::as_u64) {
1291                let (floats, count, comps): (Vec<f32>, usize, usize) =
1292                    decode_accessor_f32(&root, &buffers, ibm_acc as usize)?;
1293                if comps == 16 {
1294                    for idx in 0..count {
1295                        let base: usize = idx * 16;
1296                        let mut elems: [f32; 16] = [0.0; 16];
1297                        elems.copy_from_slice(&floats[base..(base + 16)]);
1298                        inverse_bind_matrices.push(Mat4::from_cols_array(elems));
1299                    }
1300                }
1301            }
1302            while inverse_bind_matrices.len() < joints.len() {
1303                inverse_bind_matrices.push(Mat4::identity());
1304            }
1305            skins.push(ImportedSkin3D {
1306                name,
1307                joints,
1308                skeleton_root,
1309                inverse_bind_matrices,
1310            });
1311        }
1312    }
1313    let mut animations: Vec<ImportedAnimationClip3D> = Vec::new();
1314    if let Some(anims_arr) = root.get(KEY_ANIMATIONS).and_then(Value::as_array) {
1315        for (anim_idx, anim_val) in anims_arr.iter().enumerate() {
1316            let name: String = anim_val
1317                .get(KEY_NAME)
1318                .and_then(Value::as_str)
1319                .map(str::to_string)
1320                .unwrap_or_else(|| format!("animation_{anim_idx}"));
1321            let mut duration_secs: f32 = 0.0;
1322            let mut parsed_samplers: Vec<ImportedAnimationSampler3D> = Vec::new();
1323            if let Some(samps_arr) = anim_val.get(KEY_SAMPLERS).and_then(Value::as_array) {
1324                for samp_val in samps_arr.iter() {
1325                    let Some(in_acc) = samp_val.get(KEY_INPUT).and_then(Value::as_u64) else {
1326                        parsed_samplers.push(ImportedAnimationSampler3D::default());
1327                        continue;
1328                    };
1329                    let Some(out_acc) = samp_val.get(KEY_OUTPUT).and_then(Value::as_u64) else {
1330                        parsed_samplers.push(ImportedAnimationSampler3D::default());
1331                        continue;
1332                    };
1333                    let (timestamps, t_cnt, _): (Vec<f32>, usize, usize) =
1334                        decode_accessor_f32(&root, &buffers, in_acc as usize)?;
1335                    let (values, v_cnt, v_comps): (Vec<f32>, usize, usize) =
1336                        decode_accessor_f32(&root, &buffers, out_acc as usize)?;
1337                    for &ts in timestamps.iter() {
1338                        if ts > duration_secs {
1339                            duration_secs = ts;
1340                        }
1341                    }
1342                    let interp: GltfInterpolationMode =
1343                        match samp_val.get(KEY_INTERPOLATION).and_then(Value::as_str) {
1344                            Some(INTERP_STEP) => GltfInterpolationMode::Step,
1345                            Some(INTERP_CUBICSPLINE) => GltfInterpolationMode::CubicSpline,
1346                            _ => GltfInterpolationMode::Linear,
1347                        };
1348                    let per_key_mult: usize = if interp == GltfInterpolationMode::CubicSpline {
1349                        3
1350                    } else {
1351                        1
1352                    };
1353                    let denom: usize = t_cnt.saturating_mul(per_key_mult).max(1);
1354                    let value_stride: usize = ((v_cnt * v_comps) / denom).max(1);
1355                    parsed_samplers.push(ImportedAnimationSampler3D {
1356                        timestamps,
1357                        values,
1358                        value_stride,
1359                        interpolation: interp,
1360                    });
1361                }
1362            }
1363            let mut parsed_channels: Vec<ImportedAnimationChannel3D> = Vec::new();
1364            if let Some(ch_arr) = anim_val.get(KEY_CHANNELS).and_then(Value::as_array) {
1365                for ch_val in ch_arr.iter() {
1366                    let Some(sampler_index) = ch_val.get(KEY_SAMPLER).and_then(Value::as_u64)
1367                    else {
1368                        continue;
1369                    };
1370                    let Some(target_obj) = ch_val.get(KEY_TARGET) else {
1371                        continue;
1372                    };
1373                    let Some(target_node) = target_obj.get(KEY_NODE).and_then(Value::as_u64) else {
1374                        continue;
1375                    };
1376                    let Some(path_str) = target_obj.get(KEY_PATH).and_then(Value::as_str) else {
1377                        continue;
1378                    };
1379                    let path: GltfAnimationPath = if path_str == KEY_TRANSLATION {
1380                        GltfAnimationPath::Translation
1381                    } else if path_str == KEY_ROTATION {
1382                        GltfAnimationPath::Rotation
1383                    } else if path_str == KEY_SCALE {
1384                        GltfAnimationPath::Scale
1385                    } else if path_str == KEY_WEIGHTS {
1386                        GltfAnimationPath::MorphWeights
1387                    } else {
1388                        continue;
1389                    };
1390                    parsed_channels.push(ImportedAnimationChannel3D::new(
1391                        target_node as u32,
1392                        path,
1393                        sampler_index as usize,
1394                    ));
1395                }
1396            }
1397            animations.push(ImportedAnimationClip3D {
1398                name,
1399                duration_secs,
1400                samplers: parsed_samplers,
1401                channels: parsed_channels,
1402            });
1403        }
1404    }
1405    let mut cameras: Vec<ImportedCamera3D> = Vec::new();
1406    if let Some(cams_arr) = root.get(KEY_CAMERAS).and_then(Value::as_array) {
1407        for (cam_idx, cam_val) in cams_arr.iter().enumerate() {
1408            let name: String = cam_val
1409                .get(KEY_NAME)
1410                .and_then(Value::as_str)
1411                .map(str::to_string)
1412                .unwrap_or_else(|| format!("camera_{cam_idx}"));
1413            if let Some(persp) = cam_val.get(KEY_PERSPECTIVE) {
1414                let yfov_rad: f32 =
1415                    persp.get(KEY_YFOV).and_then(Value::as_f64).unwrap_or(0.8) as f32;
1416                let aspect_ratio: Option<f32> = persp
1417                    .get(KEY_ASPECT_RATIO)
1418                    .and_then(Value::as_f64)
1419                    .map(|val: f64| val as f32);
1420                let znear: f32 = persp.get(KEY_ZNEAR).and_then(Value::as_f64).unwrap_or(0.1) as f32;
1421                let zfar: Option<f32> = persp
1422                    .get(KEY_ZFAR)
1423                    .and_then(Value::as_f64)
1424                    .map(|val: f64| val as f32);
1425                cameras.push(ImportedCamera3D {
1426                    name,
1427                    projection: GltfCameraProjection::Perspective {
1428                        yfov_rad,
1429                        aspect_ratio,
1430                        znear,
1431                        zfar,
1432                    },
1433                });
1434            } else if let Some(ortho) = cam_val.get(KEY_ORTHOGRAPHIC) {
1435                let xmag: f32 = ortho.get(KEY_XMAG).and_then(Value::as_f64).unwrap_or(1.0) as f32;
1436                let ymag: f32 = ortho.get(KEY_YMAG).and_then(Value::as_f64).unwrap_or(1.0) as f32;
1437                let znear: f32 = ortho.get(KEY_ZNEAR).and_then(Value::as_f64).unwrap_or(0.1) as f32;
1438                let zfar: f32 = ortho.get(KEY_ZFAR).and_then(Value::as_f64).unwrap_or(100.0) as f32;
1439                cameras.push(ImportedCamera3D {
1440                    name,
1441                    projection: GltfCameraProjection::Orthographic {
1442                        xmag,
1443                        ymag,
1444                        znear,
1445                        zfar,
1446                    },
1447                });
1448            }
1449        }
1450    }
1451    let mut lights: Vec<ImportedLight3D> = Vec::new();
1452    if let Some(lights_arr) = root
1453        .get(KEY_EXTENSIONS)
1454        .and_then(|ext: &Value| ext.get(GLTF_EXT_LIGHTS_PUNCTUAL))
1455        .and_then(|lp: &Value| lp.get(KEY_LIGHTS))
1456        .and_then(Value::as_array)
1457    {
1458        for (light_idx, light_val) in lights_arr.iter().enumerate() {
1459            let name: String = light_val
1460                .get(KEY_NAME)
1461                .and_then(Value::as_str)
1462                .map(str::to_string)
1463                .unwrap_or_else(|| format!("light_{light_idx}"));
1464            let color_arr: [f32; 3] = json_f32_3(light_val.get(KEY_COLOR), [1.0, 1.0, 1.0]);
1465            let intensity: f32 = light_val
1466                .get(KEY_INTENSITY)
1467                .and_then(Value::as_f64)
1468                .unwrap_or(1.0) as f32;
1469            let range: Option<f32> = light_val
1470                .get(KEY_RANGE)
1471                .and_then(Value::as_f64)
1472                .map(|val: f64| val as f32);
1473            let light_type: &str = light_val
1474                .get(KEY_TYPE)
1475                .and_then(Value::as_str)
1476                .unwrap_or(LIGHT_TYPE_POINT);
1477            let kind: GltfLightKind = if light_type == LIGHT_TYPE_DIRECTIONAL {
1478                GltfLightKind::Directional
1479            } else if light_type == LIGHT_TYPE_SPOT {
1480                let spot_obj: Option<&Value> = light_val.get(KEY_SPOT);
1481                let inner_cone_angle: f32 = spot_obj
1482                    .and_then(|s: &Value| s.get(KEY_INNER_CONE))
1483                    .and_then(Value::as_f64)
1484                    .unwrap_or(0.0) as f32;
1485                let outer_cone_angle: f32 = spot_obj
1486                    .and_then(|s: &Value| s.get(KEY_OUTER_CONE))
1487                    .and_then(Value::as_f64)
1488                    .map(|val: f64| val as f32)
1489                    .unwrap_or(FRAC_PI_2 * 0.5);
1490                GltfLightKind::Spot {
1491                    range,
1492                    inner_cone_angle,
1493                    outer_cone_angle,
1494                }
1495            } else if light_type == LIGHT_TYPE_AREA {
1496                GltfLightKind::Area {
1497                    width: 1.0,
1498                    height: 1.0,
1499                }
1500            } else {
1501                GltfLightKind::Point { range }
1502            };
1503            lights.push(ImportedLight3D {
1504                name,
1505                color: Vec3::from_array(color_arr),
1506                intensity,
1507                kind,
1508            });
1509        }
1510    }
1511    let mut scene_graph: SceneGraph3D = SceneGraph3D::default();
1512    if let Some(nodes_arr) = root.get(KEY_NODES).and_then(Value::as_array) {
1513        let mut parent_of: Vec<Option<u32>> = vec![None; nodes_arr.len()];
1514        for (parent_idx, node_val) in nodes_arr.iter().enumerate() {
1515            if let Some(children) = node_val.get(KEY_CHILDREN).and_then(Value::as_array) {
1516                for child_val in children.iter() {
1517                    if let Some(child_idx) = child_val.as_u64() {
1518                        let c_usize: usize = child_idx as usize;
1519                        if c_usize < parent_of.len() {
1520                            parent_of[c_usize] = Some(parent_idx as u32);
1521                        }
1522                    }
1523                }
1524            }
1525        }
1526        for (node_idx, node_val) in nodes_arr.iter().enumerate() {
1527            let name: String = node_val
1528                .get(KEY_NAME)
1529                .and_then(Value::as_str)
1530                .map(str::to_string)
1531                .unwrap_or_else(|| format!("node_{node_idx}"));
1532            let mut node: SceneNode3D = SceneNode3D::from_name(&name, parent_of[node_idx]);
1533            if let Some(mat_arr) = node_val.get(KEY_MATRIX).and_then(Value::as_array)
1534                && mat_arr.len() == 16
1535            {
1536                let mut elems: [f32; 16] = [0.0; 16];
1537                for i in 0..16usize {
1538                    elems[i] = mat_arr[i].as_f64().unwrap_or(0.0) as f32;
1539                }
1540                let (tr, rot, sc): (Vec3, Quat, Vec3) =
1541                    Mat4::from_cols_array(elems).decompose_trs();
1542                node.set_local_translation(tr);
1543                node.set_local_rotation(rot);
1544                node.set_local_scale(sc);
1545            } else {
1546                let tr: [f32; 3] = json_f32_3(node_val.get(KEY_TRANSLATION), [0.0, 0.0, 0.0]);
1547                let rot: [f32; 4] = json_f32_4(node_val.get(KEY_ROTATION), [0.0, 0.0, 0.0, 1.0]);
1548                let sc: [f32; 3] = json_f32_3(node_val.get(KEY_SCALE), [1.0, 1.0, 1.0]);
1549                node.set_local_translation(Vec3::from_array(tr));
1550                node.set_local_rotation(Quat::from_array(rot).normalize());
1551                node.set_local_scale(Vec3::from_array(sc));
1552            }
1553            if let Some(mesh_idx) = node_val.get(KEY_MESH).and_then(Value::as_u64)
1554                && let Some(&first_prim) = gltf_mesh_to_first_prim.get(mesh_idx as usize)
1555                && first_prim < meshes.len()
1556            {
1557                node.set_mesh_id(Some(first_prim as u32));
1558            }
1559            if let Some(skin_idx) = node_val.get(KEY_SKIN).and_then(Value::as_u64) {
1560                node.set_skin_id(Some(skin_idx as u32));
1561            }
1562            if let Some(cam_idx) = node_val.get(KEY_CAMERA).and_then(Value::as_u64) {
1563                node.set_camera_id(Some(cam_idx as u32));
1564            }
1565            if let Some(light_idx) = node_val
1566                .get(KEY_EXTENSIONS)
1567                .and_then(|ext: &Value| ext.get(GLTF_EXT_LIGHTS_PUNCTUAL))
1568                .and_then(|lp: &Value| lp.get(KEY_LIGHT))
1569                .and_then(Value::as_u64)
1570            {
1571                node.set_light_id(Some(light_idx as u32));
1572            }
1573            if let Some(extras_obj) = node_val.get(KEY_EXTRAS) {
1574                let euv_obj: &Value = extras_obj.get("euv").unwrap_or(extras_obj);
1575                if let Some(colls) = euv_obj
1576                    .get(KEY_EUV_COLLECTIONS)
1577                    .or_else(|| extras_obj.get(KEY_EUV_COLLECTIONS))
1578                    .and_then(Value::as_array)
1579                {
1580                    let mut mask: u64 = 0;
1581                    for coll_val in colls.iter() {
1582                        if let Some(coll_name) = coll_val.as_str() {
1583                            mask |= scene_graph
1584                                .get_mut_collections()
1585                                .register_collection(coll_name);
1586                        }
1587                    }
1588                    if mask != 0 {
1589                        node.set_collection_mask(mask);
1590                    }
1591                }
1592                let mut tags: BlenderExtrasTags3D = BlenderExtrasTags3D::default();
1593                if let Some(col_str) = euv_obj.get(KEY_EUV_COLLIDER).and_then(Value::as_str) {
1594                    let shape: SceneColliderShape3D = if col_str == COLLIDER_SPHERE {
1595                        SceneColliderShape3D::Sphere
1596                    } else if col_str == COLLIDER_CONVEX || col_str == COLLIDER_CONVEX_HULL {
1597                        SceneColliderShape3D::ConvexHull
1598                    } else if col_str == COLLIDER_MESH {
1599                        SceneColliderShape3D::Mesh
1600                    } else if col_str == "box" {
1601                        SceneColliderShape3D::Box
1602                    } else {
1603                        SceneColliderShape3D::None
1604                    };
1605                    tags.set_collider(shape);
1606                }
1607                if let Some(buoy) = euv_obj.get(KEY_EUV_BUOYANCY).and_then(Value::as_f64) {
1608                    tags.set_buoyancy_density(buoy as f32);
1609                }
1610                if let Some(trig) = euv_obj.get(KEY_EUV_TRIGGER).and_then(Value::as_bool) {
1611                    tags.set_is_trigger(trig);
1612                }
1613                if let Some(cast) = euv_obj.get(KEY_EUV_CAST_SHADOWS).and_then(Value::as_bool) {
1614                    tags.set_cast_shadows(cast);
1615                }
1616                if let Ok(raw_json) = to_string(extras_obj) {
1617                    tags.set_custom_json(Some(raw_json));
1618                }
1619                node.set_extras(tags);
1620            }
1621            let added_id: u32 = scene_graph.add_node(node);
1622            if let Some(weights_arr) = node_val.get(KEY_WEIGHTS).and_then(Value::as_array) {
1623                let w_vec: Vec<f32> = weights_arr
1624                    .iter()
1625                    .filter_map(|item: &Value| item.as_f64().map(|val: f64| val as f32))
1626                    .collect();
1627                scene_graph.attach_morph_weights(added_id, &w_vec);
1628            }
1629        }
1630        let _: usize = scene_graph.propagate_world_matrices();
1631    }
1632    Ok(ImportedScene3D {
1633        name: scene_name,
1634        generator,
1635        scene_graph,
1636        meshes,
1637        materials,
1638        textures,
1639        skins,
1640        animations,
1641        cameras,
1642        lights,
1643    })
1644}
1645
1646/// Parses a self-contained binary Khronos GLB v2 container (`.glb`) into an `ImportedScene3D`.
1647///
1648/// # Arguments
1649///
1650/// - `&[u8]` - Raw `.glb` file bytes.
1651///
1652/// # Returns
1653///
1654/// - `Result<ImportedScene3D, String>` - Fully imported scene bundle or validation error.
1655pub fn parse_glb_bytes(bytes: &[u8]) -> Result<ImportedScene3D, String> {
1656    if bytes.len() < 20 {
1657        return Err(ERR_GLB_INVALID.to_string());
1658    }
1659    let magic: u32 = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
1660    let version: u32 = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
1661    let total_len: usize = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;
1662    if magic != GLB_MAGIC || version != GLB_VERSION_2 || total_len > bytes.len() || total_len < 20 {
1663        return Err(ERR_GLB_INVALID.to_string());
1664    }
1665    let mut cursor: usize = 12;
1666    let mut json_slice: Option<&[u8]> = None;
1667    let mut bin_slice: Option<&[u8]> = None;
1668    while cursor + 8 <= total_len {
1669        let chunk_len: usize = u32::from_le_bytes([
1670            bytes[cursor],
1671            bytes[cursor + 1],
1672            bytes[cursor + 2],
1673            bytes[cursor + 3],
1674        ]) as usize;
1675        let chunk_type: u32 = u32::from_le_bytes([
1676            bytes[cursor + 4],
1677            bytes[cursor + 5],
1678            bytes[cursor + 6],
1679            bytes[cursor + 7],
1680        ]);
1681        let payload_start: usize = cursor + 8;
1682        let payload_end: usize = payload_start.saturating_add(chunk_len);
1683        if payload_end > total_len {
1684            return Err(ERR_GLB_INVALID.to_string());
1685        }
1686        if chunk_type == GLB_CHUNK_JSON && json_slice.is_none() {
1687            json_slice = Some(&bytes[payload_start..payload_end]);
1688        } else if chunk_type == GLB_CHUNK_BIN && bin_slice.is_none() {
1689            bin_slice = Some(&bytes[payload_start..payload_end]);
1690        }
1691        cursor = payload_end;
1692    }
1693    let raw_json: &[u8] = json_slice.ok_or_else(|| ERR_GLB_INVALID.to_string())?;
1694    let json_text: &str = from_utf8(raw_json)
1695        .ok()
1696        .ok_or_else(|| ERR_GLB_INVALID.to_string())?;
1697    parse_gltf_document(json_text, bin_slice, None)
1698}
1699
1700/// Parses either a binary `.glb` container or UTF-8 `.gltf` JSON byte slice with optional external URI resolver.
1701///
1702/// # Arguments
1703///
1704/// - `&[u8]` - Raw `.glb` or `.gltf` bytes.
1705/// - `Option<&dyn GltfBufferResolver>` - Optional external buffer/image resolver for `.gltf`.
1706///
1707/// # Returns
1708///
1709/// - `Result<ImportedScene3D, String>` - Imported scene bundle or parse error.
1710pub fn parse_gltf_or_glb_bytes(
1711    bytes: &[u8],
1712    resolver: Option<&dyn GltfBufferResolver>,
1713) -> Result<ImportedScene3D, String> {
1714    if bytes.len() >= 4 && u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) == GLB_MAGIC
1715    {
1716        return parse_glb_bytes(bytes);
1717    }
1718    let json_text: &str = from_utf8(bytes)
1719        .ok()
1720        .ok_or_else(|| ERR_GLTF_PARSE.to_string())?;
1721    parse_gltf_document(json_text, None, resolver)
1722}