Skip to main content

qualia_core_db/container_10d/
mesh_section.rs

1//! `.10d` QuantizedMesh section — the geometry half of a mesh asset in the
2//! container (P0.4).
3//!
4//! A QuantizedMesh section wraps a [`Mesh`] as a
5//! self-describing `.10d` section. Vertex positions are quantized to **u16
6//! per axis within the mesh's bounding box** — 6 bytes/vertex vs 12 for raw
7//! f32 (2×), and the bbox is exactly what the semantic quins already carry,
8//! so it doubles as the dequantization frame (no information is invented).
9//! Triangle indices are u16 when the mesh has ≤65 536 vertices (6 bytes/tri
10//! vs 12). Quantization error is `bbox_extent / 65535` per axis — sub-micron
11//! at organ scale, visually lossless.
12//!
13//! **Layout:** a 40-byte [`MeshMiniHeader`] (flags + counts + dequantization
14//! bbox + reserved) followed by the quantized vertex data (N × 6 bytes:
15//! u16×3 per vertex) and then the triangle indices (u16×3 or u32×3 per
16//! triangle, selected by the `FLAG_U16_INDICES` flag). The mini-header is
17//! `repr(C)`, naturally aligned, no implicit padding.
18//!
19//! **This replaces the erroneous legacy mesh build artifact** that lived in
20//! `render/mesh_asset.rs` — a pre-release format that was never shipped and
21//! has been refactored out rather than carried forward. The legacy 48-byte
22//! header with its per-format magic is gone; the `.10d` section-type tag
23//! (`SectionType::QuantizedMesh = 1`) replaces the magic, and the `.10d`
24//! container version replaces the per-format version. No backward-compat is
25//! provided — the legacy format was an erroneous build artifact, not a
26//! shipped format anyone depends on.
27//!
28//! **Determinism + CRC:** two encodes of the same mesh are byte-identical
29//! (the quantization is deterministic). The per-section CRC-32C (P0.2)
30//! catches a flipped bit in the payload. The whole-file CRC-32C (P0.3)
31//! catches header corruption.
32
33mod view;
34pub use view::MeshSectionView;
35
36use bytemuck::{bytes_of, Pod, Zeroable};
37
38use crate::render::assets::Mesh;
39
40/// Section payload mini-header size in bytes.
41pub const MESH_MINI_HEADER_SIZE: usize = 40;
42
43/// `flags` bit 0: triangle indices are u16 (else u32).
44pub const FLAG_U16_INDICES: u16 = 0x0001;
45
46/// Maximum vertex count the mesh section will accept. Bounds against a
47/// hostile/malformed file. u16 indices cap at 65 536; above that the encoder
48/// switches to u32. The practical ceiling is the 42MB Sentinel: 40MB of
49/// vertex data / 6 bytes per vertex ≈ 6.7M vertices. 4M (2^22) is a
50/// comfortable upper bound.
51pub const MAX_VERTEX_COUNT: usize = 4_194_304; // 2^22
52
53/// Maximum triangle count. Similarly bounded by the Sentinel: 40MB / 6 bytes
54/// per u16-indexed triangle ≈ 6.7M triangles. 4M is the matching ceiling.
55pub const MAX_TRIANGLE_COUNT: usize = 4_194_304; // 2^22
56
57/// The 40-byte QuantizedMesh-section mini-header. `repr(C)`, naturally
58/// aligned, no implicit padding.
59///
60/// ```text
61/// offset  size  field
62/// 0       2     flags:u16         (bit 0 = u16 indices, else u32)
63/// 2       2     reserved_u16      (must be zero)
64/// 4       4     vertex_count:u32
65/// 8       4     triangle_count:u32
66/// 12      12    min:[f32;3]       (dequantization frame: position = min + (q/65535)*(max-min))
67/// 24      12    max:[f32;3]
68/// 36      4     reserved_u32      (must be zero — future: LOD tier, material index)
69/// ```
70#[repr(C)]
71#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
72pub struct MeshMiniHeader {
73    pub flags: u16,
74    pub reserved_u16: u16,
75    pub vertex_count: u32,
76    pub triangle_count: u32,
77    pub min: [f32; 3],
78    pub max: [f32; 3],
79    pub reserved_u32: u32,
80}
81
82impl MeshMiniHeader {
83    /// Total payload byte length (mini-header + vertex data + index data).
84    #[inline]
85    pub fn payload_bytes(vertex_count: usize, triangle_count: usize, u16_idx: bool) -> usize {
86        let idx_bytes = if u16_idx { 6 } else { 12 };
87        MESH_MINI_HEADER_SIZE + vertex_count * 6 + triangle_count * idx_bytes
88    }
89}
90
91/// Mesh-section read/write error.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub enum MeshSectionError {
94    /// The payload is too short for the mini-header.
95    PayloadTooShort { got: usize, need: usize },
96    /// A reserved field in the mini-header is non-zero.
97    NonZeroReserved { field: &'static str },
98    /// `vertex_count` exceeds `MAX_VERTEX_COUNT`.
99    VertexCountTooLarge { got: u32, max: usize },
100    /// `triangle_count` exceeds `MAX_TRIANGLE_COUNT`.
101    TriangleCountTooLarge { got: u32, max: usize },
102    /// The payload is too short for the declared counts.
103    PayloadTruncated { expected: usize, got: usize },
104    /// The output buffer is too small.
105    OutputBufferTooSmall { needed: usize, have: usize },
106    /// Unknown flags bit set (only bit 0 is defined in v1).
107    UnknownFlags { got: u16 },
108    /// A dequantization-frame bound is non-finite or min exceeds max.
109    InvalidBounds { axis: usize },
110    /// A triangle references a vertex outside this section.
111    IndexOutOfBounds { index: u32, vertices: u32 },
112    /// Exact section extent has unclaimed trailing bytes.
113    TrailingBytes { expected: usize, got: usize },
114    /// Encoder input contains a non-finite coordinate.
115    InvalidPosition { vertex: usize, axis: usize },
116}
117
118impl std::fmt::Display for MeshSectionError {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        match self {
121            Self::PayloadTooShort { got, need } => {
122                write!(f, "10d MESH payload too short: got {got}, need {need}")
123            }
124            Self::NonZeroReserved { field } => {
125                write!(f, "10d MESH non-zero reserved field {field:?}")
126            }
127            Self::VertexCountTooLarge { got, max } => {
128                write!(f, "10d MESH vertex_count {got} exceeds max {max}")
129            }
130            Self::TriangleCountTooLarge { got, max } => {
131                write!(f, "10d MESH triangle_count {got} exceeds max {max}")
132            }
133            Self::PayloadTruncated { expected, got } => write!(
134                f,
135                "10d MESH payload truncated: expected {expected}, got {got}"
136            ),
137            Self::OutputBufferTooSmall { needed, have } => write!(
138                f,
139                "10d MESH output buffer too small: need {needed}, have {have}"
140            ),
141            Self::IndexOutOfBounds { index, vertices } => {
142                write!(f, "10d MESH index {index} outside {vertices} vertices")
143            }
144            Self::TrailingBytes { expected, got } => {
145                write!(f, "10d MESH trailing bytes: expected {expected}, got {got}")
146            }
147            Self::InvalidPosition { vertex, axis } => {
148                write!(f, "10d MESH non-finite vertex {vertex} axis {axis}")
149            }
150            Self::InvalidBounds { axis } => write!(f, "10d MESH invalid bounds on axis {axis}"),
151            Self::UnknownFlags { got } => write!(
152                f,
153                "10d MESH unknown flags bits {got:#06x} (only bit 0 defined in v1)"
154            ),
155        }
156    }
157}
158
159impl std::error::Error for MeshSectionError {}
160
161/// Whether a mesh with `vertex_count` vertices can use u16 indices.
162#[inline]
163pub fn fits_u16_indices(vertex_count: usize) -> bool {
164    vertex_count <= u16::MAX as usize + 1 // indices 0..=65535
165}
166
167/// Encoded length in bytes for a mesh of the given size (for size reporting without allocating).
168#[inline]
169pub fn encoded_len(vertex_count: usize, triangle_count: usize) -> usize {
170    let idx_bytes = if fits_u16_indices(vertex_count) {
171        6
172    } else {
173        12
174    };
175    MESH_MINI_HEADER_SIZE + vertex_count * 6 + triangle_count * idx_bytes
176}
177
178/// Raw in-memory geometry size (f32 positions + u32 triangle indices) — the baseline we shrink from.
179#[inline]
180pub fn raw_geometry_len(vertex_count: usize, triangle_count: usize) -> usize {
181    vertex_count * 12 + triangle_count * 12
182}
183
184#[inline]
185fn quantize(v: f32, min: f32, max: f32) -> u16 {
186    let extent = max - min;
187    if !extent.is_finite() || !(v - min).is_finite() {
188        let n = ((v as f64 - min as f64) / (max as f64 - min as f64)).clamp(0.0, 1.0);
189        return (n * 65535.0 + 0.5) as u16;
190    }
191    if extent <= 0.0 {
192        return 0;
193    }
194    let n = ((v - min) / extent).clamp(0.0, 1.0);
195    (n * 65535.0 + 0.5) as u16
196}
197
198#[inline]
199fn dequantize(q: u16, min: f32, max: f32) -> f32 {
200    // Use the actual stored endpoints. f32 (max - min) can round upward or
201    // overflow even for finite ordered bounds, placing decoded points outside
202    // their declared frame. This changes no serialized bytes or encoder policy.
203    if q == 0 {
204        return min;
205    }
206    if q == u16::MAX {
207        return max;
208    }
209    if min == max {
210        return min;
211    }
212    let fraction = q as f64 / u16::MAX as f64;
213    (min as f64 + fraction * (max as f64 - min as f64)) as f32
214}
215
216fn bbox(positions: &[[f32; 3]]) -> ([f32; 3], [f32; 3]) {
217    let mut min = [f32::INFINITY; 3];
218    let mut max = [f32::NEG_INFINITY; 3];
219    for p in positions {
220        for a in 0..3 {
221            if p[a] < min[a] {
222                min[a] = p[a];
223            }
224            if p[a] > max[a] {
225                max[a] = p[a];
226            }
227        }
228    }
229    if positions.is_empty() {
230        min = [0.0; 3];
231        max = [0.0; 3];
232    }
233    (min, max)
234}
235
236/// Parse and validate the mesh-section mini-header. Returns the header and the
237/// total payload byte length it claims.
238pub fn parse_mesh_header(bytes: &[u8]) -> Result<(MeshMiniHeader, usize), MeshSectionError> {
239    if bytes.len() < MESH_MINI_HEADER_SIZE {
240        return Err(MeshSectionError::PayloadTooShort {
241            got: bytes.len(),
242            need: MESH_MINI_HEADER_SIZE,
243        });
244    }
245    let header: MeshMiniHeader = {
246        let mut buf = [0u8; MESH_MINI_HEADER_SIZE];
247        buf.copy_from_slice(&bytes[..MESH_MINI_HEADER_SIZE]);
248        bytemuck::pod_read_unaligned(&buf)
249    };
250    if header.reserved_u16 != 0 {
251        return Err(MeshSectionError::NonZeroReserved {
252            field: "reserved_u16",
253        });
254    }
255    if header.reserved_u32 != 0 {
256        return Err(MeshSectionError::NonZeroReserved {
257            field: "reserved_u32",
258        });
259    }
260    // Only bit 0 (FLAG_U16_INDICES) is defined in v1.
261    if header.flags & !FLAG_U16_INDICES != 0 {
262        return Err(MeshSectionError::UnknownFlags { got: header.flags });
263    }
264    for axis in 0..3 {
265        if !header.min[axis].is_finite()
266            || !header.max[axis].is_finite()
267            || header.min[axis] > header.max[axis]
268        {
269            return Err(MeshSectionError::InvalidBounds { axis });
270        }
271    }
272    let vcount = header.vertex_count as usize;
273    let tcount = header.triangle_count as usize;
274    if vcount > MAX_VERTEX_COUNT {
275        return Err(MeshSectionError::VertexCountTooLarge {
276            got: header.vertex_count,
277            max: MAX_VERTEX_COUNT,
278        });
279    }
280    if tcount > MAX_TRIANGLE_COUNT {
281        return Err(MeshSectionError::TriangleCountTooLarge {
282            got: header.triangle_count,
283            max: MAX_TRIANGLE_COUNT,
284        });
285    }
286    let u16_idx = header.flags & FLAG_U16_INDICES != 0;
287    let total = MeshMiniHeader::payload_bytes(vcount, tcount, u16_idx);
288    if bytes.len() < total {
289        return Err(MeshSectionError::PayloadTruncated {
290            expected: total,
291            got: bytes.len(),
292        });
293    }
294    Ok((header, total))
295}
296
297/// Encode a [`Mesh`] into a `.10d` QuantizedMesh section payload in a
298/// caller-supplied buffer. Returns the bytes written. Zero-heap. The bbox is
299/// recomputed from the positions (independent of any stale `mesh.min/max`)
300/// so it is a faithful dequantization frame.
301pub fn encode_mesh_section(mesh: &Mesh, out: &mut [u8]) -> Result<usize, MeshSectionError> {
302    let vcount = mesh.positions.len();
303    let tcount = mesh.triangles.len();
304    if vcount > MAX_VERTEX_COUNT {
305        return Err(MeshSectionError::VertexCountTooLarge {
306            got: vcount as u32,
307            max: MAX_VERTEX_COUNT,
308        });
309    }
310    if tcount > MAX_TRIANGLE_COUNT {
311        return Err(MeshSectionError::TriangleCountTooLarge {
312            got: tcount as u32,
313            max: MAX_TRIANGLE_COUNT,
314        });
315    }
316    // Validate before writing; narrowing an invalid u32 index would hide it.
317    for triangle in &mesh.triangles {
318        for &index in triangle {
319            if index as usize >= vcount {
320                return Err(MeshSectionError::IndexOutOfBounds {
321                    index,
322                    vertices: vcount as u32,
323                });
324            }
325        }
326    }
327    for (vertex, position) in mesh.positions.iter().enumerate() {
328        for (axis, value) in position.iter().enumerate() {
329            if !value.is_finite() {
330                return Err(MeshSectionError::InvalidPosition { vertex, axis });
331            }
332        }
333    }
334    let u16_idx = fits_u16_indices(vcount);
335    let (min, max) = bbox(&mesh.positions);
336    let need = encoded_len(vcount, tcount);
337    if out.len() < need {
338        return Err(MeshSectionError::OutputBufferTooSmall {
339            needed: need,
340            have: out.len(),
341        });
342    }
343    let header = MeshMiniHeader {
344        flags: if u16_idx { FLAG_U16_INDICES } else { 0 },
345        reserved_u16: 0,
346        vertex_count: vcount as u32,
347        triangle_count: tcount as u32,
348        min,
349        max,
350        reserved_u32: 0,
351    };
352    let header_bytes = bytes_of(&header);
353    out[..MESH_MINI_HEADER_SIZE].copy_from_slice(header_bytes);
354    let mut off = MESH_MINI_HEADER_SIZE;
355    for p in &mesh.positions {
356        for a in 0..3 {
357            out[off..off + 2].copy_from_slice(&quantize(p[a], min[a], max[a]).to_le_bytes());
358            off += 2;
359        }
360    }
361    for t in &mesh.triangles {
362        for &idx in t {
363            if u16_idx {
364                out[off..off + 2].copy_from_slice(&(idx as u16).to_le_bytes());
365                off += 2;
366            } else {
367                out[off..off + 4].copy_from_slice(&idx.to_le_bytes());
368                off += 4;
369            }
370        }
371    }
372    debug_assert_eq!(off, need, "encode must fill exactly the computed length");
373    Ok(off)
374}
375
376/// Decode a `.10d` QuantizedMesh section payload back into a [`Mesh`]
377/// (dequantized positions, exact indices). This is the ingest path (not a
378/// hot path), so `Vec` allocation is fine per AGENTS.md §2-B.
379pub fn decode_mesh_section(bytes: &[u8]) -> Result<Mesh, MeshSectionError> {
380    let view = MeshSectionView::parse(bytes)?;
381    let header = view.header();
382    let mut positions = Vec::with_capacity(header.vertex_count as usize);
383    let mut triangles = Vec::with_capacity(header.triangle_count as usize);
384    for i in 0..header.vertex_count as usize {
385        positions.push(view.vertex(i).expect("admitted vertex count"));
386    }
387    for i in 0..header.triangle_count as usize {
388        triangles.push(view.triangle(i).expect("admitted triangle count"));
389    }
390    Ok(Mesh {
391        positions,
392        triangles,
393        min: header.min,
394        max: header.max,
395    })
396}
397
398#[cfg(test)]
399mod tests {
400    use super::*;
401    use crate::container_10d::header::Container10dHeader;
402    use crate::container_10d::integrity::{seal_whole_file_crc32c, verify_whole_file_crc32c};
403    use crate::container_10d::section::{
404        encode_container, parse_section_table, AlignmentTier, SectionInput, SectionType,
405    };
406
407    /// A unit cube: 8 vertices, 12 triangles.
408    fn cube() -> Mesh {
409        let positions = vec![
410            [0.0, 0.0, 0.0],
411            [1.0, 0.0, 0.0],
412            [1.0, 1.0, 0.0],
413            [0.0, 1.0, 0.0],
414            [0.0, 0.0, 1.0],
415            [1.0, 0.0, 1.0],
416            [1.0, 1.0, 1.0],
417            [0.0, 1.0, 1.0],
418        ];
419        let triangles = vec![
420            [0, 1, 2],
421            [0, 2, 3],
422            [4, 5, 6],
423            [4, 6, 7],
424            [0, 1, 5],
425            [0, 5, 4],
426            [2, 3, 7],
427            [2, 7, 6],
428            [1, 2, 6],
429            [1, 6, 5],
430            [0, 3, 7],
431            [0, 7, 4],
432        ];
433        Mesh {
434            positions,
435            triangles,
436            min: [0.0; 3],
437            max: [1.0; 3],
438        }
439    }
440
441    #[test]
442    fn mini_header_is_pod_with_exact_size() {
443        assert_eq!(std::mem::size_of::<MeshMiniHeader>(), MESH_MINI_HEADER_SIZE);
444        assert_eq!(std::mem::offset_of!(MeshMiniHeader, flags), 0);
445        assert_eq!(std::mem::offset_of!(MeshMiniHeader, reserved_u16), 2);
446        assert_eq!(std::mem::offset_of!(MeshMiniHeader, vertex_count), 4);
447        assert_eq!(std::mem::offset_of!(MeshMiniHeader, triangle_count), 8);
448        assert_eq!(std::mem::offset_of!(MeshMiniHeader, min), 12);
449        assert_eq!(std::mem::offset_of!(MeshMiniHeader, max), 24);
450        assert_eq!(std::mem::offset_of!(MeshMiniHeader, reserved_u32), 36);
451    }
452
453    #[test]
454    fn round_trips_within_quantization_tolerance_and_indices_exact() {
455        let mesh = cube();
456        let need = encoded_len(mesh.positions.len(), mesh.triangles.len());
457        let mut buf = vec![0u8; need];
458        let n = encode_mesh_section(&mesh, &mut buf).expect("encode");
459        assert_eq!(n, need);
460        let back = decode_mesh_section(&buf).expect("decode");
461
462        assert_eq!(back.positions.len(), mesh.positions.len());
463        assert_eq!(back.triangles, mesh.triangles, "indices are exact");
464
465        // Positions are within one quantization step of the original (extent/65535 per axis).
466        let extent = 1.0f32; // unit cube
467        let tol = extent / 65535.0 * 2.0;
468        for (a, b) in mesh.positions.iter().zip(&back.positions) {
469            for k in 0..3 {
470                assert!((a[k] - b[k]).abs() <= tol, "axis {k}: {} vs {}", a[k], b[k]);
471            }
472        }
473    }
474
475    #[test]
476    fn encoded_is_smaller_than_raw_f32_geometry() {
477        let vcount = 50_000usize;
478        let tcount = 100_000usize;
479        let raw = raw_geometry_len(vcount, tcount);
480        let enc = encoded_len(vcount, tcount);
481        assert!(enc < raw, "encoded {enc} !< raw {raw}");
482        let ratio = enc as f64 / raw as f64;
483        assert!(ratio < 0.52 && ratio > 0.48, "ratio {ratio} not ~0.5");
484    }
485
486    #[test]
487    fn u32_indices_when_over_65k_vertices() {
488        let positions = vec![[0.0f32, 0.0, 0.0]; 70_000];
489        let triangles = vec![[0u32, 1, 69_999]];
490        let mesh = Mesh {
491            positions,
492            triangles: triangles.clone(),
493            min: [0.0; 3],
494            max: [0.0; 3],
495        };
496        let need = encoded_len(mesh.positions.len(), mesh.triangles.len());
497        let mut buf = vec![0u8; need];
498        encode_mesh_section(&mesh, &mut buf).expect("encode");
499        let (header, _) = parse_mesh_header(&buf).expect("parse header");
500        assert_eq!(header.flags & FLAG_U16_INDICES, 0, "u32 indices selected");
501        let back = decode_mesh_section(&buf).expect("decode");
502        assert_eq!(back.triangles, triangles, "large indices survive");
503    }
504
505    #[test]
506    fn rejects_bad_payload_and_truncation() {
507        assert!(parse_mesh_header(&[0u8; 8]).is_err());
508        let mesh = cube();
509        let need = encoded_len(mesh.positions.len(), mesh.triangles.len());
510        let mut buf = vec![0u8; need];
511        encode_mesh_section(&mesh, &mut buf).expect("encode");
512        buf.truncate(MESH_MINI_HEADER_SIZE + 4); // header ok, body truncated
513        assert!(parse_mesh_header(&buf).is_err());
514    }
515
516    #[test]
517    fn rejects_non_zero_reserved() {
518        let mesh = cube();
519        let need = encoded_len(mesh.positions.len(), mesh.triangles.len());
520        let mut buf = vec![0u8; need];
521        encode_mesh_section(&mesh, &mut buf).expect("encode");
522        buf[2] = 1; // reserved_u16
523        let err = parse_mesh_header(&buf).expect_err("non-zero reserved_u16 must reject");
524        assert!(
525            matches!(
526                err,
527                MeshSectionError::NonZeroReserved {
528                    field: "reserved_u16"
529                }
530            ),
531            "{err}"
532        );
533        // Restore and corrupt reserved_u32 (offset 36).
534        buf[2] = 0;
535        buf[36] = 1;
536        let err = parse_mesh_header(&buf).expect_err("non-zero reserved_u32 must reject");
537        assert!(
538            matches!(
539                err,
540                MeshSectionError::NonZeroReserved {
541                    field: "reserved_u32"
542                }
543            ),
544            "{err}"
545        );
546    }
547
548    #[test]
549    fn rejects_unknown_flags() {
550        let mesh = cube();
551        let need = encoded_len(mesh.positions.len(), mesh.triangles.len());
552        let mut buf = vec![0u8; need];
553        encode_mesh_section(&mesh, &mut buf).expect("encode");
554        buf[0] = 0x02; // bit 1 is undefined in v1
555        let err = parse_mesh_header(&buf).expect_err("unknown flags must reject");
556        assert!(
557            matches!(err, MeshSectionError::UnknownFlags { .. }),
558            "{err}"
559        );
560    }
561
562    #[test]
563    fn rejects_vertex_count_too_large() {
564        let header = MeshMiniHeader {
565            flags: FLAG_U16_INDICES,
566            reserved_u16: 0,
567            vertex_count: (MAX_VERTEX_COUNT + 1) as u32,
568            triangle_count: 0,
569            min: [0.0; 3],
570            max: [0.0; 3],
571            reserved_u32: 0,
572        };
573        let mut buf = vec![0u8; MESH_MINI_HEADER_SIZE];
574        buf[..MESH_MINI_HEADER_SIZE].copy_from_slice(bytemuck::bytes_of(&header));
575        let err = parse_mesh_header(&buf).expect_err("too-large vertex count must reject");
576        assert!(
577            matches!(err, MeshSectionError::VertexCountTooLarge { .. }),
578            "{err}"
579        );
580    }
581
582    #[test]
583    fn determinism_two_encodes_byte_identical() {
584        let mesh = cube();
585        let need = encoded_len(mesh.positions.len(), mesh.triangles.len());
586        let mut a = vec![0u8; need];
587        let mut b = vec![0u8; need];
588        encode_mesh_section(&mesh, &mut a).expect("encode a");
589        encode_mesh_section(&mesh, &mut b).expect("encode b");
590        assert_eq!(a, b, "two encodes of the same mesh must be byte-identical");
591    }
592
593    #[test]
594    fn mesh_section_round_trips_through_10d_container_with_crc() {
595        let mesh = cube();
596        let mesh_need = encoded_len(mesh.positions.len(), mesh.triangles.len());
597        let mut mesh_payload = vec![0u8; mesh_need];
598        encode_mesh_section(&mesh, &mut mesh_payload).expect("mesh encode");
599
600        let h = Container10dHeader::proposed();
601        let inputs = [SectionInput {
602            section_type: SectionType::QuantizedMesh,
603            alignment_tier: AlignmentTier::Word,
604            stride: 0,
605            element_count: 0,
606            payload: &mesh_payload,
607        }];
608        let mut out = vec![0u8; 512];
609        let n = encode_container(&h, &inputs, &mut out).expect("container encode");
610        seal_whole_file_crc32c(&mut out[..n]);
611        verify_whole_file_crc32c(&mut out[..n]).expect("whole-file CRC");
612
613        let parsed_h = Container10dHeader::parse(&out[..n]).expect("header parse");
614        let descs = parse_section_table(&out[..n], &parsed_h).expect("table parse");
615        assert_eq!(descs.len(), 1);
616        assert_eq!(descs[0].section_type, SectionType::QuantizedMesh as u8);
617
618        let p_off = descs[0].byte_offset as usize;
619        let p_len = descs[0].byte_length as usize;
620        let mesh_back = decode_mesh_section(&out[p_off..p_off + p_len]).expect("mesh decode");
621        assert_eq!(
622            mesh_back.triangles, mesh.triangles,
623            "indices exact through container"
624        );
625        // Positions within quantization tolerance.
626        let tol = 1.0f32 / 65535.0 * 2.0;
627        for (a, b) in mesh.positions.iter().zip(&mesh_back.positions) {
628            for k in 0..3 {
629                assert!((a[k] - b[k]).abs() <= tol, "axis {k}: {} vs {}", a[k], b[k]);
630            }
631        }
632    }
633
634    #[test]
635    fn flipped_payload_bit_in_mesh_section_is_caught_by_per_section_crc() {
636        let mesh = cube();
637        let mesh_need = encoded_len(mesh.positions.len(), mesh.triangles.len());
638        let mut mesh_payload = vec![0u8; mesh_need];
639        encode_mesh_section(&mesh, &mut mesh_payload).expect("mesh encode");
640
641        let h = Container10dHeader::proposed();
642        let inputs = [SectionInput {
643            section_type: SectionType::QuantizedMesh,
644            alignment_tier: AlignmentTier::Word,
645            stride: 0,
646            element_count: 0,
647            payload: &mesh_payload,
648        }];
649        let mut out = vec![0u8; 512];
650        let n = encode_container(&h, &inputs, &mut out).expect("encode");
651        let parsed_h = Container10dHeader::parse(&out[..n]).expect("header parse");
652        let descs = parse_section_table(&out[..n], &parsed_h).expect("clean table parses");
653        let p_off = descs[0].byte_offset as usize;
654        // Flip a bit in the mesh payload (past the mini-header, in vertex data).
655        out[p_off + MESH_MINI_HEADER_SIZE + 1] ^= 0x01;
656        let err =
657            parse_section_table(&out[..n], &parsed_h).expect_err("flipped bit must be caught");
658        assert!(
659            matches!(
660                err,
661                crate::container_10d::section::SectionTableError::CrcMismatch { .. }
662            ),
663            "{err}"
664        );
665    }
666
667    #[test]
668    fn empty_mesh_round_trips() {
669        let mesh = Mesh {
670            positions: vec![],
671            triangles: vec![],
672            min: [0.0; 3],
673            max: [0.0; 3],
674        };
675        let need = encoded_len(0, 0);
676        assert_eq!(need, MESH_MINI_HEADER_SIZE);
677        let mut buf = vec![0u8; need];
678        encode_mesh_section(&mesh, &mut buf).expect("empty encode");
679        let back = decode_mesh_section(&buf).expect("empty decode");
680        assert!(back.positions.is_empty());
681        assert!(back.triangles.is_empty());
682    }
683}