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;
const WGS84_A: f64 = 6_378_137.0;
const WGS84_INV_F: f64 = 298.257_223_563;
const EXT_CONTENT_GLTF: &str = "3DTILES_content_gltf";
#[derive(Debug, Clone)]
pub struct SplatTilesetOptions {
pub longitude: f64,
pub latitude: f64,
pub altitude: f64,
pub max_splats_per_tile: usize,
pub max_depth: u8,
pub root_geometric_error: f64,
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,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SplatTilesetStats {
pub tiles: usize,
pub splats: usize,
pub max_depth: u8,
}
#[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,
]
}
#[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,
]
}
#[derive(Debug, Clone)]
struct OctreeNode {
center: [f64; 3],
half_size: [f64; 3],
indices: Vec<u32>,
children: Vec<OctreeNode>,
depth: u8,
geometric_error: f64,
}
impl OctreeNode {
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],
]
}
}
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)
}
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()
}
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,
}
}
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)
}
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
);
}
}
}
}