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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//! OGC 3D Tiles tileset construction for Gaussian splat scenes.
//!
//! Subdivides a splat cloud into an octree, writes one GLB per node, and
//! emits a `tileset.json` whose root `transform` places the scene at its
//! geographic anchor. Nodes refine with `REPLACE`, so a parent holds a
//! decimated view of everything beneath it.

use std::path::Path;

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

use crate::splat::glb::{EXT_GAUSSIAN_SPLATTING, EXT_SPZ_2, tile_node_matrix, write_splat_glb};
use crate::splat::ply::SplatCloud;
use crate::splat::spz::encode_spz;

/// WGS84 semi-major axis in metres.
const WGS84_A: f64 = 6_378_137.0;

/// WGS84 inverse flattening.
const WGS84_INV_F: f64 = 298.257_223_563;

/// The 3D Tiles glTF content extension declaration key.
const EXT_CONTENT_GLTF: &str = "3DTILES_content_gltf";

/// Options controlling splat tileset generation.
#[derive(Debug, Clone)]
pub struct SplatTilesetOptions {
    /// Longitude of the scene anchor in degrees.
    pub longitude: f64,
    /// Latitude of the scene anchor in degrees.
    pub latitude: f64,
    /// Height of the scene anchor above the ellipsoid in metres.
    pub altitude: f64,
    /// Maximum splats stored in a single tile.
    pub max_splats_per_tile: usize,
    /// Maximum octree depth.
    pub max_depth: u8,
    /// Geometric error assigned to the root tile.
    pub root_geometric_error: f64,
    /// Whether the splats were trained with antialiasing.
    pub antialiased: bool,
}

impl Default for SplatTilesetOptions {
    fn default() -> Self {
        Self {
            longitude: 0.0,
            latitude: 0.0,
            altitude: 0.0,
            max_splats_per_tile: 100_000,
            max_depth: 6,
            root_geometric_error: 64.0,
            antialiased: false,
        }
    }
}

/// Summary of a completed splat tiling run.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SplatTilesetStats {
    /// Number of tiles written.
    pub tiles: usize,
    /// Total splats across every emitted tile.
    pub splats: usize,
    /// Deepest octree level reached.
    pub max_depth: u8,
}

/// Convert geodetic coordinates to earth-centred, earth-fixed metres.
#[must_use]
pub fn geodetic_to_ecef(longitude: f64, latitude: f64, altitude: f64) -> [f64; 3] {
    let f = 1.0 / WGS84_INV_F;
    let e2 = f * (2.0 - f);
    let (sin_lat, cos_lat) = latitude.to_radians().sin_cos();
    let (sin_lon, cos_lon) = longitude.to_radians().sin_cos();

    let n = WGS84_A / (1.0 - e2 * sin_lat * sin_lat).sqrt();
    [
        (n + altitude) * cos_lat * cos_lon,
        (n + altitude) * cos_lat * sin_lon,
        (n * (1.0 - e2) + altitude) * sin_lat,
    ]
}

/// Build the column-major east-north-up to ECEF transform for an anchor.
///
/// 3D Tiles applies the root `transform` to place tile-local coordinates on
/// the globe. The basis columns are the east, north and up unit vectors at
/// the anchor, with the ECEF anchor position as the translation column.
#[must_use]
pub fn enu_to_ecef_matrix(longitude: f64, latitude: f64, altitude: f64) -> [f64; 16] {
    let (sin_lat, cos_lat) = latitude.to_radians().sin_cos();
    let (sin_lon, cos_lon) = longitude.to_radians().sin_cos();
    let origin = geodetic_to_ecef(longitude, latitude, altitude);

    let east = [-sin_lon, cos_lon, 0.0];
    let north = [-sin_lat * cos_lon, -sin_lat * sin_lon, cos_lat];
    let up = [cos_lat * cos_lon, cos_lat * sin_lon, sin_lat];

    [
        east[0], east[1], east[2], 0.0, north[0], north[1], north[2], 0.0, up[0], up[1], up[2],
        0.0, origin[0], origin[1], origin[2], 1.0,
    ]
}

/// An axis-aligned box holding the splat indices assigned to one octree node.
#[derive(Debug, Clone)]
struct OctreeNode {
    /// Node centre in source coordinates.
    center: [f64; 3],
    /// Half-extent along each axis in source coordinates.
    half_size: [f64; 3],
    /// Splat indices retained at this level.
    indices: Vec<u32>,
    /// Child nodes, empty for leaves.
    children: Vec<OctreeNode>,
    /// Depth below the root.
    depth: u8,
    /// Geometric error for this node.
    geometric_error: f64,
}

