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
//! Drone-video photogrammetry pipeline: video → 3D Gaussian Splatting → 3D Tiles.
//!
//! Orchestrates the full end-to-end reconstruction chain that turns a drone
//! video into OGC 3D Tiles renderable in a web map:
//!
//! ```text
//! drone video
//!    │  ffmpeg frame extraction (stage 1)
//!    ▼
//! frames/  +  COLMAP sparse reconstruction (stage 2)
//!    │  cameras.bin / images.bin / points3D.bin
//!    ▼
//! brush 3DGS training (stage 3)
//!    │  exported PLY
//!    ▼
//! splat-tiles octree subdivision (stage 4)
//!    │  tileset.json + tiles/*.glb + scene.spz
//!    ▼
//! v-maplibre VLayerSplat / VLayer3DTiles
//! ```
//!
//! Each stage shells out to an external tool following the `osmium`
//! integration precedent: `ffmpeg` (frames), `colmap` (`SfM`), `brush-cli`
//! (3DGS training). The final tiling stage runs entirely in-process on the
//! [`crate::splat`] module.
//!
//! Stage outputs are written under a single working directory so the
//! pipeline is resumable: re-running with the same `--output` skips stages
//! whose outputs already exist.

mod frames;
mod sfm;
mod train;

use std::path::{Path, PathBuf};

/// Description of a single pipeline stage, used for status logging.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Stage {
    /// Video frame extraction via ffmpeg.
    Frames,
    /// COLMAP sparse reconstruction (poses + points).
    Sfm,
    /// Brush 3DGS training.
    Train,
    /// In-process splat-tiles subdivision.
    Tile,
}

impl Stage {
    /// Human-readable stage name for tracing.
    #[must_use]
    const fn name(self) -> &'static str {
        match self {
            Self::Frames => "frames",
            Self::Sfm => "sfm",
            Self::Train => "train",
            Self::Tile => "tile",
        }
    }
}

/// Output layout of the reconstruction pipeline under the working directory.
#[derive(Debug)]
struct Layout {
    /// Working directory root (`--output`).
    root: PathBuf,
    /// Extracted video frames.
    frames: PathBuf,
    /// COLMAP database.
    database: PathBuf,
    /// COLMAP sparse model output (`sparse/0/`).
    sparse: PathBuf,
    /// Brush PLY export directory.
    exports: PathBuf,
    /// Final 3D Tiles output directory.
    tiles: PathBuf,
}

impl Layout {
    /// Derive the output layout for a working directory.
    #[must_use]
    fn new(root: &Path) -> Self {
        Self {
            root: root.to_path_buf(),
            frames: root.join("frames"),
            database: root.join("colmap.db"),
            sparse: root.join("sparse"),
            exports: root.join("exports"),
            tiles: root.join("tiles"),
        }
    }

    /// Create all output directories.
    ///
    /// # Errors
    ///
    /// Returns an error if any directory cannot be created.
    fn create_dirs(&self) -> crate::error::Result<()> {
        std::fs::create_dir_all(&self.frames)?;
        std::fs::create_dir_all(&self.sparse)?;
        std::fs::create_dir_all(&self.exports)?;
        std::fs::create_dir_all(&self.tiles)?;
        Ok(())
    }

    /// Whether a stage's output already exists (used for resume).
    #[must_use]
    fn stage_done(&self, stage: Stage) -> bool {
        match stage {
            Stage::Frames => std::fs::read_dir(&self.frames)
                .map(|entries| {
                    entries.filter_map(std::result::Result::ok).any(|entry| {
                        entry
                            .path()
                            .extension()
                            .and_then(|ext| ext.to_str())
                            .is_some_and(|ext| matches!(ext, "jpg" | "jpeg" | "png"))
                    })
                })
                .unwrap_or(false),
            Stage::Sfm => self.sparse.join("0").join("cameras.bin").is_file(),
            Stage::Train => self.exports.join("scene.ply").is_file(),
            Stage::Tile => self.tiles.join("tileset.json").is_file(),
        }
    }
}

/// Options for the drone-video reconstruction pipeline.
#[derive(Debug, Clone)]
pub struct ReconstructOptions {
    /// Frame extraction rate in frames per second.
    pub fps: f64,
    /// Maximum number of frames to extract (optional cap).
    pub max_frames: Option<usize>,
    /// COLMAP binary path (default: `colmap` on `$PATH`).
    pub colmap_bin: String,
    /// Brush CLI binary path (default: `brush-cli` on `$PATH`).
    pub brush_bin: String,
    /// Total brush training iterations.
    pub train_iters: u32,
    /// 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,
    /// Trim this percentage from both ends of every axis before tiling.
    pub crop_percentile: f64,
    /// Trim this percentage from the far end of the radial distance
    /// distribution from the cloud centroid before tiling.
    pub crop_radial_percentile: f64,
    /// Uniform scale factor applied to the scene.
    pub scale: f32,
    /// Coverage boost applied before encoding (0 disables it).
    pub coverage_boost_scale: f32,
    /// 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 to emit a standalone `scene.spz` alongside the tileset.
    pub emit_scene_spz: bool,
}

