Skip to main content

qualia_core_db/render/assets/
mod.rs

1//! Asset-import bridge — `OBJ` / `STL` mesh → `NQuin` stream (Phase 1.3,
2//! `RENDERER_IMPLEMENTATION_PLAN.md`).
3//!
4//! Pure `&[u8]` → (geometry, semantic NQuins). **No `std::fs`** — wasm-safe (migration review
5//! §2.1): the shell / CLI reads the file (or runs the OS picker) and hands the bytes down. This is
6//! the ingest path (not a hot path), so `Vec` / `HashMap` are fine — the same convention as
7//! `kml_bridge`.
8//!
9//! Two layers, per STELLAR §E ("artefacts carry their geometry, and are *semantically known*"):
10//!   * `Mesh` — raw geometry (vertex positions + triangle indices + bounding box): the data the
11//!     GPU vertex/index buffers (Phase 1.2) will consume.
12//!   * `mesh_to_nquins` — the **semantic** layer: the asset is *known* (type, counts, bounding
13//!     box, centroid, source format) as NQuins in the one identity space — not just points/pixels.
14//!
15//! Hot-path rendering (depth-stencil, mesh buffers, projection) is the GPU half of Phase 1 and is
16//! verified on hardware; this module is the CPU half and is unit-tested here.
17
18use std::collections::HashMap;
19
20use crate::container_10d::{MaterialRecord, SubmeshRange};
21use crate::frame_layout::pack_float_object;
22use crate::{q_hash, NQuin};
23
24// ── Named-graph context + predicate / class hashes (one identity space; `q_hash`) ──────────────
25pub const GEOMETRY_CONTEXT: u64 = q_hash("urn:qualia:context:geometry");
26
27const P_RDF_TYPE: u64 = q_hash("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
28const C_MESH: u64 = q_hash("urn:qualia:geometry:Mesh");
29const P_VERTEX_COUNT: u64 = q_hash("urn:qualia:geometry:vertexCount");
30const P_TRIANGLE_COUNT: u64 = q_hash("urn:qualia:geometry:triangleCount");
31const P_SOURCE_FORMAT: u64 = q_hash("urn:qualia:geometry:sourceFormat");
32const P_BBOX_MIN_X: u64 = q_hash("urn:qualia:geometry:bboxMinX");
33const P_BBOX_MIN_Y: u64 = q_hash("urn:qualia:geometry:bboxMinY");
34const P_BBOX_MIN_Z: u64 = q_hash("urn:qualia:geometry:bboxMinZ");
35const P_BBOX_MAX_X: u64 = q_hash("urn:qualia:geometry:bboxMaxX");
36const P_BBOX_MAX_Y: u64 = q_hash("urn:qualia:geometry:bboxMaxY");
37const P_BBOX_MAX_Z: u64 = q_hash("urn:qualia:geometry:bboxMaxZ");
38const P_CENTROID_X: u64 = q_hash("urn:qualia:geometry:centroidX");
39const P_CENTROID_Y: u64 = q_hash("urn:qualia:geometry:centroidY");
40const P_CENTROID_Z: u64 = q_hash("urn:qualia:geometry:centroidZ");
41const P_SOURCE_DIGEST: u64 = q_hash("urn:qualia:geometry:sourceDigest");
42const P_COMPILED_DIGEST: u64 = q_hash("urn:qualia:geometry:compiledDigest");
43const P_BODY_SYSTEM: u64 = q_hash("urn:qualia:geometry:bodySystem");
44const P_ANATOMY_MODEL: u64 = q_hash("urn:qualia:geometry:anatomyModel");
45const P_GESTATIONAL_AGE_DAYS: u64 = q_hash("urn:qualia:geometry:gestationalAgeDays");
46const P_CARNEGIE_STAGE: u64 = q_hash("urn:qualia:geometry:carnegieStage");
47
48/// Error type for asset import.
49#[derive(Debug, PartialEq, Eq)]
50pub enum AssetError {
51    /// The bytes parsed but produced no geometry.
52    Empty,
53    /// The format could not be recognised from the bytes (and no usable hint was given).
54    UnknownFormat,
55    /// A structural parse failure, with a human-readable reason.
56    Parse(String),
57}
58
59impl std::fmt::Display for AssetError {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        match self {
62            AssetError::Empty => write!(f, "asset import: no geometry produced"),
63            AssetError::UnknownFormat => write!(f, "asset import: unrecognised format"),
64            AssetError::Parse(s) => write!(f, "asset import: parse error: {s}"),
65        }
66    }
67}
68
69impl std::error::Error for AssetError {}
70
71/// Raw triangle-mesh geometry. The hot-path GPU buffers (Phase 1.2) consume `positions` +
72/// `triangles`; the bounding box is precomputed for the projection / culling layer (§E §4).
73#[derive(Debug, Clone, PartialEq)]
74pub struct Mesh {
75    /// Vertex positions in model space.
76    pub positions: Vec<[f32; 3]>,
77    /// Triangle vertex indices into `positions` (CCW winding as authored).
78    pub triangles: Vec<[u32; 3]>,
79    /// Axis-aligned bounding-box minimum corner.
80    pub min: [f32; 3],
81    /// Axis-aligned bounding-box maximum corner.
82    pub max: [f32; 3],
83}
84
85/// Mesh plus optional normal and tangent streams. Tangents may be authored or generated from
86/// TEXCOORD_0; importers without the required data leave a stream empty for renderer fallback.
87#[derive(Debug, Clone, PartialEq)]
88pub struct ImportedMesh {
89    pub mesh: Mesh,
90    pub normals: Option<Vec<[f32; 3]>>,
91    /// Authored glTF tangent direction and handedness, or MikkTSpace-generated frames when UV0 is
92    /// available. A missing UV0 leaves the stream absent for the renderer's capability fallback.
93    pub tangents: Option<Vec<[f32; 4]>>,
94    /// Vertex-aligned glTF TEXCOORD_0 pairs, including any vertices split to preserve tangent seams.
95    pub texture_coordinates_0: Option<Vec<[f32; 2]>>,
96    /// Imported glTF materials. Their IDs are source-local (`index + 1`) until the asset
97    /// compiler scopes them to a stable asset identity.
98    pub materials: Vec<MaterialRecord>,
99    /// Content-addressed image payloads referenced by imported material records. Payload bytes
100    /// remain intact for HMC/resource packaging; they are not copied into the 10D semantic arena.
101    pub texture_dependencies: Vec<TextureDependency>,
102    /// Contiguous index ranges in the same order as the flattened primitive index stream.
103    pub submeshes: Vec<SubmeshRange>,
104}
105
106/// Immutable image asset discovered while importing an embedded glTF image.
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct TextureDependency {
109    /// SHA-256 of `bytes`, matching the corresponding MAT2/MAT1 resource references.
110    pub digest: [u8; 32],
111    /// Source MIME type (for example `image/png`, `image/jpeg`, or `image/ktx2`).
112    pub mime_type: String,
113    /// Original encoded image bytes, retained for external HMC/Webizen processing.
114    pub bytes: Vec<u8>,
115}
116
117impl Mesh {
118    /// Number of vertices.
119    #[inline]
120    pub fn vertex_count(&self) -> usize {
121        self.positions.len()
122    }
123
124    /// Number of triangles.
125    #[inline]
126    pub fn triangle_count(&self) -> usize {
127        self.triangles.len()
128    }
129
130    /// Bounding-box centre (the simple centroid used by the projection/culling layer).
131    #[inline]
132    pub fn centroid(&self) -> [f32; 3] {
133        [
134            0.5 * (self.min[0] + self.max[0]),
135            0.5 * (self.min[1] + self.max[1]),
136            0.5 * (self.min[2] + self.max[2]),
137        ]
138    }
139
140    /// Build a mesh from positions + triangles, computing the bounding box. Validates that every
141    /// index is in range.
142    fn build(positions: Vec<[f32; 3]>, triangles: Vec<[u32; 3]>) -> Result<Mesh, AssetError> {
143        if positions.is_empty() || triangles.is_empty() {
144            return Err(AssetError::Empty);
145        }
146        let n = positions.len() as u32;
147        for t in &triangles {
148            if t[0] >= n || t[1] >= n || t[2] >= n {
149                return Err(AssetError::Parse(format!(
150                    "triangle index out of range (verts={n}, tri={t:?})"
151                )));
152            }
153        }
154        let mut min = [f32::INFINITY; 3];
155        let mut max = [f32::NEG_INFINITY; 3];
156        for p in &positions {
157            for k in 0..3 {
158                min[k] = min[k].min(p[k]);
159                max[k] = max[k].max(p[k]);
160            }
161        }
162        Ok(Mesh {
163            positions,
164            triangles,
165            min,
166            max,
167        })
168    }
169}
170
171// ── Format detection + dispatch ───────────────────────────────────────────────────────────────
172
173/// Import a mesh, sniffing the format from the bytes (or trusting an explicit lowercase
174/// extension hint like `"obj"` / `"stl"`).
175pub fn import_asset(bytes: &[u8], hint: Option<&str>) -> Result<Mesh, AssetError> {
176    import_asset_with_normals(bytes, hint).map(|imported| imported.mesh)
177}
178
179/// Import a mesh and preserve authored normals when the source format provides them. Missing
180/// normals in individual primitives are generated from the primitive's triangle geometry.
181pub fn import_asset_with_normals(
182    bytes: &[u8],
183    hint: Option<&str>,
184) -> Result<ImportedMesh, AssetError> {
185    match hint {
186        Some(h) if h.eq_ignore_ascii_case("obj") => {
187            return import_obj(bytes).map(|mesh| ImportedMesh {
188                mesh,
189                normals: None,
190                tangents: None,
191                texture_coordinates_0: None,
192                materials: Vec::new(),
193                texture_dependencies: Vec::new(),
194                submeshes: Vec::new(),
195            });
196        }
197        Some(h) if h.eq_ignore_ascii_case("stl") => {
198            return import_stl(bytes).map(|mesh| ImportedMesh {
199                mesh,
200                normals: None,
201                tangents: None,
202                texture_coordinates_0: None,
203                materials: Vec::new(),
204                texture_dependencies: Vec::new(),
205                submeshes: Vec::new(),
206            });
207        }
208        Some(h) if h.eq_ignore_ascii_case("glb") || h.eq_ignore_ascii_case("gltf") => {
209            return import_glb_with_normals(bytes);
210        }
211        _ => {}
212    }
213    if looks_like_glb(bytes) {
214        import_glb_with_normals(bytes) // unambiguous "glTF" magic — check first
215    } else if looks_like_binary_stl(bytes) || looks_like_ascii_stl(bytes) {
216        import_stl(bytes).map(|mesh| ImportedMesh {
217            mesh,
218            normals: None,
219            tangents: None,
220            texture_coordinates_0: None,
221            materials: Vec::new(),
222            texture_dependencies: Vec::new(),
223            submeshes: Vec::new(),
224        })
225    } else if looks_like_obj(bytes) {
226        import_obj(bytes).map(|mesh| ImportedMesh {
227            mesh,
228            normals: None,
229            tangents: None,
230            texture_coordinates_0: None,
231            materials: Vec::new(),
232            texture_dependencies: Vec::new(),
233            submeshes: Vec::new(),
234        })
235    } else {
236        Err(AssetError::UnknownFormat)
237    }
238}
239
240fn looks_like_obj(bytes: &[u8]) -> bool {
241    // An OBJ has `v ` (vertex) lines and usually `f ` (face) lines; comments start with `#`.
242    let text = match core::str::from_utf8(bytes) {
243        Ok(t) => t,
244        Err(_) => return false,
245    };
246    text.lines().any(|l| {
247        let l = l.trim_start();
248        l.starts_with("v ") || l.starts_with("f ") || l.starts_with("vn ") || l.starts_with("vt ")
249    })
250}
251
252fn looks_like_ascii_stl(bytes: &[u8]) -> bool {
253    let prefix = &bytes[..bytes.len().min(512)];
254    match core::str::from_utf8(prefix) {
255        Ok(t) => {
256            let t = t.trim_start();
257            t.starts_with("solid") && t.contains("facet")
258        }
259        Err(_) => false,
260    }
261}
262
263/// Binary STL has no magic; it is detected structurally: an 80-byte header, a `u32` triangle
264/// count, then exactly `50 * count` bytes. (Some exporters start a *binary* file with "solid",
265/// which is why the size check — not the prefix — is authoritative.)
266fn looks_like_binary_stl(bytes: &[u8]) -> bool {
267    if bytes.len() < 84 {
268        return false;
269    }
270    let count = u32::from_le_bytes([bytes[80], bytes[81], bytes[82], bytes[83]]) as usize;
271    bytes.len() == 84 + count * 50
272}
273
274// ── Wavefront OBJ ─────────────────────────────────────────────────────────────────────────────
275
276/// Parse a Wavefront `.obj`: `v x y z` vertices and `f` faces (polygons fan-triangulated).
277/// Face tokens may be `v`, `v/vt`, `v//vn`, or `v/vt/vn`; indices are 1-based and may be negative
278/// (relative to the current vertex count). `vt` / `vn` / `vp` / groups are ignored for geometry.
279pub fn import_obj(bytes: &[u8]) -> Result<Mesh, AssetError> {
280    let text = core::str::from_utf8(bytes)
281        .map_err(|_| AssetError::Parse("OBJ is not valid UTF-8".into()))?;
282
283    let mut positions: Vec<[f32; 3]> = Vec::new();
284    let mut triangles: Vec<[u32; 3]> = Vec::new();
285
286    for (lineno, raw) in text.lines().enumerate() {
287        let line = raw.trim();
288        if line.is_empty() || line.starts_with('#') {
289            continue;
290        }
291        let mut tok = line.split_whitespace();
292        match tok.next() {
293            Some("v") => {
294                let coords: Vec<f32> = tok.filter_map(|s| s.parse::<f32>().ok()).collect();
295                if coords.len() < 3 {
296                    return Err(AssetError::Parse(format!(
297                        "OBJ line {}: vertex needs 3 coords",
298                        lineno + 1
299                    )));
300                }
301                positions.push([coords[0], coords[1], coords[2]]);
302            }
303            Some("f") => {
304                // Resolve each face vertex token to a 0-based index, then fan-triangulate.
305                let mut face: Vec<u32> = Vec::new();
306                for t in tok {
307                    let first = t.split('/').next().unwrap_or("");
308                    let idx: i64 = match first.parse() {
309                        Ok(i) => i,
310                        Err(_) => {
311                            return Err(AssetError::Parse(format!(
312                                "OBJ line {}: bad face index {t:?}",
313                                lineno + 1
314                            )));
315                        }
316                    };
317                    let zero_based = if idx > 0 {
318                        (idx - 1) as i64
319                    } else if idx < 0 {
320                        positions.len() as i64 + idx
321                    } else {
322                        return Err(AssetError::Parse(format!(
323                            "OBJ line {}: face index 0 is invalid",
324                            lineno + 1
325                        )));
326                    };
327                    if zero_based < 0 || zero_based as usize >= positions.len() {
328                        return Err(AssetError::Parse(format!(
329                            "OBJ line {}: face index {idx} out of range",
330                            lineno + 1
331                        )));
332                    }
333                    face.push(zero_based as u32);
334                }
335                for i in 1..face.len().saturating_sub(1) {
336                    triangles.push([face[0], face[i], face[i + 1]]);
337                }
338            }
339            _ => {} // vt / vn / vp / g / o / s / mtllib / usemtl — not needed for geometry
340        }
341    }
342
343    Mesh::build(positions, triangles)
344}
345
346// ── STL (binary + ASCII) ──────────────────────────────────────────────────────────────────────
347
348/// Parse a `.stl` (auto-detects binary vs ASCII). Each STL triangle contributes 3 fresh vertices
349/// (no welding) — a faithful, lossless first cut; vertex de-duplication is a later optimisation.
350pub fn import_stl(bytes: &[u8]) -> Result<Mesh, AssetError> {
351    if looks_like_binary_stl(bytes) {
352        import_stl_binary(bytes)
353    } else {
354        import_stl_ascii(bytes)
355    }
356}
357
358fn import_stl_binary(bytes: &[u8]) -> Result<Mesh, AssetError> {
359    if bytes.len() < 84 {
360        return Err(AssetError::Parse("binary STL shorter than header".into()));
361    }
362    let count = u32::from_le_bytes([bytes[80], bytes[81], bytes[82], bytes[83]]) as usize;
363    let expected = 84 + count * 50;
364    if bytes.len() != expected {
365        return Err(AssetError::Parse(format!(
366            "binary STL size {} != expected {expected} for {count} triangles",
367            bytes.len()
368        )));
369    }
370    let mut positions: Vec<[f32; 3]> = Vec::with_capacity(count * 3);
371    let mut triangles: Vec<[u32; 3]> = Vec::with_capacity(count);
372    let read_f32 = |o: usize| -> f32 {
373        f32::from_le_bytes([bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]])
374    };
375    for t in 0..count {
376        // 50 bytes/triangle: 12 (normal) + 3×12 (verts) + 2 (attr). Skip the normal.
377        let base = 84 + t * 50 + 12;
378        let v0 = positions.len() as u32;
379        for v in 0..3 {
380            let o = base + v * 12;
381            positions.push([read_f32(o), read_f32(o + 4), read_f32(o + 8)]);
382        }
383        triangles.push([v0, v0 + 1, v0 + 2]);
384    }
385    Mesh::build(positions, triangles)
386}
387
388fn import_stl_ascii(bytes: &[u8]) -> Result<Mesh, AssetError> {
389    let text = core::str::from_utf8(bytes)
390        .map_err(|_| AssetError::Parse("ASCII STL is not valid UTF-8".into()))?;
391    let mut positions: Vec<[f32; 3]> = Vec::new();
392    let mut triangles: Vec<[u32; 3]> = Vec::new();
393    let mut pending: Vec<[f32; 3]> = Vec::new();
394    for raw in text.lines() {
395        let line = raw.trim();
396        if let Some(rest) = line.strip_prefix("vertex ") {
397            let c: Vec<f32> = rest
398                .split_whitespace()
399                .filter_map(|s| s.parse().ok())
400                .collect();
401            if c.len() < 3 {
402                return Err(AssetError::Parse("ASCII STL: vertex needs 3 coords".into()));
403            }
404            pending.push([c[0], c[1], c[2]]);
405            if pending.len() == 3 {
406                let v0 = positions.len() as u32;
407                positions.extend_from_slice(&pending);
408                triangles.push([v0, v0 + 1, v0 + 2]);
409                pending.clear();
410            }
411        }
412    }
413    Mesh::build(positions, triangles)
414}
415
416const GLB_MAGIC: u32 = 0x4654_6C67; // "glTF" little-endian
417const CHUNK_JSON: u32 = 0x4E4F_534A; // "JSON"
418const CHUNK_BIN: u32 = 0x004E_4942; // "BIN\\0"
419
420#[path = "glb.rs"]
421mod glb;
422mod glb_static_scene;
423#[path = "glb_materials.rs"]
424mod glb_materials;
425#[path = "glb_texture_transform.rs"]
426mod glb_texture_transform;
427#[path = "tangents.rs"]
428mod tangents;
429use glb::looks_like_glb;
430pub use glb::{import_glb, import_glb_with_normals, import_glb_static_scene};
431#[path = "glb_skins_anims.rs"]
432pub mod glb_skins_anims;
433pub use glb_skins_anims::{
434    matrix4_to_motor_and_scale, parse_glb_living_scene, GlbInterpolation, GlbLivingScene,
435    GlbMorphWeightTrack, GlbNodeRecord, KhrMaterialExtensions, KhrPunctualLight,
436};
437// ── Semantic layer: Mesh → NQuins ─────────────────────────────────────────────────────────────
438
439/// Emit the **semantic** quins for a mesh asset (the asset is *known*, not just drawn): its type,
440/// vertex/triangle counts, bounding box, centroid, and source format — all in `GEOMETRY_CONTEXT`,
441/// in the one identity space. Floats use the inline-float object tag (ADR 0008); counts are raw
442/// integers. The returned lexicon maps the asset-URI / format hashes back to their strings.
443pub fn mesh_to_nquins(
444    mesh: &Mesh,
445    asset_uri: &str,
446    source_format: &str,
447) -> (Vec<NQuin>, HashMap<u64, String>) {
448    let subject = fnv_hash(asset_uri.as_bytes());
449    let mut quins: Vec<NQuin> = Vec::with_capacity(13);
450    let mut lexicon: HashMap<u64, String> = HashMap::new();
451    lexicon.insert(subject, asset_uri.to_owned());
452
453    quins.push(make_quin(subject, P_RDF_TYPE, C_MESH));
454    quins.push(make_quin(
455        subject,
456        P_VERTEX_COUNT,
457        mesh.vertex_count() as u64,
458    ));
459    quins.push(make_quin(
460        subject,
461        P_TRIANGLE_COUNT,
462        mesh.triangle_count() as u64,
463    ));
464
465    let fmt_hash = fnv_hash(source_format.as_bytes());
466    lexicon.insert(fmt_hash, source_format.to_owned());
467    quins.push(make_quin(subject, P_SOURCE_FORMAT, fmt_hash));
468
469    quins.push(make_quin(
470        subject,
471        P_BBOX_MIN_X,
472        pack_float_object(mesh.min[0]),
473    ));
474    quins.push(make_quin(
475        subject,
476        P_BBOX_MIN_Y,
477        pack_float_object(mesh.min[1]),
478    ));
479    quins.push(make_quin(
480        subject,
481        P_BBOX_MIN_Z,
482        pack_float_object(mesh.min[2]),
483    ));
484    quins.push(make_quin(
485        subject,
486        P_BBOX_MAX_X,
487        pack_float_object(mesh.max[0]),
488    ));
489    quins.push(make_quin(
490        subject,
491        P_BBOX_MAX_Y,
492        pack_float_object(mesh.max[1]),
493    ));
494    quins.push(make_quin(
495        subject,
496        P_BBOX_MAX_Z,
497        pack_float_object(mesh.max[2]),
498    ));
499
500    let c = mesh.centroid();
501    quins.push(make_quin(subject, P_CENTROID_X, pack_float_object(c[0])));
502    quins.push(make_quin(subject, P_CENTROID_Y, pack_float_object(c[1])));
503    quins.push(make_quin(subject, P_CENTROID_Z, pack_float_object(c[2])));
504
505    (quins, lexicon)
506}
507
508/// Like `mesh_to_nquins` but also asserts the immutable `sourceDigest` and the `.10d`
509/// `compiledDigest` — the manifest→container join (geometry-asset-ontology §4). Both are CRC-32C
510/// `u32` content hashes stored as `u64` objects: `sourceDigest` over the immutable source asset
511/// bytes, `compiledDigest` the whole-file CRC of the `.10d` container this manifest describes.
512pub fn mesh_to_nquins_with_digests(
513    mesh: &Mesh,
514    asset_uri: &str,
515    source_format: &str,
516    source_digest: u32,
517    compiled_digest: u32,
518) -> (Vec<NQuin>, HashMap<u64, String>) {
519    let (mut quins, lexicon) = mesh_to_nquins(mesh, asset_uri, source_format);
520    let subject = fnv_hash(asset_uri.as_bytes());
521    quins.push(make_quin(subject, P_SOURCE_DIGEST, source_digest as u64));
522    quins.push(make_quin(
523        subject,
524        P_COMPILED_DIGEST,
525        compiled_digest as u64,
526    ));
527    (quins, lexicon)
528}
529
530/// Like [`mesh_to_nquins_with_digests`] but also asserts the anatomy binding for a 3D-body organ:
531/// `bodySystem` (which of the 17 body systems this organ belongs to — which system's burden colours
532/// it) and `anatomyModel` (`"male"` / `"female"` — the reference model whose set it is part of, chosen
533/// from the user's declared XY/XX chromosomal basis). Both are string facts carried in the lexicon,
534/// like `sourceFormat`; a `None` field is simply not asserted.
535#[allow(clippy::too_many_arguments)]
536pub fn mesh_to_nquins_with_meta(
537    mesh: &Mesh,
538    asset_uri: &str,
539    source_format: &str,
540    source_digest: u32,
541    compiled_digest: u32,
542    body_system: Option<&str>,
543    anatomy_model: Option<&str>,
544) -> (Vec<NQuin>, HashMap<u64, String>) {
545    let (mut quins, mut lexicon) = mesh_to_nquins_with_digests(
546        mesh,
547        asset_uri,
548        source_format,
549        source_digest,
550        compiled_digest,
551    );
552    let subject = fnv_hash(asset_uri.as_bytes());
553    if let Some(sys) = body_system {
554        let h = fnv_hash(sys.as_bytes());
555        lexicon.insert(h, sys.to_owned());
556        quins.push(make_quin(subject, P_BODY_SYSTEM, h));
557    }
558    if let Some(model) = anatomy_model {
559        let h = fnv_hash(model.as_bytes());
560        lexicon.insert(h, model.to_owned());
561        quins.push(make_quin(subject, P_ANATOMY_MODEL, h));
562    }
563    (quins, lexicon)
564}
565
566/// Like [`mesh_to_nquins_with_digests`] but for a **developmental** body: also asserts the gestational
567/// `t`-axis coordinate — `gestationalAgeDays` (postfertilization) and `carnegieStage`. This is what makes
568/// a fetal `.10d` a *slice* of a 4-D developmental body: consecutive stages, ordered by gestational age,
569/// are the same body along the `t`-axis (reproductive-continuum plan §2). Both are plain `u64` objects.
570pub fn mesh_to_nquins_with_dev(
571    mesh: &Mesh,
572    asset_uri: &str,
573    source_format: &str,
574    source_digest: u32,
575    compiled_digest: u32,
576    gestational_age_days: u16,
577    carnegie_stage: u8,
578) -> (Vec<NQuin>, HashMap<u64, String>) {
579    let (mut quins, lexicon) = mesh_to_nquins_with_digests(
580        mesh,
581        asset_uri,
582        source_format,
583        source_digest,
584        compiled_digest,
585    );
586    let subject = fnv_hash(asset_uri.as_bytes());
587    quins.push(make_quin(
588        subject,
589        P_GESTATIONAL_AGE_DAYS,
590        gestational_age_days as u64,
591    ));
592    quins.push(make_quin(subject, P_CARNEGIE_STAGE, carnegie_stage as u64));
593    (quins, lexicon)
594}
595
596#[inline]
597fn make_quin(subject: u64, predicate: u64, object: u64) -> NQuin {
598    let context = GEOMETRY_CONTEXT;
599    let metadata = 0;
600    NQuin {
601        subject,
602        predicate,
603        object,
604        context,
605        metadata,
606        // Was hardcoded `0` — emitted invalid-parity geometry NQuins. Use the canonical parity so
607        // the "every runtime NQuin has valid field parity" invariant holds (visual-plan §3.1 fix).
608        parity: NQuin::calculate_parity(subject, predicate, object, context, metadata),
609    }
610}
611
612/// FNV-1a (60-bit), matching `crate::q_hash` for runtime strings so asset IRIs hashed here share
613/// the one identity space (same convention as `kml_bridge`).
614#[inline]
615fn fnv_hash(bytes: &[u8]) -> u64 {
616    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
617    for &b in bytes {
618        h ^= b as u64;
619        h = h.wrapping_mul(0x0000_0100_0000_01b3);
620    }
621    h & 0x0FFF_FFFF_FFFF_FFFF
622}
623
624#[cfg(test)]
625mod tests {
626    use super::*;
627    use super::{glb::read_texcoords_0, tangents::generate_mikktspace_tangents};
628    use crate::frame_layout::unpack_float_object;
629
630    const TRI_OBJ: &str = "# a single triangle\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n";
631
632    // A unit quad (two triangles via fan) + face tokens with v/vt/vn slashes.
633    const QUAD_OBJ: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nf 1/1/1 2/2/1 3/3/1 4/4/1\n";
634
635    #[test]
636    fn obj_triangle() {
637        let m = import_obj(TRI_OBJ.as_bytes()).unwrap();
638        assert_eq!(m.vertex_count(), 3);
639        assert_eq!(m.triangle_count(), 1);
640        assert_eq!(m.min, [0.0, 0.0, 0.0]);
641        assert_eq!(m.max, [1.0, 1.0, 0.0]);
642        assert_eq!(m.triangles[0], [0, 1, 2]);
643    }
644
645    #[test]
646    fn obj_quad_fan_triangulates_and_ignores_vt_vn() {
647        let m = import_obj(QUAD_OBJ.as_bytes()).unwrap();
648        assert_eq!(m.vertex_count(), 4);
649        assert_eq!(m.triangle_count(), 2); // quad → 2 triangles
650        assert_eq!(m.triangles[0], [0, 1, 2]);
651        assert_eq!(m.triangles[1], [0, 2, 3]);
652    }
653
654    #[test]
655    fn obj_negative_indices() {
656        // -1/-2/-3 reference the three most-recent vertices.
657        let obj = "v 0 0 0\nv 1 0 0\nv 0 1 0\nf -3 -2 -1\n";
658        let m = import_obj(obj.as_bytes()).unwrap();
659        assert_eq!(m.triangles[0], [0, 1, 2]);
660    }
661
662    #[test]
663    fn obj_out_of_range_face_is_error() {
664        let obj = "v 0 0 0\nv 1 0 0\nf 1 2 9\n";
665        assert!(matches!(
666            import_obj(obj.as_bytes()),
667            Err(AssetError::Parse(_))
668        ));
669    }
670
671    #[test]
672    fn stl_ascii_triangle() {
673        let stl = "solid t\nfacet normal 0 0 1\nouter loop\nvertex 0 0 0\nvertex 1 0 0\nvertex 0 1 0\nendloop\nendfacet\nendsolid t\n";
674        let m = import_stl(stl.as_bytes()).unwrap();
675        assert_eq!(m.vertex_count(), 3);
676        assert_eq!(m.triangle_count(), 1);
677        assert_eq!(m.max, [1.0, 1.0, 0.0]);
678    }
679
680    #[test]
681    fn stl_binary_triangle() {
682        // 80-byte header + u32(1) + one 50-byte triangle record.
683        let mut b = vec![0u8; 80];
684        b.extend_from_slice(&1u32.to_le_bytes());
685        b.extend_from_slice(&[0u8; 12]); // normal
686        for v in [[0f32, 0., 0.], [2., 0., 0.], [0., 3., 0.]] {
687            for c in v {
688                b.extend_from_slice(&c.to_le_bytes());
689            }
690        }
691        b.extend_from_slice(&[0u8; 2]); // attribute byte count
692        assert!(looks_like_binary_stl(&b));
693        let m = import_stl(&b).unwrap();
694        assert_eq!(m.vertex_count(), 3);
695        assert_eq!(m.triangle_count(), 1);
696        assert_eq!(m.max, [2.0, 3.0, 0.0]);
697    }
698
699    #[test]
700    fn dispatch_sniffs_format() {
701        assert_eq!(
702            import_asset(TRI_OBJ.as_bytes(), None)
703                .unwrap()
704                .triangle_count(),
705            1
706        );
707        assert_eq!(
708            import_asset(TRI_OBJ.as_bytes(), Some("obj"))
709                .unwrap()
710                .vertex_count(),
711            3
712        );
713    }
714
715    #[test]
716    fn mesh_to_nquins_emits_known_geometry() {
717        let m = import_obj(TRI_OBJ.as_bytes()).unwrap();
718        let (quins, lex) = mesh_to_nquins(&m, "urn:asset:tri", "obj");
719        // type + 2 counts + format + 6 bbox + 3 centroid = 13.
720        assert_eq!(quins.len(), 13);
721        let subject = fnv_hash(b"urn:asset:tri");
722        assert_eq!(lex.get(&subject).unwrap(), "urn:asset:tri");
723        // The type quin is present.
724        assert!(quins
725            .iter()
726            .any(|q| q.predicate == P_RDF_TYPE && q.object == C_MESH));
727        // bboxMaxX round-trips through the inline-float tag.
728        let max_x = quins.iter().find(|q| q.predicate == P_BBOX_MAX_X).unwrap();
729        assert_eq!(unpack_float_object(max_x.object), 1.0);
730        // Every emitted geometry NQuin has valid (non-zero, canonical) parity — regression guard for
731        // the former hardcoded `parity: 0`.
732        for q in &quins {
733            assert_eq!(
734                q.parity,
735                NQuin::calculate_parity(q.subject, q.predicate, q.object, q.context, q.metadata),
736                "geometry NQuin must carry canonical parity"
737            );
738        }
739    }
740
741    fn build_test_glb() -> Vec<u8> {
742        // BIN: positions (36 B), normals (36 B), tangents (48 B), indices (6 B), padded -> 128 B.
743        let mut bin = Vec::new();
744        for v in [[0f32, 0., 0.], [2., 0., 0.], [0., 4., 0.]] {
745            for c in v {
746                bin.extend_from_slice(&c.to_le_bytes());
747            }
748        }
749        for _ in 0..3 {
750            for c in [0f32, 0., 2.] {
751                bin.extend_from_slice(&c.to_le_bytes());
752            }
753        }
754        for _ in 0..3 {
755            for c in [2f32, 0., 0.5, 1.] {
756                bin.extend_from_slice(&c.to_le_bytes());
757            }
758        }
759        for i in [0u16, 1, 2] {
760            bin.extend_from_slice(&i.to_le_bytes());
761        }
762        while bin.len() % 4 != 0 {
763            bin.push(0);
764        }
765        let json = r#"{"asset":{"version":"2.0"},"buffers":[{"byteLength":128}],"bufferViews":[{"buffer":0,"byteOffset":0,"byteLength":36},{"buffer":0,"byteOffset":36,"byteLength":36},{"buffer":0,"byteOffset":72,"byteLength":48},{"buffer":0,"byteOffset":120,"byteLength":6}],"accessors":[{"bufferView":0,"componentType":5126,"count":3,"type":"VEC3"},{"bufferView":1,"componentType":5126,"count":3,"type":"VEC3"},{"bufferView":2,"componentType":5126,"count":3,"type":"VEC4"},{"bufferView":3,"componentType":5123,"count":3,"type":"SCALAR"}],"meshes":[{"primitives":[{"attributes":{"POSITION":0,"NORMAL":1,"TANGENT":2},"indices":3}]}]}"#;
766        let mut jb = json.as_bytes().to_vec();
767        while jb.len() % 4 != 0 {
768            jb.push(b' ');
769        }
770        let total = 12 + 8 + jb.len() + 8 + bin.len();
771        let mut glb = Vec::new();
772        glb.extend_from_slice(&GLB_MAGIC.to_le_bytes());
773        glb.extend_from_slice(&2u32.to_le_bytes());
774        glb.extend_from_slice(&(total as u32).to_le_bytes());
775        glb.extend_from_slice(&(jb.len() as u32).to_le_bytes());
776        glb.extend_from_slice(&CHUNK_JSON.to_le_bytes());
777        glb.extend_from_slice(&jb);
778        glb.extend_from_slice(&(bin.len() as u32).to_le_bytes());
779        glb.extend_from_slice(&CHUNK_BIN.to_le_bytes());
780        glb.extend_from_slice(&bin);
781        glb
782    }
783
784    fn build_test_glb_without_tangents_with_uv0() -> Vec<u8> {
785        let mut bin = Vec::new();
786        for position in [[0.0f32, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 4.0, 0.0]] {
787            for component in position {
788                bin.extend_from_slice(&component.to_le_bytes());
789            }
790        }
791        for _ in 0..3 {
792            for component in [0.0f32, 0.0, 1.0] {
793                bin.extend_from_slice(&component.to_le_bytes());
794            }
795        }
796        for uv in [[0.0f32, 0.0], [1.0, 0.0], [0.0, 1.0]] {
797            for component in uv {
798                bin.extend_from_slice(&component.to_le_bytes());
799            }
800        }
801        for index in [0u16, 1, 2] {
802            bin.extend_from_slice(&index.to_le_bytes());
803        }
804        while bin.len() % 4 != 0 {
805            bin.push(0);
806        }
807        let json = r#"{"asset":{"version":"2.0"},"buffers":[{"byteLength":104}],"bufferViews":[{"buffer":0,"byteOffset":0,"byteLength":36},{"buffer":0,"byteOffset":36,"byteLength":36},{"buffer":0,"byteOffset":72,"byteLength":24},{"buffer":0,"byteOffset":96,"byteLength":6}],"accessors":[{"bufferView":0,"componentType":5126,"count":3,"type":"VEC3"},{"bufferView":1,"componentType":5126,"count":3,"type":"VEC3"},{"bufferView":2,"componentType":5126,"count":3,"type":"VEC2"},{"bufferView":3,"componentType":5123,"count":3,"type":"SCALAR"}],"meshes":[{"primitives":[{"attributes":{"POSITION":0,"NORMAL":1,"TEXCOORD_0":2},"indices":3}]}]}"#;
808        let mut json_bytes = json.as_bytes().to_vec();
809        while json_bytes.len() % 4 != 0 {
810            json_bytes.push(b' ');
811        }
812        let total = 12 + 8 + json_bytes.len() + 8 + bin.len();
813        let mut glb = Vec::new();
814        glb.extend_from_slice(&GLB_MAGIC.to_le_bytes());
815        glb.extend_from_slice(&2u32.to_le_bytes());
816        glb.extend_from_slice(&(total as u32).to_le_bytes());
817        glb.extend_from_slice(&(json_bytes.len() as u32).to_le_bytes());
818        glb.extend_from_slice(&CHUNK_JSON.to_le_bytes());
819        glb.extend_from_slice(&json_bytes);
820        glb.extend_from_slice(&(bin.len() as u32).to_le_bytes());
821        glb.extend_from_slice(&CHUNK_BIN.to_le_bytes());
822        glb.extend_from_slice(&bin);
823        glb
824    }
825
826    #[test]
827    fn glb_single_triangle() {
828        let glb = build_test_glb();
829        assert!(looks_like_glb(&glb));
830        let m = import_glb(&glb).unwrap();
831        assert_eq!(m.vertex_count(), 3);
832        assert_eq!(m.triangle_count(), 1);
833        assert_eq!(m.max, [2.0, 4.0, 0.0]);
834        assert_eq!(m.triangles[0], [0, 1, 2]);
835        let imported = import_glb_with_normals(&glb).unwrap();
836        assert_eq!(imported.normals.unwrap(), vec![[0.0, 0.0, 1.0]; 3]);
837        let imported = import_glb_with_normals(&glb).unwrap();
838        assert_eq!(imported.tangents.unwrap(), vec![[1.0, 0.0, 0.0, 1.0]; 3]);
839        // dispatch via the "glTF" magic
840        assert_eq!(import_asset(&glb, None).unwrap().triangle_count(), 1);
841        assert_eq!(import_asset(&glb, Some("glb")).unwrap().vertex_count(), 3);
842        let compiled = crate::render::compile_10d::compile_asset(
843            &glb,
844            Some("glb"),
845            "urn:test:authored-normal-triangle",
846            "glb",
847        )
848        .unwrap();
849        let compiled_normals = crate::render::compile_10d::decode_10d_normals(
850            &compiled.container_10d,
851            compiled.mesh.vertex_count(),
852        )
853        .unwrap()
854        .unwrap();
855        assert_eq!(compiled_normals, vec![[0.0, 0.0, 1.0]; 3]);
856        let compiled_tangents = crate::render::compile_10d::decode_10d_tangents(
857            &compiled.container_10d,
858            compiled.mesh.vertex_count(),
859        )
860        .unwrap()
861        .unwrap();
862        assert_eq!(compiled_tangents, vec![[1.0, 0.0, 0.0, 1.0]; 3]);
863    }
864
865    #[test]
866    fn glb_rejects_zero_length_authored_normal() {
867        let mut glb = build_test_glb();
868        // The second view is the authored NORMAL stream, beginning at byte 36 in BIN.
869        let bin_chunk = glb
870            .windows(4)
871            .position(|w| w == CHUNK_BIN.to_le_bytes())
872            .unwrap()
873            + 4;
874        for byte in &mut glb[bin_chunk + 36..bin_chunk + 72] {
875            *byte = 0;
876        }
877        assert!(matches!(
878            import_glb_with_normals(&glb),
879            Err(AssetError::Parse(_))
880        ));
881    }
882
883    #[test]
884    fn glb_rejects_invalid_tangent_handedness() {
885        let mut glb = build_test_glb();
886        // The third view is TANGENT VEC4 at byte 72; w is the fourth f32.
887        let bin_chunk = glb
888            .windows(4)
889            .position(|w| w == CHUNK_BIN.to_le_bytes())
890            .unwrap()
891            + 4;
892        glb[bin_chunk + 84..bin_chunk + 88].copy_from_slice(&0.0f32.to_le_bytes());
893        assert!(matches!(
894            import_glb_with_normals(&glb),
895            Err(AssetError::Parse(_))
896        ));
897    }
898
899    #[test]
900    fn mikktspace_generation_tracks_uv_orientation_and_corner_splits() {
901        let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
902        let normals = [[0.0, 0.0, 1.0]; 3];
903        let indices = [0, 1, 2];
904        let standard = generate_mikktspace_tangents(
905            &positions,
906            &normals,
907            &[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]],
908            &indices,
909        )
910        .unwrap();
911        assert_eq!(standard.source_vertices, vec![0, 1, 2]);
912        assert_eq!(standard.indices, vec![0, 1, 2]);
913        for tangent in standard.tangents {
914            assert!((tangent[0] - 1.0).abs() < 1e-5);
915            assert!(tangent[1].abs() < 1e-5 && tangent[2].abs() < 1e-5);
916            assert_eq!(tangent[3], 1.0);
917        }
918
919        let mirrored = generate_mikktspace_tangents(
920            &positions,
921            &normals,
922            &[[0.0, 0.0], [1.0, 0.0], [0.0, -1.0]],
923            &indices,
924        )
925        .unwrap();
926        assert!(mirrored.tangents.iter().all(|tangent| tangent[3] == -1.0));
927
928        let quad_positions = [
929            [0.0, 0.0, 0.0],
930            [1.0, 0.0, 0.0],
931            [1.0, 1.0, 0.0],
932            [0.0, 1.0, 0.0],
933        ];
934        let quad_normals = [[0.0, 0.0, 1.0]; 4];
935        let quad_uv = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0]];
936        let split = generate_mikktspace_tangents(
937            &quad_positions,
938            &quad_normals,
939            &quad_uv,
940            &[0, 1, 2, 0, 2, 3],
941        )
942        .unwrap();
943        assert_eq!(split.indices.len(), 6);
944        assert!(split.source_vertices.len() > quad_positions.len());
945        let signs_for_shared_vertex: std::collections::HashSet<_> = split
946            .source_vertices
947            .iter()
948            .enumerate()
949            .filter(|(_, source)| **source == 0)
950            .map(|(output, _)| split.tangents[output][3].is_sign_negative())
951            .collect();
952        assert_eq!(signs_for_shared_vertex.len(), 2);
953    }
954
955    #[test]
956    fn mikktspace_degenerate_uvs_produce_finite_fallback_frames() {
957        let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
958        let normals = [[0.0, 0.0, 1.0]; 3];
959        let generated =
960            generate_mikktspace_tangents(&positions, &normals, &[[0.0, 0.0]; 3], &[0, 1, 2])
961                .unwrap();
962
963        assert_eq!(generated.indices, vec![0, 1, 2]);
964        assert!(generated.tangents.iter().all(|tangent| {
965            tangent.iter().all(|component| component.is_finite())
966                && (tangent[3].abs() - 1.0).abs() < f32::EPSILON
967        }));
968    }
969
970    #[test]
971    fn glb_uv_tangents_survive_asset_compilation_and_10d_decode() {
972        let glb = build_test_glb_without_tangents_with_uv0();
973        let imported = import_glb_with_normals(&glb).unwrap();
974        assert_eq!(imported.tangents.unwrap(), vec![[1.0, 0.0, 0.0, 1.0]; 3]);
975
976        let compiled = crate::render::compile_10d::compile_asset(
977            &glb,
978            Some("glb"),
979            "urn:test:uv-tangent-triangle",
980            "glb",
981        )
982        .unwrap();
983        let decoded = crate::render::compile_10d::decode_10d_tangents(
984            &compiled.container_10d,
985            compiled.mesh.vertex_count(),
986        )
987        .unwrap()
988        .unwrap();
989        assert_eq!(decoded, vec![[1.0, 0.0, 0.0, 1.0]; 3]);
990    }
991
992    #[test]
993    fn texcoord_reader_decodes_normalized_unsigned_bytes_and_checks_view_bounds() {
994        let accessor = serde_json::json!({
995            "componentType": 5121,
996            "normalized": true,
997            "count": 2,
998            "type": "VEC2",
999            "bufferView": 0
1000        });
1001        let view = serde_json::json!({ "byteOffset": 0, "byteLength": 4 });
1002        assert_eq!(
1003            read_texcoords_0(&accessor, &[view.clone()], &[0, 255, 127, 64]).unwrap(),
1004            vec![[0.0, 1.0], [127.0 / 255.0, 64.0 / 255.0]]
1005        );
1006
1007        let short_view = serde_json::json!({ "byteOffset": 0, "byteLength": 3 });
1008        assert!(matches!(
1009            read_texcoords_0(&accessor, &[short_view], &[0, 255, 127, 64]),
1010            Err(AssetError::Parse(_))
1011        ));
1012    }
1013
1014    #[test]
1015    fn empty_obj_is_error() {
1016        assert_eq!(import_obj(b"# nothing here\n"), Err(AssetError::Empty));
1017    }
1018
1019    #[test]
1020    fn parse_glb_living_scene_decodes_hierarchy_skins_anims_morphs_and_khr() {
1021        let mut bin = Vec::new();
1022        // bv 0: 3 positions (36 B)
1023        for v in [[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]] {
1024            for c in v {
1025                bin.extend_from_slice(&c.to_le_bytes());
1026            }
1027        }
1028        // bv 1: 3 JOINTS_0 u8x4 (12 B)
1029        for _ in 0..3 {
1030            bin.extend_from_slice(&[0u8, 1, 0, 0]);
1031        }
1032        // bv 2: 3 WEIGHTS_0 f32x4 (48 B)
1033        for _ in 0..3 {
1034            for w in [0.75f32, 0.25, 0.0, 0.0] {
1035                bin.extend_from_slice(&w.to_le_bytes());
1036            }
1037        }
1038        // bv 3: 2 IBM MAT4 (128 B)
1039        let ident_mat: [f32; 16] = [
1040            1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
1041        ];
1042        for _ in 0..2 {
1043            for f in ident_mat {
1044                bin.extend_from_slice(&f.to_le_bytes());
1045            }
1046        }
1047        // bv 4: anim times [0.0, 0.5] (8 B)
1048        for t in [0.0f32, 0.5] {
1049            bin.extend_from_slice(&t.to_le_bytes());
1050        }
1051        // bv 5: anim translations [[0,0,0], [0,2,0]] (24 B)
1052        for tr in [[0.0f32, 0.0, 0.0], [0.0, 2.0, 0.0]] {
1053            for c in tr {
1054                bin.extend_from_slice(&c.to_le_bytes());
1055            }
1056        }
1057        // bv 6: morph target POSITION deltas (36 B)
1058        for md in [[0.0f32, 0.5, 0.0], [0.0, 0.0, 0.0], [0.0, -0.25, 0.0]] {
1059            for c in md {
1060                bin.extend_from_slice(&c.to_le_bytes());
1061            }
1062        }
1063        while bin.len() % 4 != 0 {
1064            bin.push(0);
1065        }
1066        let json = serde_json::json!({
1067            "asset": { "version": "2.0", "extras": { "qualia": { "taxon_iri": "urn:qualia:flora:corymbia" } } },
1068            "buffers": [{ "byteLength": bin.len() }],
1069            "bufferViews": [
1070                { "buffer": 0, "byteOffset": 0, "byteLength": 36 },
1071                { "buffer": 0, "byteOffset": 36, "byteLength": 12 },
1072                { "buffer": 0, "byteOffset": 48, "byteLength": 48 },
1073                { "buffer": 0, "byteOffset": 96, "byteLength": 128 },
1074                { "buffer": 0, "byteOffset": 224, "byteLength": 8 },
1075                { "buffer": 0, "byteOffset": 232, "byteLength": 24 },
1076                { "buffer": 0, "byteOffset": 256, "byteLength": 36 }
1077            ],
1078            "accessors": [
1079                { "bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3" },
1080                { "bufferView": 1, "componentType": 5121, "count": 3, "type": "VEC4" },
1081                { "bufferView": 2, "componentType": 5126, "count": 3, "type": "VEC4" },
1082                { "bufferView": 3, "componentType": 5126, "count": 2, "type": "MAT4" },
1083                { "bufferView": 4, "componentType": 5126, "count": 2, "type": "SCALAR" },
1084                { "bufferView": 5, "componentType": 5126, "count": 2, "type": "VEC3" },
1085                { "bufferView": 6, "componentType": 5126, "count": 3, "type": "VEC3" }
1086            ],
1087            "materials": [{
1088                "extensions": {
1089                    "KHR_materials_clearcoat": { "clearcoatFactor": 0.8, "clearcoatRoughnessFactor": 0.2 },
1090                    "KHR_materials_ior": { "ior": 1.333 },
1091                    "KHR_materials_emissive_strength": { "emissiveStrength": 4.5 }
1092                }
1093            }],
1094            "extensions": {
1095                "KHR_lights_punctual": {
1096                    "lights": [{ "name": "SunSpot", "type": "spot", "color": [1.0, 0.9, 0.8], "intensity": 12.0 }]
1097                }
1098            },
1099            "meshes": [{
1100                "primitives": [{
1101                    "attributes": { "POSITION": 0, "JOINTS_0": 1, "WEIGHTS_0": 2 },
1102                    "targets": [{ "POSITION": 6 }],
1103                    "material": 0
1104                }]
1105            }],
1106            "nodes": [
1107                { "name": "RootJoint", "children": [1], "translation": [0.0, 1.0, 0.0] },
1108                { "name": "ChildJoint", "translation": [0.0, 0.5, 0.0], "extensions": { "KHR_lights_punctual": { "light": 0 } } },
1109                { "name": "SkinnedMeshNode", "mesh": 0, "skin": 0 }
1110            ],
1111            "scenes": [{ "nodes": [0, 2] }],
1112            "skins": [{ "joints": [0, 1], "skeleton": 0, "inverseBindMatrices": 3 }],
1113            "animations": [{
1114                "name": "Sway",
1115                "samplers": [{ "input": 4, "output": 5, "interpolation": "LINEAR" }],
1116                "channels": [{ "sampler": 0, "target": { "node": 1, "path": "translation" } }]
1117            }]
1118        });
1119        let mut jb = serde_json::to_vec(&json).unwrap();
1120        while jb.len() % 4 != 0 {
1121            jb.push(b' ');
1122        }
1123        let total = 12 + 8 + jb.len() + 8 + bin.len();
1124        let mut glb = Vec::with_capacity(total);
1125        glb.extend_from_slice(&GLB_MAGIC.to_le_bytes());
1126        glb.extend_from_slice(&2u32.to_le_bytes());
1127        glb.extend_from_slice(&(total as u32).to_le_bytes());
1128        glb.extend_from_slice(&(jb.len() as u32).to_le_bytes());
1129        glb.extend_from_slice(&CHUNK_JSON.to_le_bytes());
1130        glb.extend_from_slice(&jb);
1131        glb.extend_from_slice(&(bin.len() as u32).to_le_bytes());
1132        glb.extend_from_slice(&CHUNK_BIN.to_le_bytes());
1133        glb.extend_from_slice(&bin);
1134
1135        let scene = parse_glb_living_scene(&glb).unwrap();
1136        assert_eq!(scene.nodes.len(), 3);
1137        assert_eq!(scene.nodes[1].parent, Some(0));
1138        assert_eq!(scene.joints.len(), 2);
1139        assert_eq!(scene.skin_weights.len(), 3);
1140        assert_eq!(scene.clips.len(), 1);
1141        assert!(scene.skl1_section.is_some());
1142        assert!(scene.mrp1_section.is_some());
1143        assert_eq!(scene.morph_deltas.len(), 2);
1144        assert!((scene.material_extensions[0].clearcoat_factor - 0.8).abs() < 1e-5);
1145        assert!((scene.material_extensions[0].ior - 1.333).abs() < 1e-5);
1146        assert_eq!(scene.punctual_lights.len(), 1);
1147        assert_eq!(scene.proc1_header.magic, *b"PROC");
1148        assert_eq!(scene.eont1_header.magic, *b"EONT");
1149    }
1150}