impl OctreeNode {
    /// The 3D Tiles `box` bounding volume: centre followed by three half-axes.
    const fn bounding_box(&self) -> [f64; 12] {
        [
            self.center[0],
            self.center[1],
            self.center[2],
            self.half_size[0],
            0.0,
            0.0,
            0.0,
            self.half_size[1],
            0.0,
            0.0,
            0.0,
            self.half_size[2],
        ]
    }
}

/// Compute the bounding box of the given splats.
fn bounds_of(cloud: &SplatCloud, indices: &[u32]) -> ([f64; 3], [f64; 3]) {
    let mut min = [f64::INFINITY; 3];
    let mut max = [f64::NEG_INFINITY; 3];
    for &index in indices {
        let position = cloud.positions[index as usize];
        for axis in 0..3 {
            let value = f64::from(position[axis]);
            min[axis] = min[axis].min(value);
            max[axis] = max[axis].max(value);
        }
    }
    (min, max)
}

/// Select every `stride`-th index so a parent tile previews its subtree.
fn decimate(indices: &[u32], target: usize) -> Vec<u32> {
    if indices.len() <= target || target == 0 {
        return indices.to_vec();
    }
    let stride = indices.len().div_ceil(target);
    indices.iter().copied().step_by(stride).collect()
}

/// Recursively build the octree.
fn build_node(
    cloud: &SplatCloud,
    indices: Vec<u32>,
    depth: u8,
    geometric_error: f64,
    options: &SplatTilesetOptions,
) -> OctreeNode {
    let (min, max) = bounds_of(cloud, &indices);
    let center = [
        (min[0] + max[0]) / 2.0,
        (min[1] + max[1]) / 2.0,
        (min[2] + max[2]) / 2.0,
    ];
    let half_size = [
        ((max[0] - min[0]) / 2.0).max(f64::EPSILON),
        ((max[1] - min[1]) / 2.0).max(f64::EPSILON),
        ((max[2] - min[2]) / 2.0).max(f64::EPSILON),
    ];

    let should_split = indices.len() > options.max_splats_per_tile && depth < options.max_depth;
    if !should_split {
        return OctreeNode {
            center,
            half_size,
            indices,
            children: Vec::new(),
            depth,
            geometric_error: 0.0,
        };
    }

    let mut buckets: Vec<Vec<u32>> = vec![Vec::new(); 8];
    for index in &indices {
        let position = cloud.positions[*index as usize];
        let octant = usize::from(f64::from(position[0]) >= center[0])
            | (usize::from(f64::from(position[1]) >= center[1]) << 1)
            | (usize::from(f64::from(position[2]) >= center[2]) << 2);
        buckets[octant].push(*index);
    }

    let child_error = geometric_error / 2.0;
    let children: Vec<OctreeNode> = buckets
        .into_iter()
        .filter(|bucket| !bucket.is_empty())
        .map(|bucket| build_node(cloud, bucket, depth + 1, child_error, options))
        .collect();

    if children.len() < 2 {
        return OctreeNode {
            center,
            half_size,
            indices,
            children: Vec::new(),
            depth,
            geometric_error: 0.0,
        };
    }

    OctreeNode {
        center,
        half_size,
        indices: decimate(&indices, options.max_splats_per_tile),
        children,
        depth,
        geometric_error,
    }
}

/// Walk the tree, writing one GLB per node and building its tileset entry.
fn emit_node(
    node: &OctreeNode,
    cloud: &SplatCloud,
    output_dir: &Path,
    options: &SplatTilesetOptions,
    next_id: &mut usize,
    stats: &mut SplatTilesetStats,
) -> Result<Value> {
    let tile_id = *next_id;
    *next_id += 1;

    let mut local = cloud.subset(&node.indices)?;
    for position in &mut local.positions {
        position[0] -= node.center[0] as f32;
        position[1] -= node.center[1] as f32;
        position[2] -= node.center[2] as f32;
    }

    let spz = encode_spz(&local, options.antialiased)?;
    let glb = write_splat_glb(
        &spz,
        local.len(),
        local.sh_degree,
        tile_node_matrix(node.center),
    )?;

    let content_uri = format!("tiles/{tile_id}.glb");
    std::fs::create_dir_all(output_dir.join("tiles"))?;
    crate::fsio::write_file(&output_dir.join(&content_uri), &glb)?;

    stats.tiles += 1;
    stats.splats += local.len();
    stats.max_depth = stats.max_depth.max(node.depth);

    let mut tile = json!({
        "boundingVolume": { "box": node.bounding_box() },
        "geometricError": node.geometric_error,
        "refine": "REPLACE",
        "content": { "uri": content_uri },
    });

    if !node.children.is_empty() {
        let children: Vec<Value> = node
            .children
            .iter()
            .map(|child| emit_node(child, cloud, output_dir, options, next_id, stats))
            .collect::<Result<_>>()?;
        tile["children"] = Value::Array(children);
    }

    Ok(tile)
}