impl Default for ReconstructOptions {
    fn default() -> Self {
        Self {
            fps: 2.0,
            max_frames: None,
            colmap_bin: "colmap".to_owned(),
            brush_bin: "brush-cli".to_owned(),
            train_iters: 30_000,
            longitude: 0.0,
            latitude: 0.0,
            altitude: 0.0,
            crop_percentile: 0.0,
            crop_radial_percentile: 0.0,
            scale: 1.0,
            coverage_boost_scale: 0.0,
            max_splats_per_tile: 100_000,
            max_depth: 6,
            root_geometric_error: 64.0,
            emit_scene_spz: true,
        }
    }
}

/// Run the full drone-video reconstruction pipeline into `output`.
///
/// Stages whose outputs already exist are skipped, making the pipeline
/// resumable across partial failures.
///
/// # Errors
///
/// Returns an error if any stage fails: ffmpeg extraction, COLMAP sparse
/// reconstruction, brush training, or tile writing.
pub fn run_reconstruct(
    video: &Path,
    output: &Path,
    options: &ReconstructOptions,
) -> crate::error::Result<()> {
    let layout = Layout::new(output);
    layout.create_dirs()?;

    run_stage(Stage::Frames, &layout, || {
        frames::extract_frames(video, &layout.frames, options.fps, options.max_frames)
    })?;

    run_stage(Stage::Sfm, &layout, || {
        sfm::run_colmap(&layout, &options.colmap_bin)
    })?;

    run_stage(Stage::Train, &layout, || {
        train::train_splats(&layout, &options.brush_bin, options.train_iters)
    })?;

    let ply = layout.exports.join("scene.ply");
    let stats = run_stage(Stage::Tile, &layout, || {
        tile_ply(&ply, &layout.tiles, options)
    })?;

    tracing::info!(
        output = %layout.tiles.display(),
        tiles = stats.as_ref().map(|s| s.tiles).unwrap_or_default(),
        splats = stats.as_ref().map(|s| s.splats).unwrap_or_default(),
        max_depth = stats.as_ref().map(|s| s.max_depth).unwrap_or_default(),
        "reconstruction complete — tileset ready"
    );
    Ok(())
}

/// Run a single stage, skipping it when its output already exists.
///
/// Returns `None` when the stage was skipped.
///
/// # Errors
///
/// Returns the stage's error when it runs and fails.
fn run_stage<T>(
    stage: Stage,
    layout: &Layout,
    f: impl FnOnce() -> crate::error::Result<T>,
) -> crate::error::Result<Option<T>> {
    if layout.stage_done(stage) {
        tracing::info!(stage = stage.name(), "stage already complete — skipping");
        return Ok(None);
    }
    tracing::info!(stage = stage.name(), "running stage");
    f().map(Some)
}

