Skip to main content

rusting_brain/
gltf.rs

1//! Reading glTF binary files, which is what a 3D asset dataset is made of.
2//!
3//! GLB is a twelve-byte header followed by chunks: one of JSON describing the
4//! scene, one of the bytes the JSON points into. The JSON names *accessors*,
5//! each of which is a typed view — so many `VEC3`s of `f32`, at this offset,
6//! with this stride — onto a slice of that binary chunk. Reading a mesh is
7//! walking the scene graph for primitives, resolving their accessors, and
8//! applying the transform each node's ancestors put on it.
9//!
10//! [`Glb::read`] keeps the two chunks and [`Glb::mesh`] flattens the whole
11//! scene into one [`Mesh`]. That is the right shape for this pipeline, which
12//! wants one surface to sample distances from and has no use for the material
13//! or animation the file also carries.
14//!
15//! NOTE: no Draco, no sparse accessors, no external buffer files, no
16//! materials or textures beyond [`Glb::base_color_image`]'s raw bytes. Draco is a whole decompressor and is refused by name
17//! rather than silently producing an empty mesh; the others are rare enough in
18//! published asset sets that the error message is a better use of the lines
19//! than the implementation.
20
21use crate::mesh::Mesh;
22use crate::network::NetworkError;
23use serde_json::Value;
24use std::path::Path;
25
26/// A parsed GLB file: its JSON description and its binary chunk.
27pub struct Glb {
28    json: Value,
29    binary: Vec<u8>,
30}
31
32const MAGIC: u32 = 0x4654_6C67;
33const JSON_CHUNK: u32 = 0x4E4F_534A;
34const BINARY_CHUNK: u32 = 0x004E_4942;
35/// What this writer emitted before: the four bytes `BIN\0` read as two. Files
36/// written then are still read, because nothing else about them was wrong.
37const LEGACY_BINARY_CHUNK: u32 = 0x0000_4E42;
38
39impl Glb {
40    /// Reads a `.glb` file.
41    pub fn read<P: AsRef<Path>>(path: P) -> Result<Self, NetworkError> {
42        Self::parse(std::fs::read(path)?)
43    }
44
45    /// The same, from bytes that are already in memory.
46    pub fn parse(bytes: Vec<u8>) -> Result<Self, NetworkError> {
47        let word = |at: usize| -> Result<u32, NetworkError> {
48            bytes
49                .get(at..at + 4)
50                .map(|slice| u32::from_le_bytes(slice.try_into().unwrap()))
51                .ok_or_else(|| NetworkError::InvalidDataset("the file ends mid-header".into()))
52        };
53        if word(0)? != MAGIC {
54            return Err(NetworkError::InvalidDataset(
55                "this is not a GLB file: the magic word is wrong".into(),
56            ));
57        }
58        if word(4)? != 2 {
59            return Err(NetworkError::InvalidDataset(format!(
60                "GLB version {}, and only 2 is defined",
61                word(4)?
62            )));
63        }
64
65        let mut json = None;
66        let mut binary = Vec::new();
67        let mut at = 12;
68        while at + 8 <= bytes.len() {
69            let length = word(at)? as usize;
70            let kind = word(at + 4)?;
71            let start = at + 8;
72            let chunk = bytes
73                .get(start..start + length)
74                .ok_or_else(|| NetworkError::InvalidDataset("a chunk runs past the file".into()))?;
75            match kind {
76                JSON_CHUNK => json = Some(serde_json::from_slice::<Value>(chunk)?),
77                BINARY_CHUNK | LEGACY_BINARY_CHUNK => binary = chunk.to_vec(),
78                // Unknown chunk types are to be skipped, says the format.
79                _ => {}
80            }
81            // Chunks are padded to a four-byte boundary.
82            at = start + length.next_multiple_of(4);
83        }
84
85        Ok(Self {
86            json: json
87                .ok_or_else(|| NetworkError::InvalidDataset("the file has no JSON chunk".into()))?,
88            binary,
89        })
90    }
91
92    /// The whole scene as one mesh, with every node's transform applied.
93    ///
94    /// Primitives are concatenated and their indices renumbered, so what comes
95    /// back is a single surface whatever the file's node structure was.
96    pub fn mesh(&self) -> Result<Mesh, NetworkError> {
97        let scene = self.json["scene"].as_u64().unwrap_or(0) as usize;
98        let roots = self.json["scenes"][scene]["nodes"]
99            .as_array()
100            .ok_or_else(|| NetworkError::InvalidDataset("the file has no scene".into()))?
101            .clone();
102
103        let mut mesh = Mesh::default();
104        for root in roots {
105            let index = root.as_u64().ok_or_else(|| {
106                NetworkError::InvalidDataset("a scene names a node that is not a number".into())
107            })? as usize;
108            self.walk(index, IDENTITY, &mut mesh)?;
109        }
110        if mesh.indices.is_empty() {
111            return Err(NetworkError::InvalidDataset(
112                "the scene holds no triangles".into(),
113            ));
114        }
115        // Half a vertex's attributes is worse than none: one primitive with
116        // normals and one without would leave the arrays out of step.
117        if mesh.normals.len() != mesh.positions.len() {
118            mesh.normals.clear();
119        }
120        if mesh.uvs.len() != mesh.positions.len() {
121            mesh.uvs.clear();
122        }
123        if mesh.colors.len() != mesh.positions.len() {
124            mesh.colors.clear();
125        }
126        Ok(mesh)
127    }
128
129    fn walk(&self, index: usize, parent: [f32; 16], mesh: &mut Mesh) -> Result<(), NetworkError> {
130        let node = &self.json["nodes"][index];
131        let local = node_transform(node);
132        let transform = multiply(parent, local);
133
134        if let Some(which) = node["mesh"].as_u64() {
135            let primitives = self.json["meshes"][which as usize]["primitives"]
136                .as_array()
137                .ok_or_else(|| {
138                    NetworkError::InvalidDataset(format!("mesh {which} has no primitives"))
139                })?;
140            for primitive in primitives {
141                self.append(primitive, transform, mesh)?;
142            }
143        }
144
145        if let Some(children) = node["children"].as_array() {
146            for child in children {
147                let child = child.as_u64().ok_or_else(|| {
148                    NetworkError::InvalidDataset("a child index is not a number".into())
149                })? as usize;
150                self.walk(child, transform, mesh)?;
151            }
152        }
153        Ok(())
154    }
155
156    fn append(
157        &self,
158        primitive: &Value,
159        transform: [f32; 16],
160        mesh: &mut Mesh,
161    ) -> Result<(), NetworkError> {
162        if primitive["extensions"]
163            .get("KHR_draco_mesh_compression")
164            .is_some()
165        {
166            return Err(NetworkError::InvalidDataset(
167                "this file is Draco compressed, which is not read here".into(),
168            ));
169        }
170        // 4 is TRIANGLES, and is the default when the mode is left out.
171        match primitive["mode"].as_u64().unwrap_or(4) {
172            4 => {}
173            mode => {
174                return Err(NetworkError::InvalidDataset(format!(
175                    "primitive mode {mode} is not triangles"
176                )));
177            }
178        }
179
180        let Some(position) = primitive["attributes"]["POSITION"].as_u64() else {
181            return Ok(());
182        };
183        let positions = self.floats(position as usize, 3)?;
184        let base = mesh.positions.len() as u32;
185        for corner in positions.as_chunks::<3>().0 {
186            mesh.positions.push(transform_point(
187                transform,
188                [corner[0], corner[1], corner[2]],
189            ));
190        }
191
192        if let Some(normal) = primitive["attributes"]["NORMAL"].as_u64() {
193            for corner in self.floats(normal as usize, 3)?.as_chunks::<3>().0 {
194                mesh.normals.push(transform_normal(
195                    transform,
196                    [corner[0], corner[1], corner[2]],
197                ));
198            }
199        }
200        if let Some(uv) = primitive["attributes"]["TEXCOORD_0"].as_u64() {
201            for corner in self.floats(uv as usize, 2)?.as_chunks::<2>().0 {
202                mesh.uvs.push([corner[0], corner[1]]);
203            }
204        }
205
206        let added = mesh.positions.len() - base as usize;
207        for colour in self.colours(primitive, added)? {
208            mesh.colors.push(colour);
209        }
210
211        let count = (mesh.positions.len() as u32 - base) as usize;
212        match primitive["indices"].as_u64() {
213            Some(indices) => {
214                let indices = self.integers(indices as usize)?;
215                for face in indices.as_chunks::<3>().0 {
216                    mesh.indices
217                        .push([base + face[0], base + face[1], base + face[2]]);
218                }
219            }
220            // No index buffer means the vertices are already in triangle order.
221            None => {
222                for face in 0..count / 3 {
223                    let first = base + face as u32 * 3;
224                    mesh.indices.push([first, first + 1, first + 2]);
225                }
226            }
227        }
228        Ok(())
229    }
230
231    /// One colour per vertex of a primitive, or nothing if the file says none.
232    ///
233    /// `COLOR_0` first, which a vertex-painted asset carries directly. Failing
234    /// that, the material's flat base colour, which is what most exported
235    /// assets have and is still a better answer than grey. A base colour
236    /// *texture* is not read: sampling it needs an image decoder and the UVs,
237    /// and the stand-in this feeds — per-vertex colour regressed off the shape
238    /// latent — cannot represent the detail a texture holds anyway.
239    ///
240    /// NOTE: no `KHR_materials_*` extension, no texture sampling. Both
241    /// belong with the rasterizer the texture stage would bring.
242    fn colours(&self, primitive: &Value, vertices: usize) -> Result<Vec<[f32; 3]>, NetworkError> {
243        if let Some(attribute) = primitive["attributes"]["COLOR_0"].as_u64() {
244            // The spec allows VEC3 and VEC4 here, and the alpha is dropped
245            // either way: this pipeline has no transparency.
246            let components = self.accessor(attribute as usize)?.components;
247            let values = self.floats(attribute as usize, components)?;
248            return Ok(values
249                .chunks_exact(components)
250                .map(|colour| [colour[0], colour[1], colour[2]])
251                .collect());
252        }
253
254        let Some(material) = primitive["material"].as_u64() else {
255            return Ok(Vec::new());
256        };
257        let factor =
258            &self.json["materials"][material as usize]["pbrMetallicRoughness"]["baseColorFactor"];
259        // A material with no factor is the spec's default, which is white.
260        let colour = match factor.as_array() {
261            Some(values) if values.len() >= 3 => {
262                std::array::from_fn(|channel| values[channel].as_f64().unwrap_or(1.0) as f32)
263            }
264            _ => [1.0, 1.0, 1.0],
265        };
266        Ok(vec![colour; vertices])
267    }
268
269    /// An accessor of floating-point vectors, widened to `f32` and flattened.
270    fn floats(&self, index: usize, components: usize) -> Result<Vec<f32>, NetworkError> {
271        let accessor = self.accessor(index)?;
272        if accessor.components != components {
273            return Err(NetworkError::InvalidDataset(format!(
274                "accessor {index} holds {}-vectors and a {components}-vector was wanted",
275                accessor.components
276            )));
277        }
278        self.elements(&accessor, |bytes, kind| match kind {
279            5126 => f32::from_le_bytes(bytes[..4].try_into().unwrap()),
280            // Normalized integer attributes, which is how compact files store
281            // texture coordinates.
282            5121 => f32::from(bytes[0]) / 255.0,
283            5123 => f32::from(u16::from_le_bytes(bytes[..2].try_into().unwrap())) / 65535.0,
284            5120 => (f32::from(bytes[0] as i8) / 127.0).max(-1.0),
285            5122 => {
286                (f32::from(i16::from_le_bytes(bytes[..2].try_into().unwrap())) / 32767.0).max(-1.0)
287            }
288            _ => 0.0,
289        })
290    }
291
292    /// An accessor of scalar indices, widened to `u32`.
293    fn integers(&self, index: usize) -> Result<Vec<u32>, NetworkError> {
294        let accessor = self.accessor(index)?;
295        if accessor.components != 1 {
296            return Err(NetworkError::InvalidDataset(format!(
297                "accessor {index} is not scalar, so it is not an index buffer"
298            )));
299        }
300        Ok(self
301            .elements(&accessor, |bytes, kind| match kind {
302                5121 => f32::from(bytes[0]),
303                5123 => f32::from(u16::from_le_bytes(bytes[..2].try_into().unwrap())),
304                5125 => u32::from_le_bytes(bytes[..4].try_into().unwrap()) as f32,
305                _ => 0.0,
306            })?
307            .into_iter()
308            .map(|value| value as u32)
309            .collect())
310    }
311
312    fn accessor(&self, index: usize) -> Result<Accessor, NetworkError> {
313        let accessor = &self.json["accessors"][index];
314        if accessor.is_null() {
315            return Err(NetworkError::InvalidDataset(format!(
316                "accessor {index} is not in the file"
317            )));
318        }
319        if accessor.get("sparse").is_some() {
320            return Err(NetworkError::InvalidDataset(
321                "sparse accessors are not read here".into(),
322            ));
323        }
324        let kind = accessor["componentType"].as_u64().unwrap_or(0) as u32;
325        let width = match kind {
326            5120 | 5121 => 1,
327            5122 | 5123 => 2,
328            5125 | 5126 => 4,
329            other => {
330                return Err(NetworkError::InvalidDataset(format!(
331                    "component type {other} is not one glTF defines"
332                )));
333            }
334        };
335        let components = match accessor["type"].as_str().unwrap_or("") {
336            "SCALAR" => 1,
337            "VEC2" => 2,
338            "VEC3" => 3,
339            "VEC4" => 4,
340            "MAT4" => 16,
341            other => {
342                return Err(NetworkError::InvalidDataset(format!(
343                    "accessor type {other} is not read here"
344                )));
345            }
346        };
347
348        let view = &self.json["bufferViews"][accessor["bufferView"].as_u64().unwrap_or(0) as usize];
349        let stride = view["byteStride"].as_u64().unwrap_or(0) as usize;
350        Ok(Accessor {
351            kind,
352            components,
353            count: accessor["count"].as_u64().unwrap_or(0) as usize,
354            offset: view["byteOffset"].as_u64().unwrap_or(0) as usize
355                + accessor["byteOffset"].as_u64().unwrap_or(0) as usize,
356            // A stride of zero means tightly packed, which is the common case.
357            stride: match stride {
358                0 => width * components,
359                stride => stride,
360            },
361            width,
362        })
363    }
364
365    fn elements(
366        &self,
367        accessor: &Accessor,
368        widen: impl Fn(&[u8], u32) -> f32,
369    ) -> Result<Vec<f32>, NetworkError> {
370        let mut values = Vec::with_capacity(accessor.count * accessor.components);
371        for element in 0..accessor.count {
372            let start = accessor.offset + element * accessor.stride;
373            for component in 0..accessor.components {
374                let at = start + component * accessor.width;
375                let bytes = self.binary.get(at..at + accessor.width).ok_or_else(|| {
376                    NetworkError::InvalidDataset(
377                        "an accessor reads past the end of the buffer".into(),
378                    )
379                })?;
380                values.push(widen(bytes, accessor.kind));
381            }
382        }
383        Ok(values)
384    }
385}
386
387/// One typed view onto the binary chunk, with the JSON already resolved.
388struct Accessor {
389    kind: u32,
390    components: usize,
391    count: usize,
392    offset: usize,
393    stride: usize,
394    width: usize,
395}
396
397impl Mesh {
398    /// Reads the whole scene of a `.glb` file as one mesh.
399    pub fn read_glb<P: AsRef<Path>>(path: P) -> Result<Self, NetworkError> {
400        Glb::read(path)?.mesh()
401    }
402}
403
404impl Glb {
405    /// A GLB from a scene description and the bytes it points into.
406    pub fn new(json: Value, binary: Vec<u8>) -> Self {
407        Self { json, binary }
408    }
409
410    /// The scene description, for anything [`Glb::mesh`] does not read.
411    pub fn json(&self) -> &Value {
412        &self.json
413    }
414
415    /// The binary chunk the description's buffer views point into.
416    pub fn binary(&self) -> &[u8] {
417        &self.binary
418    }
419
420    /// The encoded base-colour image of `primitive` of `mesh` and its MIME
421    /// type, as stored: `images[textures[material.pbrMetallicRoughness
422    /// .baseColorTexture.index].source]`. `None` for an untextured primitive
423    /// or an image held outside the binary chunk (a URI).
424    pub fn base_color_image(&self, mesh: usize, primitive: usize) -> Option<(&[u8], &str)> {
425        let json = &self.json;
426        let material = json["meshes"][mesh]["primitives"][primitive]["material"].as_u64()?;
427        let texture = json["materials"][material as usize]["pbrMetallicRoughness"]
428            ["baseColorTexture"]["index"]
429            .as_u64()?;
430        let source = json["textures"][texture as usize]["source"].as_u64()?;
431        let image = &json["images"][source as usize];
432        let view = &json["bufferViews"][image["bufferView"].as_u64()? as usize];
433        let start = view["byteOffset"].as_u64().unwrap_or(0) as usize;
434        let end = start.checked_add(view["byteLength"].as_u64()? as usize)?;
435        Some((self.binary.get(start..end)?, image["mimeType"].as_str()?))
436    }
437
438    /// The container: header, JSON chunk, binary chunk.
439    ///
440    /// Both chunks are padded to four bytes — the JSON with spaces so it still
441    /// parses, the binary with zeros — because the header's lengths are read
442    /// as words and a reader is entitled to assume the alignment.
443    pub fn to_bytes(&self) -> Vec<u8> {
444        let mut json = serde_json::to_vec(&self.json).unwrap_or_default();
445        json.resize(json.len().next_multiple_of(4), b' ');
446        let mut binary = self.binary.clone();
447        binary.resize(binary.len().next_multiple_of(4), 0);
448
449        let mut bytes = Vec::with_capacity(28 + json.len() + binary.len());
450        bytes.extend(MAGIC.to_le_bytes());
451        bytes.extend(2u32.to_le_bytes());
452        bytes.extend(((28 + json.len() + binary.len()) as u32).to_le_bytes());
453        bytes.extend((json.len() as u32).to_le_bytes());
454        bytes.extend(JSON_CHUNK.to_le_bytes());
455        bytes.extend(&json);
456        bytes.extend((binary.len() as u32).to_le_bytes());
457        bytes.extend(BINARY_CHUNK.to_le_bytes());
458        bytes.extend(&binary);
459        bytes
460    }
461
462    pub fn write<P: AsRef<Path>>(&self, path: P) -> Result<(), NetworkError> {
463        Ok(std::fs::write(path, self.to_bytes())?)
464    }
465}
466
467/// One accessor being assembled: where its bytes went and what they are.
468struct Written {
469    view: usize,
470    kind: u32,
471    components: &'static str,
472    count: usize,
473}
474
475impl Mesh {
476    /// Writes the mesh as a `.glb`.
477    ///
478    /// One node, one mesh, one triangle primitive, one buffer view per
479    /// attribute, and one material — an untextured PBR white, because nothing
480    /// in this pipeline produces a texture or the UVs that would place one.
481    /// Normals, UVs and vertex colours are written when the mesh carries them;
482    /// a viewer multiplies `COLOR_0` by the material's base colour, which is
483    /// why that base colour is white.
484    pub fn write_glb<P: AsRef<Path>>(&self, path: P) -> Result<(), NetworkError> {
485        self.to_glb()?.write(path)
486    }
487
488    /// The same, kept in memory.
489    pub fn to_glb(&self) -> Result<Glb, NetworkError> {
490        if self.indices.is_empty() || self.positions.is_empty() {
491            return Err(NetworkError::InvalidDataset(
492                "a glTF primitive needs at least one triangle".into(),
493            ));
494        }
495        let vertices = self.positions.len();
496        for face in &self.indices {
497            for corner in face {
498                if *corner as usize >= vertices {
499                    return Err(NetworkError::InvalidDataset(format!(
500                        "a face names vertex {corner} of {vertices}"
501                    )));
502                }
503            }
504        }
505        if !self.normals.is_empty() && self.normals.len() != vertices {
506            return Err(NetworkError::InvalidDataset(format!(
507                "{} normals for {vertices} vertices",
508                self.normals.len()
509            )));
510        }
511        if !self.uvs.is_empty() && self.uvs.len() != vertices {
512            return Err(NetworkError::InvalidDataset(format!(
513                "{} texture coordinates for {vertices} vertices",
514                self.uvs.len()
515            )));
516        }
517        if !self.colors.is_empty() && self.colors.len() != vertices {
518            return Err(NetworkError::InvalidDataset(format!(
519                "{} vertex colours for {vertices} vertices",
520                self.colors.len()
521            )));
522        }
523
524        let mut binary: Vec<u8> = Vec::new();
525        let mut views = Vec::new();
526        // Every accessor here is four bytes wide, so padding each view to four
527        // keeps all of them aligned to their component size.
528        let mut push = |binary: &mut Vec<u8>, bytes: Vec<u8>, target: u32| {
529            binary.resize(binary.len().next_multiple_of(4), 0);
530            let view = serde_json::json!({
531                "buffer": 0,
532                "byteOffset": binary.len(),
533                "byteLength": bytes.len(),
534                "target": target,
535            });
536            binary.extend(bytes);
537            views.push(view);
538            views.len() - 1
539        };
540
541        const ARRAY: u32 = 34962;
542        const ELEMENT_ARRAY: u32 = 34963;
543        const FLOAT: u32 = 5126;
544        const UNSIGNED_INT: u32 = 5125;
545
546        let index_view = push(
547            &mut binary,
548            self.indices
549                .iter()
550                .flatten()
551                .flat_map(|corner| corner.to_le_bytes())
552                .collect(),
553            ELEMENT_ARRAY,
554        );
555        let mut written = vec![Written {
556            view: index_view,
557            kind: UNSIGNED_INT,
558            components: "SCALAR",
559            count: self.indices.len() * 3,
560        }];
561
562        let mut attributes = serde_json::Map::new();
563        let mut attribute = |binary: &mut Vec<u8>,
564                             written: &mut Vec<Written>,
565                             name: &str,
566                             data: Vec<u8>,
567                             components: &'static str,
568                             count: usize| {
569            let view = push(binary, data, ARRAY);
570            written.push(Written {
571                view,
572                kind: FLOAT,
573                components,
574                count,
575            });
576            attributes.insert(name.into(), (written.len() - 1).into());
577        };
578
579        attribute(
580            &mut binary,
581            &mut written,
582            "POSITION",
583            self.positions
584                .iter()
585                .flatten()
586                .flat_map(|value| value.to_le_bytes())
587                .collect(),
588            "VEC3",
589            vertices,
590        );
591        if !self.normals.is_empty() {
592            attribute(
593                &mut binary,
594                &mut written,
595                "NORMAL",
596                self.normals
597                    .iter()
598                    .flatten()
599                    .flat_map(|value| value.to_le_bytes())
600                    .collect(),
601                "VEC3",
602                vertices,
603            );
604        }
605        if !self.uvs.is_empty() {
606            attribute(
607                &mut binary,
608                &mut written,
609                "TEXCOORD_0",
610                self.uvs
611                    .iter()
612                    .flatten()
613                    .flat_map(|value| value.to_le_bytes())
614                    .collect(),
615                "VEC2",
616                vertices,
617            );
618        }
619        if !self.colors.is_empty() {
620            attribute(
621                &mut binary,
622                &mut written,
623                "COLOR_0",
624                self.colors
625                    .iter()
626                    .flatten()
627                    // A viewer clamps this anyway, and a regressed colour can
628                    // land slightly outside the range it was trained on.
629                    .flat_map(|value| value.clamp(0.0, 1.0).to_le_bytes())
630                    .collect(),
631                "VEC3",
632                vertices,
633            );
634        }
635
636        // The position accessor has to carry the bounding box: a viewer sizes
637        // its camera from it without touching the binary chunk, and a
638        // validator rejects the file without it.
639        let (low, high) = self.bounds();
640        let accessors: Vec<Value> = written
641            .iter()
642            .enumerate()
643            .map(|(index, written)| {
644                let mut accessor = serde_json::json!({
645                    "bufferView": written.view,
646                    "componentType": written.kind,
647                    "count": written.count,
648                    "type": written.components,
649                });
650                if index == 1 {
651                    accessor["min"] = low.to_vec().into();
652                    accessor["max"] = high.to_vec().into();
653                }
654                accessor
655            })
656            .collect();
657
658        let json = serde_json::json!({
659            "asset": { "version": "2.0", "generator": "rusting_brain" },
660            "scene": 0,
661            "scenes": [{ "nodes": [0] }],
662            "nodes": [{ "mesh": 0 }],
663            "meshes": [{ "primitives": [{
664                "attributes": attributes,
665                "indices": 0,
666                "material": 0,
667                "mode": 4,
668            }] }],
669            "materials": [{
670                "pbrMetallicRoughness": {
671                    "baseColorFactor": [0.8, 0.8, 0.8, 1.0],
672                    "metallicFactor": 0.0,
673                    "roughnessFactor": 0.8,
674                },
675            }],
676            "buffers": [{ "byteLength": binary.len().next_multiple_of(4) }],
677            "bufferViews": views,
678            "accessors": accessors,
679        });
680
681        Ok(Glb::new(json, binary))
682    }
683}
684
685/// glTF stores matrices column-major, so this is the column-major identity.
686const IDENTITY: [f32; 16] = [
687    1.0, 0.0, 0.0, 0.0, //
688    0.0, 1.0, 0.0, 0.0, //
689    0.0, 0.0, 1.0, 0.0, //
690    0.0, 0.0, 0.0, 1.0,
691];
692
693/// A node's local transform: either the matrix it states, or the translation,
694/// rotation and scale it states instead.
695fn node_transform(node: &Value) -> [f32; 16] {
696    if let Some(matrix) = node["matrix"].as_array() {
697        let mut out = IDENTITY;
698        for (slot, value) in out.iter_mut().zip(matrix) {
699            *slot = value.as_f64().unwrap_or(0.0) as f32;
700        }
701        return out;
702    }
703
704    let read = |name: &str, fallback: [f32; 4]| -> [f32; 4] {
705        match node[name].as_array() {
706            Some(values) => {
707                let mut out = fallback;
708                for (slot, value) in out.iter_mut().zip(values) {
709                    *slot = value.as_f64().unwrap_or(0.0) as f32;
710                }
711                out
712            }
713            None => fallback,
714        }
715    };
716    let translation = read("translation", [0.0; 4]);
717    let rotation = read("rotation", [0.0, 0.0, 0.0, 1.0]);
718    let scale = read("scale", [1.0, 1.0, 1.0, 1.0]);
719
720    // The quaternion as a rotation matrix, then scaled by column and given the
721    // translation, which is the order glTF defines: T * R * S.
722    let [x, y, z, w] = rotation;
723    let rotation = [
724        1.0 - 2.0 * (y * y + z * z),
725        2.0 * (x * y + z * w),
726        2.0 * (x * z - y * w),
727        0.0,
728        2.0 * (x * y - z * w),
729        1.0 - 2.0 * (x * x + z * z),
730        2.0 * (y * z + x * w),
731        0.0,
732        2.0 * (x * z + y * w),
733        2.0 * (y * z - x * w),
734        1.0 - 2.0 * (x * x + y * y),
735        0.0,
736        translation[0],
737        translation[1],
738        translation[2],
739        1.0,
740    ];
741    let mut out = rotation;
742    for column in 0..3 {
743        for row in 0..3 {
744            out[column * 4 + row] *= scale[column];
745        }
746    }
747    out
748}
749
750/// Column-major matrix product, `a` applied after `b`.
751fn multiply(a: [f32; 16], b: [f32; 16]) -> [f32; 16] {
752    let mut out = [0.0; 16];
753    for column in 0..4 {
754        for row in 0..4 {
755            out[column * 4 + row] = (0..4).map(|k| a[k * 4 + row] * b[column * 4 + k]).sum();
756        }
757    }
758    out
759}
760
761fn transform_point(matrix: [f32; 16], point: [f32; 3]) -> [f32; 3] {
762    std::array::from_fn(|row| {
763        (0..3).map(|k| matrix[k * 4 + row] * point[k]).sum::<f32>() + matrix[12 + row]
764    })
765}
766
767/// NOTE: the upper three by three, not its inverse transpose, so a node
768/// with a non-uniform scale tilts its normals. Nothing here reads normals —
769/// the distance field comes from the triangles — and [`Mesh::recompute_normals`]
770/// is the fix for a caller that does.
771fn transform_normal(matrix: [f32; 16], normal: [f32; 3]) -> [f32; 3] {
772    let rotated: [f32; 3] =
773        std::array::from_fn(|row| (0..3).map(|k| matrix[k * 4 + row] * normal[k]).sum());
774    let length = rotated
775        .iter()
776        .map(|value| value * value)
777        .sum::<f32>()
778        .sqrt();
779    match length == 0.0 {
780        true => [0.0; 3],
781        false => rotated.map(|value| value / length),
782    }
783}
784
785#[cfg(test)]
786mod tests {
787    use super::*;
788
789    #[test]
790    fn a_textured_primitive_hands_back_its_embedded_image() {
791        let png = b"\x89PNG\r\n\x1a\nnot really";
792        let mut binary = vec![7u8; 8];
793        binary.extend_from_slice(png);
794        let json = format!(
795            r#"{{
796              "meshes": [{{"primitives": [{{"material": 0}}, {{"material": 1}}, {{}}]}}],
797              "materials": [
798                {{"pbrMetallicRoughness": {{"baseColorTexture": {{"index": 0}}}}}},
799                {{"pbrMetallicRoughness": {{"baseColorFactor": [1, 0, 0, 1]}}}}
800              ],
801              "textures": [{{"source": 0}}],
802              "images": [{{"bufferView": 0, "mimeType": "image/png"}}],
803              "bufferViews": [{{"buffer": 0, "byteOffset": 8, "byteLength": {}}}]
804            }}"#,
805            png.len()
806        );
807        let file = Glb::parse(glb(&json, &binary)).unwrap();
808        assert_eq!(file.base_color_image(0, 0), Some((&png[..], "image/png")));
809        assert_eq!(file.base_color_image(0, 1), None, "a flat colour");
810        assert_eq!(file.base_color_image(0, 2), None, "no material");
811        assert_eq!(file.json()["textures"][0]["source"], 0);
812        assert_eq!(&file.binary()[8..8 + png.len()], png);
813    }
814
815    /// Builds a GLB out of a JSON description and a binary chunk, the way a
816    /// real exporter would, so the tests exercise the actual byte layout.
817    fn glb(json: &str, binary: &[u8]) -> Vec<u8> {
818        let mut json = json.as_bytes().to_vec();
819        json.resize(json.len().next_multiple_of(4), b' ');
820        let mut binary = binary.to_vec();
821        binary.resize(binary.len().next_multiple_of(4), 0);
822
823        let mut bytes = Vec::new();
824        bytes.extend(MAGIC.to_le_bytes());
825        bytes.extend(2u32.to_le_bytes());
826        bytes.extend(((12 + 8 + json.len() + 8 + binary.len()) as u32).to_le_bytes());
827        bytes.extend((json.len() as u32).to_le_bytes());
828        bytes.extend(JSON_CHUNK.to_le_bytes());
829        bytes.extend(&json);
830        bytes.extend((binary.len() as u32).to_le_bytes());
831        bytes.extend(BINARY_CHUNK.to_le_bytes());
832        bytes.extend(&binary);
833        bytes
834    }
835
836    #[test]
837    fn a_mesh_survives_a_round_trip_through_a_written_glb() {
838        let mut original = Mesh {
839            positions: vec![
840                [0.0, 0.0, 0.0],
841                [1.0, 0.0, 0.0],
842                [0.0, 1.0, 0.0],
843                [0.0, 0.0, 1.0],
844            ],
845            indices: vec![[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]],
846            uvs: vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]],
847            ..Mesh::default()
848        };
849        original.recompute_normals();
850
851        let bytes = original.to_glb().unwrap().to_bytes();
852        let read = Glb::parse(bytes).unwrap().mesh().unwrap();
853
854        assert_eq!(read.positions, original.positions);
855        assert_eq!(read.indices, original.indices);
856        assert_eq!(read.uvs, original.uvs);
857        for (read, original) in read.normals.iter().zip(&original.normals) {
858            for axis in 0..3 {
859                assert!((read[axis] - original[axis]).abs() < 1e-6);
860            }
861        }
862    }
863
864    /// A mesh with no normals and no UVs is the common case coming out of
865    /// marching tetrahedra, and it has to write as well as a complete one.
866    #[test]
867    fn a_bare_mesh_writes_only_the_attributes_it_has() {
868        let mesh = Mesh {
869            positions: vec![[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 3.0, 0.0]],
870            indices: vec![[0, 1, 2]],
871            ..Mesh::default()
872        };
873
874        let glb = mesh.to_glb().unwrap();
875        let attributes = &glb.json["meshes"][0]["primitives"][0]["attributes"];
876        assert!(attributes.get("POSITION").is_some());
877        assert!(attributes.get("NORMAL").is_none());
878        assert!(attributes.get("TEXCOORD_0").is_none());
879        assert!(attributes.get("COLOR_0").is_none());
880
881        // The bounding box the spec requires on the position accessor.
882        assert_eq!(
883            glb.json["accessors"][1]["min"],
884            serde_json::json!([0.0, 0.0, 0.0])
885        );
886        assert_eq!(
887            glb.json["accessors"][1]["max"],
888            serde_json::json!([2.0, 3.0, 0.0])
889        );
890
891        let read = Glb::parse(glb.to_bytes()).unwrap().mesh().unwrap();
892        assert_eq!(read.positions, mesh.positions);
893        assert_eq!(read.indices, mesh.indices);
894        assert!(read.normals.is_empty());
895    }
896
897    /// Vertex colours are the pipeline's stand-in for a texture, so they have
898    /// to survive the trip out and back in.
899    #[test]
900    fn vertex_colours_survive_a_round_trip_through_a_written_glb() {
901        let mesh = Mesh {
902            positions: vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
903            indices: vec![[0, 1, 2]],
904            colors: vec![[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.25, 0.5, 0.75]],
905            ..Mesh::default()
906        };
907
908        let glb = mesh.to_glb().unwrap();
909        assert!(glb.json["meshes"][0]["primitives"][0]["attributes"]["COLOR_0"].is_number());
910
911        let read = Glb::parse(glb.to_bytes()).unwrap().mesh().unwrap();
912        assert_eq!(read.colors, mesh.colors);
913    }
914
915    /// A regressed colour can land a little outside the range it was trained
916    /// on, and the file should still hold a legal colour.
917    #[test]
918    fn a_colour_outside_the_unit_range_is_clamped_on_the_way_out() {
919        let mesh = Mesh {
920            positions: vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
921            indices: vec![[0, 1, 2]],
922            colors: vec![[-0.2, 1.4, 0.5]; 3],
923            ..Mesh::default()
924        };
925
926        let read = Glb::parse(mesh.to_glb().unwrap().to_bytes())
927            .unwrap()
928            .mesh()
929            .unwrap();
930        assert_eq!(read.colors, vec![[0.0, 1.0, 0.5]; 3]);
931    }
932
933    /// Most meshes in the wild carry no COLOR_0 at all, only a flat base
934    /// colour on the material, and that is the colour the mesh should get.
935    #[test]
936    fn a_material_base_colour_stands_in_for_missing_vertex_colours() {
937        let mesh = Mesh {
938            positions: vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
939            indices: vec![[0, 1, 2]],
940            ..Mesh::default()
941        };
942        let mut glb = mesh.to_glb().unwrap();
943        glb.json["materials"][0]["pbrMetallicRoughness"]["baseColorFactor"] =
944            serde_json::json!([0.2, 0.4, 0.6, 1.0]);
945
946        let read = Glb::parse(glb.to_bytes()).unwrap().mesh().unwrap();
947        assert_eq!(read.colors, vec![[0.2, 0.4, 0.6]; 3]);
948    }
949
950    /// The header and chunk layout, checked as bytes rather than through the
951    /// reader, since a reader that shares the writer's mistake agrees with it.
952    #[test]
953    fn a_written_glb_has_the_header_and_padding_the_spec_asks_for() {
954        let mesh = Mesh {
955            positions: vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
956            indices: vec![[0, 1, 2]],
957            ..Mesh::default()
958        };
959        let bytes = mesh.to_glb().unwrap().to_bytes();
960
961        let word = |at: usize| u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap());
962        assert_eq!(word(0), MAGIC);
963        assert_eq!(word(4), 2);
964        assert_eq!(word(8) as usize, bytes.len());
965        assert_eq!(bytes.len() % 4, 0);
966
967        let json_length = word(12) as usize;
968        assert_eq!(word(16), JSON_CHUNK);
969        assert_eq!(json_length % 4, 0);
970        // The JSON is padded with spaces, so it still parses as it stands.
971        serde_json::from_slice::<Value>(&bytes[20..20 + json_length]).unwrap();
972
973        let binary_at = 20 + json_length;
974        assert_eq!(word(binary_at + 4), BINARY_CHUNK);
975        assert_eq!(word(binary_at) as usize % 4, 0);
976        assert_eq!(binary_at + 8 + word(binary_at) as usize, bytes.len());
977    }
978
979    #[test]
980    fn a_mesh_that_is_not_a_mesh_is_refused() {
981        assert!(Mesh::default().to_glb().is_err());
982
983        let broken = Mesh {
984            positions: vec![[0.0, 0.0, 0.0]],
985            indices: vec![[0, 1, 2]],
986            ..Mesh::default()
987        };
988        let error = match broken.to_glb() {
989            Ok(_) => panic!("a face naming a vertex that is not there was written"),
990            Err(error) => error.to_string(),
991        };
992        assert!(error.contains("vertex 1 of 1"), "{error}");
993
994        let mismatched = Mesh {
995            positions: vec![[0.0; 3], [1.0; 3], [2.0; 3]],
996            indices: vec![[0, 1, 2]],
997            normals: vec![[0.0, 0.0, 1.0]],
998            ..Mesh::default()
999        };
1000        assert!(mismatched.to_glb().is_err());
1001    }
1002
1003    /// The whole geometry path end to end: a distance field becomes a mesh,
1004    /// the mesh is simplified, and what comes back out of the file is still
1005    /// the same surface.
1006    #[test]
1007    fn a_simplified_sphere_writes_and_reads_back_as_the_same_surface() {
1008        let mut mesh = crate::mesh::marching_tetrahedra(
1009            |points| {
1010                Ok((0..points.rows)
1011                    .map(|row| {
1012                        let point = points.row(row);
1013                        (point[0] * point[0] + point[1] * point[1] + point[2] * point[2]).sqrt()
1014                            - 0.7
1015                    })
1016                    .collect())
1017            },
1018            20,
1019            ([-1.0; 3], [1.0; 3]),
1020            0.0,
1021        )
1022        .unwrap();
1023        mesh.simplify(mesh.indices.len() / 3);
1024        mesh.recompute_normals();
1025
1026        let read = Glb::parse(mesh.to_glb().unwrap().to_bytes())
1027            .unwrap()
1028            .mesh()
1029            .unwrap();
1030        assert_eq!(read.indices.len(), mesh.indices.len());
1031        for point in &read.positions {
1032            let radius = (point[0] * point[0] + point[1] * point[1] + point[2] * point[2]).sqrt();
1033            assert!((radius - 0.7).abs() < 0.1, "{point:?}");
1034        }
1035    }
1036
1037    /// One triangle: three `f32` positions then three `u16` indices.
1038    fn triangle_binary() -> Vec<u8> {
1039        let positions: [f32; 9] = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
1040        let mut bytes: Vec<u8> = positions.iter().flat_map(|v| v.to_le_bytes()).collect();
1041        bytes.extend([0u16, 1, 2].iter().flat_map(|v| v.to_le_bytes()));
1042        bytes
1043    }
1044
1045    fn triangle_json(node: &str) -> String {
1046        format!(
1047            r#"{{
1048              "scene": 0,
1049              "scenes": [{{"nodes": [0]}}],
1050              "nodes": [{{"mesh": 0 {node}}}],
1051              "meshes": [{{"primitives": [{{"attributes": {{"POSITION": 0}}, "indices": 1}}]}}],
1052              "accessors": [
1053                {{"bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3"}},
1054                {{"bufferView": 1, "componentType": 5123, "count": 3, "type": "SCALAR"}}
1055              ],
1056              "bufferViews": [
1057                {{"buffer": 0, "byteOffset": 0, "byteLength": 36}},
1058                {{"buffer": 0, "byteOffset": 36, "byteLength": 6}}
1059              ],
1060              "buffers": [{{"byteLength": 42}}]
1061            }}"#
1062        )
1063    }
1064
1065    #[test]
1066    fn a_triangle_comes_back_with_its_indices() {
1067        let bytes = glb(&triangle_json(""), &triangle_binary());
1068        let mesh = Glb::parse(bytes).unwrap().mesh().unwrap();
1069
1070        assert_eq!(mesh.positions.len(), 3);
1071        assert_eq!(mesh.indices, vec![[0, 1, 2]]);
1072        assert_eq!(mesh.triangle(0)[1], [1.0, 0.0, 0.0]);
1073        assert!(mesh.normals.is_empty());
1074    }
1075
1076    #[test]
1077    fn a_nodes_translation_and_scale_move_its_vertices() {
1078        let node = r#", "translation": [5.0, 0.0, 0.0], "scale": [2.0, 3.0, 1.0]"#;
1079        let bytes = glb(&triangle_json(node), &triangle_binary());
1080        let mesh = Glb::parse(bytes).unwrap().mesh().unwrap();
1081
1082        // Scale first, then translate: (1, 0, 0) scales to (2, 0, 0).
1083        assert_eq!(mesh.positions[0], [5.0, 0.0, 0.0]);
1084        assert_eq!(mesh.positions[1], [7.0, 0.0, 0.0]);
1085        assert_eq!(mesh.positions[2], [5.0, 3.0, 0.0]);
1086    }
1087
1088    #[test]
1089    fn a_quarter_turn_about_z_sends_x_to_y() {
1090        // The quaternion for ninety degrees about z.
1091        let half = std::f32::consts::FRAC_1_SQRT_2;
1092        let node = format!(r#", "rotation": [0.0, 0.0, {half}, {half}]"#);
1093        let bytes = glb(&triangle_json(&node), &triangle_binary());
1094        let mesh = Glb::parse(bytes).unwrap().mesh().unwrap();
1095
1096        let moved = mesh.positions[1];
1097        assert!((moved[0] - 0.0).abs() < 1e-6, "{moved:?}");
1098        assert!((moved[1] - 1.0).abs() < 1e-6, "{moved:?}");
1099    }
1100
1101    #[test]
1102    fn a_child_node_inherits_its_parents_transform() {
1103        let json = r#"{
1104          "scene": 0,
1105          "scenes": [{"nodes": [0]}],
1106          "nodes": [
1107            {"translation": [0.0, 10.0, 0.0], "children": [1]},
1108            {"mesh": 0, "translation": [0.0, 1.0, 0.0]}
1109          ],
1110          "meshes": [{"primitives": [{"attributes": {"POSITION": 0}, "indices": 1}]}],
1111          "accessors": [
1112            {"bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3"},
1113            {"bufferView": 1, "componentType": 5123, "count": 3, "type": "SCALAR"}
1114          ],
1115          "bufferViews": [
1116            {"buffer": 0, "byteOffset": 0, "byteLength": 36},
1117            {"buffer": 0, "byteOffset": 36, "byteLength": 6}
1118          ],
1119          "buffers": [{"byteLength": 42}]
1120        }"#;
1121        let bytes = glb(json, &triangle_binary());
1122        let mesh = Glb::parse(bytes).unwrap().mesh().unwrap();
1123
1124        assert_eq!(mesh.positions[0], [0.0, 11.0, 0.0]);
1125    }
1126
1127    #[test]
1128    fn an_interleaved_buffer_is_read_through_its_stride() {
1129        // Position and normal packed together, twenty-four bytes per vertex.
1130        let vertices: [[f32; 6]; 3] = [
1131            [0.0, 0.0, 0.0, 0.0, 0.0, 1.0],
1132            [1.0, 0.0, 0.0, 0.0, 0.0, 1.0],
1133            [0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
1134        ];
1135        let mut binary: Vec<u8> = vertices
1136            .iter()
1137            .flat_map(|vertex| vertex.iter().flat_map(|v| v.to_le_bytes()))
1138            .collect();
1139        binary.extend([0u16, 1, 2].iter().flat_map(|v| v.to_le_bytes()));
1140
1141        let json = r#"{
1142          "scene": 0,
1143          "scenes": [{"nodes": [0]}],
1144          "nodes": [{"mesh": 0}],
1145          "meshes": [{"primitives": [
1146            {"attributes": {"POSITION": 0, "NORMAL": 1}, "indices": 2}
1147          ]}],
1148          "accessors": [
1149            {"bufferView": 0, "byteOffset": 0, "componentType": 5126, "count": 3, "type": "VEC3"},
1150            {"bufferView": 0, "byteOffset": 12, "componentType": 5126, "count": 3, "type": "VEC3"},
1151            {"bufferView": 1, "componentType": 5123, "count": 3, "type": "SCALAR"}
1152          ],
1153          "bufferViews": [
1154            {"buffer": 0, "byteOffset": 0, "byteLength": 72, "byteStride": 24},
1155            {"buffer": 0, "byteOffset": 72, "byteLength": 6}
1156          ],
1157          "buffers": [{"byteLength": 78}]
1158        }"#;
1159        let mesh = Glb::parse(glb(json, &binary)).unwrap().mesh().unwrap();
1160
1161        assert_eq!(mesh.positions[2], [0.0, 1.0, 0.0]);
1162        assert_eq!(mesh.normals[2], [0.0, 0.0, 1.0]);
1163    }
1164
1165    #[test]
1166    fn a_file_that_is_not_a_glb_is_refused() {
1167        let error = match Glb::parse(b"not a gltf file at all".to_vec()) {
1168            Ok(_) => panic!("a file with no magic word was read as a GLB"),
1169            Err(error) => error,
1170        };
1171        assert!(format!("{error}").contains("magic"), "{error}");
1172    }
1173
1174    #[test]
1175    fn a_draco_compressed_primitive_is_refused_by_name() {
1176        let json = r#"{
1177          "scene": 0,
1178          "scenes": [{"nodes": [0]}],
1179          "nodes": [{"mesh": 0}],
1180          "meshes": [{"primitives": [{
1181            "attributes": {"POSITION": 0},
1182            "extensions": {"KHR_draco_mesh_compression": {"bufferView": 0}}
1183          }]}],
1184          "accessors": [{"bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3"}],
1185          "bufferViews": [{"buffer": 0, "byteOffset": 0, "byteLength": 36}],
1186          "buffers": [{"byteLength": 36}]
1187        }"#;
1188        let error = Glb::parse(glb(json, &triangle_binary()))
1189            .unwrap()
1190            .mesh()
1191            .unwrap_err();
1192        assert!(format!("{error}").contains("Draco"), "{error}");
1193    }
1194
1195    #[test]
1196    fn an_accessor_that_reads_past_the_buffer_is_refused() {
1197        let json = r#"{
1198          "scene": 0,
1199          "scenes": [{"nodes": [0]}],
1200          "nodes": [{"mesh": 0}],
1201          "meshes": [{"primitives": [{"attributes": {"POSITION": 0}}]}],
1202          "accessors": [{"bufferView": 0, "componentType": 5126, "count": 300, "type": "VEC3"}],
1203          "bufferViews": [{"buffer": 0, "byteOffset": 0, "byteLength": 36}],
1204          "buffers": [{"byteLength": 36}]
1205        }"#;
1206        let error = Glb::parse(glb(json, &triangle_binary()))
1207            .unwrap()
1208            .mesh()
1209            .unwrap_err();
1210        assert!(format!("{error}").contains("past the end"), "{error}");
1211    }
1212
1213    #[test]
1214    fn a_glb_survives_a_trip_through_the_distance_field() {
1215        // The geometry layer end to end from a real container: read a cube out
1216        // of a GLB, march its distance field back, and measure the surfaces.
1217        let mut binary: Vec<u8> = Vec::new();
1218        let corners: [[f32; 3]; 8] = [
1219            [-1.0, -1.0, -1.0],
1220            [1.0, -1.0, -1.0],
1221            [1.0, 1.0, -1.0],
1222            [-1.0, 1.0, -1.0],
1223            [-1.0, -1.0, 1.0],
1224            [1.0, -1.0, 1.0],
1225            [1.0, 1.0, 1.0],
1226            [-1.0, 1.0, 1.0],
1227        ];
1228        for corner in corners {
1229            binary.extend(corner.iter().flat_map(|v| v.to_le_bytes()));
1230        }
1231        let faces: [[u16; 3]; 12] = [
1232            [0, 2, 1],
1233            [0, 3, 2],
1234            [4, 5, 6],
1235            [4, 6, 7],
1236            [0, 1, 5],
1237            [0, 5, 4],
1238            [2, 3, 7],
1239            [2, 7, 6],
1240            [1, 2, 6],
1241            [1, 6, 5],
1242            [0, 4, 7],
1243            [0, 7, 3],
1244        ];
1245        for face in faces {
1246            binary.extend(face.iter().flat_map(|v| v.to_le_bytes()));
1247        }
1248        let json = r#"{
1249          "scene": 0,
1250          "scenes": [{"nodes": [0]}],
1251          "nodes": [{"mesh": 0}],
1252          "meshes": [{"primitives": [{"attributes": {"POSITION": 0}, "indices": 1}]}],
1253          "accessors": [
1254            {"bufferView": 0, "componentType": 5126, "count": 8, "type": "VEC3"},
1255            {"bufferView": 1, "componentType": 5123, "count": 36, "type": "SCALAR"}
1256          ],
1257          "bufferViews": [
1258            {"buffer": 0, "byteOffset": 0, "byteLength": 96},
1259            {"buffer": 0, "byteOffset": 96, "byteLength": 72}
1260          ],
1261          "buffers": [{"byteLength": 168}]
1262        }"#;
1263        let mut mesh = Glb::parse(glb(json, &binary)).unwrap().mesh().unwrap();
1264        assert_eq!(mesh.indices.len(), 12);
1265
1266        mesh.normalize();
1267        let bvh = crate::mesh::Bvh::build(&mesh);
1268        let marched = crate::mesh::marching_tetrahedra(
1269            |queries| {
1270                let points: Vec<[f32; 3]> = (0..queries.rows)
1271                    .map(|row| {
1272                        let at = row * queries.cols;
1273                        [queries.data[at], queries.data[at + 1], queries.data[at + 2]]
1274                    })
1275                    .collect();
1276                Ok(bvh.signed_distance(&points))
1277            },
1278            48,
1279            ([-1.2; 3], [1.2; 3]),
1280            0.0,
1281        )
1282        .unwrap();
1283
1284        // Every marched vertex should sit on the original cube's surface.
1285        let worst = marched
1286            .positions
1287            .iter()
1288            .map(|point| bvh.closest_point(*point).unwrap().1)
1289            .fold(0.0f32, f32::max);
1290        assert!(worst < 0.05, "worst vertex sits {worst} from the surface");
1291    }
1292}