Skip to main content

geolith_tiles_builder/splat/
glb.rs

1//! GLB writer for `KHR_gaussian_splatting` splat tiles.
2//!
3//! Emits the tile payload consumed by `3d-tiles-rendererjs-3dgs-plugin`: a
4//! single point primitive whose attributes are declared as bufferView-less
5//! accessors, with the actual splat data carried by an SPZ bufferView under
6//! `KHR_gaussian_splatting_compression_spz_2`.
7
8use geolith::error::Result;
9use serde_json::{Value, json};
10
11/// glTF component type for `FLOAT`.
12const COMPONENT_TYPE_FLOAT: u32 = 5126;
13
14/// glTF component type for `UNSIGNED_BYTE`.
15const COMPONENT_TYPE_UNSIGNED_BYTE: u32 = 5121;
16
17/// glTF primitive mode for `POINTS`.
18const PRIMITIVE_MODE_POINTS: u32 = 0;
19
20/// Number of degree-1 spherical harmonic coefficient attributes.
21const SH_DEGREE_1_COEFS: usize = 3;
22
23/// Number of degree-2 spherical harmonic coefficient attributes.
24const SH_DEGREE_2_COEFS: usize = 5;
25
26/// Number of degree-3 spherical harmonic coefficient attributes.
27const SH_DEGREE_3_COEFS: usize = 7;
28
29/// The `KHR_gaussian_splatting` extension name.
30pub const EXT_GAUSSIAN_SPLATTING: &str = "KHR_gaussian_splatting";
31
32/// The SPZ compression extension name required by the renderer plugin.
33pub const EXT_SPZ_2: &str = "KHR_gaussian_splatting_compression_spz_2";
34
35/// The unlit material extension name.
36pub const EXT_MATERIALS_UNLIT: &str = "KHR_materials_unlit";
37
38/// Round a length up to the next multiple of four.
39#[must_use]
40const fn pad4(length: usize) -> usize {
41    match length % 4 {
42        0 => 0,
43        rem => 4 - rem,
44    }
45}
46
47/// Build a column-major 4x4 node matrix that rebases and orients the tile.
48///
49/// The splat trainers emit camera-space axes (Y down, Z forward), so the
50/// upper 3x3 flips Y and Z to reach glTF's Y-up convention before the 3D
51/// Tiles runtime applies its own Y-up to Z-up rotation. `translation` is the
52/// tile centre in the source frame and is rotated into the same basis.
53#[must_use]
54pub fn tile_node_matrix(translation: [f64; 3]) -> [f64; 16] {
55    let rotation = [[1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, -1.0]];
56
57    let mut translated = [0.0_f64; 3];
58    for (row, axis) in rotation.iter().enumerate() {
59        translated[row] =
60            axis[0] * translation[0] + axis[1] * translation[1] + axis[2] * translation[2];
61    }
62
63    [
64        rotation[0][0],
65        rotation[1][0],
66        rotation[2][0],
67        0.0,
68        rotation[0][1],
69        rotation[1][1],
70        rotation[2][1],
71        0.0,
72        rotation[0][2],
73        rotation[1][2],
74        rotation[2][2],
75        0.0,
76        translated[0],
77        translated[1],
78        translated[2],
79        1.0,
80    ]
81}
82
83/// Accessor declarations for a splat primitive.
84struct AccessorSet {
85    /// Accessor objects in index order.
86    accessors: Vec<Value>,
87    /// Attribute name to accessor index mapping.
88    attributes: serde_json::Map<String, Value>,
89}
90
91/// Declare the bufferView-less accessors the extension requires.
92///
93/// The renderer reads splat data from the SPZ payload, so these accessors
94/// exist purely to satisfy glTF validation and to carry the splat count.
95fn build_accessors(splat_count: usize, sh_degree: u8) -> AccessorSet {
96    let mut accessors = Vec::new();
97    let mut attributes = serde_json::Map::new();
98
99    let mut push =
100        |accessor: Value, name: &str, attributes: &mut serde_json::Map<String, Value>| {
101            accessors.push(accessor);
102            attributes.insert(name.to_owned(), json!(accessors.len() - 1));
103        };
104
105    push(
106        json!({
107            "componentType": COMPONENT_TYPE_FLOAT,
108            "count": splat_count,
109            "type": "VEC3",
110            "min": [-1.0, -1.0, -1.0],
111            "max": [1.0, 1.0, 1.0],
112        }),
113        "POSITION",
114        &mut attributes,
115    );
116
117    push(
118        json!({
119            "componentType": COMPONENT_TYPE_UNSIGNED_BYTE,
120            "count": splat_count,
121            "type": "VEC4",
122            "normalized": true,
123        }),
124        "COLOR_0",
125        &mut attributes,
126    );
127
128    push(
129        json!({
130            "componentType": COMPONENT_TYPE_FLOAT,
131            "count": splat_count,
132            "type": "VEC3",
133        }),
134        "KHR_gaussian_splatting:SCALE",
135        &mut attributes,
136    );
137
138    push(
139        json!({
140            "componentType": COMPONENT_TYPE_FLOAT,
141            "count": splat_count,
142            "type": "VEC4",
143        }),
144        "KHR_gaussian_splatting:ROTATION",
145        &mut attributes,
146    );
147
148    let bands: [(u8, usize); 3] = [
149        (1, SH_DEGREE_1_COEFS),
150        (2, SH_DEGREE_2_COEFS),
151        (3, SH_DEGREE_3_COEFS),
152    ];
153    for (degree, coefficients) in bands {
154        if sh_degree < degree {
155            continue;
156        }
157        for index in 0..coefficients {
158            push(
159                json!({
160                    "componentType": COMPONENT_TYPE_FLOAT,
161                    "count": splat_count,
162                    "type": "VEC4",
163                }),
164                &format!("KHR_gaussian_splatting:SH_DEGREE_{degree}_COEF_{index}"),
165                &mut attributes,
166            );
167        }
168    }
169
170    AccessorSet {
171        accessors,
172        attributes,
173    }
174}
175
176/// Build the glTF JSON document for a splat tile.
177#[must_use]
178pub fn build_splat_gltf(
179    spz_byte_length: usize,
180    splat_count: usize,
181    sh_degree: u8,
182    node_matrix: [f64; 16],
183) -> Value {
184    let AccessorSet {
185        accessors,
186        attributes,
187    } = build_accessors(splat_count, sh_degree);
188
189    let bin_length = spz_byte_length + pad4(spz_byte_length);
190
191    json!({
192        "asset": { "version": "2.0", "copyright": geolith::attribution::CREDIT },
193        "extensionsUsed": [EXT_GAUSSIAN_SPLATTING, EXT_SPZ_2, EXT_MATERIALS_UNLIT],
194        "extensionsRequired": [EXT_GAUSSIAN_SPLATTING, EXT_SPZ_2],
195        "scene": 0,
196        "scenes": [{ "nodes": [0] }],
197        "nodes": [{ "mesh": 0, "matrix": node_matrix.to_vec() }],
198        "materials": [{ "extensions": { EXT_MATERIALS_UNLIT: {} } }],
199        "meshes": [{
200            "primitives": [{
201                "mode": PRIMITIVE_MODE_POINTS,
202                "attributes": attributes,
203                "material": 0,
204                "extensions": {
205                    EXT_GAUSSIAN_SPLATTING: {
206                        "kernel": "ellipse",
207                        "projection": "perspective",
208                        "extensions": {
209                            EXT_SPZ_2: { "bufferView": 0 }
210                        }
211                    }
212                }
213            }]
214        }],
215        "buffers": [{ "byteLength": bin_length }],
216        "bufferViews": [{
217            "buffer": 0,
218            "byteOffset": 0,
219            "byteLength": spz_byte_length,
220        }],
221        "accessors": accessors,
222    })
223}
224
225/// Serialise a splat tile as a binary glTF container.
226///
227/// # Errors
228///
229/// Returns an error when the glTF document cannot be serialised.
230pub fn write_splat_glb(
231    spz_bytes: &[u8],
232    splat_count: usize,
233    sh_degree: u8,
234    node_matrix: [f64; 16],
235) -> Result<Vec<u8>> {
236    let gltf = build_splat_gltf(spz_bytes.len(), splat_count, sh_degree, node_matrix);
237    let json_chunk = serde_json::to_vec(&gltf)?;
238
239    let json_pad = pad4(json_chunk.len());
240    let bin_pad = pad4(spz_bytes.len());
241    let json_length = json_chunk.len() + json_pad;
242    let bin_length = spz_bytes.len() + bin_pad;
243    let total = 12 + 8 + json_length + 8 + bin_length;
244
245    let mut glb = Vec::with_capacity(total);
246    glb.extend_from_slice(b"glTF");
247    glb.extend_from_slice(&2_u32.to_le_bytes());
248    glb.extend_from_slice(&(total as u32).to_le_bytes());
249
250    glb.extend_from_slice(&(json_length as u32).to_le_bytes());
251    glb.extend_from_slice(b"JSON");
252    glb.extend_from_slice(&json_chunk);
253    glb.extend(std::iter::repeat_n(b' ', json_pad));
254
255    glb.extend_from_slice(&(bin_length as u32).to_le_bytes());
256    glb.extend_from_slice(b"BIN\0");
257    glb.extend_from_slice(spz_bytes);
258    glb.extend(std::iter::repeat_n(0_u8, bin_pad));
259
260    Ok(glb)
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    fn parse_glb_json(glb: &[u8]) -> Value {
268        let json_length = u32::from_le_bytes(glb[12..16].try_into().expect("json length")) as usize;
269        let start = 20;
270        serde_json::from_slice(&glb[start..start + json_length]).expect("valid json chunk")
271    }
272
273    #[test]
274    fn pad4_rounds_up_to_four_byte_alignment() {
275        assert_eq!(pad4(0), 0);
276        assert_eq!(pad4(1), 3);
277        assert_eq!(pad4(2), 2);
278        assert_eq!(pad4(3), 1);
279        assert_eq!(pad4(4), 0);
280    }
281
282    #[test]
283    fn glb_container_header_is_well_formed() {
284        let glb = write_splat_glb(&[1, 2, 3], 4, 0, tile_node_matrix([0.0; 3])).expect("writes");
285
286        assert_eq!(&glb[0..4], b"glTF");
287        assert_eq!(
288            u32::from_le_bytes(glb[4..8].try_into().expect("version")),
289            2
290        );
291        assert_eq!(
292            u32::from_le_bytes(glb[8..12].try_into().expect("length")) as usize,
293            glb.len(),
294            "declared length matches the actual container"
295        );
296        assert_eq!(&glb[16..20], b"JSON");
297    }
298
299    #[test]
300    fn glb_chunks_are_four_byte_aligned() {
301        for payload_len in 1..=9 {
302            let spz = vec![7_u8; payload_len];
303            let glb = write_splat_glb(&spz, 1, 0, tile_node_matrix([0.0; 3])).expect("writes");
304            assert_eq!(
305                glb.len() % 4,
306                0,
307                "payload of {payload_len} bytes must still align"
308            );
309
310            let json_length =
311                u32::from_le_bytes(glb[12..16].try_into().expect("json length")) as usize;
312            assert_eq!(json_length % 4, 0, "JSON chunk is padded");
313
314            let bin_header = 20 + json_length;
315            assert_eq!(&glb[bin_header + 4..bin_header + 8], b"BIN\0");
316        }
317    }
318
319    #[test]
320    fn spz_payload_is_embedded_verbatim() {
321        let spz: Vec<u8> = (0..16).collect();
322        let glb = write_splat_glb(&spz, 2, 0, tile_node_matrix([0.0; 3])).expect("writes");
323        let json_length = u32::from_le_bytes(glb[12..16].try_into().expect("json length")) as usize;
324        let bin_start = 20 + json_length + 8;
325        assert_eq!(&glb[bin_start..bin_start + spz.len()], &spz[..]);
326    }
327
328    #[test]
329    fn gltf_declares_the_required_extensions() {
330        let glb = write_splat_glb(&[0; 8], 3, 0, tile_node_matrix([0.0; 3])).expect("writes");
331        let gltf = parse_glb_json(&glb);
332
333        let required = gltf["extensionsRequired"]
334            .as_array()
335            .expect("extensionsRequired");
336        assert!(required.iter().any(|v| v == EXT_GAUSSIAN_SPLATTING));
337        assert!(
338            required.iter().any(|v| v == EXT_SPZ_2),
339            "the renderer plugin rejects tiles without spz_2"
340        );
341
342        let used = gltf["extensionsUsed"].as_array().expect("extensionsUsed");
343        assert!(used.iter().any(|v| v == EXT_MATERIALS_UNLIT));
344    }
345
346    #[test]
347    fn primitive_points_at_the_spz_buffer_view() {
348        let glb = write_splat_glb(&[0; 8], 3, 0, tile_node_matrix([0.0; 3])).expect("writes");
349        let gltf = parse_glb_json(&glb);
350        let primitive = &gltf["meshes"][0]["primitives"][0];
351
352        assert_eq!(primitive["mode"], PRIMITIVE_MODE_POINTS);
353        assert_eq!(
354            primitive["extensions"][EXT_GAUSSIAN_SPLATTING]["extensions"][EXT_SPZ_2]["bufferView"],
355            0
356        );
357        assert_eq!(
358            primitive["extensions"][EXT_GAUSSIAN_SPLATTING]["kernel"],
359            "ellipse"
360        );
361        assert_eq!(gltf["bufferViews"][0]["byteLength"], 8);
362    }
363
364    #[test]
365    fn the_asset_carries_the_credit() {
366        let gltf = build_splat_gltf(16, 5, 0, tile_node_matrix([0.0; 3]));
367        assert_eq!(gltf["asset"]["copyright"], "© geolith");
368        assert_eq!(gltf["asset"]["version"], "2.0");
369    }
370
371    #[test]
372    fn base_attributes_are_always_declared() {
373        let gltf = build_splat_gltf(16, 5, 0, tile_node_matrix([0.0; 3]));
374        let attributes = &gltf["meshes"][0]["primitives"][0]["attributes"];
375
376        for name in [
377            "POSITION",
378            "COLOR_0",
379            "KHR_gaussian_splatting:SCALE",
380            "KHR_gaussian_splatting:ROTATION",
381        ] {
382            assert!(!attributes[name].is_null(), "missing attribute {name}");
383        }
384        assert_eq!(gltf["accessors"][0]["count"], 5);
385    }
386
387    #[test]
388    fn spherical_harmonic_attributes_scale_with_degree() {
389        let counts = [0_u8, 1, 2, 3].map(|degree| {
390            let gltf = build_splat_gltf(16, 2, degree, tile_node_matrix([0.0; 3]));
391            gltf["meshes"][0]["primitives"][0]["attributes"]
392                .as_object()
393                .expect("attributes")
394                .len()
395        });
396
397        assert_eq!(counts[0], 4, "degree 0 declares only the base attributes");
398        // Band l adds 2l + 1 coefficients: 3, then 5, then 7.
399        assert_eq!(counts[1], 7);
400        assert_eq!(counts[2], 12);
401        assert_eq!(counts[3], 19);
402    }
403
404    #[test]
405    fn degree_three_declares_every_band_attribute() {
406        let gltf = build_splat_gltf(16, 2, 3, tile_node_matrix([0.0; 3]));
407        let attributes = &gltf["meshes"][0]["primitives"][0]["attributes"];
408        assert!(!attributes["KHR_gaussian_splatting:SH_DEGREE_1_COEF_2"].is_null());
409        assert!(!attributes["KHR_gaussian_splatting:SH_DEGREE_2_COEF_4"].is_null());
410        assert!(!attributes["KHR_gaussian_splatting:SH_DEGREE_3_COEF_6"].is_null());
411    }
412
413    #[test]
414    fn node_matrix_is_column_major_with_flipped_axes() {
415        let matrix = tile_node_matrix([0.0, 0.0, 0.0]);
416        assert_eq!(matrix.len(), 16);
417        assert_eq!(matrix[0], 1.0);
418        assert_eq!(matrix[5], -1.0, "Y is flipped to reach glTF Y-up");
419        assert_eq!(matrix[10], -1.0, "Z is flipped to reach glTF Y-up");
420        assert_eq!(matrix[15], 1.0);
421    }
422
423    #[test]
424    fn node_matrix_rotates_the_translation_into_the_gltf_basis() {
425        let matrix = tile_node_matrix([2.0, 3.0, 4.0]);
426        assert_eq!(matrix[12], 2.0);
427        assert_eq!(matrix[13], -3.0, "translation follows the Y flip");
428        assert_eq!(matrix[14], -4.0, "translation follows the Z flip");
429    }
430
431    #[test]
432    fn buffer_byte_length_includes_alignment_padding() {
433        let gltf = build_splat_gltf(5, 1, 0, tile_node_matrix([0.0; 3]));
434        assert_eq!(
435            gltf["buffers"][0]["byteLength"], 8,
436            "5 bytes pad up to an 8-byte buffer"
437        );
438        assert_eq!(gltf["bufferViews"][0]["byteLength"], 5);
439    }
440}