Skip to main content

qualia_core_db/render/assets/
glb.rs

1use serde_json::Value;
2
3use super::glb_materials::{gltf_default_material, parse_gltf_materials};
4use super::tangents::{
5    default_tangent_for_normal, generate_import_normals, generate_mikktspace_tangents,
6    normalize_imported_normal, orthogonalize_imported_tangent,
7};
8use super::{AssetError, ImportedMesh, Mesh, CHUNK_BIN, CHUNK_JSON, GLB_MAGIC};
9use crate::container_10d::SubmeshRange;
10/// `true` when the data looks like GLB.
11pub(super) fn looks_like_glb(bytes: &[u8]) -> bool {
12    bytes.len() >= 12 && u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) == GLB_MAGIC
13}
14
15/// Parse a binary glTF (`.glb`): the 12-byte header, JSON chunk, and BIN chunk, then walk
16/// `meshes[].primitives[]`, reading `POSITION` (FLOAT VEC3), optional `NORMAL` (FLOAT VEC3),
17/// optional `TANGENT` (FLOAT VEC4), optional `TEXCOORD_0` VEC2, and optional index accessors
18/// (u8/u16/u32 SCALAR) out of the BIN buffer. Triangle primitives only (mode 4); other
19/// modes are skipped (a faithful first cut). Embedded/external-URI buffers are not handled here —
20/// self-contained GLB binary only.
21pub fn import_glb(bytes: &[u8]) -> Result<Mesh, AssetError> {
22    import_glb_with_normals(bytes).map(|imported| imported.mesh)
23}
24
25/// GLB importer variant that retains NORMAL VEC3 and TANGENT VEC4 attributes, generates fallback
26/// normals where needed, and uses MikkTSpace with deterministic corner splitting when UV0 is
27/// available but authored tangents are absent. Authored tangent directions are orthogonalized
28/// before returning GPU streams.
29pub fn import_glb_with_normals(bytes: &[u8]) -> Result<ImportedMesh, AssetError> {
30    import_glb_impl(bytes, None)
31}
32
33/// Import the selected static scene, baking each node instance and its frames.
34/// The caller supplies hard output limits before instances are expanded.
35pub fn import_glb_static_scene(bytes: &[u8], max_vertices: usize, max_triangles: usize) -> Result<ImportedMesh, AssetError> {
36    import_glb_impl(bytes, Some((max_vertices, max_triangles)))
37}
38
39fn import_glb_impl(bytes: &[u8], scene_limits: Option<(usize, usize)>) -> Result<ImportedMesh, AssetError> {
40    if bytes.len() < 12 {
41        return Err(AssetError::Parse("GLB shorter than 12-byte header".into()));
42    }
43    if u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) != GLB_MAGIC {
44        return Err(AssetError::UnknownFormat);
45    }
46    // bytes[4..8] = version, bytes[8..12] = total length (not re-validated).
47
48    let mut json: Option<&[u8]> = None;
49    let mut bin: Option<&[u8]> = None;
50    let mut off = 12usize;
51    while off + 8 <= bytes.len() {
52        let clen = u32::from_le_bytes([bytes[off], bytes[off + 1], bytes[off + 2], bytes[off + 3]])
53            as usize;
54        let ctype = u32::from_le_bytes([
55            bytes[off + 4],
56            bytes[off + 5],
57            bytes[off + 6],
58            bytes[off + 7],
59        ]);
60        let dstart = off + 8;
61        let dend = dstart
62            .checked_add(clen)
63            .ok_or_else(|| AssetError::Parse("GLB chunk length overflow".into()))?;
64        if dend > bytes.len() {
65            return Err(AssetError::Parse("GLB chunk exceeds file".into()));
66        }
67        match ctype {
68            CHUNK_JSON => json = Some(&bytes[dstart..dend]),
69            CHUNK_BIN => bin = Some(&bytes[dstart..dend]),
70            _ => {}
71        }
72        off = dend;
73    }
74
75    let json = json.ok_or_else(|| AssetError::Parse("GLB has no JSON chunk".into()))?;
76    let gltf: Value =
77        serde_json::from_slice(json).map_err(|e| AssetError::Parse(format!("glTF JSON: {e}")))?;
78    let bin = bin.unwrap_or(&[]);
79
80    let empty: Vec<Value> = Vec::new();
81    let accessors = gltf["accessors"].as_array().unwrap_or(&empty);
82    let buffer_views = gltf["bufferViews"].as_array().unwrap_or(&empty);
83    let meshes = gltf["meshes"].as_array().unwrap_or(&empty);
84    let (mut materials, texture_dependencies) = parse_gltf_materials(&gltf, buffer_views, bin)?;
85    let implicit_default_id = materials.len() as u64 + 1;
86    let mut uses_implicit_default = false;
87
88    let mut positions: Vec<[f32; 3]> = Vec::new();
89    let mut triangles: Vec<[u32; 3]> = Vec::new();
90    let mut normals: Vec<[f32; 3]> = Vec::new();
91    let mut saw_authored_normals = false;
92    let mut tangents: Vec<[f32; 4]> = Vec::new();
93    let mut saw_tangents = false;
94    let mut texture_coordinates_0: Vec<[f32; 2]> = Vec::new();
95    let mut saw_texture_coordinates_0 = false;
96    let mut submeshes = Vec::new();
97
98    let instances = if scene_limits.is_some() {
99        super::glb_static_scene::instances(&gltf, meshes.len())?
100    } else {
101        (0..meshes.len()).map(|i| (i, crate::specialized_libs::computational_geometry::authoring::identity())).collect()
102    };
103    for (mesh_index, world) in instances {
104        let mesh = &meshes[mesh_index];
105        for prim in mesh["primitives"].as_array().into_iter().flatten() {
106            if prim["mode"].as_u64().unwrap_or(4) != 4 {
107                continue; // not TRIANGLES
108            }
109            let pos_idx = prim["attributes"]["POSITION"]
110                .as_u64()
111                .ok_or_else(|| AssetError::Parse("primitive has no POSITION".into()))?
112                as usize;
113            let pos_acc = accessors
114                .get(pos_idx)
115                .ok_or_else(|| AssetError::Parse("POSITION accessor index out of range".into()))?;
116            if let Some((max_vertices, max_triangles)) = scene_limits {
117                let position_count = accessor_count(pos_acc)?;
118                let index_count = match prim["indices"].as_u64() {
119                    Some(i) => accessor_count(accessors.get(usize::try_from(i).map_err(|_| AssetError::Parse("index accessor out of range".into()))?).ok_or_else(|| AssetError::Parse("index accessor out of range".into()))?)?,
120                    None => position_count,
121                };
122                if position_count > max_vertices.saturating_sub(positions.len())
123                    || index_count > max_triangles.saturating_sub(triangles.len()).saturating_mul(3) {
124                    return Err(AssetError::Parse("GLB scene exceeds caller mesh budget".into()));
125                }
126                // MikkTSpace may allocate and split up to one vertex per index. Its
127                // temporary corner arrays are bounded by the same triangle budget.
128                for semantic in ["NORMAL", "TANGENT", "TEXCOORD_0"] {
129                    if let Some(i) = prim["attributes"][semantic].as_u64() {
130                        let accessor = accessors.get(usize::try_from(i).map_err(|_| AssetError::Parse(format!("{semantic} accessor out of range")))?).ok_or_else(|| AssetError::Parse(format!("{semantic} accessor out of range")))?;
131                        if accessor_count(accessor)? != position_count { return Err(AssetError::Parse(format!("{semantic} count must match POSITION count"))); }
132                    }
133                }
134            }
135            let mut prim_pos = read_positions(pos_acc, buffer_views, bin)?;
136            let vcount = prim_pos.len() as u32;
137            let mut prim_indices = match prim["indices"].as_u64() {
138                Some(idx_i) => {
139                    let idx_acc = accessors
140                        .get(idx_i as usize)
141                        .ok_or_else(|| AssetError::Parse("index accessor out of range".into()))?;
142                    read_indices(idx_acc, buffer_views, bin)?
143                }
144                None => (0..vcount).collect(),
145            };
146            if prim_indices.len() % 3 != 0 {
147                return Err(AssetError::Parse(
148                    "triangle index count must be divisible by 3".into(),
149                ));
150            }
151            if prim_indices.iter().any(|&i| i >= vcount) {
152                return Err(AssetError::Parse("primitive index out of range".into()));
153            }
154            let material_id = match prim["material"].as_u64() {
155                Some(index) if index < materials.len() as u64 => index + 1,
156                Some(_) => {
157                    return Err(AssetError::Parse(
158                        "primitive material index out of range".into(),
159                    ));
160                }
161                None => {
162                    uses_implicit_default = true;
163                    implicit_default_id
164                }
165            };
166            let mut prim_normals = match prim["attributes"]["NORMAL"].as_u64() {
167                Some(normal_idx) => {
168                    let accessor = accessors.get(normal_idx as usize).ok_or_else(|| {
169                        AssetError::Parse("NORMAL accessor index out of range".into())
170                    })?;
171                    let mut values = read_vec3(accessor, buffer_views, bin, "NORMAL")?;
172                    if values.len() != prim_pos.len() {
173                        return Err(AssetError::Parse(
174                            "NORMAL count must match POSITION count".into(),
175                        ));
176                    }
177                    for normal in &mut values {
178                        if normal.iter().any(|v| !v.is_finite()) {
179                            return Err(AssetError::Parse(
180                                "NORMAL contains non-finite values".into(),
181                            ));
182                        }
183                        *normal = normalize_imported_normal(*normal)?;
184                    }
185                    saw_authored_normals = true;
186                    values
187                }
188                None => generate_import_normals(&prim_pos, &prim_indices)?,
189            };
190            let mut prim_texcoords = match prim["attributes"]["TEXCOORD_0"].as_u64() {
191                Some(texcoord_idx) => {
192                    let accessor = accessors.get(texcoord_idx as usize).ok_or_else(|| {
193                        AssetError::Parse("TEXCOORD_0 accessor index out of range".into())
194                    })?;
195                    let values = read_texcoords_0(accessor, buffer_views, bin)?;
196                    if values.len() != prim_pos.len() {
197                        return Err(AssetError::Parse(
198                            "TEXCOORD_0 count must match POSITION count".into(),
199                        ));
200                    }
201                    saw_texture_coordinates_0 = true;
202                    values
203                }
204                None => vec![[0.0, 0.0]; prim_pos.len()],
205            };
206            let mut prim_tangents = match prim["attributes"]["TANGENT"].as_u64() {
207                Some(tangent_idx) => {
208                    let accessor = accessors.get(tangent_idx as usize).ok_or_else(|| {
209                        AssetError::Parse("TANGENT accessor index out of range".into())
210                    })?;
211                    let values = read_vec4(accessor, buffer_views, bin, "TANGENT")?;
212                    if values.len() != prim_pos.len() {
213                        return Err(AssetError::Parse(
214                            "TANGENT count must match POSITION count".into(),
215                        ));
216                    }
217                    saw_tangents = true;
218                    values
219                        .into_iter()
220                        .zip(&prim_normals)
221                        .map(|(tangent, normal)| orthogonalize_imported_tangent(tangent, *normal))
222                        .collect::<Result<Vec<_>, _>>()?
223                }
224                None => {
225                    if prim["attributes"]["TEXCOORD_0"].as_u64().is_some() {
226                        saw_tangents = true;
227                        let split = generate_mikktspace_tangents(
228                            &prim_pos,
229                            &prim_normals,
230                            &prim_texcoords,
231                            &prim_indices,
232                        )?;
233                        prim_pos = split
234                            .source_vertices
235                            .iter()
236                            .map(|&source| prim_pos[source as usize])
237                            .collect();
238                        prim_normals = split
239                            .source_vertices
240                            .iter()
241                            .map(|&source| prim_normals[source as usize])
242                            .collect();
243                        prim_texcoords = split
244                            .source_vertices
245                            .iter()
246                            .map(|&source| prim_texcoords[source as usize])
247                            .collect();
248                        prim_indices = split.indices;
249                        split.tangents
250                    } else {
251                        prim_normals
252                            .iter()
253                            .copied()
254                            .map(default_tangent_for_normal)
255                            .collect()
256                    }
257                }
258            };
259            if let Some((max_vertices, max_triangles)) = scene_limits {
260                if positions.len().checked_add(prim_pos.len()).is_none_or(|n| n > max_vertices)
261                    || triangles.len().checked_add(prim_indices.len() / 3).is_none_or(|n| n > max_triangles) {
262                    return Err(AssetError::Parse("GLB scene exceeds caller mesh budget".into()));
263                }
264                super::glb_static_scene::apply(&world, &mut prim_pos, &mut prim_normals, &mut prim_tangents, &mut prim_indices)?;
265            }
266            let base = u32::try_from(positions.len())
267                .map_err(|_| AssetError::Parse("GLB mesh exceeds the u32 vertex limit".into()))?;
268            let first_index = u32::try_from(triangles.len().saturating_mul(3))
269                .map_err(|_| AssetError::Parse("GLB index stream exceeds the u32 limit".into()))?;
270            positions.extend_from_slice(&prim_pos);
271            normals.extend_from_slice(&prim_normals);
272            tangents.extend_from_slice(&prim_tangents);
273            texture_coordinates_0.extend_from_slice(&prim_texcoords);
274            for c in prim_indices.chunks_exact(3) {
275                triangles.push([base + c[0], base + c[1], base + c[2]]);
276            }
277            let index_count = u32::try_from(prim_indices.len()).map_err(|_| {
278                AssetError::Parse("GLB primitive exceeds the u32 index limit".into())
279            })?;
280            if index_count != 0 {
281                submeshes.push(SubmeshRange {
282                    first_index,
283                    index_count,
284                    material_id,
285                    semantic_id: 0,
286                });
287            }
288        }
289    }
290
291    if uses_implicit_default {
292        let mut default_material = gltf_default_material();
293        default_material.id = implicit_default_id;
294        materials.push(default_material);
295    }
296    let mesh = Mesh::build(positions, triangles)?;
297    Ok(ImportedMesh {
298        mesh,
299        normals: saw_authored_normals.then_some(normals),
300        tangents: saw_tangents.then_some(tangents),
301        texture_coordinates_0: saw_texture_coordinates_0.then_some(texture_coordinates_0),
302        materials,
303        texture_dependencies,
304        submeshes,
305    })
306}
307
308fn accessor_count(accessor: &Value) -> Result<usize, AssetError> {
309    accessor["count"].as_u64().and_then(|v| usize::try_from(v).ok())
310        .ok_or_else(|| AssetError::Parse("invalid accessor.count".into()))
311}
312
313/// Prove the complete accessor range before allocating any output. glTF bufferView
314/// limits apply independently of the enclosing BIN chunk, including interleaved data.
315fn preflight_accessor(accessor: &Value, bvs: &[Value], bin: &[u8], element: usize, component: usize, allow_stride: bool) -> Result<(), AssetError> {
316    if accessor.get("sparse").is_some() { return Err(AssetError::Parse("sparse accessors are unsupported".into())); }
317    let parse = |v: Option<u64>| -> Result<usize, AssetError> { v.and_then(|x| usize::try_from(x).ok()).ok_or_else(|| AssetError::Parse("invalid accessor range".into())) };
318    let count = accessor_count(accessor)?;
319    let index = parse(accessor["bufferView"].as_u64())?;
320    let view = bvs.get(index).ok_or_else(|| AssetError::Parse("bufferView index out of range".into()))?;
321    if view["buffer"].as_u64().unwrap_or(0) != 0 { return Err(AssetError::Parse("GLB accessor references external buffer".into())); }
322    let offset = parse(Some(view["byteOffset"].as_u64().unwrap_or(0)))?;
323    let length = parse(view["byteLength"].as_u64())?;
324    let inner = parse(Some(accessor["byteOffset"].as_u64().unwrap_or(0)))?;
325    let stride = parse(Some(view["byteStride"].as_u64().unwrap_or(element as u64)))?;
326    if stride < element || stride % component != 0 || (!allow_stride && stride != element) {
327        return Err(AssetError::Parse("invalid accessor byteStride".into()));
328    }
329    let end = offset.checked_add(length).filter(|&n| n <= bin.len()).ok_or_else(|| AssetError::Parse("bufferView exceeds BIN".into()))?;
330    let start = offset.checked_add(inner).filter(|&n| n <= end).ok_or_else(|| AssetError::Parse("accessor offset exceeds bufferView".into()))?;
331    if count != 0 {
332        let last = (count - 1).checked_mul(stride).and_then(|n| start.checked_add(n)).and_then(|n| n.checked_add(element)).ok_or_else(|| AssetError::Parse("accessor range overflow".into()))?;
333        if last > end { return Err(AssetError::Parse("accessor exceeds bufferView".into())); }
334    }
335    Ok(())
336}
337
338/// Read a FLOAT VEC3 accessor (e.g. `POSITION`) out of the GLB binary buffer.
339fn read_positions(
340    accessor: &Value,
341    bvs: &[Value],
342    bin: &[u8],
343) -> Result<Vec<[f32; 3]>, AssetError> {
344    read_vec3(accessor, bvs, bin, "POSITION")
345}
346
347pub(super) fn read_vec3(
348    accessor: &Value,
349    bvs: &[Value],
350    bin: &[u8],
351    semantic: &str,
352) -> Result<Vec<[f32; 3]>, AssetError> {
353    if accessor["componentType"].as_u64() != Some(5126) {
354        return Err(AssetError::Parse(format!(
355            "{semantic} componentType must be FLOAT (5126)"
356        )));
357    }
358    if accessor["type"].as_str() != Some("VEC3") {
359        return Err(AssetError::Parse(format!(
360            "{semantic} accessor type must be VEC3"
361        )));
362    }
363    preflight_accessor(accessor, bvs, bin, 12, 4, true)?;
364    let count = accessor["count"]
365        .as_u64()
366        .ok_or_else(|| AssetError::Parse("accessor.count missing".into()))?
367        as usize;
368    let acc_off = accessor["byteOffset"].as_u64().unwrap_or(0) as usize;
369    let bv_idx = accessor["bufferView"]
370        .as_u64()
371        .ok_or_else(|| AssetError::Parse("accessor.bufferView missing".into()))?
372        as usize;
373    let bv = bvs
374        .get(bv_idx)
375        .ok_or_else(|| AssetError::Parse("bufferView index out of range".into()))?;
376    let bv_off = bv["byteOffset"].as_u64().unwrap_or(0) as usize;
377    let stride = match bv["byteStride"].as_u64().unwrap_or(0) {
378        0 => 12, // tightly packed VEC3 f32
379        s => s as usize,
380    };
381    let start = bv_off + acc_off;
382    let mut out = Vec::with_capacity(count);
383    for i in 0..count {
384        let o = start + i * stride;
385        if o + 12 > bin.len() {
386            return Err(AssetError::Parse(format!(
387                "{semantic} read past end of BIN"
388            )));
389        }
390        let rd = |k: usize| {
391            f32::from_le_bytes([bin[o + k], bin[o + k + 1], bin[o + k + 2], bin[o + k + 3]])
392        };
393        out.push([rd(0), rd(4), rd(8)]);
394    }
395    Ok(out)
396}
397
398pub(super) fn read_vec4(
399    accessor: &Value,
400    bvs: &[Value],
401    bin: &[u8],
402    semantic: &str,
403) -> Result<Vec<[f32; 4]>, AssetError> {
404    if accessor["componentType"].as_u64() != Some(5126) {
405        return Err(AssetError::Parse(format!(
406            "{semantic} componentType must be FLOAT (5126)"
407        )));
408    }
409    if accessor["type"].as_str() != Some("VEC4") {
410        return Err(AssetError::Parse(format!(
411            "{semantic} accessor type must be VEC4"
412        )));
413    }
414    preflight_accessor(accessor, bvs, bin, 16, 4, true)?;
415    let count = accessor["count"]
416        .as_u64()
417        .ok_or_else(|| AssetError::Parse("accessor.count missing".into()))?
418        as usize;
419    let acc_off = accessor["byteOffset"].as_u64().unwrap_or(0) as usize;
420    let bv_idx = accessor["bufferView"]
421        .as_u64()
422        .ok_or_else(|| AssetError::Parse("accessor.bufferView missing".into()))?
423        as usize;
424    let bv = bvs
425        .get(bv_idx)
426        .ok_or_else(|| AssetError::Parse("bufferView index out of range".into()))?;
427    let bv_off = bv["byteOffset"].as_u64().unwrap_or(0) as usize;
428    let stride = match bv["byteStride"].as_u64().unwrap_or(0) {
429        0 => 16,
430        s => s as usize,
431    };
432    let start = bv_off + acc_off;
433    let mut out = Vec::with_capacity(count);
434    for i in 0..count {
435        let o = start + i * stride;
436        if o + 16 > bin.len() {
437            return Err(AssetError::Parse(format!(
438                "{semantic} read past end of BIN"
439            )));
440        }
441        let rd = |k: usize| {
442            f32::from_le_bytes([bin[o + k], bin[o + k + 1], bin[o + k + 2], bin[o + k + 3]])
443        };
444        out.push([rd(0), rd(4), rd(8), rd(12)]);
445    }
446    Ok(out)
447}
448
449/// Read glTF `TEXCOORD_0` values from FLOAT or normalized unsigned-byte/unsigned-short VEC2
450/// accessors. Sparse accessors are rejected until the importer applies their overlays.
451pub(super) fn read_texcoords_0(
452    accessor: &Value,
453    bvs: &[Value],
454    bin: &[u8],
455) -> Result<Vec<[f32; 2]>, AssetError> {
456    if accessor.get("sparse").is_some() {
457        return Err(AssetError::Parse(
458            "sparse TEXCOORD_0 accessors are not supported".into(),
459        ));
460    }
461    if accessor["type"].as_str() != Some("VEC2") {
462        return Err(AssetError::Parse(
463            "TEXCOORD_0 accessor type must be VEC2".into(),
464        ));
465    }
466    let component_type = accessor["componentType"]
467        .as_u64()
468        .ok_or_else(|| AssetError::Parse("TEXCOORD_0 componentType missing".into()))?;
469    let normalized = accessor["normalized"].as_bool().unwrap_or(false);
470    let (component_size, default_stride) = match component_type {
471        5126 if !normalized => (4usize, 8usize),
472        5121 if normalized => (1usize, 2usize),
473        5123 if normalized => (2usize, 4usize),
474        5121 | 5123 => {
475            return Err(AssetError::Parse(
476                "integer TEXCOORD_0 accessors must be normalized".into(),
477            ));
478        }
479        _ => {
480            return Err(AssetError::Parse(
481                "TEXCOORD_0 must use FLOAT or normalized UNSIGNED_BYTE/UNSIGNED_SHORT".into(),
482            ));
483        }
484    };
485    preflight_accessor(accessor, bvs, bin, default_stride, component_size, true)?;
486    let count = accessor["count"]
487        .as_u64()
488        .ok_or_else(|| AssetError::Parse("TEXCOORD_0 accessor.count missing".into()))?
489        as usize;
490    let accessor_offset = accessor["byteOffset"].as_u64().unwrap_or(0) as usize;
491    let view_index = accessor["bufferView"]
492        .as_u64()
493        .ok_or_else(|| AssetError::Parse("TEXCOORD_0 accessor.bufferView missing".into()))?
494        as usize;
495    let view = bvs
496        .get(view_index)
497        .ok_or_else(|| AssetError::Parse("TEXCOORD_0 bufferView index out of range".into()))?;
498    let view_offset = view["byteOffset"].as_u64().unwrap_or(0) as usize;
499    let stride = view["byteStride"].as_u64().unwrap_or(default_stride as u64) as usize;
500    let element_size = component_size * 2;
501    if stride < element_size || stride % component_size != 0 {
502        return Err(AssetError::Parse(
503            "TEXCOORD_0 byteStride is invalid for its component type".into(),
504        ));
505    }
506    let start = view_offset
507        .checked_add(accessor_offset)
508        .ok_or_else(|| AssetError::Parse("TEXCOORD_0 byte offset overflow".into()))?;
509    let view_end =
510        view_offset
511            .checked_add(view["byteLength"].as_u64().ok_or_else(|| {
512                AssetError::Parse("TEXCOORD_0 bufferView.byteLength missing".into())
513            })? as usize)
514            .ok_or_else(|| AssetError::Parse("TEXCOORD_0 bufferView range overflow".into()))?;
515    let mut values = Vec::with_capacity(count);
516    for index in 0..count {
517        let element_offset = index
518            .checked_mul(stride)
519            .and_then(|offset| start.checked_add(offset))
520            .ok_or_else(|| AssetError::Parse("TEXCOORD_0 range overflow".into()))?;
521        let end = element_offset
522            .checked_add(element_size)
523            .ok_or_else(|| AssetError::Parse("TEXCOORD_0 range overflow".into()))?;
524        if end > view_end {
525            return Err(AssetError::Parse(
526                "TEXCOORD_0 accessor exceeds its bufferView".into(),
527            ));
528        }
529        let bytes = bin
530            .get(element_offset..end)
531            .ok_or_else(|| AssetError::Parse("TEXCOORD_0 read past end of BIN".into()))?;
532        let read_component = |component: usize| -> f32 {
533            let offset = component * component_size;
534            match component_type {
535                5126 => f32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap()),
536                5121 => bytes[offset] as f32 / u8::MAX as f32,
537                5123 => {
538                    u16::from_le_bytes([bytes[offset], bytes[offset + 1]]) as f32 / u16::MAX as f32
539                }
540                _ => unreachable!("component type validated above"),
541            }
542        };
543        let uv = [read_component(0), read_component(1)];
544        if uv.iter().any(|value| !value.is_finite()) {
545            return Err(AssetError::Parse(
546                "TEXCOORD_0 contains non-finite values".into(),
547            ));
548        }
549        values.push(uv);
550    }
551    Ok(values)
552}
553
554/// Read a SCALAR index accessor (u8/u16/u32) out of the GLB binary buffer, widened to `u32`.
555pub(super) fn read_indices(
556    accessor: &Value,
557    bvs: &[Value],
558    bin: &[u8],
559) -> Result<Vec<u32>, AssetError> {
560    if accessor["type"].as_str() != Some("SCALAR") {
561        return Err(AssetError::Parse(
562            "index accessor type must be SCALAR".into(),
563        ));
564    }
565    let comp = match accessor["componentType"].as_u64() {
566        Some(5121) => 1usize,
567        Some(5123) => 2,
568        Some(5125) => 4,
569        _ => {
570            return Err(AssetError::Parse(
571                "index componentType must be u8/u16/u32".into(),
572            ));
573        }
574    };
575    preflight_accessor(accessor, bvs, bin, comp, comp, false)?;
576    let count = accessor["count"]
577        .as_u64()
578        .ok_or_else(|| AssetError::Parse("accessor.count missing".into()))?
579        as usize;
580    let acc_off = accessor["byteOffset"].as_u64().unwrap_or(0) as usize;
581    let bv_idx = accessor["bufferView"]
582        .as_u64()
583        .ok_or_else(|| AssetError::Parse("accessor.bufferView missing".into()))?
584        as usize;
585    let bv = bvs
586        .get(bv_idx)
587        .ok_or_else(|| AssetError::Parse("bufferView index out of range".into()))?;
588    let bv_off = bv["byteOffset"].as_u64().unwrap_or(0) as usize;
589    let start = bv_off + acc_off;
590    let mut out = Vec::with_capacity(count);
591    for i in 0..count {
592        let o = start + i * comp;
593        if o + comp > bin.len() {
594            return Err(AssetError::Parse("index read past end of BIN".into()));
595        }
596        let v = match comp {
597            1 => bin[o] as u32,
598            2 => u16::from_le_bytes([bin[o], bin[o + 1]]) as u32,
599            _ => u32::from_le_bytes([bin[o], bin[o + 1], bin[o + 2], bin[o + 3]]),
600        };
601        out.push(v);
602    }
603    Ok(out)
604}