geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! GLB writer for `KHR_gaussian_splatting` splat tiles.
//!
//! Emits the tile payload consumed by `3d-tiles-rendererjs-3dgs-plugin`: a
//! single point primitive whose attributes are declared as bufferView-less
//! accessors, with the actual splat data carried by an SPZ bufferView under
//! `KHR_gaussian_splatting_compression_spz_2`.

use geolith::error::Result;
use serde_json::{Value, json};

/// glTF component type for `FLOAT`.
const COMPONENT_TYPE_FLOAT: u32 = 5126;

/// glTF component type for `UNSIGNED_BYTE`.
const COMPONENT_TYPE_UNSIGNED_BYTE: u32 = 5121;

/// glTF primitive mode for `POINTS`.
const PRIMITIVE_MODE_POINTS: u32 = 0;

/// Number of degree-1 spherical harmonic coefficient attributes.
const SH_DEGREE_1_COEFS: usize = 3;

/// Number of degree-2 spherical harmonic coefficient attributes.
const SH_DEGREE_2_COEFS: usize = 5;

/// Number of degree-3 spherical harmonic coefficient attributes.
const SH_DEGREE_3_COEFS: usize = 7;

/// The `KHR_gaussian_splatting` extension name.
pub const EXT_GAUSSIAN_SPLATTING: &str = "KHR_gaussian_splatting";

/// The SPZ compression extension name required by the renderer plugin.
pub const EXT_SPZ_2: &str = "KHR_gaussian_splatting_compression_spz_2";

/// The unlit material extension name.
pub const EXT_MATERIALS_UNLIT: &str = "KHR_materials_unlit";

/// Round a length up to the next multiple of four.
#[must_use]
const fn pad4(length: usize) -> usize {
    match length % 4 {
        0 => 0,
        rem => 4 - rem,
    }
}

/// Build a column-major 4x4 node matrix that rebases and orients the tile.
///
/// The splat trainers emit camera-space axes (Y down, Z forward), so the
/// upper 3x3 flips Y and Z to reach glTF's Y-up convention before the 3D
/// Tiles runtime applies its own Y-up to Z-up rotation. `translation` is the
/// tile centre in the source frame and is rotated into the same basis.
#[must_use]
pub fn tile_node_matrix(translation: [f64; 3]) -> [f64; 16] {
    let rotation = [[1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, -1.0]];

    let mut translated = [0.0_f64; 3];
    for (row, axis) in rotation.iter().enumerate() {
        translated[row] =
            axis[0] * translation[0] + axis[1] * translation[1] + axis[2] * translation[2];
    }

    [
        rotation[0][0],
        rotation[1][0],
        rotation[2][0],
        0.0,
        rotation[0][1],
        rotation[1][1],
        rotation[2][1],
        0.0,
        rotation[0][2],
        rotation[1][2],
        rotation[2][2],
        0.0,
        translated[0],
        translated[1],
        translated[2],
        1.0,
    ]
}

/// Accessor declarations for a splat primitive.
struct AccessorSet {
    /// Accessor objects in index order.
    accessors: Vec<Value>,
    /// Attribute name to accessor index mapping.
    attributes: serde_json::Map<String, Value>,
}

