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
//! Stage 2: COLMAP sparse reconstruction (camera poses + sparse points).
//!
//! Runs the standard COLMAP command sequence against the extracted frames:
//!
//! 1. `feature_extractor` — detect + describe SIFT features per image.
//! 2. `exhaustive_matcher` — match features across all image pairs.
//! 3. `mapper` — incremental bundle adjustment producing `sparse/0/`
//!    (`cameras.bin`, `images.bin`, `points3D.bin`).
//!
//! The output sparse model is exactly what `brush` consumes natively, so no
//! format conversion is needed between stages 2 and 3.

use std::path::Path;
use std::process::{Command, Stdio};

use super::Layout;

/// Run the COLMAP feature→match→map sequence for a [`Layout`].
///
/// The database and sparse model are written under the layout root; the
/// sequence is skipped by the caller when `sparse/0/cameras.bin` exists.
///
/// # Errors
///
/// Returns an error if `colmap` is missing, a command exits non-zero, or
/// the sparse model is not produced.
pub fn run_colmap(layout: &Layout, colmap_bin: &str) -> crate::error::Result<()> {
    if !frames_exist(&layout.frames) {
        return Err(crate::error::GeolithError::Colmap(format!(
            "no frames in {} — run the frames stage first",
            layout.frames.display()
        )));
    }

    run_tool(
        colmap_bin,
        &[
            "feature_extractor",
            "--database_path",
            layout.database.to_str().unwrap_or_default(),
            "--image_path",
            layout.frames.to_str().unwrap_or_default(),
        ],
    )?;

    run_tool(
        colmap_bin,
        &[
            "exhaustive_matcher",
            "--database_path",
            layout.database.to_str().unwrap_or_default(),
        ],
    )?;

    run_tool(
        colmap_bin,
        &[
            "mapper",
            "--database_path",
            layout.database.to_str().unwrap_or_default(),
            "--image_path",
            layout.frames.to_str().unwrap_or_default(),
            "--output_path",
            layout.sparse.to_str().unwrap_or_default(),
        ],
    )?;

    let model = layout.sparse.join("0");
    if !model.join("cameras.bin").is_file() {
        return Err(crate::error::GeolithError::Colmap(format!(
            "mapper did not produce a model in {} — reconstruction failed \
             (check that frames have sufficient overlap)",
            model.display()
        )));
    }

    let images = std::fs::read_dir(&layout.frames)?
        .filter_map(std::result::Result::ok)
        .count();
    tracing::info!(
        frames = images,
        model = %model.display(),
        "COLMAP sparse reconstruction complete"
    );
    Ok(())
}

/// Whether any image files exist in a directory.
#[must_use]
fn frames_exist(dir: &Path) -> bool {
    std::fs::read_dir(dir)
        .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)
}

/// Run an external CLI with the given arguments, returning its exit status.
///
/// # Errors
///
/// Returns a [`GeolithError::Colmap`] when the binary is missing, cannot be
/// spawned, or exits non-zero.
fn run_tool(bin: &str, args: &[&str]) -> crate::error::Result<()> {
    let mut command = Command::new(bin);
    command
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());

    tracing::info!(bin, args = %args.join(" "), "running COLMAP command");
    let output = match command.output() {
        Ok(output) => output,
        Err(error) => {
            return Err(crate::error::GeolithError::Colmap(format!(
                "failed to spawn {bin}: {error} (is COLMAP installed and on $PATH?)"
            )));
        }
    };

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let last = stderr.lines().rev().take(10).collect::<Vec<_>>().join("\n");
        return Err(crate::error::GeolithError::Colmap(format!(
            "{bin} exited with {:?}\n{last}",
            output.status.code()
        )));
    }
    Ok(())
}

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

    #[test]
    fn missing_frames_is_an_error() {
        let dir = tempfile::tempdir().expect("tempdir");
        let layout = Layout::new(dir.path());
        let err = run_colmap(&layout, "colmap").expect_err("no frames must fail");
        assert!(err.to_string().contains("no frames"));
    }

    #[test]
    fn frames_exist_detects_images_only() {
        let dir = tempfile::tempdir().expect("tempdir");
        assert!(!frames_exist(dir.path()));

        std::fs::write(dir.path().join("a.jpg"), b"jpeg").expect("jpg");
        assert!(frames_exist(dir.path()));

        std::fs::write(dir.path().join("b.txt"), b"x").expect("txt");
        assert!(frames_exist(dir.path()));
    }

    #[test]
    fn run_tool_reports_missing_binary() {
        let err = run_tool("definitely-not-a-real-binary-xyz", &["--help"])
            .expect_err("missing binary must fail");
        assert!(err.to_string().contains("failed to spawn"));
    }

    #[test]
    fn run_tool_reports_nonzero_exit() {
        // `false` exits 1 on every platform.
        let err = run_tool("false", &[]).expect_err("non-zero exit must fail");
        assert!(err.to_string().contains("exited with"));
    }
}