Skip to main content

qualia_core_db/render/
compile_10d.rs

1//! Compile an imported triangle `Mesh` into a sealed `.10d` container — the
2//! **dense compiled-geometry** half of a geometry asset (see
3//! `docs/manuals/standards/geometry-asset-ontology.md` §3). This is the
4//! "mesh → `.10d`" step of the 3-D-anatomy asset pipeline: the renderer and the
5//! anatomy layer read the `.10d` back with `decode_10d_mesh` instead of
6//! reparsing the source GLB, and the q42 semantic manifest cites the container's
7//! `compiled_digest`.
8//!
9//! **Scope (honest):** emits a `QuantizedMesh` section (u16-quantized
10//! vertices in the bbox + u16/u32 indices). Optional `Tensor10DNodes` (D1),
11//! provenance sidecars, and on native / `wasm-scientific` builds optional
12//! `Topology` + `SpatialIndex` sections (C3) for scan-free picking. LOD chain
13//! from `decimate_3` remains a separate pre-compile step.
14
15use crate::container_10d::crc32c::crc32c;
16use crate::container_10d::header::Container10dHeader;
17use crate::container_10d::integrity::{compute_whole_file_crc32c, seal_whole_file_crc32c};
18use crate::container_10d::mesh_section::{
19    decode_mesh_section, encode_mesh_section, encoded_len, MeshSectionError,
20};
21use crate::container_10d::node_section::{
22    parse_node_header, read_node, write_node_section_aos, NodeMiniHeader, NodeSectionError,
23};
24use crate::container_10d::normal_section::NormalSectionError;
25use crate::container_10d::provenance_section::{
26    encode_provenance_section, encoded_len as provenance_encoded_len, ProvenanceSectionError,
27    ProvenanceSidecar,
28};
29use crate::container_10d::section::{
30    encode_container, parse_section_table, AlignmentTier, SectionInput, SectionTableError,
31    SectionType,
32};
33use crate::container_10d::{attach_material_section, MaterialContainerError};
34use crate::render::assets::{
35    import_asset_with_normals, mesh_to_nquins_with_dev, mesh_to_nquins_with_meta, AssetError, Mesh,
36};
37use crate::tensor::Tensor10D;
38use crate::NQuin;
39use std::collections::HashMap;
40
41/// Optional extra sections for vision / recon seals (programme C3).
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
43pub struct Compile10dExtras {
44    /// Build half-edge Topology section from mesh triangles.
45    pub topology: bool,
46    /// Build BVH + kd-tree SpatialIndex over triangle AABBs / vertices.
47    pub spatial_index: bool,
48}
49
50impl Compile10dExtras {
51    /// Full vision recon package: topology + spatial index (when CG available).
52    pub const VISION: Self = Self {
53        topology: true,
54        spatial_index: true,
55    };
56}
57
58/// Failure modes for `.10d` compilation and read-back.
59///
60/// Not `Clone` — it wraps [`AssetError`], which is not `Clone`. Errors are consumed
61/// on the failure path, not duplicated.
62#[derive(Debug, PartialEq, Eq)]
63pub enum Compile10dError {
64    /// Decoding the source asset bytes (OBJ/STL/GLB) failed.
65    Import(AssetError),
66    /// The QuantizedMesh section encode/decode failed.
67    Mesh(MeshSectionError),
68    /// The optional vertex-normal field sidecar failed validation or encoding.
69    Normals(NormalSectionError),
70    /// Typed MID2 payload selection or codec admission failed.
71    TypedPayload(crate::container_10d::TypedPayloadError),
72    /// The container section table encode/decode failed.
73    Section(SectionTableError),
74    /// Encoding the provenance sidecar section failed.
75    Provenance(ProvenanceSectionError),
76    /// Encoding or reading the Tensor10DNodes section failed.
77    Nodes(NodeSectionError),
78    /// The optional MAT1 material/submesh section failed validation or encoding.
79    Materials(MaterialContainerError),
80    /// The optional UV01 texture-coordinate section failed validation or encoding.
81    TextureCoordinates(crate::container_10d::TextureCoordinateContainerError),
82    /// Stable material identities collided while scoping imported materials to an asset.
83    MaterialIdentityCollision,
84    /// A normal sidecar does not match the mesh vertex count.
85    NormalVertexCountMismatch { expected: usize, got: usize },
86    /// Topology / spatial-index extra section failed (C3).
87    ExtraSection { kind: &'static str },
88    /// The container parsed but held no `QuantizedMesh` section.
89    NoMeshSection,
90    /// The container parsed but held no `Tensor10DNodes` section.
91    NoNodesSection,
92    /// The 64-byte container header failed to parse on read-back.
93    BadHeader,
94    /// A section descriptor's byte range fell outside the container bytes.
95    SectionOutOfBounds,
96}
97
98impl std::fmt::Display for Compile10dError {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        match self {
101            Self::Import(e) => write!(f, ".10d compile: source import: {e}"),
102            Self::Mesh(e) => write!(f, ".10d compile: mesh section: {e}"),
103            Self::Normals(e) => write!(f, ".10d compile: normal field: {e}"),
104            Self::TypedPayload(e) => write!(f, ".10d compile: {e}"),
105            Self::Section(e) => write!(f, ".10d compile: section table: {e:?}"),
106            Self::Provenance(e) => write!(f, ".10d compile: provenance section: {e}"),
107            Self::Nodes(e) => write!(f, ".10d compile: Tensor10DNodes section: {e}"),
108            Self::Materials(e) => write!(f, ".10d compile: MAT1 material section: {e:?}"),
109            Self::TextureCoordinates(e) => {
110                write!(f, ".10d compile: UV01 texture coordinates: {e:?}")
111            }
112            Self::MaterialIdentityCollision => {
113                write!(f, ".10d compile: stable asset material identity collision")
114            }
115            Self::NormalVertexCountMismatch { expected, got } => write!(
116                f,
117                ".10d normal field: vertex count {got} does not match mesh count {expected}"
118            ),
119            Self::ExtraSection { kind } => write!(f, ".10d compile: extra section {kind} failed"),
120            Self::NoMeshSection => write!(f, ".10d: no QuantizedMesh section in container"),
121            Self::NoNodesSection => write!(f, ".10d: no Tensor10DNodes section in container"),
122            Self::BadHeader => write!(f, ".10d: container header failed to parse"),
123            Self::SectionOutOfBounds => write!(f, ".10d: section byte range outside container"),
124        }
125    }
126}
127
128impl std::error::Error for Compile10dError {}
129
130/// Compile a mesh into a **sealed** `.10d` container holding one `QuantizedMesh`
131/// section. The whole-file CRC-32C is written (the container is self-verifying).
132///
133/// Cold path (one-shot asset compilation) — allocates the output `Vec`; the hot
134/// render/query paths operate zero-heap on the decoded section, not here.
135/// Deterministic: identical input → byte-identical container (attestable).
136pub fn compile_mesh_to_10d(mesh: &Mesh) -> Result<Vec<u8>, Compile10dError> {
137    compile_mesh_to_10d_with_provenance(mesh, None)
138}
139
140/// Compile a mesh into a sealed `.10d`, optionally **bundling a provenance sidecar
141/// physically inside the container** (P1) — the immutable source bytes + licence
142/// (+ optional VC) the asset was derived from, so context is byte-inseparable: a
143/// `.10d` copied on its own still carries what it came from and under what licence.
144/// The renderer's governance path treats the presence of this section as the
145/// attestation that makes the mesh *citable* (see `render/portal/mod.rs`).
146pub fn compile_mesh_to_10d_with_provenance(
147    mesh: &Mesh,
148    provenance: Option<&ProvenanceSidecar>,
149) -> Result<Vec<u8>, Compile10dError> {
150    compile_mesh_to_10d_with_nodes_and_provenance(mesh, &[], provenance)
151}
152
153/// Compile mesh + optional Tensor10D nodes (vision detections / σ paint fuel).
154///
155/// Nodes are encoded as `SectionType::Tensor10DNodes` (AoS). Empty `nodes` is
156/// equivalent to [`compile_mesh_to_10d`].
157pub fn compile_mesh_to_10d_with_nodes(
158    mesh: &Mesh,
159    nodes: &[Tensor10D],
160) -> Result<Vec<u8>, Compile10dError> {
161    compile_mesh_to_10d_with_nodes_and_provenance(mesh, nodes, None)
162}
163
164/// Full vision/recon seal: mesh + nodes + optional provenance (no topology extras).
165pub fn compile_mesh_to_10d_with_nodes_and_provenance(
166    mesh: &Mesh,
167    nodes: &[Tensor10D],
168    provenance: Option<&ProvenanceSidecar>,
169) -> Result<Vec<u8>, Compile10dError> {
170    compile_mesh_to_10d_with_extras(mesh, nodes, provenance, Compile10dExtras::default(), None)
171}
172
173/// Vision recon seal: mesh + nodes + Topology + SpatialIndex when CG is linked (C3).
174///
175/// On slim WASM portal builds without `wasm-scientific`, extras are silently
176/// skipped (mesh+nodes still seal) so product paths stay portable.
177pub fn compile_mesh_to_10d_vision(
178    mesh: &Mesh,
179    nodes: &[Tensor10D],
180) -> Result<Vec<u8>, Compile10dError> {
181    compile_mesh_to_10d_with_extras(mesh, nodes, None, Compile10dExtras::VISION, None)
182}
183
184/// Vision recon seal + in-envelope provenance (D4).
185pub fn compile_mesh_to_10d_vision_with_provenance(
186    mesh: &Mesh,
187    nodes: &[Tensor10D],
188    provenance: &ProvenanceSidecar,
189) -> Result<Vec<u8>, Compile10dError> {
190    compile_mesh_to_10d_with_extras(
191        mesh,
192        nodes,
193        Some(provenance),
194        Compile10dExtras::VISION,
195        None,
196    )
197}
198
199/// Seal mesh + provenance + a per-vertex surface colour reading.
200/// The reading length must equal the vertex count. One organ albedo is not
201/// a substitute: callers that have no reading use the provenance-only seal.
202pub fn compile_mesh_to_10d_with_surface_reading(
203    mesh: &Mesh,
204    provenance: Option<&ProvenanceSidecar>,
205    reading: &[[f32; 4]],
206) -> Result<Vec<u8>, Compile10dError> {
207    compile_mesh_to_10d_with_extras(
208        mesh,
209        &[],
210        provenance,
211        Compile10dExtras::default(),
212        Some(reading),
213    )
214}
215
216/// Full seal with explicit extras (topology / spatial index).
217pub fn compile_mesh_to_10d_with_extras(
218    mesh: &Mesh,
219    nodes: &[Tensor10D],
220    provenance: Option<&ProvenanceSidecar>,
221    extras: Compile10dExtras,
222    surface_reading: Option<&[[f32; 4]]>,
223) -> Result<Vec<u8>, Compile10dError> {
224    compile_mesh_to_10d_with_extras_and_frames(
225        mesh,
226        nodes,
227        provenance,
228        extras,
229        surface_reading,
230        None,
231        None,
232    )
233}
234
235/// Compile a mesh and preserve a vertex-aligned authored normal stream in an optional `.10d`
236/// FieldSidecar. The existing QuantizedMesh payload remains unchanged.
237pub fn compile_mesh_to_10d_with_normals(
238    mesh: &Mesh,
239    normals: &[[f32; 3]],
240) -> Result<Vec<u8>, Compile10dError> {
241    compile_mesh_to_10d_with_extras_and_frames(
242        mesh,
243        &[],
244        None,
245        Compile10dExtras::default(),
246        None,
247        Some(normals),
248        None,
249    )
250}
251
252/// Compile authored vertex normals and tangent handedness in an optional FieldSidecar.
253pub fn compile_mesh_to_10d_with_frames(
254    mesh: &Mesh,
255    normals: Option<&[[f32; 3]]>,
256    tangents: Option<&[[f32; 4]]>,
257) -> Result<Vec<u8>, Compile10dError> {
258    compile_mesh_to_10d_with_extras_and_frames(
259        mesh,
260        &[],
261        None,
262        Compile10dExtras::default(),
263        None,
264        normals,
265        tangents,
266    )
267}
268
269/// Full seal with optional color reading and vertex frame fields plus topology/spatial extras.
270pub fn compile_mesh_to_10d_with_extras_and_frames(
271    mesh: &Mesh,
272    nodes: &[Tensor10D],
273    provenance: Option<&ProvenanceSidecar>,
274    extras: Compile10dExtras,
275    surface_reading: Option<&[[f32; 4]]>,
276    normals: Option<&[[f32; 3]]>,
277    tangents: Option<&[[f32; 4]]>,
278) -> Result<Vec<u8>, Compile10dError> {
279    // 1. Encode the QuantizedMesh section payload.
280    let mut payload = vec![0u8; encoded_len(mesh.vertex_count(), mesh.triangle_count())];
281    let written = encode_mesh_section(mesh, &mut payload).map_err(Compile10dError::Mesh)?;
282    payload.truncate(written);
283
284    // 1b. Encode Tensor10DNodes (AoS) when present.
285    let node_payload: Option<Vec<u8>> = if nodes.is_empty() {
286        None
287    } else {
288        let mut buf = vec![0u8; NodeMiniHeader::payload_bytes(nodes.len())];
289        let n = write_node_section_aos(nodes, &mut buf).map_err(Compile10dError::Nodes)?;
290        buf.truncate(n);
291        Some(buf)
292    };
293
294    // 1c. Encode the provenance sidecar payload, if bundling one.
295    let prov_payload: Option<Vec<u8>> = match provenance {
296        Some(p) => {
297            let mut buf = vec![0u8; provenance_encoded_len(p)];
298            let n = encode_provenance_section(p, &mut buf).map_err(Compile10dError::Provenance)?;
299            buf.truncate(n);
300            Some(buf)
301        }
302        None => None,
303    };
304
305    // 1d. Optional Topology + SpatialIndex (native / wasm-scientific only).
306    let topo_payload = if extras.topology {
307        encode_topology_for_mesh(mesh)?
308    } else {
309        None
310    };
311    let spatial_payload = if extras.spatial_index {
312        encode_spatial_index_for_mesh(mesh)?
313    } else {
314        None
315    };
316
317    let surface_payload = match surface_reading {
318        Some(reading) if reading.len() == mesh.vertex_count() && !reading.is_empty() => {
319            Some(crate::container_10d::surface_reading::encode_surface_reading(reading))
320        }
321        Some(_) => {
322            return Err(Compile10dError::ExtraSection {
323                kind: "surface reading length",
324            });
325        }
326        None => None,
327    };
328
329    let frame_payload = match (normals, tangents) {
330        (None, None) => None,
331        (Some(values), _) if values.len() != mesh.vertex_count() => {
332            return Err(Compile10dError::ExtraSection {
333                kind: "normal field length",
334            });
335        }
336        (_, Some(values)) if values.len() != mesh.vertex_count() => {
337            return Err(Compile10dError::ExtraSection {
338                kind: "tangent field length",
339            });
340        }
341        _ => {
342            let count = mesh.vertex_count();
343            let needed = crate::container_10d::normal_section::frame_encoded_len(
344                count,
345                normals.is_some(),
346                tangents.is_some(),
347            )
348            .ok_or(Compile10dError::ExtraSection {
349                kind: "mesh frame field size",
350            })?;
351            let mut payload = vec![0u8; needed];
352            let written = crate::container_10d::normal_section::encode_mesh_frames(
353                normals,
354                tangents,
355                &mut payload,
356            )
357            .map_err(Compile10dError::Normals)?;
358            payload.truncate(written);
359            Some(payload)
360        }
361    };
362
363    // 2. Assemble the container. Writer canonical-orders by section type.
364    let header = Container10dHeader::proposed();
365    let mut inputs = vec![SectionInput {
366        section_type: SectionType::QuantizedMesh,
367        alignment_tier: AlignmentTier::Page,
368        stride: 0,
369        element_count: 0,
370        payload: &payload,
371    }];
372    if let Some(np) = &node_payload {
373        // stride/element_count stay 0: payload includes 16-byte NodeMiniHeader +
374        // N×40 tensors (same contract as container_10d conformance golden).
375        inputs.push(SectionInput {
376            section_type: SectionType::Tensor10DNodes,
377            alignment_tier: AlignmentTier::CacheLine,
378            stride: 0,
379            element_count: 0,
380            payload: np,
381        });
382    }
383    if let Some(pp) = &prov_payload {
384        inputs.push(SectionInput {
385            section_type: SectionType::ProvenanceSidecar,
386            alignment_tier: AlignmentTier::Word,
387            stride: 0,
388            element_count: 0,
389            payload: pp,
390        });
391    }
392    if let Some(np) = &frame_payload {
393        inputs.push(SectionInput {
394            section_type: SectionType::FieldSidecar,
395            alignment_tier: AlignmentTier::Word,
396            stride: 0,
397            element_count: 0,
398            payload: np,
399        });
400    }
401    if let Some(tp) = &topo_payload {
402        inputs.push(SectionInput {
403            section_type: SectionType::Topology,
404            alignment_tier: AlignmentTier::Word,
405            stride: 0,
406            element_count: 0,
407            payload: tp,
408        });
409    }
410    if let Some(sp) = &spatial_payload {
411        inputs.push(SectionInput {
412            section_type: SectionType::SpatialIndex,
413            alignment_tier: AlignmentTier::Page,
414            stride: 0,
415            element_count: 0,
416            payload: sp,
417        });
418    }
419    if let Some(sr) = &surface_payload {
420        inputs.push(SectionInput {
421            section_type: SectionType::SurfaceReading,
422            alignment_tier: AlignmentTier::Word,
423            stride: 0,
424            element_count: 0,
425            payload: sr,
426        });
427    }
428    // Dry-run against an empty buffer to size the output exactly.
429    let needed = match encode_container(&header, &inputs, &mut []) {
430        Err(SectionTableError::OutputBufferTooSmall { needed, .. }) => needed,
431        Ok(n) => n,
432        Err(e) => return Err(Compile10dError::Section(e)),
433    };
434    let mut out = vec![0u8; needed];
435    let total = encode_container(&header, &inputs, &mut out).map_err(Compile10dError::Section)?;
436    out.truncate(total);
437
438    // 3. Seal the whole-file CRC-32C (the `compiledDigest` source).
439    seal_whole_file_crc32c(&mut out);
440    Ok(out)
441}
442
443#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-scientific"))]
444fn encode_topology_for_mesh(mesh: &Mesh) -> Result<Option<Vec<u8>>, Compile10dError> {
445    use crate::container_10d::topology_section::{
446        encode_topology_section, encoded_len as topo_len,
447    };
448    use crate::specialized_libs::computational_geometry::{
449        build_triangle_half_edges, required_edge_slots, EdgeSlot, HalfEdge,
450    };
451
452    if mesh.triangle_count() == 0 || mesh.vertex_count() == 0 {
453        return Ok(None);
454    }
455    let vc = mesh.vertex_count() as u32;
456    let fc = mesh.triangle_count() as u32;
457    let mut edges = vec![HalfEdge::default(); mesh.triangles.len().saturating_mul(3)];
458    let mut slots = vec![EdgeSlot::default(); required_edge_slots(mesh.triangles.len())];
459    build_triangle_half_edges(vc, &mesh.triangles, &mut edges, &mut slots).map_err(|_| {
460        Compile10dError::ExtraSection {
461            kind: "topology_half_edges",
462        }
463    })?;
464    let need = topo_len(vc, fc, edges.len() as u32);
465    let mut buf = vec![0u8; need];
466    let n = encode_topology_section(vc, fc, &edges, &mut buf).map_err(|_| {
467        Compile10dError::ExtraSection {
468            kind: "topology_encode",
469        }
470    })?;
471    buf.truncate(n);
472    Ok(Some(buf))
473}
474
475#[cfg(not(any(not(target_arch = "wasm32"), feature = "wasm-scientific")))]
476fn encode_topology_for_mesh(_mesh: &Mesh) -> Result<Option<Vec<u8>>, Compile10dError> {
477    Ok(None)
478}
479
480#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-scientific"))]
481fn encode_spatial_index_for_mesh(mesh: &Mesh) -> Result<Option<Vec<u8>>, Compile10dError> {
482    use crate::container_10d::spatial_index_section::{
483        encode_spatial_index_section, encoded_len as spatial_len,
484    };
485    use crate::specialized_libs::computational_geometry::{
486        build_bvh_recursive, build_kd_tree_3d, Aabb, BvhNode, KdNode, Point3,
487    };
488
489    if mesh.triangle_count() == 0 || mesh.vertex_count() == 0 {
490        return Ok(None);
491    }
492
493    let mut aabbs = Vec::with_capacity(mesh.triangles.len());
494    for tri in &mesh.triangles {
495        let p0 = mesh.positions[tri[0] as usize];
496        let p1 = mesh.positions[tri[1] as usize];
497        let p2 = mesh.positions[tri[2] as usize];
498        let min = Point3::new(
499            p0[0].min(p1[0]).min(p2[0]) as f64,
500            p0[1].min(p1[1]).min(p2[1]) as f64,
501            p0[2].min(p1[2]).min(p2[2]) as f64,
502        );
503        let max = Point3::new(
504            p0[0].max(p1[0]).max(p2[0]) as f64,
505            p0[1].max(p1[1]).max(p2[1]) as f64,
506            p0[2].max(p1[2]).max(p2[2]) as f64,
507        );
508        aabbs.push(Aabb::new(min, max));
509    }
510    let n = aabbs.len();
511    let mut bvh_nodes = vec![BvhNode::default(); 2 * n];
512    let mut bvh_indices = vec![0u32; n];
513    let mut bvh_codes = vec![0u64; n];
514    let mut bvh_sort = vec![0u32; n];
515    let (bvh_count, bvh_root) = build_bvh_recursive(
516        &aabbs,
517        &mut bvh_nodes,
518        &mut bvh_indices,
519        &mut bvh_codes,
520        &mut bvh_sort,
521    )
522    .map_err(|_| Compile10dError::ExtraSection { kind: "bvh_build" })?;
523
524    let points: Vec<[f64; 3]> = mesh
525        .positions
526        .iter()
527        .map(|p| [p[0] as f64, p[1] as f64, p[2] as f64])
528        .collect();
529    let np = points.len();
530    let mut kd_nodes = vec![KdNode::default(); np];
531    let mut kd_indices = vec![0u32; np];
532    let mut kd_codes = vec![0u64; np];
533    let mut kd_sort = vec![0u32; np];
534    let (kd_count, kd_root) = build_kd_tree_3d(
535        &points,
536        &mut kd_nodes,
537        &mut kd_indices,
538        &mut kd_codes,
539        &mut kd_sort,
540    )
541    .map_err(|_| Compile10dError::ExtraSection { kind: "kd_build" })?;
542
543    let need = spatial_len(bvh_count as u32, kd_count as u32, n as u32, np as u32);
544    let mut buf = vec![0u8; need];
545    encode_spatial_index_section(
546        &bvh_nodes[..bvh_count],
547        &bvh_indices,
548        bvh_root as u32,
549        &kd_nodes[..kd_count],
550        &kd_indices,
551        kd_root as u32,
552        &mut buf,
553    )
554    .map_err(|_| Compile10dError::ExtraSection {
555        kind: "spatial_encode",
556    })?;
557    Ok(Some(buf))
558}
559
560#[cfg(not(any(not(target_arch = "wasm32"), feature = "wasm-scientific")))]
561fn encode_spatial_index_for_mesh(_mesh: &Mesh) -> Result<Option<Vec<u8>>, Compile10dError> {
562    Ok(None)
563}
564
565/// The `compiledDigest` a q42 asset manifest cites: the container's whole-file
566/// CRC-32C (computed with the header's own CRC field zeroed, so it equals the
567/// sealed header value). Deterministic; changes on any geometry-byte change.
568#[inline]
569pub fn compiled_digest(container_10d: &[u8]) -> u32 {
570    compute_whole_file_crc32c(container_10d)
571}
572
573/// Read a `.10d` container back into a dequantized `Mesh` — the renderer /
574/// anatomy path that avoids reparsing the source GLB. Extracts the first
575/// `QuantizedMesh` section.
576pub fn decode_10d_mesh(container_10d: &[u8]) -> Result<Mesh, Compile10dError> {
577    let header =
578        Container10dHeader::parse(container_10d).map_err(|_| Compile10dError::BadHeader)?;
579    let descs = parse_section_table(container_10d, &header).map_err(Compile10dError::Section)?;
580    for d in descs {
581        if d.typ() == Some(SectionType::QuantizedMesh) {
582            let start = d.byte_offset as usize;
583            let end = start
584                .checked_add(d.byte_length as usize)
585                .ok_or(Compile10dError::SectionOutOfBounds)?;
586            let payload = container_10d
587                .get(start..end)
588                .ok_or(Compile10dError::SectionOutOfBounds)?;
589            return decode_mesh_section(payload).map_err(Compile10dError::Mesh);
590        }
591    }
592    Err(Compile10dError::NoMeshSection)
593}
594
595/// Read an optional vertex-aligned normal sidecar from a `.10d` container. Missing sidecars
596/// return `Ok(None)` so existing mesh-only assets retain their established generated-normal path.
597pub fn decode_10d_normals(
598    container_10d: &[u8],
599    expected_vertex_count: usize,
600) -> Result<Option<Vec<[f32; 3]>>, Compile10dError> {
601    Ok(decode_10d_mesh_frames(container_10d, expected_vertex_count)?.and_then(|f| f.normals))
602}
603
604/// Read an optional vertex-aligned tangent frame stream from a `.10d` container.
605pub fn decode_10d_tangents(
606    container_10d: &[u8],
607    expected_vertex_count: usize,
608) -> Result<Option<Vec<[f32; 4]>>, Compile10dError> {
609    Ok(decode_10d_mesh_frames(container_10d, expected_vertex_count)?.and_then(|f| f.tangents))
610}
611
612/// Read an optional vertex-aligned UV0 stream into caller-owned storage.
613pub fn decode_10d_texture_coordinates_into(
614    container_10d: &[u8],
615    expected_vertex_count: usize,
616    out: &mut [[f32; 2]],
617) -> Result<Option<usize>, Compile10dError> {
618    let header =
619        Container10dHeader::parse(container_10d).map_err(|_| Compile10dError::BadHeader)?;
620    let descriptors =
621        parse_section_table(container_10d, &header).map_err(Compile10dError::Section)?;
622    if !descriptors
623        .iter()
624        .any(|descriptor| descriptor.typ() == Some(SectionType::TextureCoordinates))
625    {
626        return Ok(None);
627    }
628    let count = crate::container_10d::read_texture_coordinate_section_into(
629        container_10d,
630        expected_vertex_count,
631        out,
632    )
633    .map_err(Compile10dError::TextureCoordinates)?;
634    Ok(Some(count))
635}
636
637/// Decode supported normal/tangent field data from the optional mesh FieldSidecar.
638pub fn decode_10d_mesh_frames(
639    container_10d: &[u8],
640    expected_vertex_count: usize,
641) -> Result<Option<crate::container_10d::MeshFrameStreams>, Compile10dError> {
642    // Selection/codec admission lives in the focused shared SDK; this oversized
643    // legacy compiler retains only compatibility error projection (see SDK note).
644    crate::container_10d::read_container_mesh_frames_with_limits(
645        container_10d,
646        expected_vertex_count,
647        crate::container_10d::MeshFrameDecodeLimits::COMPATIBILITY,
648    )
649    .map_err(|error| match error {
650        crate::container_10d::TypedPayloadError::Header(_) => Compile10dError::BadHeader,
651        crate::container_10d::TypedPayloadError::Sections(e) => Compile10dError::Section(e),
652        crate::container_10d::TypedPayloadError::Frames(e) => Compile10dError::Normals(e),
653        crate::container_10d::TypedPayloadError::VertexCount { expected, got } => {
654            Compile10dError::NormalVertexCountMismatch { expected, got }
655        }
656        other => Compile10dError::TypedPayload(other),
657    })
658}
659
660/// Read Tensor10D nodes from a sealed `.10d` (first Tensor10DNodes section).
661///
662/// Returns the node count written into `out` (caller buffer; truncated to
663/// `out.len()`). Fail-closed if the section is missing or malformed.
664pub fn decode_10d_nodes(
665    container_10d: &[u8],
666    out: &mut [Tensor10D],
667) -> Result<usize, Compile10dError> {
668    let header =
669        Container10dHeader::parse(container_10d).map_err(|_| Compile10dError::BadHeader)?;
670    let descs = parse_section_table(container_10d, &header).map_err(Compile10dError::Section)?;
671    for d in descs {
672        if d.typ() == Some(SectionType::Tensor10DNodes) {
673            let start = d.byte_offset as usize;
674            let end = start
675                .checked_add(d.byte_length as usize)
676                .ok_or(Compile10dError::SectionOutOfBounds)?;
677            let payload = container_10d
678                .get(start..end)
679                .ok_or(Compile10dError::SectionOutOfBounds)?;
680            let (nh, _) = parse_node_header(payload).map_err(Compile10dError::Nodes)?;
681            let count = (nh.node_count as usize).min(out.len());
682            for i in 0..count {
683                out[i] = read_node(payload, i).map_err(Compile10dError::Nodes)?;
684            }
685            return Ok(count);
686        }
687    }
688    Err(Compile10dError::NoNodesSection)
689}
690
691/// A fully compiled geometry asset: the source-imported `Mesh`, the sealed `.10d`
692/// container, its two content digests, and the q42 semantic manifest that cites the
693/// container by `compiledDigest` (geometry-asset-ontology §1 two-layer model).
694///
695/// This is the whole "GLB → `.10d` + manifest" pipeline output. The `container_10d`
696/// bytes are the on-disk sidecar; `quins`/`lexicon` are the portable q42 facts that
697/// travel in the graph and point at the container by hash.
698#[derive(Debug, Clone)]
699pub struct CompiledAsset {
700    /// The imported triangle mesh (positions + indices + bbox).
701    pub mesh: Mesh,
702    /// The sealed `.10d` container (dense compiled geometry).
703    pub container_10d: Vec<u8>,
704    /// Content-addressed source images referenced by MAT1, ready for separate HMC packaging;
705    /// asset bytes are intentionally not placed in the Sentinel arena.
706    pub texture_dependencies: Vec<crate::render::assets::TextureDependency>,
707    /// Whole-file CRC-32C of `container_10d` — the manifest's `compiledDigest`.
708    pub compiled_digest: u32,
709    /// CRC-32C of the immutable source bytes — the manifest's `sourceDigest`.
710    pub source_digest: u32,
711    /// The q42 manifest facts, including both digests (via `mesh_to_nquins_with_digests()`).
712    pub quins: Vec<NQuin>,
713    /// Object-lexicon for the string-valued facts in `quins`.
714    pub lexicon: HashMap<u64, String>,
715}
716
717/// The end-to-end asset-compile step: source asset bytes → [`CompiledAsset`].
718///
719/// Runs the full pipeline — import the source ([`import_asset`]), compile the dense
720/// `.10d` ([`compile_mesh_to_10d`]), hash both layers, then emit the q42 manifest that
721/// binds them (`mesh_to_nquins_with_digests()`). Deterministic: identical
722/// `(source_bytes, asset_uri, source_format)` → byte-identical container and identical
723/// digests, so the manifest→container citation is attestable.
724///
725/// `hint` is the source-format hint forwarded to `import_asset` (e.g. `Some("glb")`);
726/// `source_format` is the value recorded in the manifest and should agree with the real
727/// format of `source_bytes`.
728pub fn compile_asset(
729    source_bytes: &[u8],
730    hint: Option<&str>,
731    asset_uri: &str,
732    source_format: &str,
733) -> Result<CompiledAsset, Compile10dError> {
734    compile_organ_asset(
735        source_bytes,
736        hint,
737        asset_uri,
738        source_format,
739        None,
740        None,
741        None,
742    )
743}
744
745/// Like [`compile_asset`] but also binds the compiled asset to a 3D-body organ: its `body_system`
746/// (which of the 17 systems colours it by burden) and `anatomy_model` (`"male"` / `"female"`, from the
747/// user's declared XY/XX basis). This is the compile step for an anatomy organ mesh — the manifest it
748/// emits carries `geo:bodySystem` + `geo:anatomyModel` so the renderer can look the organ up in the
749/// per-system percept table (S5.1) and both colour and sonify it.
750#[allow(clippy::too_many_arguments)]
751pub fn compile_organ_asset(
752    source_bytes: &[u8],
753    hint: Option<&str>,
754    asset_uri: &str,
755    source_format: &str,
756    body_system: Option<&str>,
757    anatomy_model: Option<&str>,
758    provenance: Option<&ProvenanceSidecar>,
759) -> Result<CompiledAsset, Compile10dError> {
760    let imported =
761        import_asset_with_normals(source_bytes, hint).map_err(Compile10dError::Import)?;
762    let mesh = imported.mesh;
763    let texture_dependencies = imported.texture_dependencies;
764    let texture_coordinates_0 = imported.texture_coordinates_0;
765    // When provenance is supplied it is sealed into the `.10d` as a ProvenanceSidecar section, so the
766    // asset is attested (the renderer's fail-closed governance gate treats an unattested asset with the
767    // default-refuse disposition as REFUSE).
768    let mut container_10d = compile_mesh_to_10d_with_extras_and_frames(
769        &mesh,
770        &[],
771        provenance,
772        Compile10dExtras::default(),
773        None,
774        imported.normals.as_deref(),
775        imported.tangents.as_deref(),
776    )?;
777    if let Some(coordinates) = texture_coordinates_0.as_deref() {
778        container_10d =
779            crate::container_10d::attach_texture_coordinate_section(&container_10d, coordinates)
780                .map_err(Compile10dError::TextureCoordinates)?;
781    }
782    if !imported.submeshes.is_empty() {
783        let (materials, ranges) = crate::render::material_compile::scope_material_bindings(
784            asset_uri,
785            &imported.materials,
786            &imported.submeshes,
787        )
788        .map_err(|_| Compile10dError::MaterialIdentityCollision)?;
789        let mesh_index_count = u32::try_from(mesh.triangle_count().saturating_mul(3))
790            .map_err(|_| Compile10dError::MaterialIdentityCollision)?;
791        container_10d =
792            attach_material_section(&container_10d, &materials, &ranges, mesh_index_count)
793                .map_err(Compile10dError::Materials)?;
794    }
795    let compiled = compiled_digest(&container_10d);
796    let source = crc32c(source_bytes);
797    let (quins, lexicon) = mesh_to_nquins_with_meta(
798        &mesh,
799        asset_uri,
800        source_format,
801        source,
802        compiled,
803        body_system,
804        anatomy_model,
805    );
806    Ok(CompiledAsset {
807        mesh,
808        container_10d,
809        texture_dependencies,
810        compiled_digest: compiled,
811        source_digest: source,
812        quins,
813        lexicon,
814    })
815}
816
817/// Like [`compile_asset`] but binds the compiled asset to a point on the developmental **`t`-axis** — its
818/// `gestational_age_days` (postfertilization) and `carnegie_stage`. This is the compile step for a fetal/
819/// embryonic stage: consecutive stages, ordered by gestational age, form a 4-D developmental body (the
820/// maternal–fetal dyad's fetal side, reproductive-continuum plan §2).
821pub fn compile_developmental_asset(
822    source_bytes: &[u8],
823    hint: Option<&str>,
824    asset_uri: &str,
825    source_format: &str,
826    gestational_age_days: u16,
827    carnegie_stage: u8,
828) -> Result<CompiledAsset, Compile10dError> {
829    let imported =
830        import_asset_with_normals(source_bytes, hint).map_err(Compile10dError::Import)?;
831    let mesh = imported.mesh;
832    let texture_dependencies = imported.texture_dependencies;
833    let texture_coordinates_0 = imported.texture_coordinates_0;
834    let mut container_10d = compile_mesh_to_10d_with_extras_and_frames(
835        &mesh,
836        &[],
837        None,
838        Compile10dExtras::default(),
839        None,
840        imported.normals.as_deref(),
841        imported.tangents.as_deref(),
842    )?;
843    if let Some(coordinates) = texture_coordinates_0.as_deref() {
844        container_10d =
845            crate::container_10d::attach_texture_coordinate_section(&container_10d, coordinates)
846                .map_err(Compile10dError::TextureCoordinates)?;
847    }
848    if !imported.submeshes.is_empty() {
849        let (materials, ranges) = crate::render::material_compile::scope_material_bindings(
850            asset_uri,
851            &imported.materials,
852            &imported.submeshes,
853        )
854        .map_err(|_| Compile10dError::MaterialIdentityCollision)?;
855        let mesh_index_count = u32::try_from(mesh.triangle_count().saturating_mul(3))
856            .map_err(|_| Compile10dError::MaterialIdentityCollision)?;
857        container_10d =
858            attach_material_section(&container_10d, &materials, &ranges, mesh_index_count)
859                .map_err(Compile10dError::Materials)?;
860    }
861    let compiled = compiled_digest(&container_10d);
862    let source = crc32c(source_bytes);
863    let (quins, lexicon) = mesh_to_nquins_with_dev(
864        &mesh,
865        asset_uri,
866        source_format,
867        source,
868        compiled,
869        gestational_age_days,
870        carnegie_stage,
871    );
872    Ok(CompiledAsset {
873        mesh,
874        container_10d,
875        texture_dependencies,
876        compiled_digest: compiled,
877        source_digest: source,
878        quins,
879        lexicon,
880    })
881}
882
883#[cfg(test)]
884mod tests {
885    use super::*;
886    use crate::container_10d::integrity::verify_whole_file_crc32c;
887
888    /// Unit cube, 8 vertices / 12 triangles — a valid `render::Mesh`.
889    fn cube() -> Mesh {
890        Mesh {
891            positions: vec![
892                [0.0, 0.0, 0.0],
893                [1.0, 0.0, 0.0],
894                [1.0, 1.0, 0.0],
895                [0.0, 1.0, 0.0],
896                [0.0, 0.0, 1.0],
897                [1.0, 0.0, 1.0],
898                [1.0, 1.0, 1.0],
899                [0.0, 1.0, 1.0],
900            ],
901            triangles: vec![
902                [0, 3, 2],
903                [0, 2, 1],
904                [4, 5, 6],
905                [4, 6, 7],
906                [0, 1, 5],
907                [0, 5, 4],
908                [3, 7, 6],
909                [3, 6, 2],
910                [0, 4, 7],
911                [0, 7, 3],
912                [1, 2, 6],
913                [1, 6, 5],
914            ],
915            min: [0.0, 0.0, 0.0],
916            max: [1.0, 1.0, 1.0],
917        }
918    }
919
920    #[test]
921    fn container_is_well_formed_and_sealed() {
922        let mut bytes = compile_mesh_to_10d(&cube()).unwrap();
923        assert!(
924            bytes.len() > 64,
925            "container must be larger than the 64-byte header"
926        );
927        // The seal verifies (whole-file CRC matches the header) — proves it's well-formed.
928        verify_whole_file_crc32c(&mut bytes).expect(".10d whole-file CRC must verify");
929    }
930
931    #[test]
932    fn optional_normal_field_round_trips_with_mesh_without_changing_mesh_payload() {
933        let mesh = cube();
934        let normals = vec![[0.0, 0.0, 1.0]; mesh.vertex_count()];
935        let bytes = compile_mesh_to_10d_with_normals(&mesh, &normals).unwrap();
936        assert_eq!(
937            decode_10d_mesh(&bytes).unwrap().triangle_count(),
938            mesh.triangle_count()
939        );
940        let decoded = decode_10d_normals(&bytes, mesh.vertex_count())
941            .unwrap()
942            .unwrap();
943        assert_eq!(decoded.len(), normals.len());
944        assert!(decoded.iter().all(|normal| normal[2] > 0.9999));
945        assert_eq!(
946            decode_10d_normals(&compile_mesh_to_10d(&mesh).unwrap(), mesh.vertex_count()).unwrap(),
947            None
948        );
949    }
950
951    #[test]
952    fn optional_normal_field_requires_vertex_alignment() {
953        let mesh = cube();
954        assert!(matches!(
955            compile_mesh_to_10d_with_normals(&mesh, &[[0.0, 0.0, 1.0]]),
956            Err(Compile10dError::ExtraSection {
957                kind: "normal field length"
958            })
959        ));
960    }
961
962    #[test]
963    fn optional_tangent_frames_round_trip_through_the_field_sidecar() {
964        let mesh = cube();
965        let normals = vec![[0.0, 0.0, 1.0]; mesh.vertex_count()];
966        let tangents = vec![[1.0, 0.0, 0.0, -1.0]; mesh.vertex_count()];
967        let bytes =
968            compile_mesh_to_10d_with_frames(&mesh, Some(&normals), Some(&tangents)).unwrap();
969        assert_eq!(
970            decode_10d_normals(&bytes, mesh.vertex_count())
971                .unwrap()
972                .unwrap(),
973            normals
974        );
975        assert_eq!(
976            decode_10d_tangents(&bytes, mesh.vertex_count())
977                .unwrap()
978                .unwrap(),
979            tangents
980        );
981
982        let tangent_only = compile_mesh_to_10d_with_frames(&mesh, None, Some(&tangents)).unwrap();
983        assert_eq!(
984            decode_10d_normals(&tangent_only, mesh.vertex_count()).unwrap(),
985            None
986        );
987        assert_eq!(
988            decode_10d_tangents(&tangent_only, mesh.vertex_count())
989                .unwrap()
990                .unwrap(),
991            tangents
992        );
993    }
994
995    #[test]
996    fn bundles_provenance_physically_and_still_decodes_the_mesh() {
997        use crate::container_10d::provenance_section::{
998            decode_provenance_section, validate_provenance,
999        };
1000
1001        let source = b"<the original source GLB bytes for this organ>".to_vec();
1002        let sidecar = ProvenanceSidecar::new(source.clone(), "model/gltf-binary", "CC-BY-4.0");
1003        let mut bytes = compile_mesh_to_10d_with_provenance(&cube(), Some(&sidecar)).unwrap();
1004
1005        // The whole-file seal still verifies with the extra section.
1006        verify_whole_file_crc32c(&mut bytes).expect(".10d whole-file CRC must verify");
1007        // The mesh is still decodable (the provenance section does not disturb it).
1008        let mesh = decode_10d_mesh(&bytes).unwrap();
1009        assert_eq!(mesh.triangle_count(), cube().triangle_count());
1010
1011        // The provenance sidecar is physically present in the container and passes its gate.
1012        let header = Container10dHeader::parse(&bytes).unwrap();
1013        let descs = parse_section_table(&bytes, &header).unwrap();
1014        let prov = descs
1015            .iter()
1016            .find(|d| d.typ() == Some(SectionType::ProvenanceSidecar))
1017            .expect("provenance section bundled in the .10d");
1018        let payload = &bytes[prov.byte_offset as usize..][..prov.byte_length as usize];
1019        let view = decode_provenance_section(payload).unwrap();
1020        validate_provenance(&view).expect("bundled provenance validates before use");
1021        assert_eq!(view.licence(), "CC-BY-4.0");
1022        assert_eq!(view.source_bytes(), source.as_slice());
1023    }
1024
1025    #[test]
1026    fn round_trips_the_mesh_within_quantization_tolerance() {
1027        let m = cube();
1028        let bytes = compile_mesh_to_10d(&m).unwrap();
1029        let back = decode_10d_mesh(&bytes).unwrap();
1030        assert_eq!(back.vertex_count(), m.vertex_count());
1031        assert_eq!(back.triangle_count(), m.triangle_count());
1032        assert_eq!(back.triangles, m.triangles, "indices are exact");
1033        // Positions survive within the u16-in-bbox quantization bound (extent/65535).
1034        let tol = 1.0 / 65535.0 * 1.001;
1035        for (a, b) in m.positions.iter().zip(back.positions.iter()) {
1036            for k in 0..3 {
1037                assert!((a[k] - b[k]).abs() <= tol, "vertex {a:?} vs {b:?} axis {k}");
1038            }
1039        }
1040    }
1041
1042    #[test]
1043    fn compilation_is_deterministic() {
1044        let m = cube();
1045        let a = compile_mesh_to_10d(&m).unwrap();
1046        let b = compile_mesh_to_10d(&m).unwrap();
1047        assert_eq!(a, b, "identical mesh → byte-identical .10d");
1048        assert_eq!(compiled_digest(&a), compiled_digest(&b));
1049    }
1050
1051    #[test]
1052    fn digest_changes_when_geometry_changes() {
1053        let a = compile_mesh_to_10d(&cube()).unwrap();
1054        let mut m2 = cube();
1055        m2.positions[6] = [1.0, 1.0, 0.5]; // move one vertex
1056        let b = compile_mesh_to_10d(&m2).unwrap();
1057        assert_ne!(compiled_digest(&a), compiled_digest(&b));
1058    }
1059
1060    #[test]
1061    fn decode_rejects_garbage() {
1062        assert_eq!(decode_10d_mesh(&[0u8; 8]), Err(Compile10dError::BadHeader));
1063    }
1064
1065    #[test]
1066    fn mesh_with_nodes_round_trips_sigma() {
1067        use crate::tensor::Tensor10D;
1068        let mesh = cube();
1069        let nodes = [
1070            Tensor10D::ground_truth(0.0, 0.0, 0.5, 0.5, 0.0, 1.0, 0.9, 0.0, 0.42),
1071            Tensor10D::parallel_context(1.0, 0.0, 0.0, 0.1, 0.2, 0.0, 2.0, 0.5, 0.0, 0.7),
1072        ];
1073        let mut bytes = compile_mesh_to_10d_with_nodes(&mesh, &nodes).unwrap();
1074        verify_whole_file_crc32c(&mut bytes).expect("seal");
1075        let back = decode_10d_mesh(&bytes).unwrap();
1076        assert_eq!(back.triangle_count(), mesh.triangle_count());
1077        let mut out = [Tensor10D::default(); 4];
1078        let n = decode_10d_nodes(&bytes, &mut out).unwrap();
1079        assert_eq!(n, 2);
1080        assert!((out[0].sigma - 0.42).abs() < 1e-5);
1081        assert!((out[0].x - 0.5).abs() < 1e-5);
1082        assert!((out[1].q - 1.0).abs() < 1e-5);
1083        assert!((out[1].sigma - 0.7).abs() < 1e-5);
1084        // Mesh-only compile must not invent a nodes section.
1085        let plain = compile_mesh_to_10d(&mesh).unwrap();
1086        assert!(matches!(
1087            decode_10d_nodes(&plain, &mut out),
1088            Err(Compile10dError::NoNodesSection)
1089        ));
1090    }
1091
1092    #[test]
1093    fn vision_seal_includes_topology_and_spatial_when_cg() {
1094        use crate::tensor::Tensor10D;
1095        let mesh = cube();
1096        let nodes = [Tensor10D::ground_truth(
1097            0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 1.0, 0.0, 0.33,
1098        )];
1099        let mut bytes = compile_mesh_to_10d_vision(&mesh, &nodes).unwrap();
1100        verify_whole_file_crc32c(&mut bytes).expect("seal");
1101        let header = Container10dHeader::parse(&bytes).unwrap();
1102        let descs = parse_section_table(&bytes, &header).unwrap();
1103        let types: Vec<_> = descs.iter().filter_map(|d| d.typ()).collect();
1104        assert!(types.contains(&SectionType::QuantizedMesh));
1105        assert!(types.contains(&SectionType::Tensor10DNodes));
1106        #[cfg(any(not(target_arch = "wasm32"), feature = "wasm-scientific"))]
1107        {
1108            assert!(
1109                types.contains(&SectionType::Topology),
1110                "expected Topology section, got {types:?}"
1111            );
1112            assert!(
1113                types.contains(&SectionType::SpatialIndex),
1114                "expected SpatialIndex section, got {types:?}"
1115            );
1116        }
1117        let back = decode_10d_mesh(&bytes).unwrap();
1118        assert_eq!(back.triangle_count(), mesh.triangle_count());
1119    }
1120
1121    /// A single OBJ triangle — the smallest valid source asset.
1122    const TRI_OBJ: &[u8] = b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n";
1123
1124    #[test]
1125    fn compile_asset_binds_manifest_to_its_container() {
1126        let a = compile_asset(TRI_OBJ, Some("obj"), "urn:asset:tri", "obj").unwrap();
1127
1128        // The container round-trips back to the mesh the manifest describes.
1129        let back = decode_10d_mesh(&a.container_10d).unwrap();
1130        assert_eq!(back.triangle_count(), 1);
1131        assert_eq!(back.vertex_count(), 3);
1132
1133        // compiled_digest field == the container's real whole-file CRC (the citation is honest).
1134        assert_eq!(a.compiled_digest, compiled_digest(&a.container_10d));
1135        // source_digest == CRC of the source bytes.
1136        assert_eq!(a.source_digest, crc32c(TRI_OBJ));
1137
1138        // Both digests appear as manifest facts (object-side), binding the two layers.
1139        let objs: Vec<u64> = a.quins.iter().map(|q| q.object).collect();
1140        assert!(
1141            objs.contains(&(a.compiled_digest as u64)),
1142            "manifest cites compiledDigest"
1143        );
1144        assert!(
1145            objs.contains(&(a.source_digest as u64)),
1146            "manifest cites sourceDigest"
1147        );
1148    }
1149
1150    #[test]
1151    fn compile_asset_is_deterministic() {
1152        let a = compile_asset(TRI_OBJ, Some("obj"), "urn:asset:tri", "obj").unwrap();
1153        let b = compile_asset(TRI_OBJ, Some("obj"), "urn:asset:tri", "obj").unwrap();
1154        assert_eq!(a.container_10d, b.container_10d, "byte-identical container");
1155        assert_eq!(a.compiled_digest, b.compiled_digest);
1156        assert_eq!(a.source_digest, b.source_digest);
1157    }
1158
1159    #[test]
1160    fn compile_asset_surfaces_import_errors() {
1161        // Not a recognisable asset in any supported format.
1162        let err = compile_asset(b"\x00\x01\x02\x03", None, "urn:asset:junk", "obj");
1163        assert!(matches!(err, Err(Compile10dError::Import(_))));
1164    }
1165
1166    #[test]
1167    fn compile_organ_asset_binds_body_system_and_model() {
1168        let plain = compile_asset(TRI_OBJ, Some("obj"), "urn:asset:organ", "obj").unwrap();
1169        let organ = compile_organ_asset(
1170            TRI_OBJ,
1171            Some("obj"),
1172            "urn:asset:organ",
1173            "obj",
1174            Some("respiratory"),
1175            Some("male"),
1176            None,
1177        )
1178        .unwrap();
1179        // Same geometry → identical container + digests; only the manifest gains the anatomy facts.
1180        assert_eq!(organ.container_10d, plain.container_10d);
1181        assert_eq!(organ.compiled_digest, plain.compiled_digest);
1182        assert_eq!(
1183            organ.quins.len(),
1184            plain.quins.len() + 2,
1185            "two anatomy facts added"
1186        );
1187        // bodySystem + anatomyModel strings are carried in the lexicon.
1188        let vals: Vec<&str> = organ.lexicon.values().map(String::as_str).collect();
1189        assert!(vals.contains(&"respiratory"), "bodySystem fact present");
1190        assert!(vals.contains(&"male"), "anatomyModel fact present");
1191        // None/None path is exactly compile_asset — no phantom facts.
1192        let none = compile_organ_asset(
1193            TRI_OBJ,
1194            Some("obj"),
1195            "urn:asset:organ",
1196            "obj",
1197            None,
1198            None,
1199            None,
1200        )
1201        .unwrap();
1202        assert_eq!(none.quins.len(), plain.quins.len());
1203    }
1204
1205    #[test]
1206    fn compile_developmental_asset_binds_the_t_axis_coordinate() {
1207        let plain = compile_asset(TRI_OBJ, Some("obj"), "urn:asset:fetal", "obj").unwrap();
1208        // Carnegie stage 18 ≈ 44 postfertilization days.
1209        let dev =
1210            compile_developmental_asset(TRI_OBJ, Some("obj"), "urn:asset:fetal", "obj", 44, 18)
1211                .unwrap();
1212        // Same geometry → identical container; only the manifest gains the two developmental facts.
1213        assert_eq!(dev.container_10d, plain.container_10d);
1214        assert_eq!(
1215            dev.quins.len(),
1216            plain.quins.len() + 2,
1217            "gestationalAgeDays + carnegieStage"
1218        );
1219        // The t-axis coordinate (44 days) and the stage (18) are present as u64 fact objects (a 3-vertex,
1220        // 1-triangle mesh has no other facts with those values, so this is unambiguous).
1221        assert!(
1222            dev.quins.iter().any(|q| q.object == 44),
1223            "gestationalAgeDays=44"
1224        );
1225        assert!(dev.quins.iter().any(|q| q.object == 18), "carnegieStage=18");
1226    }
1227}