/// Declare the bufferView-less accessors the extension requires.
///
/// The renderer reads splat data from the SPZ payload, so these accessors
/// exist purely to satisfy glTF validation and to carry the splat count.
fn build_accessors(splat_count: usize, sh_degree: u8) -> AccessorSet {
    let mut accessors = Vec::new();
    let mut attributes = serde_json::Map::new();

    let mut push =
        |accessor: Value, name: &str, attributes: &mut serde_json::Map<String, Value>| {
            accessors.push(accessor);
            attributes.insert(name.to_owned(), json!(accessors.len() - 1));
        };

    push(
        json!({
            "componentType": COMPONENT_TYPE_FLOAT,
            "count": splat_count,
            "type": "VEC3",
            "min": [-1.0, -1.0, -1.0],
            "max": [1.0, 1.0, 1.0],
        }),
        "POSITION",
        &mut attributes,
    );

    push(
        json!({
            "componentType": COMPONENT_TYPE_UNSIGNED_BYTE,
            "count": splat_count,
            "type": "VEC4",
            "normalized": true,
        }),
        "COLOR_0",
        &mut attributes,
    );

    push(
        json!({
            "componentType": COMPONENT_TYPE_FLOAT,
            "count": splat_count,
            "type": "VEC3",
        }),
        "KHR_gaussian_splatting:SCALE",
        &mut attributes,
    );

    push(
        json!({
            "componentType": COMPONENT_TYPE_FLOAT,
            "count": splat_count,
            "type": "VEC4",
        }),
        "KHR_gaussian_splatting:ROTATION",
        &mut attributes,
    );

    let bands: [(u8, usize); 3] = [
        (1, SH_DEGREE_1_COEFS),
        (2, SH_DEGREE_2_COEFS),
        (3, SH_DEGREE_3_COEFS),
    ];
    for (degree, coefficients) in bands {
        if sh_degree < degree {
            continue;
        }
        for index in 0..coefficients {
            push(
                json!({
                    "componentType": COMPONENT_TYPE_FLOAT,
                    "count": splat_count,
                    "type": "VEC4",
                }),
                &format!("KHR_gaussian_splatting:SH_DEGREE_{degree}_COEF_{index}"),
                &mut attributes,
            );
        }
    }

    AccessorSet {
        accessors,
        attributes,
    }
}

/// Build the glTF JSON document for a splat tile.
#[must_use]
pub fn build_splat_gltf(
    spz_byte_length: usize,
    splat_count: usize,
    sh_degree: u8,
    node_matrix: [f64; 16],
) -> Value {
    let AccessorSet {
        accessors,
        attributes,
    } = build_accessors(splat_count, sh_degree);

    let bin_length = spz_byte_length + pad4(spz_byte_length);

    json!({
        "asset": { "version": "2.0", "copyright": geolith::attribution::CREDIT },
        "extensionsUsed": [EXT_GAUSSIAN_SPLATTING, EXT_SPZ_2, EXT_MATERIALS_UNLIT],
        "extensionsRequired": [EXT_GAUSSIAN_SPLATTING, EXT_SPZ_2],
        "scene": 0,
        "scenes": [{ "nodes": [0] }],
        "nodes": [{ "mesh": 0, "matrix": node_matrix.to_vec() }],
        "materials": [{ "extensions": { EXT_MATERIALS_UNLIT: {} } }],
        "meshes": [{
            "primitives": [{
                "mode": PRIMITIVE_MODE_POINTS,
                "attributes": attributes,
                "material": 0,
                "extensions": {
                    EXT_GAUSSIAN_SPLATTING: {
                        "kernel": "ellipse",
                        "projection": "perspective",
                        "extensions": {
                            EXT_SPZ_2: { "bufferView": 0 }
                        }
                    }
                }
            }]
        }],
        "buffers": [{ "byteLength": bin_length }],
        "bufferViews": [{
            "buffer": 0,
            "byteOffset": 0,
            "byteLength": spz_byte_length,
        }],
        "accessors": accessors,
    })
}

