1use std::path::Path;
9
10use geolith::error::{GeolithError, Result};
11use serde_json::{Value, json};
12
13use crate::splat::glb::{EXT_GAUSSIAN_SPLATTING, EXT_SPZ_2, tile_node_matrix, write_splat_glb};
14use crate::splat::ply::SplatCloud;
15use crate::splat::spz::encode_spz;
16
17const WGS84_A: f64 = 6_378_137.0;
19
20const WGS84_INV_F: f64 = 298.257_223_563;
22
23const EXT_CONTENT_GLTF: &str = "3DTILES_content_gltf";
25
26#[derive(Debug, Clone)]
28pub struct SplatTilesetOptions {
29 pub longitude: f64,
31 pub latitude: f64,
33 pub altitude: f64,
35 pub max_splats_per_tile: usize,
37 pub max_depth: u8,
39 pub root_geometric_error: f64,
41 pub antialiased: bool,
43}
44
45impl Default for SplatTilesetOptions {
46 fn default() -> Self {
47 Self {
48 longitude: 0.0,
49 latitude: 0.0,
50 altitude: 0.0,
51 max_splats_per_tile: 100_000,
52 max_depth: 6,
53 root_geometric_error: 64.0,
54 antialiased: false,
55 }
56 }
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct SplatTilesetStats {
62 pub tiles: usize,
64 pub splats: usize,
66 pub max_depth: u8,
68}
69
70#[must_use]
72pub fn geodetic_to_ecef(longitude: f64, latitude: f64, altitude: f64) -> [f64; 3] {
73 let f = 1.0 / WGS84_INV_F;
74 let e2 = f * (2.0 - f);
75 let (sin_lat, cos_lat) = latitude.to_radians().sin_cos();
76 let (sin_lon, cos_lon) = longitude.to_radians().sin_cos();
77
78 let n = WGS84_A / (1.0 - e2 * sin_lat * sin_lat).sqrt();
79 [
80 (n + altitude) * cos_lat * cos_lon,
81 (n + altitude) * cos_lat * sin_lon,
82 (n * (1.0 - e2) + altitude) * sin_lat,
83 ]
84}
85
86#[must_use]
92pub fn enu_to_ecef_matrix(longitude: f64, latitude: f64, altitude: f64) -> [f64; 16] {
93 let (sin_lat, cos_lat) = latitude.to_radians().sin_cos();
94 let (sin_lon, cos_lon) = longitude.to_radians().sin_cos();
95 let origin = geodetic_to_ecef(longitude, latitude, altitude);
96
97 let east = [-sin_lon, cos_lon, 0.0];
98 let north = [-sin_lat * cos_lon, -sin_lat * sin_lon, cos_lat];
99 let up = [cos_lat * cos_lon, cos_lat * sin_lon, sin_lat];
100
101 [
102 east[0], east[1], east[2], 0.0, north[0], north[1], north[2], 0.0, up[0], up[1], up[2],
103 0.0, origin[0], origin[1], origin[2], 1.0,
104 ]
105}
106
107#[derive(Debug, Clone)]
109struct OctreeNode {
110 center: [f64; 3],
112 half_size: [f64; 3],
114 indices: Vec<u32>,
116 children: Vec<OctreeNode>,
118 depth: u8,
120 geometric_error: f64,
122}
123
124impl OctreeNode {
125 const fn bounding_box(&self) -> [f64; 12] {
127 [
128 self.center[0],
129 self.center[1],
130 self.center[2],
131 self.half_size[0],
132 0.0,
133 0.0,
134 0.0,
135 self.half_size[1],
136 0.0,
137 0.0,
138 0.0,
139 self.half_size[2],
140 ]
141 }
142}
143
144fn bounds_of(cloud: &SplatCloud, indices: &[u32]) -> ([f64; 3], [f64; 3]) {
146 let mut min = [f64::INFINITY; 3];
147 let mut max = [f64::NEG_INFINITY; 3];
148 for &index in indices {
149 let position = cloud.positions[index as usize];
150 for axis in 0..3 {
151 let value = f64::from(position[axis]);
152 min[axis] = min[axis].min(value);
153 max[axis] = max[axis].max(value);
154 }
155 }
156 (min, max)
157}
158
159fn decimate(indices: &[u32], target: usize) -> Vec<u32> {
161 if indices.len() <= target || target == 0 {
162 return indices.to_vec();
163 }
164 let stride = indices.len().div_ceil(target);
165 indices.iter().copied().step_by(stride).collect()
166}
167
168fn build_node(
170 cloud: &SplatCloud,
171 indices: Vec<u32>,
172 depth: u8,
173 geometric_error: f64,
174 options: &SplatTilesetOptions,
175) -> OctreeNode {
176 let (min, max) = bounds_of(cloud, &indices);
177 let center = [
178 (min[0] + max[0]) / 2.0,
179 (min[1] + max[1]) / 2.0,
180 (min[2] + max[2]) / 2.0,
181 ];
182 let half_size = [
183 ((max[0] - min[0]) / 2.0).max(f64::EPSILON),
184 ((max[1] - min[1]) / 2.0).max(f64::EPSILON),
185 ((max[2] - min[2]) / 2.0).max(f64::EPSILON),
186 ];
187
188 let should_split = indices.len() > options.max_splats_per_tile && depth < options.max_depth;
189 if !should_split {
190 return OctreeNode {
191 center,
192 half_size,
193 indices,
194 children: Vec::new(),
195 depth,
196 geometric_error: 0.0,
197 };
198 }
199
200 let mut buckets: Vec<Vec<u32>> = vec![Vec::new(); 8];
201 for index in &indices {
202 let position = cloud.positions[*index as usize];
203 let octant = usize::from(f64::from(position[0]) >= center[0])
204 | (usize::from(f64::from(position[1]) >= center[1]) << 1)
205 | (usize::from(f64::from(position[2]) >= center[2]) << 2);
206 buckets[octant].push(*index);
207 }
208
209 let child_error = geometric_error / 2.0;
210 let children: Vec<OctreeNode> = buckets
211 .into_iter()
212 .filter(|bucket| !bucket.is_empty())
213 .map(|bucket| build_node(cloud, bucket, depth + 1, child_error, options))
214 .collect();
215
216 if children.len() < 2 {
217 return OctreeNode {
218 center,
219 half_size,
220 indices,
221 children: Vec::new(),
222 depth,
223 geometric_error: 0.0,
224 };
225 }
226
227 OctreeNode {
228 center,
229 half_size,
230 indices: decimate(&indices, options.max_splats_per_tile),
231 children,
232 depth,
233 geometric_error,
234 }
235}
236
237fn emit_node(
239 node: &OctreeNode,
240 cloud: &SplatCloud,
241 output_dir: &Path,
242 options: &SplatTilesetOptions,
243 next_id: &mut usize,
244 stats: &mut SplatTilesetStats,
245) -> Result<Value> {
246 let tile_id = *next_id;
247 *next_id += 1;
248
249 let mut local = cloud.subset(&node.indices)?;
250 for position in &mut local.positions {
251 position[0] -= node.center[0] as f32;
252 position[1] -= node.center[1] as f32;
253 position[2] -= node.center[2] as f32;
254 }
255
256 let spz = encode_spz(&local, options.antialiased)?;
257 let glb = write_splat_glb(
258 &spz,
259 local.len(),
260 local.sh_degree,
261 tile_node_matrix(node.center),
262 )?;
263
264 let content_uri = format!("tiles/{tile_id}.glb");
265 std::fs::create_dir_all(output_dir.join("tiles"))?;
266 std::fs::write(output_dir.join(&content_uri), &glb)?;
267
268 stats.tiles += 1;
269 stats.splats += local.len();
270 stats.max_depth = stats.max_depth.max(node.depth);
271
272 let mut tile = json!({
273 "boundingVolume": { "box": node.bounding_box() },
274 "geometricError": node.geometric_error,
275 "refine": "REPLACE",
276 "content": { "uri": content_uri },
277 });
278
279 if !node.children.is_empty() {
280 let children: Vec<Value> = node
281 .children
282 .iter()
283 .map(|child| emit_node(child, cloud, output_dir, options, next_id, stats))
284 .collect::<Result<_>>()?;
285 tile["children"] = Value::Array(children);
286 }
287
288 Ok(tile)
289}
290
291pub fn write_splat_tileset(
300 cloud: &SplatCloud,
301 output_dir: &Path,
302 options: &SplatTilesetOptions,
303) -> Result<SplatTilesetStats> {
304 if cloud.is_empty() {
305 return Err(GeolithError::SplatTiles(
306 "cannot build a tileset from an empty splat cloud".to_owned(),
307 ));
308 }
309
310 std::fs::create_dir_all(output_dir)?;
311
312 let indices: Vec<u32> = (0..cloud.len() as u32).collect();
313 let root = build_node(cloud, indices, 0, options.root_geometric_error, options);
314
315 let mut stats = SplatTilesetStats {
316 tiles: 0,
317 splats: 0,
318 max_depth: 0,
319 };
320 let mut next_id = 0_usize;
321 let root_tile = emit_node(&root, cloud, output_dir, options, &mut next_id, &mut stats)?;
322
323 let tileset = json!({
324 "asset": {
325 "version": "1.1",
326 "generator": concat!("geolith ", env!("CARGO_PKG_VERSION")),
327 },
328 "extensionsUsed": [EXT_CONTENT_GLTF],
329 "extensions": {
330 EXT_CONTENT_GLTF: {
331 "extensionsUsed": [EXT_GAUSSIAN_SPLATTING, EXT_SPZ_2],
332 "extensionsRequired": [EXT_GAUSSIAN_SPLATTING, EXT_SPZ_2],
333 }
334 },
335 "geometricError": options.root_geometric_error,
336 "root": {
337 "transform": enu_to_ecef_matrix(
338 options.longitude,
339 options.latitude,
340 options.altitude,
341 ),
342 "boundingVolume": root_tile["boundingVolume"].clone(),
343 "geometricError": root_tile["geometricError"].clone(),
344 "refine": "REPLACE",
345 "content": root_tile["content"].clone(),
346 "children": root_tile.get("children").cloned().unwrap_or(json!([])),
347 },
348 });
349
350 std::fs::write(
351 output_dir.join("tileset.json"),
352 serde_json::to_vec_pretty(&tileset)?,
353 )?;
354
355 Ok(stats)
356}
357
358#[cfg(test)]
359mod tests {
360 use super::*;
361
362 fn grid_cloud(per_axis: usize) -> SplatCloud {
363 let mut cloud = SplatCloud {
364 sh_degree: 0,
365 ..SplatCloud::default()
366 };
367 for x in 0..per_axis {
368 for y in 0..per_axis {
369 for z in 0..per_axis {
370 cloud
371 .positions
372 .push([x as f32 * 0.1, y as f32 * 0.1, z as f32 * 0.1]);
373 cloud.colors.push([0.3, 0.4, 0.5]);
374 cloud.opacities.push(1.0);
375 cloud.scales.push([-4.0, -4.0, -4.0]);
376 cloud.rotations.push([1.0, 0.0, 0.0, 0.0]);
377 }
378 }
379 }
380 cloud
381 }
382
383 #[test]
384 fn ecef_at_the_equator_prime_meridian_lies_on_the_x_axis() {
385 let ecef = geodetic_to_ecef(0.0, 0.0, 0.0);
386 assert!((ecef[0] - WGS84_A).abs() < 1e-6, "x: {}", ecef[0]);
387 assert!(ecef[1].abs() < 1e-6);
388 assert!(ecef[2].abs() < 1e-6);
389 }
390
391 #[test]
392 fn ecef_at_the_north_pole_lies_on_the_z_axis() {
393 let ecef = geodetic_to_ecef(0.0, 90.0, 0.0);
394 assert!(ecef[0].abs() < 1e-3, "x: {}", ecef[0]);
395 assert!(ecef[1].abs() < 1e-3);
396 let polar_radius = WGS84_A * (1.0 - 1.0 / WGS84_INV_F);
397 assert!(
398 (ecef[2] - polar_radius).abs() < 1.0,
399 "polar radius: {} vs {polar_radius}",
400 ecef[2]
401 );
402 }
403
404 #[test]
405 fn ecef_altitude_extends_along_the_up_vector() {
406 let ground = geodetic_to_ecef(0.0, 0.0, 0.0);
407 let raised = geodetic_to_ecef(0.0, 0.0, 1000.0);
408 assert!((raised[0] - ground[0] - 1000.0).abs() < 1e-6);
409 }
410
411 #[test]
412 fn enu_matrix_is_orthonormal_and_column_major() {
413 let m = enu_to_ecef_matrix(7.9797, 45.9756, 2250.0);
414 assert_eq!(m.len(), 16);
415
416 let east = [m[0], m[1], m[2]];
417 let north = [m[4], m[5], m[6]];
418 let up = [m[8], m[9], m[10]];
419
420 for axis in [east, north, up] {
421 let length = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt();
422 assert!((length - 1.0).abs() < 1e-9, "unit length: {length}");
423 }
424
425 let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
426 assert!(dot(east, north).abs() < 1e-9);
427 assert!(dot(east, up).abs() < 1e-9);
428 assert!(dot(north, up).abs() < 1e-9);
429
430 assert_eq!(m[3], 0.0);
431 assert_eq!(m[15], 1.0);
432 }
433
434 #[test]
435 fn enu_translation_column_is_the_anchor_in_ecef() {
436 let (lon, lat, alt) = (7.9797, 45.9756, 2250.0);
437 let m = enu_to_ecef_matrix(lon, lat, alt);
438 let ecef = geodetic_to_ecef(lon, lat, alt);
439 assert!((m[12] - ecef[0]).abs() < 1e-6);
440 assert!((m[13] - ecef[1]).abs() < 1e-6);
441 assert!((m[14] - ecef[2]).abs() < 1e-6);
442 }
443
444 #[test]
445 fn enu_up_vector_points_away_from_the_geocentre() {
446 let m = enu_to_ecef_matrix(0.0, 0.0, 0.0);
447 assert!((m[8] - 1.0).abs() < 1e-9, "up is +X at lon 0 lat 0");
448 }
449
450 #[test]
451 fn decimate_keeps_everything_below_the_target() {
452 let indices: Vec<u32> = (0..10).collect();
453 assert_eq!(decimate(&indices, 20), indices);
454 assert_eq!(decimate(&indices, 0), indices);
455 }
456
457 #[test]
458 fn decimate_reduces_to_at_most_the_target() {
459 let indices: Vec<u32> = (0..100).collect();
460 let reduced = decimate(&indices, 10);
461 assert!(reduced.len() <= 10, "got {}", reduced.len());
462 assert_eq!(reduced[0], 0, "keeps a stable stride from the start");
463 }
464
465 #[test]
466 fn small_cloud_produces_a_single_leaf_tile() {
467 let cloud = grid_cloud(2);
468 let dir = tempfile::tempdir().expect("temp dir");
469 let options = SplatTilesetOptions {
470 max_splats_per_tile: 1000,
471 ..SplatTilesetOptions::default()
472 };
473
474 let stats = write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
475 assert_eq!(stats.tiles, 1);
476 assert_eq!(stats.splats, cloud.len());
477 assert_eq!(stats.max_depth, 0);
478 assert!(dir.path().join("tiles/0.glb").is_file());
479 }
480
481 #[test]
482 fn large_cloud_subdivides_into_children() {
483 let cloud = grid_cloud(8);
484 let dir = tempfile::tempdir().expect("temp dir");
485 let options = SplatTilesetOptions {
486 max_splats_per_tile: 32,
487 max_depth: 3,
488 ..SplatTilesetOptions::default()
489 };
490
491 let stats = write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
492 assert!(stats.tiles > 1, "expected subdivision, got {}", stats.tiles);
493 assert!(stats.max_depth >= 1);
494
495 let tileset: Value = serde_json::from_slice(
496 &std::fs::read(dir.path().join("tileset.json")).expect("tileset"),
497 )
498 .expect("valid json");
499 let children = tileset["root"]["children"]
500 .as_array()
501 .expect("children array");
502 assert!(!children.is_empty());
503 }
504
505 #[test]
506 fn tileset_json_matches_the_3d_tiles_contract() {
507 let cloud = grid_cloud(3);
508 let dir = tempfile::tempdir().expect("temp dir");
509 let options = SplatTilesetOptions {
510 longitude: 7.9797,
511 latitude: 45.9756,
512 altitude: 2250.0,
513 max_splats_per_tile: 1000,
514 ..SplatTilesetOptions::default()
515 };
516
517 write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
518 let tileset: Value = serde_json::from_slice(
519 &std::fs::read(dir.path().join("tileset.json")).expect("tileset"),
520 )
521 .expect("valid json");
522
523 assert_eq!(tileset["asset"]["version"], "1.1");
524 assert_eq!(tileset["root"]["refine"], "REPLACE");
525 assert!(tileset["root"]["content"]["uri"].is_string());
526 assert_eq!(
527 tileset["root"]["transform"]
528 .as_array()
529 .expect("transform")
530 .len(),
531 16,
532 "root transform is a 4x4 matrix"
533 );
534 assert_eq!(
535 tileset["root"]["boundingVolume"]["box"]
536 .as_array()
537 .expect("box")
538 .len(),
539 12,
540 "box volumes carry a centre and three half-axes"
541 );
542
543 let declared = &tileset["extensions"][EXT_CONTENT_GLTF]["extensionsRequired"];
544 let required = declared.as_array().expect("required array");
545 assert!(
546 required.iter().any(|v| v == EXT_SPZ_2),
547 "the tileset must advertise spz_2 so the renderer loads splat tiles"
548 );
549 }
550
551 #[test]
552 fn tile_positions_are_rebased_to_the_node_centre() {
553 let mut cloud = grid_cloud(2);
554 for position in &mut cloud.positions {
555 position[0] += 5000.0;
556 }
557
558 let dir = tempfile::tempdir().expect("temp dir");
559 let options = SplatTilesetOptions {
560 max_splats_per_tile: 1000,
561 ..SplatTilesetOptions::default()
562 };
563
564 write_splat_tileset(&cloud, dir.path(), &options)
565 .expect("far-from-origin scenes rebase into the fixed-point range");
566
567 let glb = std::fs::read(dir.path().join("tiles/0.glb")).expect("tile written");
568 assert_eq!(&glb[0..4], b"glTF");
569 }
570
571 #[test]
572 fn empty_cloud_is_rejected() {
573 let dir = tempfile::tempdir().expect("temp dir");
574 let err = write_splat_tileset(
575 &SplatCloud::default(),
576 dir.path(),
577 &SplatTilesetOptions::default(),
578 )
579 .expect_err("empty cloud");
580 assert!(matches!(err, GeolithError::SplatTiles(_)));
581 }
582
583 #[test]
584 fn parent_geometric_error_exceeds_child_error() {
585 let cloud = grid_cloud(8);
586 let dir = tempfile::tempdir().expect("temp dir");
587 let options = SplatTilesetOptions {
588 max_splats_per_tile: 32,
589 max_depth: 3,
590 root_geometric_error: 64.0,
591 ..SplatTilesetOptions::default()
592 };
593
594 write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
595 let tileset: Value = serde_json::from_slice(
596 &std::fs::read(dir.path().join("tileset.json")).expect("tileset"),
597 )
598 .expect("valid json");
599
600 let root_error = tileset["root"]["geometricError"]
601 .as_f64()
602 .expect("root error");
603 let child_error = tileset["root"]["children"][0]["geometricError"]
604 .as_f64()
605 .expect("child error");
606 assert!(
607 child_error < root_error,
608 "children must refine: {child_error} < {root_error}"
609 );
610 }
611
612 #[test]
613 fn default_options_are_conservative() {
614 let options = SplatTilesetOptions::default();
615 assert_eq!(options.max_splats_per_tile, 100_000);
616 assert_eq!(options.max_depth, 6);
617 assert!(!options.antialiased);
618 }
619
620 #[test]
621 fn collinear_splats_collapse_to_a_leaf_instead_of_recursing() {
622 let mut cloud = SplatCloud {
623 sh_degree: 0,
624 ..SplatCloud::default()
625 };
626 for index in 0..64 {
627 cloud.positions.push([index as f32 * 0.001, 0.0, 0.0]);
628 cloud.colors.push([0.3, 0.4, 0.5]);
629 cloud.opacities.push(1.0);
630 cloud.scales.push([-4.0, -4.0, -4.0]);
631 cloud.rotations.push([1.0, 0.0, 0.0, 0.0]);
632 }
633
634 let dir = tempfile::tempdir().expect("temp dir");
635 let options = SplatTilesetOptions {
636 max_splats_per_tile: 4,
637 max_depth: 5,
638 ..SplatTilesetOptions::default()
639 };
640
641 let stats = write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
642 let tileset: Value = serde_json::from_slice(
643 &std::fs::read(dir.path().join("tileset.json")).expect("tileset"),
644 )
645 .expect("valid json");
646
647 assert!(
648 stats.tiles >= 1,
649 "a degenerate distribution still yields a usable tileset"
650 );
651 assert_eq!(
652 tileset["root"]["boundingVolume"]["box"]
653 .as_array()
654 .expect("box")
655 .len(),
656 12,
657 "a zero-thickness axis still produces a well-formed box"
658 );
659 }
660
661 #[test]
662 fn identical_positions_produce_a_single_tile() {
663 let mut cloud = SplatCloud {
664 sh_degree: 0,
665 ..SplatCloud::default()
666 };
667 for _ in 0..32 {
668 cloud.positions.push([1.0, 1.0, 1.0]);
669 cloud.colors.push([0.3, 0.4, 0.5]);
670 cloud.opacities.push(1.0);
671 cloud.scales.push([-4.0, -4.0, -4.0]);
672 cloud.rotations.push([1.0, 0.0, 0.0, 0.0]);
673 }
674
675 let dir = tempfile::tempdir().expect("temp dir");
676 let options = SplatTilesetOptions {
677 max_splats_per_tile: 4,
678 max_depth: 4,
679 ..SplatTilesetOptions::default()
680 };
681
682 let stats = write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
683 assert_eq!(
684 stats.tiles, 1,
685 "coincident splats cannot be separated by an octant split"
686 );
687 assert_eq!(stats.splats, 32, "no splat is dropped when the split fails");
688 }
689
690 #[test]
691 fn max_depth_zero_forces_a_single_tile() {
692 let cloud = grid_cloud(4);
693 let dir = tempfile::tempdir().expect("temp dir");
694 let options = SplatTilesetOptions {
695 max_splats_per_tile: 1,
696 max_depth: 0,
697 ..SplatTilesetOptions::default()
698 };
699
700 let stats = write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
701 assert_eq!(stats.tiles, 1, "depth 0 disables subdivision entirely");
702 assert_eq!(stats.max_depth, 0);
703 }
704
705 #[test]
706 fn parents_decimate_rather_than_duplicate_their_subtree() {
707 let cloud = grid_cloud(8);
708 let dir = tempfile::tempdir().expect("temp dir");
709 let options = SplatTilesetOptions {
710 max_splats_per_tile: 32,
711 max_depth: 3,
712 ..SplatTilesetOptions::default()
713 };
714
715 let stats = write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
716 let tileset: Value = serde_json::from_slice(
717 &std::fs::read(dir.path().join("tileset.json")).expect("tileset"),
718 )
719 .expect("valid json");
720
721 let root_uri = tileset["root"]["content"]["uri"]
722 .as_str()
723 .expect("root uri");
724 assert_eq!(root_uri, "tiles/0.glb", "the root is emitted first");
725 assert!(
726 stats.splats > cloud.len(),
727 "parents hold a decimated preview on top of their leaves: {} vs {}",
728 stats.splats,
729 cloud.len()
730 );
731 }
732
733 #[test]
734 fn subdivision_writes_one_glb_per_tile() {
735 let cloud = grid_cloud(8);
736 let dir = tempfile::tempdir().expect("temp dir");
737 let options = SplatTilesetOptions {
738 max_splats_per_tile: 32,
739 max_depth: 3,
740 ..SplatTilesetOptions::default()
741 };
742
743 let stats = write_splat_tileset(&cloud, dir.path(), &options).expect("writes");
744 let written = std::fs::read_dir(dir.path().join("tiles"))
745 .expect("tiles dir")
746 .count();
747 assert_eq!(written, stats.tiles, "every counted tile has a GLB on disk");
748
749 for id in 0..stats.tiles {
750 let glb = std::fs::read(dir.path().join(format!("tiles/{id}.glb")))
751 .unwrap_or_else(|e| panic!("tile {id} missing: {e}"));
752 assert_eq!(&glb[0..4], b"glTF", "tile {id} is binary glTF");
753 }
754 }
755
756 #[test]
757 fn bounds_of_spans_only_the_requested_indices() {
758 let cloud = grid_cloud(3);
759 let (min, max) = bounds_of(&cloud, &[0]);
760 assert!((min[0] - max[0]).abs() < 1e-9, "a single index is a point");
761
762 let all: Vec<u32> = (0..cloud.len() as u32).collect();
763 let (min_all, max_all) = bounds_of(&cloud, &all);
764 assert!(max_all[0] > min_all[0], "the full set spans the grid");
765 }
766
767 #[test]
768 fn octree_child_errors_halve_at_each_level() {
769 let cloud = grid_cloud(8);
770 let indices: Vec<u32> = (0..cloud.len() as u32).collect();
771 let options = SplatTilesetOptions {
772 max_splats_per_tile: 32,
773 max_depth: 3,
774 ..SplatTilesetOptions::default()
775 };
776
777 let root = build_node(&cloud, indices, 0, 64.0, &options);
778 assert!(!root.children.is_empty(), "the grid subdivides");
779 for child in &root.children {
780 if !child.children.is_empty() {
781 assert!(
782 (child.geometric_error - 32.0).abs() < 1e-9,
783 "child error halves: {}",
784 child.geometric_error
785 );
786 }
787 }
788 }
789}