/// Subdivide a trained PLY into an OGC 3D Tiles tileset.
///
/// Reuses the [`crate::splat`] module in-process; no external tool.
///
/// # Errors
///
/// Returns an error if the PLY cannot be read or the tileset written.
fn tile_ply(
    ply: &Path,
    tiles_dir: &Path,
    options: &ReconstructOptions,
) -> crate::error::Result<crate::splat::tileset::SplatTilesetStats> {
    tracing::info!(ply = %ply.display(), "reading trained splat PLY");
    let mut cloud = crate::splat::read_splat_ply(ply)?;
    tracing::info!(
        splats = cloud.len(),
        sh_degree = cloud.sh_degree,
        "splat cloud loaded"
    );

    if options.crop_percentile > 0.0 {
        let before = cloud.len();
        cloud = cloud.crop_percentile(options.crop_percentile)?;
        tracing::info!(
            kept = cloud.len(),
            dropped = before - cloud.len(),
            percentile = options.crop_percentile,
            "cropped far-field splats"
        );
    }
    if options.crop_radial_percentile > 0.0 {
        let before = cloud.len();
        cloud = cloud.crop_radial_percentile(options.crop_radial_percentile)?;
        tracing::info!(
            kept = cloud.len(),
            dropped = before - cloud.len(),
            percentile = options.crop_radial_percentile,
            "cropped radial far-field splats"
        );
    }
    cloud.rescale(options.scale);
    if options.coverage_boost_scale > 0.0 {
        cloud.coverage_boost(options.coverage_boost_scale);
        tracing::info!(
            boost = options.coverage_boost_scale,
            "applied coverage boost"
        );
    }

    let tileset_options = crate::splat::tileset::SplatTilesetOptions {
        longitude: options.longitude,
        latitude: options.latitude,
        altitude: options.altitude,
        max_splats_per_tile: options.max_splats_per_tile,
        max_depth: options.max_depth,
        root_geometric_error: options.root_geometric_error,
        antialiased: false,
    };
    let stats = crate::splat::write_splat_tileset(&cloud, tiles_dir, &tileset_options)?;
    tracing::info!(
        output = %tiles_dir.display(),
        tiles = stats.tiles,
        splats = stats.splats,
        max_depth = stats.max_depth,
        "3D Tiles tileset written"
    );

    if options.emit_scene_spz {
        let scene = tiles_dir.join("scene.spz");
        let mut centered = cloud.clone();
        if let Some((min, max)) = cloud.bounds() {
            let center = [
                (min[0] + max[0]) / 2.0,
                (min[1] + max[1]) / 2.0,
                (min[2] + max[2]) / 2.0,
            ];
            for position in &mut centered.positions {
                position[0] -= center[0];
                position[1] -= center[1];
                position[2] -= center[2];
            }
        }
        crate::fsio::write_file(&scene, crate::splat::encode_spz(&centered, false)?)?;
        tracing::info!(path = %scene.display(), "standalone scene.spz written");
    }

    Ok(stats)
}

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

    #[test]
    fn stage_names_are_stable() {
        assert_eq!(Stage::Frames.name(), "frames");
        assert_eq!(Stage::Sfm.name(), "sfm");
        assert_eq!(Stage::Train.name(), "train");
        assert_eq!(Stage::Tile.name(), "tile");
    }

    #[test]
    fn layout_paths_follow_working_dir() {
        let layout = Layout::new(Path::new("/tmp/recon"));
        assert_eq!(layout.frames, PathBuf::from("/tmp/recon/frames"));
        assert_eq!(layout.database, PathBuf::from("/tmp/recon/colmap.db"));
        assert_eq!(layout.sparse, PathBuf::from("/tmp/recon/sparse"));
        assert_eq!(layout.exports, PathBuf::from("/tmp/recon/exports"));
        assert_eq!(layout.tiles, PathBuf::from("/tmp/recon/tiles"));
    }

    #[test]
    fn stage_done_detects_frames() {
        let dir = tempfile::tempdir().expect("tempdir");
        let layout = Layout::new(dir.path());
        assert!(!layout.stage_done(Stage::Frames));

        std::fs::create_dir_all(&layout.frames).expect("frames dir");
        std::fs::write(layout.frames.join("notes.txt"), b"x").expect("write file");
        assert!(
            !layout.stage_done(Stage::Frames),
            "a non-image file is not a frame"
        );
        std::fs::write(layout.frames.join("0001.jpg"), b"jpeg").expect("write frame");
        assert!(layout.stage_done(Stage::Frames));
    }

    #[test]
    fn stage_done_detects_sparse_model() {
        let dir = tempfile::tempdir().expect("tempdir");
        let layout = Layout::new(dir.path());
        assert!(!layout.stage_done(Stage::Sfm));

        let model = layout.sparse.join("0");
        std::fs::create_dir_all(&model).expect("sparse dir");
        std::fs::write(model.join("cameras.bin"), b"bin").expect("cameras");
        assert!(layout.stage_done(Stage::Sfm));
    }

    #[test]
    fn stage_done_detects_ply_and_tileset() {
        let dir = tempfile::tempdir().expect("tempdir");
        let layout = Layout::new(dir.path());
        assert!(!layout.stage_done(Stage::Train));
        assert!(!layout.stage_done(Stage::Tile));

        std::fs::create_dir_all(&layout.exports).expect("exports dir");
        std::fs::write(layout.exports.join("scene.ply"), b"ply").expect("write ply");
        assert!(layout.stage_done(Stage::Train));
        assert!(!layout.stage_done(Stage::Tile));

        std::fs::create_dir_all(&layout.tiles).expect("tiles dir");
        std::fs::write(layout.tiles.join("tileset.json"), b"{}").expect("tileset");
        assert!(layout.stage_done(Stage::Tile));
    }

    #[test]
    fn run_stage_skips_when_done_and_runs_when_not() {
        let dir = tempfile::tempdir().expect("tempdir");
        let layout = Layout::new(dir.path());

        // Not done → runs, returns Some.
        let ran = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let ran_clone = std::sync::Arc::clone(&ran);
        let result = run_stage(Stage::Frames, &layout, || {
            ran_clone.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Ok(42)
        })
        .expect("run");
        assert_eq!(result, Some(42));
        assert_eq!(ran.load(std::sync::atomic::Ordering::SeqCst), 1);

        // Done → skips, returns None without calling the closure.
        std::fs::create_dir_all(&layout.frames).expect("frames dir");
        std::fs::write(layout.frames.join("0001.jpg"), b"jpeg").expect("frame");
        let result = run_stage(Stage::Frames, &layout, || -> crate::error::Result<i32> {
            panic!("closure must not run on skip");
        })
        .expect("skip");
        assert_eq!(result, None);
    }
}