/// Serialise a splat tile as a binary glTF container.
///
/// # Errors
///
/// Returns an error when the glTF document cannot be serialised.
pub fn write_splat_glb(
    spz_bytes: &[u8],
    splat_count: usize,
    sh_degree: u8,
    node_matrix: [f64; 16],
) -> Result<Vec<u8>> {
    let gltf = build_splat_gltf(spz_bytes.len(), splat_count, sh_degree, node_matrix);
    let json_chunk = serde_json::to_vec(&gltf)?;

    let json_pad = pad4(json_chunk.len());
    let bin_pad = pad4(spz_bytes.len());
    let json_length = json_chunk.len() + json_pad;
    let bin_length = spz_bytes.len() + bin_pad;
    let total = 12 + 8 + json_length + 8 + bin_length;

    let mut glb = Vec::with_capacity(total);
    glb.extend_from_slice(b"glTF");
    glb.extend_from_slice(&2_u32.to_le_bytes());
    glb.extend_from_slice(&(total as u32).to_le_bytes());

    glb.extend_from_slice(&(json_length as u32).to_le_bytes());
    glb.extend_from_slice(b"JSON");
    glb.extend_from_slice(&json_chunk);
    glb.extend(std::iter::repeat_n(b' ', json_pad));

    glb.extend_from_slice(&(bin_length as u32).to_le_bytes());
    glb.extend_from_slice(b"BIN\0");
    glb.extend_from_slice(spz_bytes);
    glb.extend(std::iter::repeat_n(0_u8, bin_pad));

    Ok(glb)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse_glb_json(glb: &[u8]) -> Value {
        let json_length = u32::from_le_bytes(glb[12..16].try_into().expect("json length")) as usize;
        let start = 20;
        serde_json::from_slice(&glb[start..start + json_length]).expect("valid json chunk")
    }

    #[test]
    fn pad4_rounds_up_to_four_byte_alignment() {
        assert_eq!(pad4(0), 0);
        assert_eq!(pad4(1), 3);
        assert_eq!(pad4(2), 2);
        assert_eq!(pad4(3), 1);
        assert_eq!(pad4(4), 0);
    }

    #[test]
    fn glb_container_header_is_well_formed() {
        let glb = write_splat_glb(&[1, 2, 3], 4, 0, tile_node_matrix([0.0; 3])).expect("writes");

        assert_eq!(&glb[0..4], b"glTF");
        assert_eq!(
            u32::from_le_bytes(glb[4..8].try_into().expect("version")),
            2
        );
        assert_eq!(
            u32::from_le_bytes(glb[8..12].try_into().expect("length")) as usize,
            glb.len(),
            "declared length matches the actual container"
        );
        assert_eq!(&glb[16..20], b"JSON");
    }

    #[test]
    fn glb_chunks_are_four_byte_aligned() {
        for payload_len in 1..=9 {
            let spz = vec![7_u8; payload_len];
            let glb = write_splat_glb(&spz, 1, 0, tile_node_matrix([0.0; 3])).expect("writes");
            assert_eq!(
                glb.len() % 4,
                0,
                "payload of {payload_len} bytes must still align"
            );

            let json_length =
                u32::from_le_bytes(glb[12..16].try_into().expect("json length")) as usize;
            assert_eq!(json_length % 4, 0, "JSON chunk is padded");

            let bin_header = 20 + json_length;
            assert_eq!(&glb[bin_header + 4..bin_header + 8], b"BIN\0");
        }
    }

    #[test]
    fn spz_payload_is_embedded_verbatim() {
        let spz: Vec<u8> = (0..16).collect();
        let glb = write_splat_glb(&spz, 2, 0, tile_node_matrix([0.0; 3])).expect("writes");
        let json_length = u32::from_le_bytes(glb[12..16].try_into().expect("json length")) as usize;
        let bin_start = 20 + json_length + 8;
        assert_eq!(&glb[bin_start..bin_start + spz.len()], &spz[..]);
    }

    #[test]
    fn gltf_declares_the_required_extensions() {
        let glb = write_splat_glb(&[0; 8], 3, 0, tile_node_matrix([0.0; 3])).expect("writes");
        let gltf = parse_glb_json(&glb);

        let required = gltf["extensionsRequired"]
            .as_array()
            .expect("extensionsRequired");
        assert!(required.iter().any(|v| v == EXT_GAUSSIAN_SPLATTING));
        assert!(
            required.iter().any(|v| v == EXT_SPZ_2),
            "the renderer plugin rejects tiles without spz_2"
        );

        let used = gltf["extensionsUsed"].as_array().expect("extensionsUsed");
        assert!(used.iter().any(|v| v == EXT_MATERIALS_UNLIT));
    }

    #[test]
    fn primitive_points_at_the_spz_buffer_view() {
        let glb = write_splat_glb(&[0; 8], 3, 0, tile_node_matrix([0.0; 3])).expect("writes");
        let gltf = parse_glb_json(&glb);
        let primitive = &gltf["meshes"][0]["primitives"][0];

        assert_eq!(primitive["mode"], PRIMITIVE_MODE_POINTS);
        assert_eq!(
            primitive["extensions"][EXT_GAUSSIAN_SPLATTING]["extensions"][EXT_SPZ_2]["bufferView"],
            0
        );
        assert_eq!(
            primitive["extensions"][EXT_GAUSSIAN_SPLATTING]["kernel"],
            "ellipse"
        );
        assert_eq!(gltf["bufferViews"][0]["byteLength"], 8);
    }

    #[test]
    fn the_asset_carries_the_credit() {
        let gltf = build_splat_gltf(16, 5, 0, tile_node_matrix([0.0; 3]));
        assert_eq!(gltf["asset"]["copyright"], "© geolith");
        assert_eq!(gltf["asset"]["version"], "2.0");
    }

    #[test]
    fn base_attributes_are_always_declared() {
        let gltf = build_splat_gltf(16, 5, 0, tile_node_matrix([0.0; 3]));
        let attributes = &gltf["meshes"][0]["primitives"][0]["attributes"];

        for name in [
            "POSITION",
            "COLOR_0",
            "KHR_gaussian_splatting:SCALE",
            "KHR_gaussian_splatting:ROTATION",
        ] {
            assert!(!attributes[name].is_null(), "missing attribute {name}");
        }
        assert_eq!(gltf["accessors"][0]["count"], 5);
    }

    #[test]
    fn spherical_harmonic_attributes_scale_with_degree() {
        let counts = [0_u8, 1, 2, 3].map(|degree| {
            let gltf = build_splat_gltf(16, 2, degree, tile_node_matrix([0.0; 3]));
            gltf["meshes"][0]["primitives"][0]["attributes"]
                .as_object()
                .expect("attributes")
                .len()
        });

        assert_eq!(counts[0], 4, "degree 0 declares only the base attributes");
        // Band l adds 2l + 1 coefficients: 3, then 5, then 7.
        assert_eq!(counts[1], 7);
        assert_eq!(counts[2], 12);
        assert_eq!(counts[3], 19);
    }

    #[test]
    fn degree_three_declares_every_band_attribute() {
        let gltf = build_splat_gltf(16, 2, 3, tile_node_matrix([0.0; 3]));
        let attributes = &gltf["meshes"][0]["primitives"][0]["attributes"];
        assert!(!attributes["KHR_gaussian_splatting:SH_DEGREE_1_COEF_2"].is_null());
        assert!(!attributes["KHR_gaussian_splatting:SH_DEGREE_2_COEF_4"].is_null());
        assert!(!attributes["KHR_gaussian_splatting:SH_DEGREE_3_COEF_6"].is_null());
    }

    #[test]
    fn node_matrix_is_column_major_with_flipped_axes() {
        let matrix = tile_node_matrix([0.0, 0.0, 0.0]);
        assert_eq!(matrix.len(), 16);
        assert_eq!(matrix[0], 1.0);
        assert_eq!(matrix[5], -1.0, "Y is flipped to reach glTF Y-up");
        assert_eq!(matrix[10], -1.0, "Z is flipped to reach glTF Y-up");
        assert_eq!(matrix[15], 1.0);
    }

    #[test]
    fn node_matrix_rotates_the_translation_into_the_gltf_basis() {
        let matrix = tile_node_matrix([2.0, 3.0, 4.0]);
        assert_eq!(matrix[12], 2.0);
        assert_eq!(matrix[13], -3.0, "translation follows the Y flip");
        assert_eq!(matrix[14], -4.0, "translation follows the Z flip");
    }

    #[test]
    fn buffer_byte_length_includes_alignment_padding() {
        let gltf = build_splat_gltf(5, 1, 0, tile_node_matrix([0.0; 3]));
        assert_eq!(
            gltf["buffers"][0]["byteLength"], 8,
            "5 bytes pad up to an 8-byte buffer"
        );
        assert_eq!(gltf["bufferViews"][0]["byteLength"], 5);
    }
}