diff options
| author | Johannes Hofmann <Johannes.Hofmann@gmx.de> | 2026-10-27 10:08:22 +0100 |
|---|---|---|
| committer | Johannes Hofmann <Johannes.Hofmann@gmx.de> | 2026-10-27 10:08:28 +0100 |
| commit | 912a2d0b15b873923698126ac8112d1aa4bdbb1a (patch) | |
| tree | ce3e204e6636ce49044c85f7ced1553a399b79e1 /crates/gipfel-wasm | |
| parent | 6e38ef31467a85edc2aff0a1b6889a417f5ef20f (diff) | |
wasm: experimental browser spike
Proves the gipfel core can run in the browser via WASM. Enabled by the
earlier GSL removal: the core is now pure Rust.
gipfel-core gains byte-oriented entry points (no filesystem) alongside
the existing path-based ones:
- hill::load_from_bytes, Panorama::load_data_from_bytes
- metadata: load_image_from_bytes, read_jpeg_comment_from_bytes,
write_jpeg_comment_to_bytes, save_image_to_bytes (EXIF via Cursor)
New crate gipfel-wasm (experimental, not shipped with the app):
- wasm-bindgen surface: version() + fit_demo(db_bytes, jpg_bytes)
which runs the whole pipeline in memory: parse hill DB, read gipfel
JPEG comment / EXIF, synthesize 5 observations from visible hills,
perturb, refit (pure-Rust LM), report JSON with reprojection error
- demo/index.html: file pickers + result pane (wasm-pack --target web)
- build.sh: adds the wasm target, builds with wasm-pack, prints serve cmd
- native test runs the same pipeline against gipfel.dat + test.jpg and
asserts sub-pixel reprojection error (passes here)
To try on a machine with rustup:
cd crates/gipfel-wasm && ./build.sh
Diffstat (limited to 'crates/gipfel-wasm')
| -rw-r--r-- | crates/gipfel-wasm/Cargo.toml | 14 | ||||
| -rwxr-xr-x | crates/gipfel-wasm/build.sh | 22 | ||||
| -rw-r--r-- | crates/gipfel-wasm/demo/index.html | 39 | ||||
| -rw-r--r-- | crates/gipfel-wasm/src/lib.rs | 147 |
4 files changed, 222 insertions, 0 deletions
diff --git a/crates/gipfel-wasm/Cargo.toml b/crates/gipfel-wasm/Cargo.toml new file mode 100644 index 0000000..34cbbbd --- /dev/null +++ b/crates/gipfel-wasm/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "gipfel-wasm" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "EXPERIMENT: WebAssembly bindings for gipfel-core (browser spike, not part of the app)" + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +gipfel-core = { path = "../gipfel-core" } +image.workspace = true +wasm-bindgen = "0.2" diff --git a/crates/gipfel-wasm/build.sh b/crates/gipfel-wasm/build.sh new file mode 100755 index 0000000..8d1d812 --- /dev/null +++ b/crates/gipfel-wasm/build.sh @@ -0,0 +1,22 @@ +#!/bin/sh +# Build the gipfel WASM spike and serve the demo page. +# Requires: rustup (for the wasm target) and wasm-pack. +set -e +cd "$(dirname "$0")" + +if ! rustup target list --installed 2>/dev/null | grep -q wasm32-unknown-unknown; then + echo "adding wasm32-unknown-unknown target ..." + rustup target add wasm32-unknown-unknown +fi +command -v wasm-pack >/dev/null 2>&1 || { + echo "wasm-pack not found. Install it once with:" + echo " cargo install wasm-pack (or: cargo binstall wasm-pack)" + exit 1 +} + +wasm-pack build --target web + +echo +echo "built. serve the demo with:" +echo " (cd crates/gipfel-wasm && python3 -m http.server 8080)" +echo "then open http://localhost:8080/demo/" diff --git a/crates/gipfel-wasm/demo/index.html b/crates/gipfel-wasm/demo/index.html new file mode 100644 index 0000000..f8e764d --- /dev/null +++ b/crates/gipfel-wasm/demo/index.html @@ -0,0 +1,39 @@ +<!doctype html> +<html lang="en"> +<head> + <meta charset="utf-8" /> + <title>gipfel WASM spike</title> + <style> + body { font-family: system-ui, sans-serif; max-width: 720px; margin: 3em auto; line-height: 1.5; } + pre { background: #f4f4f4; padding: 1em; overflow-x: auto; } + label { display: block; margin: 0.6em 0; } + button { margin-top: 1em; padding: 0.5em 1.2em; } + </style> +</head> +<body> + <h1>gipfel WASM spike</h1> + <p>core version: <code id="ver">loading…</code></p> + <p>Pick a hill database and a JPEG (ideally one saved by gipfel, or with EXIF GPS data):</p> + <label>gipfel.dat: <input type="file" id="db" /></label> + <label>image.jpg: <input type="file" id="jpg" /></label> + <button id="go" disabled>Run fit pipeline</button> + <pre id="out">pick both files, then run</pre> + + <script type="module"> + import init, { fit_demo, version } from '../pkg/gipfel_wasm.js'; + const $ = (id) => document.getElementById(id); + await init(); + $('ver').textContent = version(); + $('go').disabled = false; + $('go').onclick = async () => { + const f = (id) => $(id).files[0]; + if (!f('db') || !f('jpg')) { $('out').textContent = 'pick both files first'; return; } + const db = new Uint8Array(await f('db').arrayBuffer()); + const jpg = new Uint8Array(await f('jpg').arrayBuffer()); + const t0 = performance.now(); + const res = fit_demo(db, jpg); + $('out').textContent = res + `\n\n(wall time: ${(performance.now() - t0).toFixed(1)} ms)`; + }; + </script> +</body> +</html> diff --git a/crates/gipfel-wasm/src/lib.rs b/crates/gipfel-wasm/src/lib.rs new file mode 100644 index 0000000..b521829 --- /dev/null +++ b/crates/gipfel-wasm/src/lib.rs @@ -0,0 +1,147 @@ +//! EXPERIMENT: browser spike exposing the gipfel core pipeline to JavaScript. +//! +//! The whole computational core (hill DB, geodesy, projections, LM fit, +//! JPEG comment + EXIF I/O) is pure Rust and WASM-friendly — the GSL +//! removal made this possible. This crate proves the pipeline end-to-end +//! in the browser: bytes in (hill DB + JPEG), fit report out. +//! +//! Build (requires rustup): +//! rustup target add wasm32-unknown-unknown +//! cargo install wasm-pack # once +//! cd crates/gipfel-wasm && wasm-pack build --target web +//! python3 -m http.server 8080 # then open /demo/ + +use wasm_bindgen::prelude::*; + +/// Crate version (from Cargo.toml, via the workspace). +#[wasm_bindgen] +pub fn version() -> String { + env!("CARGO_PKG_VERSION").to_string() +} + +/// End-to-end pipeline smoke test, all in memory: +/// +/// 1. parse the hill database (`db` = gipfel.dat bytes, Latin-1 CSV) +/// 2. read gipfel metadata from the JPEG bytes (comment, else EXIF) +/// 3. build the panorama, take up to 5 visible hills as synthetic +/// "user-marked" observations, perturb the view parameters, refit +/// 4. return a JSON report (recovered parameters + max reprojection error) +/// +/// This mirrors the native golden fit test; a correct WASM build reports +/// a reprojection error well below one pixel. +#[wasm_bindgen] +pub fn fit_demo(db: &[u8], jpg: &[u8]) -> String { + match fit_inner(db, jpg) { + Ok(json) => json, + Err(e) => format!(r#"{{"ok":false,"error":"{}"}}"#, e.replace('\\', "\\\\").replace('"', "\\\"")), + } +} + +fn fit_inner(db: &[u8], jpg: &[u8]) -> Result<String, String> { + use gipfel_core::metadata::{apply_image_metadata, ImageMetaData}; + use gipfel_core::panorama::Panorama; + use gipfel_core::projection::projection_from_type; + + let mut pan = Panorama::new(); + pan.load_data_from_bytes(db).map_err(|e| format!("hill db: {e}"))?; + + let mut md = ImageMetaData::new(); + md.load_image_from_bytes(jpg); + + let (w, h) = image::ImageReader::new(std::io::Cursor::new(jpg)) + .with_guessed_format() + .map_err(|e| format!("image: {e}"))? + .into_dimensions() + .map_err(|e| format!("image: {e}"))?; + if w == 0 || h == 0 { + return Err("image has zero dimensions".into()); + } + + let have = apply_image_metadata(&mut pan, &md, w, h); + if !have { + // demo fallback: a fixed Alpine viewpoint so the pipeline always runs + pan.set_view_lat(47.36); + pan.set_view_long(11.15); + pan.set_view_height(2100.0); + pan.set_center_angle(20.0); + pan.set_pitch_angle(0.0); + pan.set_roll_angle(1.0); + pan.set_scale(3000.0); + } + + let n = pan.visible.len().min(5); + if n < 2 { + return Err("fewer than 2 hills visible from this viewpoint".into()); + } + // snapshot the "observations" (what a user would have marked) + let obs: Vec<_> = pan.visible[..n].iter().map(|&i| pan.hills[i].clone()).collect(); + let known: Vec<usize> = (0..n).collect(); + + // perturb, then refit (distortion stays locked for the spike) + let center0 = pan.get_center_angle(); + let scale0 = pan.get_scale(); + pan.set_center_angle(center0 + 0.5); + pan.set_scale(scale0 * 0.95); + pan.comp_params_with(&obs, &known, false)?; + + // reprojection error of the recovered parameters against the snapshot + let proj = projection_from_type(pan.projection_type); + let mut max_err = 0.0f64; + for ob in &obs { + let (x, y) = proj.get_coordinates(ob.alph, ob.a_elev, &pan.parms); + max_err = max_err.max((x - ob.x).hypot(y - ob.y)); + } + + Ok(format!( + concat!( + "{{\"ok\":true,\"hills_in_db\":{},\"image\":\"{}x{}\",\"had_gipfel_info\":{},", + "\"observations\":{},\"viewpoint\":{{\"lat\":{:.5},\"lon\":{:.5},\"height_m\":{:.0}}},", + "\"perturbed\":{{\"center_deg\":{:.4},\"scale\":{:.1}}},", + "\"refitted\":{{\"center_deg\":{:.6},\"pitch_deg\":{:.6},\"roll_deg\":{:.6},\"scale\":{:.2}}},", + "\"max_reproj_err_px\":{:.4}}}" + ), + pan.hills.len(), + w, + h, + have, + n, + pan.get_view_lat(), + pan.get_view_long(), + pan.get_view_height(), + center0 + 0.5, + scale0 * 0.95, + pan.get_center_angle(), + pan.get_pitch_angle(), + pan.get_roll_angle(), + pan.get_scale(), + max_err, + )) +} + +#[cfg(test)] +mod tests { + use crate::fit_demo; + + /// The spike must also work natively (the wasm-bindgen attribute is a + /// no-op off-wasm), so CI here covers the whole byte-oriented pipeline. + /// Skips when the repo data files are not present (e.g. stripped checkouts). + #[test] + fn fit_demo_native_pipeline() { + let (Ok(db), Ok(jpg)) = ( + std::fs::read("../../gipfel.dat"), + std::fs::read("../../tests/golden/test.jpg"), + ) else { + eprintln!("gipfel.dat / test.jpg not found, skipping"); + return; + }; + let out = fit_demo(&db, &jpg); + assert!(out.contains(r#""ok":true"#), "fit_demo failed: {out}"); + // recovered parameters must reproduce the observations sub-pixel + let err = out + .split("max_reproj_err_px\":") + .nth(1) + .and_then(|s| s.trim_end_matches('}').parse::<f64>().ok()) + .expect("error value present"); + assert!(err < 0.01, "reprojection error too large: {out}"); + } +} |