/// Build a 3D Tiles tileset from a splat cloud.
///
/// Writes `tileset.json` and `tiles/*.glb` beneath `output_dir`.
///
/// # Errors
///
/// Returns [`GeolithError::SplatTiles`] when the cloud is empty, and
/// propagates I/O and encoding failures.
pub fn write_splat_tileset(
    cloud: &SplatCloud,
    output_dir: &Path,
    options: &SplatTilesetOptions,
) -> Result<SplatTilesetStats> {
    if cloud.is_empty() {
        return Err(GeolithError::SplatTiles(
            "cannot build a tileset from an empty splat cloud".to_owned(),
        ));
    }

    std::fs::create_dir_all(output_dir)?;

    let indices: Vec<u32> = (0..cloud.len() as u32).collect();
    let root = build_node(cloud, indices, 0, options.root_geometric_error, options);

    let mut stats = SplatTilesetStats {
        tiles: 0,
        splats: 0,
        max_depth: 0,
    };
    let mut next_id = 0_usize;
    let root_tile = emit_node(&root, cloud, output_dir, options, &mut next_id, &mut stats)?;

    let tileset = json!({
        "asset": {
            "version": "1.1",
            "generator": concat!("geolith ", env!("CARGO_PKG_VERSION")),
        },
        "extensionsUsed": [EXT_CONTENT_GLTF],
        "extensions": {
            EXT_CONTENT_GLTF: {
                "extensionsUsed": [EXT_GAUSSIAN_SPLATTING, EXT_SPZ_2],
                "extensionsRequired": [EXT_GAUSSIAN_SPLATTING, EXT_SPZ_2],
            }
        },
        "geometricError": options.root_geometric_error,
        "root": {
            "transform": enu_to_ecef_matrix(
                options.longitude,
                options.latitude,
                options.altitude,
            ),
            "boundingVolume": root_tile["boundingVolume"].clone(),
            "geometricError": root_tile["geometricError"].clone(),
            "refine": "REPLACE",
            "content": root_tile["content"].clone(),
            "children": root_tile.get("children").cloned().unwrap_or(json!([])),
        },
    });

    crate::fsio::write_file(
        &output_dir.join("tileset.json"),
        serde_json::to_vec_pretty(&tileset)?,
    )?;

    Ok(stats)
}

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

    fn grid_cloud(per_axis: usize) -> SplatCloud {
        let mut cloud = SplatCloud {
            sh_degree: 0,
            ..SplatCloud::default()
        };
        for x in 0..per_axis {
            for y in 0..per_axis {
                for z in 0..per_axis {
                    cloud
                        .positions
                        .push([x as f32 * 0.1, y as f32 * 0.1, z as f32 * 0.1]);
                    cloud.colors.push([0.3, 0.4, 0.5]);
                    cloud.opacities.push(1.0);
                    cloud.scales.push([-4.0, -4.0, -4.0]);
                    cloud.rotations.push([1.0, 0.0, 0.0, 0.0]);
                }
            }
        }
        cloud
    }

    #[test]
    fn ecef_at_the_equator_prime_meridian_lies_on_the_x_axis() {
        let ecef = geodetic_to_ecef(0.0, 0.0, 0.0);
        assert!((ecef[0] - WGS84_A).abs() < 1e-6, "x: {}", ecef[0]);
        assert!(ecef[1].abs() < 1e-6);
        assert!(ecef[2].abs() < 1e-6);
    }

    #[test]
    fn ecef_at_the_north_pole_lies_on_the_z_axis() {
        let ecef = geodetic_to_ecef(0.0, 90.0, 0.0);
        assert!(ecef[0].abs() < 1e-3, "x: {}", ecef[0]);
        assert!(ecef[1].abs() < 1e-3);
        let polar_radius = WGS84_A * (1.0 - 1.0 / WGS84_INV_F);
        assert!(
            (ecef[2] - polar_radius).abs() < 1.0,
            "polar radius: {} vs {polar_radius}",
            ecef[2]
        );
    }

    #[test]
    fn ecef_altitude_extends_along_the_up_vector() {
        let ground = geodetic_to_ecef(0.0, 0.0, 0.0);
        let raised = geodetic_to_ecef(0.0, 0.0, 1000.0);
        assert!((raised[0] - ground[0] - 1000.0).abs() < 1e-6);
    }

    #[test]
    fn enu_matrix_is_orthonormal_and_column_major() {
        let m = enu_to_ecef_matrix(7.9797, 45.9756, 2250.0);
        assert_eq!(m.len(), 16);

        let east = [m[0], m[1], m[2]];
        let north = [m[4], m[5], m[6]];
        let up = [m[8], m[9], m[10]];

        for axis in [east, north, up] {
            let length = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt();
            assert!((length - 1.0).abs() < 1e-9, "unit length: {length}");
        }

        let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
        assert!(dot(east, north).abs() < 1e-9);
        assert!(dot(east, up).abs() < 1e-9);
        assert!(dot(north, up).abs() < 1e-9);

        assert_eq!(m[3], 0.0);
        assert_eq!(m[15], 1.0);
    }

    #[test]
    fn enu_translation_column_is_the_anchor_in_ecef() {
        let (lon, lat, alt) = (7.9797, 45.9756, 2250.0);
        let m = enu_to_ecef_matrix(lon, lat, alt);
        let ecef = geodetic_to_ecef(lon, lat, alt);
        assert!((m[12] - ecef[0]).abs() < 1e-6);
        assert!((m[13] - ecef[1]).abs() < 1e-6);
        assert!((m[14] - ecef[2]).abs() < 1e-6);
    }

    #[test]
    fn enu_up_vector_points_away_from_the_geocentre() {
        let m = enu_to_ecef_matrix(0.0, 0.0, 0.0);
        assert!((m[8] - 1.0).abs() < 1e-9, "up is +X at lon 0 lat 0");
    }

    #[test]
    fn decimate_keeps_everything_below_the_target() {
        let indices: Vec<u32> = (0..10).collect();
        assert_eq!(decimate(&indices, 20), indices);
        assert_eq!(decimate(&indices, 0), indices);
    }

    #[test]
    fn decimate_reduces_to_at_most_the_target() {
        let indices: Vec<u32> = (0..100).collect();
        let reduced = decimate(&indices, 10);
        assert!(reduced.len() <= 10, "got {}", reduced.len());
        assert_eq!(reduced[0], 0, "keeps a stable stride from the start");
    }

    #[test]
    fn small_cloud_produces_a_single_leaf_tile() {
        let cloud = grid_cloud(2);
        let dir = tempfile::tempdir().expect("temp dir");
        let options = SplatTilesetOptions {
            max_splats_per_tile: 1000,
            ..SplatTilesetOptions::default()
        };

        let stats = write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
        assert_eq!(stats.tiles, 1);
        assert_eq!(stats.splats, cloud.len());
        assert_eq!(stats.max_depth, 0);
        assert!(dir.path().join("tiles/0.glb").is_file());
    }

    #[test]
    fn large_cloud_subdivides_into_children() {
        let cloud = grid_cloud(8);
        let dir = tempfile::tempdir().expect("temp dir");
        let options = SplatTilesetOptions {
            max_splats_per_tile: 32,
            max_depth: 3,
            ..SplatTilesetOptions::default()
        };

        let stats = write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
        assert!(stats.tiles > 1, "expected subdivision, got {}", stats.tiles);
        assert!(stats.max_depth >= 1);

        let tileset: Value = serde_json::from_slice(
            &std::fs::read(dir.path().join("tileset.json")).expect("tileset"),
        )
        .expect("valid json");
        let children = tileset["root"]["children"]
            .as_array()
            .expect("children array");
        assert!(!children.is_empty());
    }

    #[test]
    fn tileset_json_matches_the_3d_tiles_contract() {
        let cloud = grid_cloud(3);
        let dir = tempfile::tempdir().expect("temp dir");
        let options = SplatTilesetOptions {
            longitude: 7.9797,
            latitude: 45.9756,
            altitude: 2250.0,
            max_splats_per_tile: 1000,
            ..SplatTilesetOptions::default()
        };

        write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
        let tileset: Value = serde_json::from_slice(
            &std::fs::read(dir.path().join("tileset.json")).expect("tileset"),
        )
        .expect("valid json");

        assert_eq!(tileset["asset"]["version"], "1.1");
        assert_eq!(tileset["root"]["refine"], "REPLACE");
        assert!(tileset["root"]["content"]["uri"].is_string());
        assert_eq!(
            tileset["root"]["transform"]
                .as_array()
                .expect("transform")
                .len(),
            16,
            "root transform is a 4x4 matrix"
        );
        assert_eq!(
            tileset["root"]["boundingVolume"]["box"]
                .as_array()
                .expect("box")
                .len(),
            12,
            "box volumes carry a centre and three half-axes"
        );

        let declared = &tileset["extensions"][EXT_CONTENT_GLTF]["extensionsRequired"];
        let required = declared.as_array().expect("required array");
        assert!(
            required.iter().any(|v| v == EXT_SPZ_2),
            "the tileset must advertise spz_2 so the renderer loads splat tiles"
        );
    }

    #[test]
    fn tile_positions_are_rebased_to_the_node_centre() {
        let mut cloud = grid_cloud(2);
        for position in &mut cloud.positions {
            position[0] += 5000.0;
        }

        let dir = tempfile::tempdir().expect("temp dir");
        let options = SplatTilesetOptions {
            max_splats_per_tile: 1000,
            ..SplatTilesetOptions::default()
        };

        write_splat_tileset(&cloud, dir.path(), &options)
            .expect("far-from-origin scenes rebase into the fixed-point range");

        let glb = std::fs::read(dir.path().join("tiles/0.glb")).expect("tile written");
        assert_eq!(&glb[0..4], b"glTF");
    }

    #[test]
    fn empty_cloud_is_rejected() {
        let dir = tempfile::tempdir().expect("temp dir");
        let err = write_splat_tileset(
            &SplatCloud::default(),
            dir.path(),
            &SplatTilesetOptions::default(),
        )
        .expect_err("empty cloud");
        assert!(matches!(err, GeolithError::SplatTiles(_)));
    }

    #[test]
    fn parent_geometric_error_exceeds_child_error() {
        let cloud = grid_cloud(8);
        let dir = tempfile::tempdir().expect("temp dir");
        let options = SplatTilesetOptions {
            max_splats_per_tile: 32,
            max_depth: 3,
            root_geometric_error: 64.0,
            ..SplatTilesetOptions::default()
        };

        write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
        let tileset: Value = serde_json::from_slice(
            &std::fs::read(dir.path().join("tileset.json")).expect("tileset"),
        )
        .expect("valid json");

        let root_error = tileset["root"]["geometricError"]
            .as_f64()
            .expect("root error");
        let child_error = tileset["root"]["children"][0]["geometricError"]
            .as_f64()
            .expect("child error");
        assert!(
            child_error < root_error,
            "children must refine: {child_error} < {root_error}"
        );
    }

    #[test]
    fn default_options_are_conservative() {
        let options = SplatTilesetOptions::default();
        assert_eq!(options.max_splats_per_tile, 100_000);
        assert_eq!(options.max_depth, 6);
        assert!(!options.antialiased);
    }

    #[test]
    fn collinear_splats_collapse_to_a_leaf_instead_of_recursing() {
        let mut cloud = SplatCloud {
            sh_degree: 0,
            ..SplatCloud::default()
        };
        for index in 0..64 {
            cloud.positions.push([index as f32 * 0.001, 0.0, 0.0]);
            cloud.colors.push([0.3, 0.4, 0.5]);
            cloud.opacities.push(1.0);
            cloud.scales.push([-4.0, -4.0, -4.0]);
            cloud.rotations.push([1.0, 0.0, 0.0, 0.0]);
        }

        let dir = tempfile::tempdir().expect("temp dir");
        let options = SplatTilesetOptions {
            max_splats_per_tile: 4,
            max_depth: 5,
            ..SplatTilesetOptions::default()
        };

        let stats = write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
        let tileset: Value = serde_json::from_slice(
            &std::fs::read(dir.path().join("tileset.json")).expect("tileset"),
        )
        .expect("valid json");

        assert!(
            stats.tiles >= 1,
            "a degenerate distribution still yields a usable tileset"
        );
        assert_eq!(
            tileset["root"]["boundingVolume"]["box"]
                .as_array()
                .expect("box")
                .len(),
            12,
            "a zero-thickness axis still produces a well-formed box"
        );
    }

    #[test]
    fn identical_positions_produce_a_single_tile() {
        let mut cloud = SplatCloud {
            sh_degree: 0,
            ..SplatCloud::default()
        };
        for _ in 0..32 {
            cloud.positions.push([1.0, 1.0, 1.0]);
            cloud.colors.push([0.3, 0.4, 0.5]);
            cloud.opacities.push(1.0);
            cloud.scales.push([-4.0, -4.0, -4.0]);
            cloud.rotations.push([1.0, 0.0, 0.0, 0.0]);
        }

        let dir = tempfile::tempdir().expect("temp dir");
        let options = SplatTilesetOptions {
            max_splats_per_tile: 4,
            max_depth: 4,
            ..SplatTilesetOptions::default()
        };

        let stats = write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
        assert_eq!(
            stats.tiles, 1,
            "coincident splats cannot be separated by an octant split"
        );
        assert_eq!(stats.splats, 32, "no splat is dropped when the split fails");
    }

    #[test]
    fn max_depth_zero_forces_a_single_tile() {
        let cloud = grid_cloud(4);
        let dir = tempfile::tempdir().expect("temp dir");
        let options = SplatTilesetOptions {
            max_splats_per_tile: 1,
            max_depth: 0,
            ..SplatTilesetOptions::default()
        };

        let stats = write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
        assert_eq!(stats.tiles, 1, "depth 0 disables subdivision entirely");
        assert_eq!(stats.max_depth, 0);
    }

    #[test]
    fn parents_decimate_rather_than_duplicate_their_subtree() {
        let cloud = grid_cloud(8);
        let dir = tempfile::tempdir().expect("temp dir");
        let options = SplatTilesetOptions {
            max_splats_per_tile: 32,
            max_depth: 3,
            ..SplatTilesetOptions::default()
        };

        let stats = write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
        let tileset: Value = serde_json::from_slice(
            &std::fs::read(dir.path().join("tileset.json")).expect("tileset"),
        )
        .expect("valid json");

        let root_uri = tileset["root"]["content"]["uri"]
            .as_str()
            .expect("root uri");
        assert_eq!(root_uri, "tiles/0.glb", "the root is emitted first");
        assert!(
            stats.splats > cloud.len(),
            "parents hold a decimated preview on top of their leaves: {} vs {}",
            stats.splats,
            cloud.len()
        );
    }

    #[test]
    fn subdivision_writes_one_glb_per_tile() {
        let cloud = grid_cloud(8);
        let dir = tempfile::tempdir().expect("temp dir");
        let options = SplatTilesetOptions {
            max_splats_per_tile: 32,
            max_depth: 3,
            ..SplatTilesetOptions::default()
        };

        let stats = write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
        let written = std::fs::read_dir(dir.path().join("tiles"))
            .expect("tiles dir")
            .count();
        assert_eq!(written, stats.tiles, "every counted tile has a GLB on disk");

        for id in 0..stats.tiles {
            let glb = std::fs::read(dir.path().join(format!("tiles/{id}.glb")))
                .unwrap_or_else(|e| panic!("tile {id} missing: {e}"));
            assert_eq!(&glb[0..4], b"glTF", "tile {id} is binary glTF");
        }
    }

    #[test]
    fn bounds_of_spans_only_the_requested_indices() {
        let cloud = grid_cloud(3);
        let (min, max) = bounds_of(&cloud, &[0]);
        assert!((min[0] - max[0]).abs() < 1e-9, "a single index is a point");

        let all: Vec<u32> = (0..cloud.len() as u32).collect();
        let (min_all, max_all) = bounds_of(&cloud, &all);
        assert!(max_all[0] > min_all[0], "the full set spans the grid");
    }

    #[test]
    fn octree_child_errors_halve_at_each_level() {
        let cloud = grid_cloud(8);
        let indices: Vec<u32> = (0..cloud.len() as u32).collect();
        let options = SplatTilesetOptions {
            max_splats_per_tile: 32,
            max_depth: 3,
            ..SplatTilesetOptions::default()
        };

        let root = build_node(&cloud, indices, 0, 64.0, &options);
        assert!(!root.children.is_empty(), "the grid subdivides");
        for child in &root.children {
            if !child.children.is_empty() {
                assert!(
                    (child.geometric_error - 32.0).abs() < 1e-9,
                    "child error halves: {}",
                    child.geometric_error
                );
            }
        }
    }
}