From f6883fa1d586a040bf228ab886b95ca64457fa34 Mon Sep 17 00:00:00 2001 From: Johannes Hofmann Date: Tue, 27 Oct 2026 13:55:35 +0100 Subject: Rename web front end to wipfel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 'gipfel web' is taken by an existing related project. The browser app is now wipfel — web based gipfel photogrammetry for mountain images: crate gipfel-web -> wipfel, updated titles, docs, plan and dev script. The shared engine crate stays gipfel-core. --- crates/gipfel-web/Cargo.toml | 42 -- crates/gipfel-web/README.md | 47 --- crates/gipfel-web/index.html | 11 - crates/gipfel-web/serve-here.sh | 12 - crates/gipfel-web/src/app.rs | 763 ----------------------------------- crates/gipfel-web/src/bridge.rs | 69 ---- crates/gipfel-web/src/canvas_view.rs | 481 ---------------------- crates/gipfel-web/src/compass.rs | 349 ---------------- crates/gipfel-web/src/main.rs | 10 - crates/gipfel-web/src/markers.rs | 60 --- crates/gipfel-web/src/widgets.rs | 77 ---- crates/gipfel-web/www/style.css | 221 ---------- crates/wipfel/Cargo.toml | 42 ++ crates/wipfel/README.md | 47 +++ crates/wipfel/index.html | 11 + crates/wipfel/serve-here.sh | 12 + crates/wipfel/src/app.rs | 763 +++++++++++++++++++++++++++++++++++ crates/wipfel/src/bridge.rs | 69 ++++ crates/wipfel/src/canvas_view.rs | 481 ++++++++++++++++++++++ crates/wipfel/src/compass.rs | 349 ++++++++++++++++ crates/wipfel/src/main.rs | 10 + crates/wipfel/src/markers.rs | 60 +++ crates/wipfel/src/widgets.rs | 77 ++++ crates/wipfel/www/style.css | 221 ++++++++++ 24 files changed, 2142 insertions(+), 2142 deletions(-) delete mode 100644 crates/gipfel-web/Cargo.toml delete mode 100644 crates/gipfel-web/README.md delete mode 100644 crates/gipfel-web/index.html delete mode 100755 crates/gipfel-web/serve-here.sh delete mode 100644 crates/gipfel-web/src/app.rs delete mode 100644 crates/gipfel-web/src/bridge.rs delete mode 100644 crates/gipfel-web/src/canvas_view.rs delete mode 100644 crates/gipfel-web/src/compass.rs delete mode 100644 crates/gipfel-web/src/main.rs delete mode 100644 crates/gipfel-web/src/markers.rs delete mode 100644 crates/gipfel-web/src/widgets.rs delete mode 100644 crates/gipfel-web/www/style.css create mode 100644 crates/wipfel/Cargo.toml create mode 100644 crates/wipfel/README.md create mode 100644 crates/wipfel/index.html create mode 100755 crates/wipfel/serve-here.sh create mode 100644 crates/wipfel/src/app.rs create mode 100644 crates/wipfel/src/bridge.rs create mode 100644 crates/wipfel/src/canvas_view.rs create mode 100644 crates/wipfel/src/compass.rs create mode 100644 crates/wipfel/src/main.rs create mode 100644 crates/wipfel/src/markers.rs create mode 100644 crates/wipfel/src/widgets.rs create mode 100644 crates/wipfel/www/style.css (limited to 'crates') diff --git a/crates/gipfel-web/Cargo.toml b/crates/gipfel-web/Cargo.toml deleted file mode 100644 index 303750a..0000000 --- a/crates/gipfel-web/Cargo.toml +++ /dev/null @@ -1,42 +0,0 @@ -[package] -name = "gipfel-web" -version.workspace = true -edition.workspace = true -license.workspace = true -description = "gipfel web — browser front end (WASM)" - -[dependencies] -gipfel-core = { path = "../gipfel-core" } -flate2 = "1" -js-sys = "0.3" -wasm-bindgen = "0.2" -wasm-bindgen-futures = "0.4" -yew = { version = "0.21", features = ["csr"] } - -[dependencies.web-sys] -version = "0.3" -features = [ - "Blob", - "CanvasRenderingContext2d", - "DataTransfer", - "Document", - "DomRect", - "DragEvent", - "Element", - "Event", - "EventTarget", - "File", - "FileList", - "HtmlCanvasElement", - "HtmlElement", - "HtmlInputElement", - "ImageBitmap", - "InputEvent", - "MouseEvent", - "PointerEvent", - "Request", - "Response", - "TextMetrics", - "Window", - "WheelEvent", -] diff --git a/crates/gipfel-web/README.md b/crates/gipfel-web/README.md deleted file mode 100644 index 74e93c5..0000000 --- a/crates/gipfel-web/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# gipfel-web - -Browser front end for gipfel (WASM, Yew + canvas 2D). See -[`/wasm-plan.md`](../../wasm-plan.md) for the overall plan and milestones. - -**Status: W1 (scaffold + image display) done** — open/drag-drop a JPEG, -pan (drag) and zoom (wheel, cursor-anchored). Peak identification, -fitting and saving arrive in W2/W3. - -## Development - -Prerequisites: [rustup](https://rustup.rs) and trunk: - -```sh -cargo install --locked trunk -``` - -Serve with hot reload: - -```sh -cd crates/gipfel-web -trunk serve --port 8090 # then open http://localhost:8090 -``` - -Release build (static output in `dist/`, serveable by any web server): - -```sh -trunk build --release -``` - -## Layout - -| File | Purpose | -|---|---| -| `src/main.rs` | entry point | -| `src/app.rs` | root component: sidebar, file loading, state | -| `src/canvas_view.rs` | viewport canvas: bitmap blit, pan/zoom | -| `src/bridge.rs` | JS glue: image decode, blob read, canvas ctx | -| `index.html` | trunk entry point (canonical trunk layout) | -| `www/style.css` | stylesheet (trunk asset) | - -## Notes - -- The base image is decoded by the browser (`createImageBitmap`), not - by the `image` crate — faster decode and GPU-backed blitting. -- The crate compiles natively (`cargo check -p gipfel-web`) so it can - be checked in CI without a wasm toolchain; runtime is wasm-only. diff --git a/crates/gipfel-web/index.html b/crates/gipfel-web/index.html deleted file mode 100644 index 32ec87f..0000000 --- a/crates/gipfel-web/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - gipfel web - - - - - diff --git a/crates/gipfel-web/serve-here.sh b/crates/gipfel-web/serve-here.sh deleted file mode 100755 index 54038a6..0000000 --- a/crates/gipfel-web/serve-here.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/sh -# Build gipfel-web for wasm and refresh the static dist dir served from -# /tmp/gipfel-web-dist (python http.server on :8090). Dev-only helper. -set -e -cd "$(dirname "$0")/../.." -cargo build -p gipfel-web --target wasm32-unknown-unknown --release -DIST=/tmp/gipfel-web-dist -mkdir -p "$DIST" -wasm-bindgen --target web --out-dir "$DIST" target/wasm32-unknown-unknown/release/gipfel-web.wasm -cp crates/gipfel-web/www/style.css "$DIST/" -gzip -9 -n -c gipfel.dat > "$DIST/gipfel.dat.gz" -echo "dist refreshed: $(ls -la "$DIST" | awk '{s+=$5} END {print s" bytes"}')" diff --git a/crates/gipfel-web/src/app.rs b/crates/gipfel-web/src/app.rs deleted file mode 100644 index f4b0de4..0000000 --- a/crates/gipfel-web/src/app.rs +++ /dev/null @@ -1,763 +0,0 @@ -//! Root component: sidebar (open/fit/status/fit-toggle) + viewport canvas. -//! Owns the `Panorama` and the marker list; refits on every marker change. - -use std::io::Read; -use std::rc::Rc; - -use flate2::read::GzDecoder; -use gipfel_core::hill::{FLAG_DUPLIC, FLAG_HIDDEN, FLAG_TRACK_POINT}; -use gipfel_core::metadata::{apply_image_metadata, ImageMetaData}; -use gipfel_core::panorama::Panorama; -use wasm_bindgen::closure::Closure; -use wasm_bindgen::JsCast; -use wasm_bindgen_futures::spawn_local; -use web_sys::{DragEvent, Event, HtmlCanvasElement, HtmlInputElement, InputEvent, MouseEvent}; -use yew::prelude::*; - -use crate::bridge; -use crate::canvas_view::{CanvasView, MarkerView, ViewCallbacks, ViewState}; -use crate::compass::{Compass, CompassData}; -use crate::markers::{self, Marker}; -use crate::widgets::{NumItem, SliderItem}; - -/// sidebar-editable view parameters (degrees / meters / mm) -#[derive(Clone, Copy, PartialEq)] -struct UiParams { - lat: f64, - lon: f64, - height: f64, - az: f64, - focal: f64, - pitch: f64, - roll: f64, - /// visibility UI value: 0.11 - height_dist_ratio (right = more visible) - vis: f64, - label_font: f32, -} - -impl Default for UiParams { - fn default() -> Self { - UiParams { - lat: 0.0, - lon: 0.0, - height: 0.0, - az: 0.0, - focal: 50.0, - pitch: 0.0, - roll: 0.0, - vis: 0.04, - label_font: 12.0, - } - } -} - -/// open Find Peak popup: anchor (screen + image coords) and search query -#[derive(Clone, PartialEq)] -struct FindPeak { - sx: f64, - sy: f64, - ix: f64, - iy: f64, - query: String, -} - -fn gunzip(gz: &[u8]) -> Result, String> { - let mut raw = Vec::new(); - GzDecoder::new(gz) - .read_to_end(&mut raw) - .map(|_| raw) - .map_err(|e| format!("gunzip: {e}")) -} - -#[derive(Properties, PartialEq)] -struct FpProps { - fp: FindPeak, - items: Vec<(String, usize)>, - on_pick: Callback, - on_query: Callback, - on_close: Callback<()>, -} - -/// searchable Find Peak dialog: type to filter, click to select -#[function_component(FindPeakPanel)] -fn find_peak_panel(p: &FpProps) -> Html { - let input_ref = use_node_ref(); - // focus the search box when the dialog opens - { - let input_ref = input_ref.clone(); - use_effect_with((), move |_| { - if let Some(i) = input_ref.cast::() { - let _ = i.focus(); - } - }); - } - let on_query = { - let on_query = p.on_query.clone(); - Callback::from(move |e: InputEvent| { - let input: HtmlInputElement = e.target_unchecked_into(); - on_query.emit(input.value()); - }) - }; - let on_close = { - let on_close = p.on_close.clone(); - Callback::from(move |_: MouseEvent| on_close.emit(())) - }; - html! { - <> -
-
-
{ "Find Peak" }
-
- -
-
- { - for p.items.iter().map(|(label, idx)| { - let onclick = { - let on_pick = p.on_pick.clone(); - let i = *idx; - Callback::from(move |_: MouseEvent| on_pick.emit(i)) - }; - html! { - - } - }) - } - if p.items.is_empty() { -

{ "no matches" }

- } -
-
- -
-
- - } -} - -#[function_component(App)] -pub fn app() -> Html { - let bitmap = use_state(|| None::); - let view = use_state(ViewState::default); - let status = use_state(|| "No image loaded.".to_string()); - let db_status = use_state(|| "Loading hill database…".to_string()); - let fit_info = use_state(String::new); - let tick = use_state(|| 0u32); - let canvas_ref = use_node_ref(); - let file_ref = use_node_ref(); - let pan = use_mut_ref(Panorama::new); - let markers = use_state(Vec::::new); - let fit_distortion = use_state(|| false); - let hover = use_state(|| Option::::None); - let vp = use_state(UiParams::default); - let img_size = use_state(|| (0u32, 0u32)); - let find_peak = use_state(|| Option::::None); - let show_hidden = use_state(|| false); - - // force a redraw when the window is resized so the canvas backing - // store tracks its CSS size (listener lives as long as the app) - { - let tick = tick.clone(); - use_effect_with((), move |_| { - let closure = Closure::wrap(Box::new(move || tick.set(*tick + 1)) as Box); - let _ = bridge::window() - .add_event_listener_with_callback("resize", closure.as_ref().unchecked_ref()); - // the listener is never removed (app lifetime); leak the closure - std::mem::forget(closure); - }); - } - - // load the hill database once at startup - { - let pan = pan.clone(); - let db_status = db_status.clone(); - use_effect_with((), move |_| { - spawn_local(async move { - let result = async { - let gz = bridge::fetch_bytes("gipfel.dat.gz").await?; - let raw = gunzip(&gz)?; - pan.borrow_mut() - .load_data_from_bytes(&raw) - .map_err(|e| format!("load: {e}")) - } - .await; - match result { - Ok(()) => { - let n = pan.borrow().hills.len(); - db_status.set(format!("Hill database: {n} peaks")); - } - Err(e) => db_status.set(format!("Hill database failed: {e}")), - } - }); - }); - } - - // Fit the current bitmap into the canvas, centered. - let fit = { - let bitmap = bitmap.clone(); - let view = view.clone(); - let canvas_ref = canvas_ref.clone(); - Callback::from(move |_: MouseEvent| { - let Some(bmp) = bitmap.as_ref() else { return }; - let (cw, ch) = canvas_ref - .cast::() - .map(|c| (c.client_width() as f64, c.client_height() as f64)) - .unwrap_or((800.0, 600.0)); - let (iw, ih) = (bmp.width() as f64, bmp.height() as f64); - if iw <= 0.0 || ih <= 0.0 || cw <= 0.0 || ch <= 0.0 { - return; - } - let scale = (cw / iw).min(ch / ih); - view.set(ViewState { - scale, - ox: (cw - iw * scale) / 2.0, - oy: (ch - ih * scale) / 2.0, - }); - }) - }; - - // refit the projection to the given markers and update the status line - let do_refit = { - let pan = pan.clone(); - let fit_info = fit_info.clone(); - let fit_distortion = fit_distortion.clone(); - Rc::new(move |mk: &[Marker]| { - if mk.is_empty() { - fit_info.set(String::new()); - return; - } - let info = { - let mut p = pan.borrow_mut(); - match markers::refit(&mut p, mk, *fit_distortion) { - Ok(()) => format!( - "fit: az {:.2}° · pitch {:.2}° · roll {:.2}° · scale {:.1}", - p.get_center_angle(), - p.get_pitch_angle(), - p.get_roll_angle(), - p.get_scale() - ), - Err(e) => format!("fit failed: {e}"), - } - }; - fit_info.set(info); - }) - }; - - // place a marker for a hill at an image position and refit - let mark_peak = { - let markers = markers.clone(); - let do_refit = do_refit.clone(); - Callback::from(move |(idx, ix, iy): (usize, f64, f64)| { - let mut mk = (*markers).clone(); - mk.retain(|m| m.hill != idx); - mk.push(Marker { hill: idx, x: ix, y: iy }); - do_refit(&mk); - markers.set(mk); - }) - }; - - // Decode selected/dropped bytes: display, read metadata, reset markers. - let load_bytes = { - let bitmap = bitmap.clone(); - let status = status.clone(); - let fit = fit.clone(); - let pan = pan.clone(); - let markers = markers.clone(); - let fit_info = fit_info.clone(); - let vp = vp.clone(); - let img_size = img_size.clone(); - let find_peak = find_peak.clone(); - Callback::from(move |(bytes, name): (Vec, String)| { - let (bitmap, status, fit, pan, markers, fit_info) = - (bitmap.clone(), status.clone(), fit.clone(), pan.clone(), markers.clone(), fit_info.clone()); - let vp = vp.clone(); - let img_size = img_size.clone(); - let find_peak = find_peak.clone(); - spawn_local(async move { - match bridge::decode_bitmap(&bytes).await { - Ok(bmp) => { - let (w, h) = (bmp.width(), bmp.height()); - let mut md = ImageMetaData::new(); - md.load_image_from_bytes(&bytes); - let have = apply_image_metadata(&mut pan.borrow_mut(), &md, w, h); - let vis = pan.borrow().visible.len(); - let u = { - let p = pan.borrow(); - UiParams { - lat: p.get_view_lat(), - lon: p.get_view_long(), - height: p.get_view_height(), - az: p.get_center_angle().rem_euclid(360.0), - focal: (p.get_scale() * 35.0 / w as f64).clamp(1.0, 300.0), - pitch: p.get_pitch_angle(), - roll: p.get_roll_angle(), - vis: (0.11 - p.height_dist_ratio).clamp(0.01, 0.1), - label_font: vp.label_font, - } - }; - vp.set(u); - img_size.set((w, h)); - let vp = if have { - format!("viewpoint from image · {vis} peaks visible") - } else { - "no gipfel/EXIF viewpoint in this image".to_string() - }; - status.set(format!("{name} — {w}×{h} px · {vp}")); - markers.set(Vec::new()); - fit_info.set(String::new()); - find_peak.set(None); - bitmap.set(Some(bmp)); - fit.emit(MouseEvent::new("fit").unwrap()); - // same nudge as the desktop app: re-fit shortly - // after the first paint so the image is guaranteed - // to appear even if layout was not ready yet - { - let fit = fit.clone(); - spawn_local(async move { - let _ = wasm_bindgen_futures::JsFuture::from( - bridge::delay_promise(120), - ) - .await; - fit.emit(MouseEvent::new("fit").unwrap()); - }); - } - } - Err(e) => status.set(format!("Failed to load {name}: {e}")), - } - }); - }) - }; - - let read_file = { - let load_bytes = load_bytes.clone(); - let status = status.clone(); - Rc::new(move |file: web_sys::File| { - let (load_bytes, status) = (load_bytes.clone(), status.clone()); - let name = file.name(); - spawn_local(async move { - match bridge::read_blob(&file).await { - Ok(bytes) => load_bytes.emit((bytes, name)), - Err(e) => status.set(format!("Failed to read {name}: {e}")), - } - }); - }) - }; - - let on_file_change = { - let read_file = read_file.clone(); - Callback::from(move |e: Event| { - let input: HtmlInputElement = e.target_unchecked_into(); - if let Some(file) = input.files().and_then(|fl| fl.item(0)) { - read_file(file); - } - }) - }; - - let on_drop = { - let read_file = read_file.clone(); - let status = status.clone(); - Callback::from(move |e: DragEvent| { - e.prevent_default(); - match e - .data_transfer() - .and_then(|dt| dt.files()) - .and_then(|fl| fl.item(0)) - { - Some(file) => read_file(file), - None => status.set("Dropped item was not a file.".to_string()), - } - }) - }; - let on_dragover = Callback::from(|e: DragEvent| e.prevent_default()); - - let open_picker = { - let file_ref = file_ref.clone(); - Callback::from(move |_: MouseEvent| { - if let Some(input) = file_ref.cast::() { - input.click(); - } - }) - }; - - let on_distortion_toggle = { - let fit_distortion = fit_distortion.clone(); - let markers = markers.clone(); - let do_refit = do_refit.clone(); - Callback::from(move |e: Event| { - let input: HtmlInputElement = e.target_unchecked_into(); - fit_distortion.set(input.checked()); - do_refit(&markers); - }) - }; - - // sidebar parameter editing: update UI state and apply to the panorama - macro_rules! param_cb { - ($field:ident, $apply:expr) => {{ - let vp = vp.clone(); - let pan = pan.clone(); - Callback::from(move |v: f64| { - let mut u = *vp; - u.$field = v; - vp.set(u); - let f: &dyn Fn(&mut Panorama, f64) = &$apply; - f(&mut pan.borrow_mut(), v); - }) - }}; - } - let on_lat = param_cb!(lat, |p: &mut Panorama, v| p.set_view_lat(v)); - let on_lon = param_cb!(lon, |p, v| p.set_view_long(v)); - let on_height = param_cb!(height, |p, v| p.set_view_height(v)); - let on_az = param_cb!(az, |p, v| p.set_center_angle(v)); - let on_pitch = param_cb!(pitch, |p, v| p.set_pitch_angle(v)); - let on_roll = param_cb!(roll, |p, v| p.set_roll_angle(v)); - let on_vis = param_cb!(vis, |p, v| p.set_height_dist_ratio(0.11 - v)); - let on_focal = { - let vp = vp.clone(); - let pan = pan.clone(); - let img_size = img_size.clone(); - Callback::from(move |v: f64| { - let mut u = *vp; - u.focal = v; - vp.set(u); - let w = img_size.0 as f64; - if w > 0.0 { - pan.borrow_mut().set_scale(v * w / 35.0); - } - }) - }; - let on_font = { - let vp = vp.clone(); - Callback::from(move |v: f64| { - let mut u = *vp; - u.label_font = v as f32; - vp.set(u); - }) - }; - let on_show_hidden = { - let show_hidden = show_hidden.clone(); - Callback::from(move |e: Event| { - let input: HtmlInputElement = e.target_unchecked_into(); - show_hidden.set(input.checked()); - }) - }; - - // compass strip: shares the image transform, drag changes azimuth - let compass_data = { - let p = pan.borrow(); - CompassData { - ptype: p.projection_type, - parms: p.parms, - center_deg: p.get_center_angle(), - zoom: view.scale, - cx: view.ox + img_size.0 as f64 * view.scale / 2.0, - max_view_angle: p.max_view_angle, - } - }; - let compass_change = { - let pan = pan.clone(); - let vp = vp.clone(); - Callback::from(move |deg: f64| { - pan.borrow_mut().set_center_angle(deg); - let mut u = *vp; - u.az = deg.rem_euclid(360.0); - vp.set(u); - }) - }; - - let fp_close = { - let find_peak = find_peak.clone(); - Callback::from(move |_: ()| find_peak.set(None)) - }; - - // Find Peak picker: searchable list over the geographically close hills - // (same candidate set and filtering as the desktop dialog) - let findpeak_popup = if let Some(fp) = &*find_peak { - let items: Vec<(String, usize)> = { - let p = pan.borrow(); - let q = fp.query.to_uppercase(); - let mut entries: Vec<(String, usize)> = p - .close - .iter() - .filter(|&&i| { - let h = &p.hills[i]; - h.flags & (FLAG_DUPLIC | FLAG_TRACK_POINT) == 0 - && (q.is_empty() || h.name.to_uppercase().contains(&q)) - }) - .map(|&i| { - ( - format!("{} ({} m)", p.hills[i].name, p.hills[i].height as i64), - i, - ) - }) - .collect(); - entries.sort_by(|a, b| a.0.cmp(&b.0)); - entries.truncate(300); - entries - }; - let on_pick = { - let mark = mark_peak.clone(); - let find_peak = find_peak.clone(); - let (ix, iy) = (fp.ix, fp.iy); - Callback::from(move |hill: usize| { - mark.emit((hill, ix, iy)); - find_peak.set(None); - }) - }; - let on_query = { - let find_peak = find_peak.clone(); - Callback::from(move |q: String| { - if let Some(mut fp) = (*find_peak).clone() { - fp.query = q; - find_peak.set(Some(fp)); - } - }) - }; - html! { - - } - } else { - Html::default() - }; - - let callbacks = ViewCallbacks { - pan: { - let view = view.clone(); - Callback::from(move |(dx, dy): (f64, f64)| { - let mut v = (*view).clone(); - v.ox += dx; - v.oy += dy; - view.set(v); - }) - }, - zoom: { - let view = view.clone(); - Callback::from(move |(cx, cy, factor): (f64, f64, f64)| { - let v = &*view; - let ns = (v.scale * factor).clamp(0.02, 64.0); - let k = ns / v.scale; - view.set(ViewState { - scale: ns, - ox: cx - (cx - v.ox) * k, - oy: cy - (cy - v.oy) * k, - }); - }) - }, - click: { - let pan = pan.clone(); - let view = view.clone(); - let mark = mark_peak.clone(); - let find_peak = find_peak.clone(); - let img_size = img_size.clone(); - let show_hidden = show_hidden.clone(); - Callback::from(move |(ix, iy): (f64, f64)| { - let scale = view.scale; - // unambiguous click right on a peak: mark directly - // (borrow must be released before mark -> do_refit!) - let near = { - let p = pan.borrow(); - markers::nearest_hill(&p, ix, iy, 10.0 / scale, *show_hidden) - }; - if let Some(idx) = near { - find_peak.set(None); - mark.emit((idx, ix, iy)); - return; - } - // otherwise open the Find Peak picker (searchable, like the - // desktop dialog): the correct peak may project far away - // while the viewpoint is still rough - let (w, h) = (img_size.0 as f64, img_size.1 as f64); - find_peak.set(Some(FindPeak { - sx: (ix + w / 2.0) * scale + view.ox, - sy: (iy + h / 2.0) * scale + view.oy, - ix, - iy, - query: String::new(), - })); - }) - }, - marker_drag: { - let markers = markers.clone(); - Callback::from(move |(i, dx, dy): (usize, f64, f64)| { - let mut mk = (*markers).clone(); - if let Some(m) = mk.get_mut(i) { - m.x += dx; - m.y += dy; - } - markers.set(mk); - }) - }, - drag_end: { - let markers = markers.clone(); - let do_refit = do_refit.clone(); - Callback::from(move |_: ()| do_refit(&markers)) - }, - context: { - let markers = markers.clone(); - let view = view.clone(); - let status = status.clone(); - let do_refit = do_refit.clone(); - Callback::from(move |(ix, iy): (f64, f64)| { - let mut mk = (*markers).clone(); - let before = mk.len(); - let r = 20.0 / view.scale; - mk.retain(|m| (m.x - ix).hypot(m.y - iy) >= r); - if mk.len() < before { - do_refit(&mk); - markers.set(mk); - status.set("Marker removed.".to_string()); - } else { - status.set("Right-click a marker to remove it.".to_string()); - } - }) - }, - hover: { - let pan = pan.clone(); - let view = view.clone(); - let hover = hover.clone(); - let show_hidden = show_hidden.clone(); - Callback::from(move |(ix, iy): (f64, f64)| { - let p = pan.borrow(); - let name = markers::nearest_hill(&p, ix, iy, 20.0 / view.scale, *show_hidden) - .map(|i| { - let h = &p.hills[i]; - format!("{} · {:.0} m", h.name, h.height) - }); - hover.set(name); - }) - }, - hover_end: { - let hover = hover.clone(); - Callback::from(move |_: ()| hover.set(None)) - }, - }; - - // overlay data for the canvas - let marker_views: Vec = { - let p = pan.borrow(); - markers - .iter() - .map(|m| MarkerView { - x: m.x, - y: m.y, - name: p.hills[m.hill].name.clone(), - }) - .collect() - }; - let candidates: Vec<(f64, f64, bool)> = { - let p = pan.borrow(); - p.visible - .iter() - .filter(|&&i| *show_hidden || p.hills[i].flags & FLAG_HIDDEN == 0) - .map(|&i| { - ( - p.hills[i].x, - p.hills[i].y, - p.hills[i].flags & FLAG_HIDDEN != 0, - ) - }) - .collect() - }; - - let zoom_pct = (view.scale * 100.0).round(); - let n_markers = markers.len(); - - html! { -
- -
-
- - { findpeak_popup.clone() } -
- if bitmap.is_some() { - - } -
-
- } -} diff --git a/crates/gipfel-web/src/bridge.rs b/crates/gipfel-web/src/bridge.rs deleted file mode 100644 index 6dbba93..0000000 --- a/crates/gipfel-web/src/bridge.rs +++ /dev/null @@ -1,69 +0,0 @@ -//! Small JS helpers: window access, browser-native image decode, blob -//! reads, canvas context — the hand-written JS boundary of the app. - -use js_sys::Uint8Array; -use wasm_bindgen::JsCast; -use wasm_bindgen_futures::JsFuture; -use web_sys::{Blob, CanvasRenderingContext2d, HtmlCanvasElement, ImageBitmap, Window}; - -pub fn window() -> Window { - web_sys::window().expect("no global window") -} - -/// Decode image bytes into a browser-native (GPU-backed) bitmap. -/// The browser does the JPEG decode and keeps the pixels where canvas -/// blitting is fast — cheaper than any pure-Rust path in wasm. -pub async fn decode_bitmap(bytes: &[u8]) -> Result { - let array = js_sys::Array::new(); - array.push(&Uint8Array::from(bytes).buffer()); - let blob = Blob::new_with_u8_array_sequence(&array).map_err(|_| "blob failed".to_string())?; - let promise = window() - .create_image_bitmap_with_blob(&blob) - .map_err(|_| "createImageBitmap failed".to_string())?; - let value = JsFuture::from(promise) - .await - .map_err(|e| format!("decode failed: {e:?}"))?; - value - .dyn_into::() - .map_err(|_| "decode produced non-bitmap".to_string()) -} - -/// Read a File/Blob fully into memory. -pub async fn read_blob(blob: &Blob) -> Result, String> { - let buf = JsFuture::from(blob.array_buffer()) - .await - .map_err(|e| format!("read failed: {e:?}"))?; - Ok(Uint8Array::new(&buf).to_vec()) -} - -/// Fetch a URL (same-origin) into memory. -pub async fn fetch_bytes(url: &str) -> Result, String> { - let resp = JsFuture::from(window().fetch_with_str(url)) - .await - .map_err(|e| format!("fetch {url}: {e:?}"))?; - let resp: web_sys::Response = resp - .dyn_into() - .map_err(|_| "bad response".to_string())?; - if !resp.ok() { - return Err(format!("{url}: HTTP {}", resp.status())); - } - let buf = JsFuture::from(resp.array_buffer().map_err(|_| "array_buffer".to_string())?) - .await - .map_err(|e| format!("body: {e:?}"))?; - Ok(Uint8Array::new(&buf).to_vec()) -} - -/// setTimeout as an awaitable Promise. -pub fn delay_promise(ms: i32) -> js_sys::Promise { - js_sys::Promise::new(&mut |resolve, _reject| { - let _ = window().set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms); - }) -} - -pub fn ctx2d(canvas: &HtmlCanvasElement) -> Option { - canvas - .get_context("2d") - .ok() - .flatten() - .and_then(|c| c.dyn_into::().ok()) -} diff --git a/crates/gipfel-web/src/canvas_view.rs b/crates/gipfel-web/src/canvas_view.rs deleted file mode 100644 index 9d4338e..0000000 --- a/crates/gipfel-web/src/canvas_view.rs +++ /dev/null @@ -1,481 +0,0 @@ -//! Viewport canvas: browser-native bitmap blitted with a pan/zoom -//! transform, plus the marker overlay and its interactions. - -use web_sys::{HtmlCanvasElement, ImageBitmap, MouseEvent, PointerEvent, WheelEvent}; -use yew::prelude::*; - -use crate::bridge; - -/// Image -> screen transform: `screen = img * scale + (ox, oy)`. -/// Same convention as the desktop viewport widget. -#[derive(Clone, Debug, PartialEq, Default)] -pub struct ViewState { - pub scale: f64, - pub ox: f64, - pub oy: f64, -} - -/// A marker in center-relative image coordinates. -#[derive(Clone, Debug, PartialEq)] -pub struct MarkerView { - pub x: f64, - pub y: f64, - pub name: String, -} - -#[derive(Clone, PartialEq)] -pub struct ViewCallbacks { - pub pan: Callback<(f64, f64)>, - /// (cursor x, cursor y, factor) — zoom anchored at the cursor. - pub zoom: Callback<(f64, f64, f64)>, - /// click on empty space: (x, y) center-relative image coords - pub click: Callback<(f64, f64)>, - /// drag a marker: (marker index, dx, dy) in image coords - pub marker_drag: Callback<(usize, f64, f64)>, - /// a marker drag finished (time to refit) - pub drag_end: Callback<()>, - /// right-click: (x, y) center-relative image coords - pub context: Callback<(f64, f64)>, - /// pointer moved over the image (not dragging): (x, y) center-relative - pub hover: Callback<(f64, f64)>, - /// pointer left the canvas - pub hover_end: Callback<()>, -} - -#[derive(Properties, PartialEq)] -pub struct Props { - pub bitmap: Option, - pub view: ViewState, - pub callbacks: ViewCallbacks, - pub canvas_ref: NodeRef, - /// bumped on window resize to force a redraw - pub tick: u32, - pub markers: Vec, - /// projected positions of all visible hills (guide dots) with their - /// hidden-by-occlusion flag - pub candidates: Vec<(f64, f64, bool)>, - /// marker label font size, screen px - pub label_font: f32, -} - -#[derive(Clone, PartialEq)] -enum DragMode { - Pan, - Marker(usize), -} - -#[derive(PartialEq)] -struct DragState { - mode: Option, - last: (f64, f64), - start: (f64, f64), - moved: bool, -} - -#[function_component(CanvasView)] -pub fn canvas_view(props: &Props) -> Html { - let drag = use_mut_ref(|| DragState { - mode: None, - last: (0.0, 0.0), - start: (0.0, 0.0), - moved: false, - }); - - // redraw on every view/bitmap/marker change and on resize ticks - { - let bitmap = props.bitmap.clone(); - let view = props.view.clone(); - let canvas_ref = props.canvas_ref.clone(); - let markers = props.markers.clone(); - let candidates = props.candidates.clone(); - let label_font = props.label_font; - use_effect_with( - (bitmap, view, props.tick, markers.clone(), candidates.clone(), label_font), - move |(bitmap, view, _tick, markers, candidates, label_font)| { - let Some(canvas) = canvas_ref.cast::() else { - return; - }; - let Some(ctx) = bridge::ctx2d(&canvas) else { - return; - }; - let dpr = bridge::window().device_pixel_ratio(); - let cw = canvas.client_width() as f64; - let ch = canvas.client_height() as f64; - // keep the backing store in sync with the CSS size - let bw = (cw * dpr).max(1.0) as u32; - let bh = (ch * dpr).max(1.0) as u32; - if canvas.width() != bw || canvas.height() != bh { - canvas.set_width(bw); - canvas.set_height(bh); - } - let _ = ctx.set_transform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0); - // web-sys 0.3: set_fill_style takes a JsValue (deprecated alias) - #[allow(deprecated)] - ctx.set_fill_style(&wasm_bindgen::JsValue::from_str("#101014")); - ctx.fill_rect(0.0, 0.0, canvas.width() as f64, canvas.height() as f64); - let Some(bitmap) = bitmap else { return }; - let _ = ctx.set_transform( - dpr * view.scale, - 0.0, - 0.0, - dpr * view.scale, - dpr * view.ox, - dpr * view.oy, - ); - let _ = ctx.draw_image_with_image_bitmap(bitmap, 0.0, 0.0); - - // overlays in screen space - let _ = ctx.set_transform(dpr, 0.0, 0.0, dpr, 0.0, 0.0); - let hw = bitmap.width() as f64 / 2.0; - let hh = bitmap.height() as f64 / 2.0; - let sx = |x: f64| (x + hw) * view.scale + view.ox; - let sy = |y: f64| (y + hh) * view.scale + view.oy; - - // guide dots for all visible peaks: dark outline ring + - // bright core so they stay visible on any photo content; - // peaks hidden by nearer terrain are drawn grey - #[allow(deprecated)] - ctx.set_fill_style(&wasm_bindgen::JsValue::from_str("rgba(0, 0, 0, 0.85)")); - for (cx, cy, _hidden) in candidates { - let (px, py) = (sx(*cx), sy(*cy)); - if px < -6.0 || py < -6.0 || px > cw + 6.0 || py > ch + 6.0 { - continue; - } - ctx.begin_path(); - let _ = ctx.arc(px, py, 4.5, 0.0, std::f64::consts::TAU); - ctx.fill(); - } - for (cx, cy, hidden) in candidates { - let (px, py) = (sx(*cx), sy(*cy)); - if px < -6.0 || py < -6.0 || px > cw + 6.0 || py > ch + 6.0 { - continue; - } - let color = if *hidden { "rgb(150, 150, 150)" } else { "rgb(110, 231, 183)" }; - #[allow(deprecated)] - ctx.set_fill_style(&wasm_bindgen::JsValue::from_str(color)); - ctx.begin_path(); - let _ = ctx.arc(px, py, 2.5, 0.0, std::f64::consts::TAU); - ctx.fill(); - } - - // markers: yellow leader lines, red crosses, collision-free - // labels (port of the desktop viewport drawing) - if !markers.is_empty() { - let label_font = *label_font; - let line_h = label_font * 1.3 + 2.0; - ctx.set_font(&format!("{label_font:.0}px system-ui, sans-serif")); - // layout runs in screen space, sorted by x - let mut order: Vec = (0..markers.len()) - .filter(|&i| { - markers[i].x.abs() * 2.0 <= bitmap.width() as f64 - && markers[i].y.abs() * 2.0 <= bitmap.height() as f64 - }) - .collect(); - order.sort_by(|&a, &b| sx(markers[a].x).total_cmp(&sx(markers[b].x))); - let xs: Vec = order.iter().map(|&i| sx(markers[i].x) as f32).collect(); - let ys: Vec = order.iter().map(|&i| sy(markers[i].y) as f32).collect(); - let widths: Vec = order - .iter() - .map(|&i| { - ctx.measure_text(&markers[i].name) - .map(|m| m.width() as f32) - .unwrap_or_else(|_| markers[i].name.len() as f32 * 7.0) - }) - .collect(); - let in_img = vec![true; order.len()]; - let entries = layout_label_y(&xs, &ys, &widths, &in_img, line_h); - - // leaders (yellow): cross, vertical, horizontal - #[allow(deprecated)] - ctx.set_stroke_style(&wasm_bindgen::JsValue::from_str("rgb(255, 230, 51)")); - ctx.set_line_width(1.0); - for (k, &i) in order.iter().enumerate() { - let (px, py) = (sx(markers[i].x), sy(markers[i].y)); - let (lx, ly) = entries[k]; - let label_line = py + ly as f64 - line_h as f64; - ctx.begin_path(); - ctx.move_to(px - 4.0, py); - ctx.line_to(px + 4.0, py); - ctx.move_to(px, py); - ctx.line_to(px, label_line); - ctx.move_to(px, label_line); - ctx.line_to(px + lx as f64, label_line); - ctx.stroke(); - } - // marker crosses (always red) - #[allow(deprecated)] - ctx.set_stroke_style(&wasm_bindgen::JsValue::from_str("rgb(255, 64, 64)")); - ctx.set_line_width(1.5); - for &i in &order { - let (px, py) = (sx(markers[i].x), sy(markers[i].y)); - ctx.begin_path(); - ctx.move_to(px - 5.0, py); - ctx.line_to(px + 5.0, py); - ctx.move_to(px, py - 5.0); - ctx.line_to(px, py + 5.0); - ctx.stroke(); - } - // labels: white on dark shadow, right-aligned at leader end - for (k, &i) in order.iter().enumerate() { - if markers[i].name.is_empty() { - continue; - } - let (px, py) = (sx(markers[i].x), sy(markers[i].y)); - let (lx, ly) = entries[k]; - let label_line = py + ly as f64 - line_h as f64; - let tx = px + lx as f64 - widths[k] as f64; - let ty = label_line - 3.0; - #[allow(deprecated)] - ctx.set_fill_style(&wasm_bindgen::JsValue::from_str("rgba(0, 0, 0, 0.85)")); - ctx.fill_text(&markers[i].name, tx + 1.0, ty + 1.0).ok(); - #[allow(deprecated)] - ctx.set_fill_style(&wasm_bindgen::JsValue::from_str("white")); - ctx.fill_text(&markers[i].name, tx, ty).ok(); - } - } - }, - ); - } - - // screen (client) -> center-relative image coordinates - let to_img = { - let canvas_ref = props.canvas_ref.clone(); - let view = props.view.clone(); - let bitmap = props.bitmap.clone(); - let w = bitmap.as_ref().map(|b| b.width() as f64).unwrap_or(0.0); - let h = bitmap.as_ref().map(|b| b.height() as f64).unwrap_or(0.0); - move |client_x: f64, client_y: f64| -> (f64, f64) { - let rect = canvas_ref - .cast::() - .map(|c| c.get_bounding_client_rect()); - let (rx, ry) = match rect { - Some(r) => (client_x - r.left(), client_y - r.top()), - None => (client_x, client_y), - }; - ( - (rx - view.ox) / view.scale - w / 2.0, - (ry - view.oy) / view.scale - h / 2.0, - ) - } - }; - - let on_pointerdown = { - let drag = drag.clone(); - let canvas_ref = props.canvas_ref.clone(); - let markers = props.markers.clone(); - let view = props.view.clone(); - let bitmap = props.bitmap.clone(); - Callback::from(move |e: PointerEvent| { - e.prevent_default(); - if let Some(c) = canvas_ref.cast::() { - let _ = c.set_pointer_capture(e.pointer_id()); - } - let rect = canvas_ref - .cast::() - .map(|c| c.get_bounding_client_rect()); - let (rx, ry) = match rect { - Some(r) => (e.client_x() as f64 - r.left(), e.client_y() as f64 - r.top()), - None => (e.client_x() as f64, e.client_y() as f64), - }; - // marker hit-test (screen space, 12 px radius) - let mut mode = DragMode::Pan; - if let Some(bmp) = &bitmap { - let hw = bmp.width() as f64 / 2.0; - let hh = bmp.height() as f64 / 2.0; - for (i, m) in markers.iter().enumerate().rev() { - let px = (m.x + hw) * view.scale + view.ox; - let py = (m.y + hh) * view.scale + view.oy; - if (rx - px).hypot(ry - py) < 12.0 { - mode = DragMode::Marker(i); - break; - } - } - } - let pos = (e.client_x() as f64, e.client_y() as f64); - let mut d = drag.borrow_mut(); - d.mode = Some(mode); - d.last = pos; - d.start = pos; - d.moved = false; - }) - }; - - let on_pointermove = { - let drag = drag.clone(); - let pan_cb = props.callbacks.pan.clone(); - let marker_drag = props.callbacks.marker_drag.clone(); - let hover = props.callbacks.hover.clone(); - let to_img = to_img.clone(); - let scale = props.view.scale; - Callback::from(move |e: PointerEvent| { - let mut d = drag.borrow_mut(); - let mode = match &d.mode { - Some(m) => m.clone(), - None => { - // free hover: report position for peak identification - let (ix, iy) = to_img(e.client_x() as f64, e.client_y() as f64); - hover.emit((ix, iy)); - return; - } - }; - let pos = (e.client_x() as f64, e.client_y() as f64); - let dx = pos.0 - d.last.0; - let dy = pos.1 - d.last.1; - d.last = pos; - if (pos.0 - d.start.0).hypot(pos.1 - d.start.1) > 3.0 { - d.moved = true; - } - if !d.moved { - return; - } - match mode { - DragMode::Pan => pan_cb.emit((dx, dy)), - DragMode::Marker(i) => marker_drag.emit((i, dx / scale, dy / scale)), - } - }) - }; - - let on_pointerleave = { - let hover_end = props.callbacks.hover_end.clone(); - Callback::from(move |_: PointerEvent| hover_end.emit(())) - }; - - let on_pointerup = { - let drag = drag.clone(); - let canvas_ref = props.canvas_ref.clone(); - let click = props.callbacks.click.clone(); - let drag_end = props.callbacks.drag_end.clone(); - let to_img = to_img.clone(); - Callback::from(move |e: PointerEvent| { - let mode = drag.borrow_mut().mode.take(); - if let Some(c) = canvas_ref.cast::() { - let _ = c.release_pointer_capture(e.pointer_id()); - } - let moved = drag.borrow().moved; - match mode { - Some(DragMode::Pan) if !moved => { - let (ix, iy) = to_img(e.client_x() as f64, e.client_y() as f64); - click.emit((ix, iy)); - } - Some(DragMode::Marker(_)) if moved => drag_end.emit(()), - _ => {} - } - }) - }; - - let on_pointercancel = { - let drag = drag.clone(); - Callback::from(move |_: PointerEvent| { - drag.borrow_mut().mode = None; - }) - }; - - let on_contextmenu = { - let context = props.callbacks.context.clone(); - let to_img = to_img.clone(); - Callback::from(move |e: MouseEvent| { - e.prevent_default(); - let (ix, iy) = to_img(e.client_x() as f64, e.client_y() as f64); - context.emit((ix, iy)); - }) - }; - - let on_wheel = { - let zoom = props.callbacks.zoom.clone(); - let canvas_ref = props.canvas_ref.clone(); - Callback::from(move |e: WheelEvent| { - e.prevent_default(); - let cx = e.client_x() as f64 - - canvas_ref - .cast::() - .map(|c| c.get_bounding_client_rect().left()) - .unwrap_or(0.0); - let cy = e.client_y() as f64 - - canvas_ref - .cast::() - .map(|c| c.get_bounding_client_rect().top()) - .unwrap_or(0.0); - let factor = 1.0015f64.powf(-(e.delta_y() as f64)); - zoom.emit((cx, cy, factor)); - }) - }; - - html! { - - } -} - -/// Port of the desktop `viewport::layout_label_y`: place labels right of -/// their crosses, pushing colliding ones up; iterate to a fixed point -/// (the C single pass can leave overlaps). Inputs must be sorted by x. -fn layout_label_y( - xs: &[f32], - ys: &[f32], - widths: &[f32], - in_img: &[bool], - line_h: f32, -) -> Vec<(f32, f32)> { - let n = xs.len(); - let mut label_x = vec![0.0f32; n]; - let mut label_y = vec![0.0f32; n]; - let cross = 4.0f32; - let overlap = |a1: f32, l1: f32, a2: f32, l2: f32| a1 <= a2 + l2 && a1 + l1 >= a2; - - for i in 0..n { - if !in_img[i] { - continue; - } - label_x[i] = widths[i] + 1.0; - label_y[i] = 0.0; - - let mut colliding: Vec = Vec::new(); - for j in (0..i).rev() { - if !in_img[j] { - continue; - } - if overlap(xs[i], label_x[i], xs[j] - cross, label_x[j]) { - colliding.push(j); - } else { - break; - } - } - colliding.sort_by(|&a, &b| { - let ya = ys[a] + label_y[a]; - let yb = ys[b] + label_y[b]; - yb.total_cmp(&ya) - }); - for _round in 0..64 { - let mut pushed = false; - for &j in &colliding { - if overlap( - ys[i] + label_y[i] - line_h, - line_h, - ys[j] + label_y[j] - line_h, - line_h, - ) || overlap(ys[i] + label_y[i] - line_h, line_h, ys[j] - cross, 2.0 * cross) - { - let ny = (ys[j] + label_y[j] - ys[i] - line_h - 2.0).round(); - if ny < label_y[i] { - label_y[i] = ny; - pushed = true; - } - } - } - if !pushed { - break; - } - } - } - - (0..n).map(|i| (label_x[i], label_y[i])).collect() -} diff --git a/crates/gipfel-web/src/compass.rs b/crates/gipfel-web/src/compass.rs deleted file mode 100644 index b539e07..0000000 --- a/crates/gipfel-web/src/compass.rs +++ /dev/null @@ -1,349 +0,0 @@ -//! Compass strip (canvas port of the desktop `compass.rs`, Aligned style): -//! shares the image's horizontal transform so each direction sits above -//! its position in the image; drag horizontally to change the view azimuth. - -use web_sys::{HtmlCanvasElement, PointerEvent};use yew::prelude::*; - -use gipfel_core::projection::{projection_from_type, ProjArgs, Projection, ProjectionType, ViewParams}; - -use crate::bridge; - -pub const STRIP_H: f64 = 56.0; - -/// Damped, clamped Newton iteration for a scalar inverse projection: find -/// `a` such that `f(a) ≈ target` (identical to the desktop solver). -pub fn newton_inverse( - target: f64, - mut f: impl FnMut(f64) -> Option, - seed: f64, - lo: f64, - hi: f64, -) -> f64 { - let mut a = seed.clamp(lo, hi); - for _ in 0..6 { - let Some(y) = f(a) else { break }; - let resid = y - target; - let h = 1e-5; - let (Some(y1), Some(y2)) = (f(a + h), f(a - h)) else { - break; - }; - let d = (y1 - y2) / (2.0 * h); - if !d.is_finite() || d.abs() < 1e-9 { - break; - } - let step = (resid / d).clamp(-0.3, 0.3); - a = (a - step).clamp(lo, hi); - if step.abs() < 1e-10 { - break; - } - } - a -} - -/// azimuth whose image x is `x_img`, measured with `c_ref` as center angle -pub fn alph_at_img_x( - ptype: ProjectionType, - proj: &dyn Projection, - p: &ViewParams, - x_img: f64, - c_ref: f64, -) -> f64 { - let mut p = *p; - p.a_center = c_ref; - let seed = match ptype { - ProjectionType::Rectilinear => c_ref + (x_img / p.scale).atan(), - ProjectionType::Cylindrical => c_ref + x_img / p.scale, - }; - let (lo, hi) = match ptype { - ProjectionType::Rectilinear => (c_ref - 1.55, c_ref + 1.55), - ProjectionType::Cylindrical => (c_ref - 3.1, c_ref + 3.1), - }; - newton_inverse( - x_img, - |a| Some(proj.mac_x(ProjArgs::from_params(&p, a, 0.0))), - seed, - lo, - hi, - ) -} - -const DIRS: [(f64, &str); 8] = [ - (0.0, "N"), - (45.0, "NE"), - (90.0, "E"), - (135.0, "SE"), - (180.0, "S"), - (225.0, "SW"), - (270.0, "W"), - (315.0, "NW"), -]; - -/// everything the strip needs; all plain data so Yew can diff it -#[derive(Clone, Copy, PartialEq)] -pub struct CompassData { - pub ptype: ProjectionType, - pub parms: ViewParams, - pub center_deg: f64, - pub zoom: f64, - /// screen x of the image center (strip shares the image transform) - pub cx: f64, - /// lens FOV half-angle limit, radians (0 = none) - pub max_view_angle: f64, -} - -#[derive(Properties, PartialEq)] -pub struct Props { - pub data: CompassData, - /// bumped on window resize to force a redraw - pub tick: u32, - /// new azimuth in degrees while dragging - pub on_change: Callback, -} - -#[function_component(Compass)] -pub fn compass(props: &Props) -> Html { - let canvas_ref = use_node_ref(); - let drag = use_mut_ref(|| Option::<(f64, f64)>::None); // (press x, center_deg) - - let d = props.data; - - // draw - { - let canvas_ref = canvas_ref.clone(); - use_effect_with((d, props.tick), move |(d, _tick)| { - let Some(canvas) = canvas_ref.cast::() else { - return; - }; - let Some(ctx) = bridge::ctx2d(&canvas) else { - return; - }; - let dpr = bridge::window().device_pixel_ratio(); - let w = canvas.client_width() as f64; - let bw = (w * dpr).max(1.0) as u32; - let bh = (STRIP_H * dpr).max(1.0) as u32; - if canvas.width() != bw || canvas.height() != bh { - canvas.set_width(bw); - canvas.set_height(bh); - } - let _ = ctx.set_transform(dpr, 0.0, 0.0, dpr, 0.0, 0.0); - - let on = "rgb(217, 217, 217)"; - let bg = "rgb(41, 41, 41)"; - let divider = "rgb(82, 82, 82)"; - let red = "rgb(255, 102, 64)"; - - let fill = |c: &str| { - #[allow(deprecated)] - ctx.set_fill_style(&wasm_bindgen::JsValue::from_str(c)); - }; - let stroke = |c: &str, width: f64| { - #[allow(deprecated)] - ctx.set_stroke_style(&wasm_bindgen::JsValue::from_str(c)); - ctx.set_line_width(width); - }; - - fill(bg); - ctx.fill_rect(0.0, 0.0, w, STRIP_H); - stroke(divider, 1.0); - ctx.begin_path(); - ctx.move_to(0.0, 0.5); - ctx.line_to(w, 0.5); - ctx.stroke(); - - let label_y = 17.0f64; // text baseline of the direction row - let y0 = (STRIP_H - 10.0).round(); // baseline of the ticks - let tri_y = 25.0f64; - let z = d.zoom; - let proj = projection_from_type(d.ptype); - let cx = d.cx; - let c = d.parms.a_center; - - let x_img_at = |alph: f64| proj.get_coordinates(alph, 0.0, &d.parms).0; - - // adaptive tick step: first that yields >= 6 px spacing - let ppd = ((x_img_at(c + 1f64.to_radians()) - x_img_at(c - 1f64.to_radians())) - * z - / 2.0) - .abs(); - let step = [1.0f64, 2.0, 5.0, 10.0, 15.0, 30.0, 45.0, 90.0] - .into_iter() - .find(|s| s * ppd >= 6.0) - .unwrap_or(90.0); - - let a_lo = alph_at_img_x(d.ptype, &*proj, &d.parms, -cx / z, c) - .min(c - std::f64::consts::PI); - let a_hi = alph_at_img_x(d.ptype, &*proj, &d.parms, (w - cx) / z, c) - .max(c + std::f64::consts::PI); - // rectilinear folds directions behind the camera onto the same - // pixels; also clamp to the lens FOV (distortion can fold - // out-of-view directions back onto the strip) - let mut fold = match d.ptype { - ProjectionType::Rectilinear => 1.535, - ProjectionType::Cylindrical => std::f64::consts::PI, - }; - if d.max_view_angle > 0.0 { - fold = fold.min(d.max_view_angle); - } - let a_lo = a_lo.max(c - fold); - let a_hi = a_hi.min(c + fold); - - // baseline - stroke(on, 1.0); - ctx.begin_path(); - ctx.move_to(0.0, y0 + 0.5); - ctx.line_to(w, y0 + 0.5); - ctx.stroke(); - - // ticks - let step_rad = step.to_radians(); - let mut a = (a_lo / step_rad).floor() * step_rad; - while a <= a_hi { - let x = cx + x_img_at(a) * z; - if x.is_finite() && x >= -1.0 && x <= w + 1.0 { - let rem = a.to_degrees().rem_euclid(45.0); - let major = rem.min(45.0 - rem) < step / 2.0; - let x = x.round(); - ctx.begin_path(); - ctx.move_to(x, y0); - ctx.line_to(x, y0 - if major { 12.0 } else { 6.0 }); - ctx.stroke(); - } - a += step_rad; - } - - // direction labels - ctx.set_font("13px system-ui, sans-serif"); - ctx.set_text_align("center"); - for (deg, name) in DIRS { - let alph = deg.to_radians(); - let rel = (alph - c + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - - std::f64::consts::PI; - if rel.abs() > fold { - continue; - } - let x = cx + x_img_at(alph) * z; - if !x.is_finite() || x < -20.0 || x > w + 20.0 { - continue; - } - fill(if deg == 0.0 { red } else { on }); - ctx.fill_text(name, x, label_y).ok(); - } - ctx.set_text_align("start"); - - // center marker: triangle + hairline + azimuth readout - fill(red); - ctx.begin_path(); - ctx.move_to(cx - 6.0, tri_y); - ctx.line_to(cx + 6.0, tri_y); - ctx.line_to(cx, tri_y + 8.0); - ctx.close_path(); - ctx.fill(); - stroke(red, 1.0); - ctx.begin_path(); - ctx.move_to(cx.round(), tri_y + 8.0); - ctx.line_to(cx.round(), y0); - ctx.stroke(); - fill(red); - ctx.fill_text(&format!("{:05.1}°", d.center_deg.rem_euclid(360.0)), cx + 10.0, tri_y + 9.0) - .ok(); - }); - } - - let local_x = { - let canvas_ref = canvas_ref.clone(); - move |client_x: f64| { - client_x - - canvas_ref - .cast::() - .map(|c| c.get_bounding_client_rect().left()) - .unwrap_or(0.0) - } - }; - - let on_pointerdown = { - let drag = drag.clone(); - let canvas_ref = canvas_ref.clone(); - let center_deg = props.data.center_deg; - Callback::from(move |e: PointerEvent| { - e.prevent_default(); - if let Some(c) = canvas_ref.cast::() { - let _ = c.set_pointer_capture(e.pointer_id()); - } - *drag.borrow_mut() = Some((e.client_x() as f64, center_deg)); - }) - }; - let on_pointermove = { - let drag = drag.clone(); - let on_change = props.on_change.clone(); - let d = props.data; - Callback::from(move |e: PointerEvent| { - let Some((x0, c0_deg)) = *drag.borrow() else { - return; - }; - let proj = projection_from_type(d.ptype); - let c0 = c0_deg.to_radians(); - let lx0 = local_x(e.client_x() as f64); - let a0 = alph_at_img_x(d.ptype, &*proj, &d.parms, (x0 - d.cx) / d.zoom, c0); - let a1 = alph_at_img_x(d.ptype, &*proj, &d.parms, (lx0 - d.cx) / d.zoom, c0); - on_change.emit((c0 - (a1 - a0)).to_degrees()); - }) - }; - let on_pointerup = { - let drag = drag.clone(); - let canvas_ref = canvas_ref.clone(); - Callback::from(move |e: PointerEvent| { - *drag.borrow_mut() = None; - if let Some(c) = canvas_ref.cast::() { - let _ = c.release_pointer_capture(e.pointer_id()); - } - }) - }; - - html! { - - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn roundtrip(ptype: ProjectionType, k0: f64, k1: f64, x0: f64) { - let proj = projection_from_type(ptype); - let mut parms = ViewParams::new(); - parms.a_center = 0.3; - parms.scale = 3000.0; - parms.k0 = k0; - parms.k1 = k1; - parms.x0 = x0; - for x in [-2500.0, -800.0, -50.0, 0.0, 120.0, 900.0, 2400.0] { - let a = alph_at_img_x(ptype, &*proj, &parms, x, parms.a_center); - let (x2, _) = proj.get_coordinates(a, 0.0, &parms); - assert!( - (x2 - x).abs() < 1e-6, - "{ptype:?} x={x}: round-trips to {x2} (alph {a})" - ); - } - } - - #[test] - fn inverse_rectilinear() { - roundtrip(ProjectionType::Rectilinear, 0.0, 0.0, 0.0); - } - #[test] - fn inverse_rectilinear_distorted() { - roundtrip(ProjectionType::Rectilinear, 0.002, -0.0003, 0.01); - } - #[test] - fn inverse_cylindrical() { - roundtrip(ProjectionType::Cylindrical, 0.0, 0.0, 0.0); - } -} diff --git a/crates/gipfel-web/src/main.rs b/crates/gipfel-web/src/main.rs deleted file mode 100644 index 741393b..0000000 --- a/crates/gipfel-web/src/main.rs +++ /dev/null @@ -1,10 +0,0 @@ -mod app; -mod bridge; -mod canvas_view; -mod compass; -mod markers; -mod widgets; - -fn main() { - yew::Renderer::::new().render(); -} diff --git a/crates/gipfel-web/src/markers.rs b/crates/gipfel-web/src/markers.rs deleted file mode 100644 index d024f2e..0000000 --- a/crates/gipfel-web/src/markers.rs +++ /dev/null @@ -1,60 +0,0 @@ -//! Markers: user observations of hills at image positions, plus the -//! refit entry point. Coordinates are center-relative image pixels, -//! matching the projection output space (same convention as the -//! desktop viewport widget). - -use gipfel_core::hill::Hill; -use gipfel_core::panorama::Panorama; - -#[derive(Clone, Debug, PartialEq)] -pub struct Marker { - /// index into `Panorama::hills` (stable: load order is preserved) - pub hill: usize, - pub x: f64, - pub y: f64, -} - -/// Refit the projection parameters to the current markers. -/// Same graduated behavior as the original: 1 marker fits the center -/// angle, 2 add the scale, 4+ the full viewpoint (+ distortion when -/// unlocked and enough markers). -pub fn refit(pan: &mut Panorama, markers: &[Marker], fit_distortion: bool) -> Result<(), String> { - if markers.is_empty() { - return Ok(()); - } - let mut obs: Vec = Vec::with_capacity(markers.len()); - for m in markers { - let mut h = pan.hills[m.hill].clone(); - h.x = m.x; - h.y = m.y; - obs.push(h); - } - let known: Vec = (0..markers.len()).collect(); - pan.comp_params_with(&obs, &known, fit_distortion) -} - -/// Nearest visible hill to image position `(x, y)`, within `max_dist` -/// image pixels. Used to resolve marker clicks. Hills hidden by the -/// occlusion heuristic are skipped unless `show_hidden`. -pub fn nearest_hill( - pan: &Panorama, - x: f64, - y: f64, - max_dist: f64, - show_hidden: bool, -) -> Option { - let mut best = None; - let mut best_d = max_dist; - for &i in &pan.visible { - if !show_hidden && pan.hills[i].flags & gipfel_core::hill::FLAG_HIDDEN != 0 { - continue; - } - let h = &pan.hills[i]; - let d = (h.x - x).hypot(h.y - y); - if d < best_d { - best_d = d; - best = Some(i); - } - } - best -} diff --git a/crates/gipfel-web/src/widgets.rs b/crates/gipfel-web/src/widgets.rs deleted file mode 100644 index 1d22bac..0000000 --- a/crates/gipfel-web/src/widgets.rs +++ /dev/null @@ -1,77 +0,0 @@ -//! Small form controls: full-width slider with value readout above -//! (mirrors the desktop `slider_item` layout) and a numeric input row. - -use web_sys::{HtmlInputElement, InputEvent}; -use yew::prelude::*; - -#[derive(Properties, PartialEq)] -pub struct SliderProps { - pub label: AttrValue, - /// formatted value shown right of the label - pub display: AttrValue, - pub value: f64, - pub min: f64, - pub max: f64, - pub step: f64, - pub onchange: Callback, -} - -#[function_component(SliderItem)] -pub fn slider_item(p: &SliderProps) -> Html { - // live update while dragging (oninput), not only on release - let oninput = { - let onchange = p.onchange.clone(); - Callback::from(move |e: InputEvent| { - let input: HtmlInputElement = e.target_unchecked_into(); - if let Ok(v) = input.value().parse::() { - onchange.emit(v); - } - }) - }; - html! { -
-
- { p.label.as_ref().to_string() } - { p.display.as_ref().to_string() } -
- -
- } -} - -#[derive(Properties, PartialEq)] -pub struct NumProps { - pub label: AttrValue, - pub value: f64, - pub step: f64, - #[prop_or(2)] - pub decimals: usize, - pub onchange: Callback, -} - -#[function_component(NumItem)] -pub fn num_item(p: &NumProps) -> Html { - let onchange = { - let onchange = p.onchange.clone(); - Callback::from(move |e: Event| { - let input: HtmlInputElement = e.target_unchecked_into(); - if let Ok(v) = input.value().parse::() { - onchange.emit(v); - } - }) - }; - let display = format!("{:.*}", p.decimals, p.value); - html! { - - } -} diff --git a/crates/gipfel-web/www/style.css b/crates/gipfel-web/www/style.css deleted file mode 100644 index 5122c43..0000000 --- a/crates/gipfel-web/www/style.css +++ /dev/null @@ -1,221 +0,0 @@ -* { - box-sizing: border-box; -} -html, -body { - margin: 0; - height: 100%; - font-family: system-ui, sans-serif; -} -.app { - display: flex; - height: 100vh; - background: #101014; - color: #e8e8ea; -} -.sidebar { - width: 300px; - padding: 16px; - background: #1a1a20; - border-right: 1px solid #2c2c34; - display: flex; - flex-direction: column; - gap: 8px; - overflow-y: auto; -} -.sidebar h1 { - margin: 0; - font-size: 22px; -} -.tag { - margin: 0 0 12px; - color: #8a8a94; - font-size: 12px; - text-transform: uppercase; - letter-spacing: 1px; -} -.sidebar button { - padding: 8px 12px; - background: #3b6fd4; - color: #fff; - border: 0; - border-radius: 6px; - font-size: 14px; - cursor: pointer; -} -.sidebar button:hover { - background: #4a7ee4; -} -.status { - font-size: 13px; - color: #c8c8d0; - word-break: break-word; -} -.hint { - font-size: 12px; - color: #8a8a94; -} -.row { - display: flex; - gap: 6px; - align-items: center; - font-size: 13px; - cursor: pointer; -} -.fitinfo { - font-size: 12px; - color: #9fd09f; - font-variant-numeric: tabular-nums; -} -.hover { - font-size: 14px; - font-weight: 600; - color: #ffffff; -} -.dim { - opacity: 0.6; -} -.hidden-file { - display: none; -} -.main { - flex: 1; - min-width: 0; - display: flex; - flex-direction: column; -} -.canvaswrap { - flex: 1; - position: relative; - min-height: 0; -} -canvas.viewport { - position: absolute; - inset: 0; - width: 100%; - height: 100%; - display: block; - touch-action: none; - cursor: grab; -} -canvas.compass { - display: block; - width: 100%; - touch-action: none; - cursor: ew-resize; -} -.section { - margin-top: 14px; - font-size: 11px; - text-transform: uppercase; - letter-spacing: 1px; - color: #8a8a94; - border-bottom: 1px solid #2c2c34; - padding-bottom: 3px; -} -.slider { - display: flex; - flex-direction: column; - gap: 2px; - margin-top: 8px; -} -.sliderhead { - display: flex; - justify-content: space-between; - font-size: 12px; - color: #c8c8d0; -} -.slider input[type="range"] { - width: 100%; -} -.numrow { - display: flex; - justify-content: space-between; - align-items: center; - gap: 8px; - font-size: 13px; - margin-top: 6px; -} -.numrow input { - width: 130px; - padding: 4px 6px; - background: #24242c; - color: #e8e8ea; - border: 1px solid #34343e; - border-radius: 4px; -} -.fpbackdrop { - position: absolute; - inset: 0; - z-index: 9; -} -.findpeak { - position: absolute; - z-index: 10; - width: 280px; - background: #1e1e26; - border: 1px solid #3a3a46; - border-radius: 6px; - box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5); - display: flex; - flex-direction: column; -} -.fpsearch { - padding: 8px; - border-bottom: 1px solid #2c2c34; -} -.fpsearch input { - width: 100%; - padding: 5px 8px; - background: #24242c; - border: 1px solid #3a3a46; - border-radius: 4px; - color: #e8e8ea; - font-size: 13px; -} -.fplist { - max-height: 320px; - overflow-y: auto; -} -.fpempty { - padding: 8px 10px; - font-size: 13px; - color: #8a8a94; - margin: 0; -} -.fpfoot { - padding: 6px 8px; - border-top: 1px solid #2c2c34; - text-align: right; -} -.fpcancel { - padding: 4px 12px; - background: #34343e; - color: #e8e8ea; - border: 0; - border-radius: 4px; - font-size: 12px; - cursor: pointer; -} -.fphead { - padding: 6px 10px; - font-size: 11px; - text-transform: uppercase; - letter-spacing: 1px; - color: #8a8a94; - border-bottom: 1px solid #2c2c34; -} -.fpitem { - display: block; - width: 100%; - text-align: left; - padding: 6px 10px; - background: none; - border: 0; - color: #e8e8ea; - font-size: 13px; - cursor: pointer; -} -.fpitem:hover { - background: #2f6fd4; -} diff --git a/crates/wipfel/Cargo.toml b/crates/wipfel/Cargo.toml new file mode 100644 index 0000000..e1e39e1 --- /dev/null +++ b/crates/wipfel/Cargo.toml @@ -0,0 +1,42 @@ +[package] +name = "wipfel" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "wipfel — web based gipfel photogrammetry for mountain images" + +[dependencies] +gipfel-core = { path = "../gipfel-core" } +flate2 = "1" +js-sys = "0.3" +wasm-bindgen = "0.2" +wasm-bindgen-futures = "0.4" +yew = { version = "0.21", features = ["csr"] } + +[dependencies.web-sys] +version = "0.3" +features = [ + "Blob", + "CanvasRenderingContext2d", + "DataTransfer", + "Document", + "DomRect", + "DragEvent", + "Element", + "Event", + "EventTarget", + "File", + "FileList", + "HtmlCanvasElement", + "HtmlElement", + "HtmlInputElement", + "ImageBitmap", + "InputEvent", + "MouseEvent", + "PointerEvent", + "Request", + "Response", + "TextMetrics", + "Window", + "WheelEvent", +] diff --git a/crates/wipfel/README.md b/crates/wipfel/README.md new file mode 100644 index 0000000..37c09ea --- /dev/null +++ b/crates/wipfel/README.md @@ -0,0 +1,47 @@ +# wipfel + +Browser front end for gipfel (WASM, Yew + canvas 2D). See +[`/wasm-plan.md`](../../wasm-plan.md) for the overall plan and milestones. + +**Status: W1 (scaffold + image display) done** — open/drag-drop a JPEG, +pan (drag) and zoom (wheel, cursor-anchored). Peak identification, +fitting and saving arrive in W2/W3. + +## Development + +Prerequisites: [rustup](https://rustup.rs) and trunk: + +```sh +cargo install --locked trunk +``` + +Serve with hot reload: + +```sh +cd crates/wipfel +trunk serve --port 8090 # then open http://localhost:8090 +``` + +Release build (static output in `dist/`, serveable by any web server): + +```sh +trunk build --release +``` + +## Layout + +| File | Purpose | +|---|---| +| `src/main.rs` | entry point | +| `src/app.rs` | root component: sidebar, file loading, state | +| `src/canvas_view.rs` | viewport canvas: bitmap blit, pan/zoom | +| `src/bridge.rs` | JS glue: image decode, blob read, canvas ctx | +| `index.html` | trunk entry point (canonical trunk layout) | +| `www/style.css` | stylesheet (trunk asset) | + +## Notes + +- The base image is decoded by the browser (`createImageBitmap`), not + by the `image` crate — faster decode and GPU-backed blitting. +- The crate compiles natively (`cargo check -p wipfel`) so it can + be checked in CI without a wasm toolchain; runtime is wasm-only. diff --git a/crates/wipfel/index.html b/crates/wipfel/index.html new file mode 100644 index 0000000..d00adbe --- /dev/null +++ b/crates/wipfel/index.html @@ -0,0 +1,11 @@ + + + + + + wipfel — web based gipfel photogrammetry + + + + + diff --git a/crates/wipfel/serve-here.sh b/crates/wipfel/serve-here.sh new file mode 100755 index 0000000..9667965 --- /dev/null +++ b/crates/wipfel/serve-here.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Build wipfel for wasm and refresh the static dist dir served from +# /tmp/wipfel-dist (python http.server on :8090). Dev-only helper. +set -e +cd "$(dirname "$0")/../.." +cargo build -p wipfel --target wasm32-unknown-unknown --release +DIST=/tmp/wipfel-dist +mkdir -p "$DIST" +wasm-bindgen --target web --out-dir "$DIST" target/wasm32-unknown-unknown/release/wipfel.wasm +cp crates/wipfel/www/style.css "$DIST/" +gzip -9 -n -c gipfel.dat > "$DIST/gipfel.dat.gz" +echo "dist refreshed: $(ls -la "$DIST" | awk '{s+=$5} END {print s" bytes"}')" diff --git a/crates/wipfel/src/app.rs b/crates/wipfel/src/app.rs new file mode 100644 index 0000000..eeb82d6 --- /dev/null +++ b/crates/wipfel/src/app.rs @@ -0,0 +1,763 @@ +//! Root component: sidebar (open/fit/status/fit-toggle) + viewport canvas. +//! Owns the `Panorama` and the marker list; refits on every marker change. + +use std::io::Read; +use std::rc::Rc; + +use flate2::read::GzDecoder; +use gipfel_core::hill::{FLAG_DUPLIC, FLAG_HIDDEN, FLAG_TRACK_POINT}; +use gipfel_core::metadata::{apply_image_metadata, ImageMetaData}; +use gipfel_core::panorama::Panorama; +use wasm_bindgen::closure::Closure; +use wasm_bindgen::JsCast; +use wasm_bindgen_futures::spawn_local; +use web_sys::{DragEvent, Event, HtmlCanvasElement, HtmlInputElement, InputEvent, MouseEvent}; +use yew::prelude::*; + +use crate::bridge; +use crate::canvas_view::{CanvasView, MarkerView, ViewCallbacks, ViewState}; +use crate::compass::{Compass, CompassData}; +use crate::markers::{self, Marker}; +use crate::widgets::{NumItem, SliderItem}; + +/// sidebar-editable view parameters (degrees / meters / mm) +#[derive(Clone, Copy, PartialEq)] +struct UiParams { + lat: f64, + lon: f64, + height: f64, + az: f64, + focal: f64, + pitch: f64, + roll: f64, + /// visibility UI value: 0.11 - height_dist_ratio (right = more visible) + vis: f64, + label_font: f32, +} + +impl Default for UiParams { + fn default() -> Self { + UiParams { + lat: 0.0, + lon: 0.0, + height: 0.0, + az: 0.0, + focal: 50.0, + pitch: 0.0, + roll: 0.0, + vis: 0.04, + label_font: 12.0, + } + } +} + +/// open Find Peak popup: anchor (screen + image coords) and search query +#[derive(Clone, PartialEq)] +struct FindPeak { + sx: f64, + sy: f64, + ix: f64, + iy: f64, + query: String, +} + +fn gunzip(gz: &[u8]) -> Result, String> { + let mut raw = Vec::new(); + GzDecoder::new(gz) + .read_to_end(&mut raw) + .map(|_| raw) + .map_err(|e| format!("gunzip: {e}")) +} + +#[derive(Properties, PartialEq)] +struct FpProps { + fp: FindPeak, + items: Vec<(String, usize)>, + on_pick: Callback, + on_query: Callback, + on_close: Callback<()>, +} + +/// searchable Find Peak dialog: type to filter, click to select +#[function_component(FindPeakPanel)] +fn find_peak_panel(p: &FpProps) -> Html { + let input_ref = use_node_ref(); + // focus the search box when the dialog opens + { + let input_ref = input_ref.clone(); + use_effect_with((), move |_| { + if let Some(i) = input_ref.cast::() { + let _ = i.focus(); + } + }); + } + let on_query = { + let on_query = p.on_query.clone(); + Callback::from(move |e: InputEvent| { + let input: HtmlInputElement = e.target_unchecked_into(); + on_query.emit(input.value()); + }) + }; + let on_close = { + let on_close = p.on_close.clone(); + Callback::from(move |_: MouseEvent| on_close.emit(())) + }; + html! { + <> +
+
+
{ "Find Peak" }
+
+ +
+
+ { + for p.items.iter().map(|(label, idx)| { + let onclick = { + let on_pick = p.on_pick.clone(); + let i = *idx; + Callback::from(move |_: MouseEvent| on_pick.emit(i)) + }; + html! { + + } + }) + } + if p.items.is_empty() { +

{ "no matches" }

+ } +
+
+ +
+
+ + } +} + +#[function_component(App)] +pub fn app() -> Html { + let bitmap = use_state(|| None::); + let view = use_state(ViewState::default); + let status = use_state(|| "No image loaded.".to_string()); + let db_status = use_state(|| "Loading hill database…".to_string()); + let fit_info = use_state(String::new); + let tick = use_state(|| 0u32); + let canvas_ref = use_node_ref(); + let file_ref = use_node_ref(); + let pan = use_mut_ref(Panorama::new); + let markers = use_state(Vec::::new); + let fit_distortion = use_state(|| false); + let hover = use_state(|| Option::::None); + let vp = use_state(UiParams::default); + let img_size = use_state(|| (0u32, 0u32)); + let find_peak = use_state(|| Option::::None); + let show_hidden = use_state(|| false); + + // force a redraw when the window is resized so the canvas backing + // store tracks its CSS size (listener lives as long as the app) + { + let tick = tick.clone(); + use_effect_with((), move |_| { + let closure = Closure::wrap(Box::new(move || tick.set(*tick + 1)) as Box); + let _ = bridge::window() + .add_event_listener_with_callback("resize", closure.as_ref().unchecked_ref()); + // the listener is never removed (app lifetime); leak the closure + std::mem::forget(closure); + }); + } + + // load the hill database once at startup + { + let pan = pan.clone(); + let db_status = db_status.clone(); + use_effect_with((), move |_| { + spawn_local(async move { + let result = async { + let gz = bridge::fetch_bytes("gipfel.dat.gz").await?; + let raw = gunzip(&gz)?; + pan.borrow_mut() + .load_data_from_bytes(&raw) + .map_err(|e| format!("load: {e}")) + } + .await; + match result { + Ok(()) => { + let n = pan.borrow().hills.len(); + db_status.set(format!("Hill database: {n} peaks")); + } + Err(e) => db_status.set(format!("Hill database failed: {e}")), + } + }); + }); + } + + // Fit the current bitmap into the canvas, centered. + let fit = { + let bitmap = bitmap.clone(); + let view = view.clone(); + let canvas_ref = canvas_ref.clone(); + Callback::from(move |_: MouseEvent| { + let Some(bmp) = bitmap.as_ref() else { return }; + let (cw, ch) = canvas_ref + .cast::() + .map(|c| (c.client_width() as f64, c.client_height() as f64)) + .unwrap_or((800.0, 600.0)); + let (iw, ih) = (bmp.width() as f64, bmp.height() as f64); + if iw <= 0.0 || ih <= 0.0 || cw <= 0.0 || ch <= 0.0 { + return; + } + let scale = (cw / iw).min(ch / ih); + view.set(ViewState { + scale, + ox: (cw - iw * scale) / 2.0, + oy: (ch - ih * scale) / 2.0, + }); + }) + }; + + // refit the projection to the given markers and update the status line + let do_refit = { + let pan = pan.clone(); + let fit_info = fit_info.clone(); + let fit_distortion = fit_distortion.clone(); + Rc::new(move |mk: &[Marker]| { + if mk.is_empty() { + fit_info.set(String::new()); + return; + } + let info = { + let mut p = pan.borrow_mut(); + match markers::refit(&mut p, mk, *fit_distortion) { + Ok(()) => format!( + "fit: az {:.2}° · pitch {:.2}° · roll {:.2}° · scale {:.1}", + p.get_center_angle(), + p.get_pitch_angle(), + p.get_roll_angle(), + p.get_scale() + ), + Err(e) => format!("fit failed: {e}"), + } + }; + fit_info.set(info); + }) + }; + + // place a marker for a hill at an image position and refit + let mark_peak = { + let markers = markers.clone(); + let do_refit = do_refit.clone(); + Callback::from(move |(idx, ix, iy): (usize, f64, f64)| { + let mut mk = (*markers).clone(); + mk.retain(|m| m.hill != idx); + mk.push(Marker { hill: idx, x: ix, y: iy }); + do_refit(&mk); + markers.set(mk); + }) + }; + + // Decode selected/dropped bytes: display, read metadata, reset markers. + let load_bytes = { + let bitmap = bitmap.clone(); + let status = status.clone(); + let fit = fit.clone(); + let pan = pan.clone(); + let markers = markers.clone(); + let fit_info = fit_info.clone(); + let vp = vp.clone(); + let img_size = img_size.clone(); + let find_peak = find_peak.clone(); + Callback::from(move |(bytes, name): (Vec, String)| { + let (bitmap, status, fit, pan, markers, fit_info) = + (bitmap.clone(), status.clone(), fit.clone(), pan.clone(), markers.clone(), fit_info.clone()); + let vp = vp.clone(); + let img_size = img_size.clone(); + let find_peak = find_peak.clone(); + spawn_local(async move { + match bridge::decode_bitmap(&bytes).await { + Ok(bmp) => { + let (w, h) = (bmp.width(), bmp.height()); + let mut md = ImageMetaData::new(); + md.load_image_from_bytes(&bytes); + let have = apply_image_metadata(&mut pan.borrow_mut(), &md, w, h); + let vis = pan.borrow().visible.len(); + let u = { + let p = pan.borrow(); + UiParams { + lat: p.get_view_lat(), + lon: p.get_view_long(), + height: p.get_view_height(), + az: p.get_center_angle().rem_euclid(360.0), + focal: (p.get_scale() * 35.0 / w as f64).clamp(1.0, 300.0), + pitch: p.get_pitch_angle(), + roll: p.get_roll_angle(), + vis: (0.11 - p.height_dist_ratio).clamp(0.01, 0.1), + label_font: vp.label_font, + } + }; + vp.set(u); + img_size.set((w, h)); + let vp = if have { + format!("viewpoint from image · {vis} peaks visible") + } else { + "no gipfel/EXIF viewpoint in this image".to_string() + }; + status.set(format!("{name} — {w}×{h} px · {vp}")); + markers.set(Vec::new()); + fit_info.set(String::new()); + find_peak.set(None); + bitmap.set(Some(bmp)); + fit.emit(MouseEvent::new("fit").unwrap()); + // same nudge as the desktop app: re-fit shortly + // after the first paint so the image is guaranteed + // to appear even if layout was not ready yet + { + let fit = fit.clone(); + spawn_local(async move { + let _ = wasm_bindgen_futures::JsFuture::from( + bridge::delay_promise(120), + ) + .await; + fit.emit(MouseEvent::new("fit").unwrap()); + }); + } + } + Err(e) => status.set(format!("Failed to load {name}: {e}")), + } + }); + }) + }; + + let read_file = { + let load_bytes = load_bytes.clone(); + let status = status.clone(); + Rc::new(move |file: web_sys::File| { + let (load_bytes, status) = (load_bytes.clone(), status.clone()); + let name = file.name(); + spawn_local(async move { + match bridge::read_blob(&file).await { + Ok(bytes) => load_bytes.emit((bytes, name)), + Err(e) => status.set(format!("Failed to read {name}: {e}")), + } + }); + }) + }; + + let on_file_change = { + let read_file = read_file.clone(); + Callback::from(move |e: Event| { + let input: HtmlInputElement = e.target_unchecked_into(); + if let Some(file) = input.files().and_then(|fl| fl.item(0)) { + read_file(file); + } + }) + }; + + let on_drop = { + let read_file = read_file.clone(); + let status = status.clone(); + Callback::from(move |e: DragEvent| { + e.prevent_default(); + match e + .data_transfer() + .and_then(|dt| dt.files()) + .and_then(|fl| fl.item(0)) + { + Some(file) => read_file(file), + None => status.set("Dropped item was not a file.".to_string()), + } + }) + }; + let on_dragover = Callback::from(|e: DragEvent| e.prevent_default()); + + let open_picker = { + let file_ref = file_ref.clone(); + Callback::from(move |_: MouseEvent| { + if let Some(input) = file_ref.cast::() { + input.click(); + } + }) + }; + + let on_distortion_toggle = { + let fit_distortion = fit_distortion.clone(); + let markers = markers.clone(); + let do_refit = do_refit.clone(); + Callback::from(move |e: Event| { + let input: HtmlInputElement = e.target_unchecked_into(); + fit_distortion.set(input.checked()); + do_refit(&markers); + }) + }; + + // sidebar parameter editing: update UI state and apply to the panorama + macro_rules! param_cb { + ($field:ident, $apply:expr) => {{ + let vp = vp.clone(); + let pan = pan.clone(); + Callback::from(move |v: f64| { + let mut u = *vp; + u.$field = v; + vp.set(u); + let f: &dyn Fn(&mut Panorama, f64) = &$apply; + f(&mut pan.borrow_mut(), v); + }) + }}; + } + let on_lat = param_cb!(lat, |p: &mut Panorama, v| p.set_view_lat(v)); + let on_lon = param_cb!(lon, |p, v| p.set_view_long(v)); + let on_height = param_cb!(height, |p, v| p.set_view_height(v)); + let on_az = param_cb!(az, |p, v| p.set_center_angle(v)); + let on_pitch = param_cb!(pitch, |p, v| p.set_pitch_angle(v)); + let on_roll = param_cb!(roll, |p, v| p.set_roll_angle(v)); + let on_vis = param_cb!(vis, |p, v| p.set_height_dist_ratio(0.11 - v)); + let on_focal = { + let vp = vp.clone(); + let pan = pan.clone(); + let img_size = img_size.clone(); + Callback::from(move |v: f64| { + let mut u = *vp; + u.focal = v; + vp.set(u); + let w = img_size.0 as f64; + if w > 0.0 { + pan.borrow_mut().set_scale(v * w / 35.0); + } + }) + }; + let on_font = { + let vp = vp.clone(); + Callback::from(move |v: f64| { + let mut u = *vp; + u.label_font = v as f32; + vp.set(u); + }) + }; + let on_show_hidden = { + let show_hidden = show_hidden.clone(); + Callback::from(move |e: Event| { + let input: HtmlInputElement = e.target_unchecked_into(); + show_hidden.set(input.checked()); + }) + }; + + // compass strip: shares the image transform, drag changes azimuth + let compass_data = { + let p = pan.borrow(); + CompassData { + ptype: p.projection_type, + parms: p.parms, + center_deg: p.get_center_angle(), + zoom: view.scale, + cx: view.ox + img_size.0 as f64 * view.scale / 2.0, + max_view_angle: p.max_view_angle, + } + }; + let compass_change = { + let pan = pan.clone(); + let vp = vp.clone(); + Callback::from(move |deg: f64| { + pan.borrow_mut().set_center_angle(deg); + let mut u = *vp; + u.az = deg.rem_euclid(360.0); + vp.set(u); + }) + }; + + let fp_close = { + let find_peak = find_peak.clone(); + Callback::from(move |_: ()| find_peak.set(None)) + }; + + // Find Peak picker: searchable list over the geographically close hills + // (same candidate set and filtering as the desktop dialog) + let findpeak_popup = if let Some(fp) = &*find_peak { + let items: Vec<(String, usize)> = { + let p = pan.borrow(); + let q = fp.query.to_uppercase(); + let mut entries: Vec<(String, usize)> = p + .close + .iter() + .filter(|&&i| { + let h = &p.hills[i]; + h.flags & (FLAG_DUPLIC | FLAG_TRACK_POINT) == 0 + && (q.is_empty() || h.name.to_uppercase().contains(&q)) + }) + .map(|&i| { + ( + format!("{} ({} m)", p.hills[i].name, p.hills[i].height as i64), + i, + ) + }) + .collect(); + entries.sort_by(|a, b| a.0.cmp(&b.0)); + entries.truncate(300); + entries + }; + let on_pick = { + let mark = mark_peak.clone(); + let find_peak = find_peak.clone(); + let (ix, iy) = (fp.ix, fp.iy); + Callback::from(move |hill: usize| { + mark.emit((hill, ix, iy)); + find_peak.set(None); + }) + }; + let on_query = { + let find_peak = find_peak.clone(); + Callback::from(move |q: String| { + if let Some(mut fp) = (*find_peak).clone() { + fp.query = q; + find_peak.set(Some(fp)); + } + }) + }; + html! { + + } + } else { + Html::default() + }; + + let callbacks = ViewCallbacks { + pan: { + let view = view.clone(); + Callback::from(move |(dx, dy): (f64, f64)| { + let mut v = (*view).clone(); + v.ox += dx; + v.oy += dy; + view.set(v); + }) + }, + zoom: { + let view = view.clone(); + Callback::from(move |(cx, cy, factor): (f64, f64, f64)| { + let v = &*view; + let ns = (v.scale * factor).clamp(0.02, 64.0); + let k = ns / v.scale; + view.set(ViewState { + scale: ns, + ox: cx - (cx - v.ox) * k, + oy: cy - (cy - v.oy) * k, + }); + }) + }, + click: { + let pan = pan.clone(); + let view = view.clone(); + let mark = mark_peak.clone(); + let find_peak = find_peak.clone(); + let img_size = img_size.clone(); + let show_hidden = show_hidden.clone(); + Callback::from(move |(ix, iy): (f64, f64)| { + let scale = view.scale; + // unambiguous click right on a peak: mark directly + // (borrow must be released before mark -> do_refit!) + let near = { + let p = pan.borrow(); + markers::nearest_hill(&p, ix, iy, 10.0 / scale, *show_hidden) + }; + if let Some(idx) = near { + find_peak.set(None); + mark.emit((idx, ix, iy)); + return; + } + // otherwise open the Find Peak picker (searchable, like the + // desktop dialog): the correct peak may project far away + // while the viewpoint is still rough + let (w, h) = (img_size.0 as f64, img_size.1 as f64); + find_peak.set(Some(FindPeak { + sx: (ix + w / 2.0) * scale + view.ox, + sy: (iy + h / 2.0) * scale + view.oy, + ix, + iy, + query: String::new(), + })); + }) + }, + marker_drag: { + let markers = markers.clone(); + Callback::from(move |(i, dx, dy): (usize, f64, f64)| { + let mut mk = (*markers).clone(); + if let Some(m) = mk.get_mut(i) { + m.x += dx; + m.y += dy; + } + markers.set(mk); + }) + }, + drag_end: { + let markers = markers.clone(); + let do_refit = do_refit.clone(); + Callback::from(move |_: ()| do_refit(&markers)) + }, + context: { + let markers = markers.clone(); + let view = view.clone(); + let status = status.clone(); + let do_refit = do_refit.clone(); + Callback::from(move |(ix, iy): (f64, f64)| { + let mut mk = (*markers).clone(); + let before = mk.len(); + let r = 20.0 / view.scale; + mk.retain(|m| (m.x - ix).hypot(m.y - iy) >= r); + if mk.len() < before { + do_refit(&mk); + markers.set(mk); + status.set("Marker removed.".to_string()); + } else { + status.set("Right-click a marker to remove it.".to_string()); + } + }) + }, + hover: { + let pan = pan.clone(); + let view = view.clone(); + let hover = hover.clone(); + let show_hidden = show_hidden.clone(); + Callback::from(move |(ix, iy): (f64, f64)| { + let p = pan.borrow(); + let name = markers::nearest_hill(&p, ix, iy, 20.0 / view.scale, *show_hidden) + .map(|i| { + let h = &p.hills[i]; + format!("{} · {:.0} m", h.name, h.height) + }); + hover.set(name); + }) + }, + hover_end: { + let hover = hover.clone(); + Callback::from(move |_: ()| hover.set(None)) + }, + }; + + // overlay data for the canvas + let marker_views: Vec = { + let p = pan.borrow(); + markers + .iter() + .map(|m| MarkerView { + x: m.x, + y: m.y, + name: p.hills[m.hill].name.clone(), + }) + .collect() + }; + let candidates: Vec<(f64, f64, bool)> = { + let p = pan.borrow(); + p.visible + .iter() + .filter(|&&i| *show_hidden || p.hills[i].flags & FLAG_HIDDEN == 0) + .map(|&i| { + ( + p.hills[i].x, + p.hills[i].y, + p.hills[i].flags & FLAG_HIDDEN != 0, + ) + }) + .collect() + }; + + let zoom_pct = (view.scale * 100.0).round(); + let n_markers = markers.len(); + + html! { +
+ +
+
+ + { findpeak_popup.clone() } +
+ if bitmap.is_some() { + + } +
+
+ } +} diff --git a/crates/wipfel/src/bridge.rs b/crates/wipfel/src/bridge.rs new file mode 100644 index 0000000..6dbba93 --- /dev/null +++ b/crates/wipfel/src/bridge.rs @@ -0,0 +1,69 @@ +//! Small JS helpers: window access, browser-native image decode, blob +//! reads, canvas context — the hand-written JS boundary of the app. + +use js_sys::Uint8Array; +use wasm_bindgen::JsCast; +use wasm_bindgen_futures::JsFuture; +use web_sys::{Blob, CanvasRenderingContext2d, HtmlCanvasElement, ImageBitmap, Window}; + +pub fn window() -> Window { + web_sys::window().expect("no global window") +} + +/// Decode image bytes into a browser-native (GPU-backed) bitmap. +/// The browser does the JPEG decode and keeps the pixels where canvas +/// blitting is fast — cheaper than any pure-Rust path in wasm. +pub async fn decode_bitmap(bytes: &[u8]) -> Result { + let array = js_sys::Array::new(); + array.push(&Uint8Array::from(bytes).buffer()); + let blob = Blob::new_with_u8_array_sequence(&array).map_err(|_| "blob failed".to_string())?; + let promise = window() + .create_image_bitmap_with_blob(&blob) + .map_err(|_| "createImageBitmap failed".to_string())?; + let value = JsFuture::from(promise) + .await + .map_err(|e| format!("decode failed: {e:?}"))?; + value + .dyn_into::() + .map_err(|_| "decode produced non-bitmap".to_string()) +} + +/// Read a File/Blob fully into memory. +pub async fn read_blob(blob: &Blob) -> Result, String> { + let buf = JsFuture::from(blob.array_buffer()) + .await + .map_err(|e| format!("read failed: {e:?}"))?; + Ok(Uint8Array::new(&buf).to_vec()) +} + +/// Fetch a URL (same-origin) into memory. +pub async fn fetch_bytes(url: &str) -> Result, String> { + let resp = JsFuture::from(window().fetch_with_str(url)) + .await + .map_err(|e| format!("fetch {url}: {e:?}"))?; + let resp: web_sys::Response = resp + .dyn_into() + .map_err(|_| "bad response".to_string())?; + if !resp.ok() { + return Err(format!("{url}: HTTP {}", resp.status())); + } + let buf = JsFuture::from(resp.array_buffer().map_err(|_| "array_buffer".to_string())?) + .await + .map_err(|e| format!("body: {e:?}"))?; + Ok(Uint8Array::new(&buf).to_vec()) +} + +/// setTimeout as an awaitable Promise. +pub fn delay_promise(ms: i32) -> js_sys::Promise { + js_sys::Promise::new(&mut |resolve, _reject| { + let _ = window().set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms); + }) +} + +pub fn ctx2d(canvas: &HtmlCanvasElement) -> Option { + canvas + .get_context("2d") + .ok() + .flatten() + .and_then(|c| c.dyn_into::().ok()) +} diff --git a/crates/wipfel/src/canvas_view.rs b/crates/wipfel/src/canvas_view.rs new file mode 100644 index 0000000..9d4338e --- /dev/null +++ b/crates/wipfel/src/canvas_view.rs @@ -0,0 +1,481 @@ +//! Viewport canvas: browser-native bitmap blitted with a pan/zoom +//! transform, plus the marker overlay and its interactions. + +use web_sys::{HtmlCanvasElement, ImageBitmap, MouseEvent, PointerEvent, WheelEvent}; +use yew::prelude::*; + +use crate::bridge; + +/// Image -> screen transform: `screen = img * scale + (ox, oy)`. +/// Same convention as the desktop viewport widget. +#[derive(Clone, Debug, PartialEq, Default)] +pub struct ViewState { + pub scale: f64, + pub ox: f64, + pub oy: f64, +} + +/// A marker in center-relative image coordinates. +#[derive(Clone, Debug, PartialEq)] +pub struct MarkerView { + pub x: f64, + pub y: f64, + pub name: String, +} + +#[derive(Clone, PartialEq)] +pub struct ViewCallbacks { + pub pan: Callback<(f64, f64)>, + /// (cursor x, cursor y, factor) — zoom anchored at the cursor. + pub zoom: Callback<(f64, f64, f64)>, + /// click on empty space: (x, y) center-relative image coords + pub click: Callback<(f64, f64)>, + /// drag a marker: (marker index, dx, dy) in image coords + pub marker_drag: Callback<(usize, f64, f64)>, + /// a marker drag finished (time to refit) + pub drag_end: Callback<()>, + /// right-click: (x, y) center-relative image coords + pub context: Callback<(f64, f64)>, + /// pointer moved over the image (not dragging): (x, y) center-relative + pub hover: Callback<(f64, f64)>, + /// pointer left the canvas + pub hover_end: Callback<()>, +} + +#[derive(Properties, PartialEq)] +pub struct Props { + pub bitmap: Option, + pub view: ViewState, + pub callbacks: ViewCallbacks, + pub canvas_ref: NodeRef, + /// bumped on window resize to force a redraw + pub tick: u32, + pub markers: Vec, + /// projected positions of all visible hills (guide dots) with their + /// hidden-by-occlusion flag + pub candidates: Vec<(f64, f64, bool)>, + /// marker label font size, screen px + pub label_font: f32, +} + +#[derive(Clone, PartialEq)] +enum DragMode { + Pan, + Marker(usize), +} + +#[derive(PartialEq)] +struct DragState { + mode: Option, + last: (f64, f64), + start: (f64, f64), + moved: bool, +} + +#[function_component(CanvasView)] +pub fn canvas_view(props: &Props) -> Html { + let drag = use_mut_ref(|| DragState { + mode: None, + last: (0.0, 0.0), + start: (0.0, 0.0), + moved: false, + }); + + // redraw on every view/bitmap/marker change and on resize ticks + { + let bitmap = props.bitmap.clone(); + let view = props.view.clone(); + let canvas_ref = props.canvas_ref.clone(); + let markers = props.markers.clone(); + let candidates = props.candidates.clone(); + let label_font = props.label_font; + use_effect_with( + (bitmap, view, props.tick, markers.clone(), candidates.clone(), label_font), + move |(bitmap, view, _tick, markers, candidates, label_font)| { + let Some(canvas) = canvas_ref.cast::() else { + return; + }; + let Some(ctx) = bridge::ctx2d(&canvas) else { + return; + }; + let dpr = bridge::window().device_pixel_ratio(); + let cw = canvas.client_width() as f64; + let ch = canvas.client_height() as f64; + // keep the backing store in sync with the CSS size + let bw = (cw * dpr).max(1.0) as u32; + let bh = (ch * dpr).max(1.0) as u32; + if canvas.width() != bw || canvas.height() != bh { + canvas.set_width(bw); + canvas.set_height(bh); + } + let _ = ctx.set_transform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0); + // web-sys 0.3: set_fill_style takes a JsValue (deprecated alias) + #[allow(deprecated)] + ctx.set_fill_style(&wasm_bindgen::JsValue::from_str("#101014")); + ctx.fill_rect(0.0, 0.0, canvas.width() as f64, canvas.height() as f64); + let Some(bitmap) = bitmap else { return }; + let _ = ctx.set_transform( + dpr * view.scale, + 0.0, + 0.0, + dpr * view.scale, + dpr * view.ox, + dpr * view.oy, + ); + let _ = ctx.draw_image_with_image_bitmap(bitmap, 0.0, 0.0); + + // overlays in screen space + let _ = ctx.set_transform(dpr, 0.0, 0.0, dpr, 0.0, 0.0); + let hw = bitmap.width() as f64 / 2.0; + let hh = bitmap.height() as f64 / 2.0; + let sx = |x: f64| (x + hw) * view.scale + view.ox; + let sy = |y: f64| (y + hh) * view.scale + view.oy; + + // guide dots for all visible peaks: dark outline ring + + // bright core so they stay visible on any photo content; + // peaks hidden by nearer terrain are drawn grey + #[allow(deprecated)] + ctx.set_fill_style(&wasm_bindgen::JsValue::from_str("rgba(0, 0, 0, 0.85)")); + for (cx, cy, _hidden) in candidates { + let (px, py) = (sx(*cx), sy(*cy)); + if px < -6.0 || py < -6.0 || px > cw + 6.0 || py > ch + 6.0 { + continue; + } + ctx.begin_path(); + let _ = ctx.arc(px, py, 4.5, 0.0, std::f64::consts::TAU); + ctx.fill(); + } + for (cx, cy, hidden) in candidates { + let (px, py) = (sx(*cx), sy(*cy)); + if px < -6.0 || py < -6.0 || px > cw + 6.0 || py > ch + 6.0 { + continue; + } + let color = if *hidden { "rgb(150, 150, 150)" } else { "rgb(110, 231, 183)" }; + #[allow(deprecated)] + ctx.set_fill_style(&wasm_bindgen::JsValue::from_str(color)); + ctx.begin_path(); + let _ = ctx.arc(px, py, 2.5, 0.0, std::f64::consts::TAU); + ctx.fill(); + } + + // markers: yellow leader lines, red crosses, collision-free + // labels (port of the desktop viewport drawing) + if !markers.is_empty() { + let label_font = *label_font; + let line_h = label_font * 1.3 + 2.0; + ctx.set_font(&format!("{label_font:.0}px system-ui, sans-serif")); + // layout runs in screen space, sorted by x + let mut order: Vec = (0..markers.len()) + .filter(|&i| { + markers[i].x.abs() * 2.0 <= bitmap.width() as f64 + && markers[i].y.abs() * 2.0 <= bitmap.height() as f64 + }) + .collect(); + order.sort_by(|&a, &b| sx(markers[a].x).total_cmp(&sx(markers[b].x))); + let xs: Vec = order.iter().map(|&i| sx(markers[i].x) as f32).collect(); + let ys: Vec = order.iter().map(|&i| sy(markers[i].y) as f32).collect(); + let widths: Vec = order + .iter() + .map(|&i| { + ctx.measure_text(&markers[i].name) + .map(|m| m.width() as f32) + .unwrap_or_else(|_| markers[i].name.len() as f32 * 7.0) + }) + .collect(); + let in_img = vec![true; order.len()]; + let entries = layout_label_y(&xs, &ys, &widths, &in_img, line_h); + + // leaders (yellow): cross, vertical, horizontal + #[allow(deprecated)] + ctx.set_stroke_style(&wasm_bindgen::JsValue::from_str("rgb(255, 230, 51)")); + ctx.set_line_width(1.0); + for (k, &i) in order.iter().enumerate() { + let (px, py) = (sx(markers[i].x), sy(markers[i].y)); + let (lx, ly) = entries[k]; + let label_line = py + ly as f64 - line_h as f64; + ctx.begin_path(); + ctx.move_to(px - 4.0, py); + ctx.line_to(px + 4.0, py); + ctx.move_to(px, py); + ctx.line_to(px, label_line); + ctx.move_to(px, label_line); + ctx.line_to(px + lx as f64, label_line); + ctx.stroke(); + } + // marker crosses (always red) + #[allow(deprecated)] + ctx.set_stroke_style(&wasm_bindgen::JsValue::from_str("rgb(255, 64, 64)")); + ctx.set_line_width(1.5); + for &i in &order { + let (px, py) = (sx(markers[i].x), sy(markers[i].y)); + ctx.begin_path(); + ctx.move_to(px - 5.0, py); + ctx.line_to(px + 5.0, py); + ctx.move_to(px, py - 5.0); + ctx.line_to(px, py + 5.0); + ctx.stroke(); + } + // labels: white on dark shadow, right-aligned at leader end + for (k, &i) in order.iter().enumerate() { + if markers[i].name.is_empty() { + continue; + } + let (px, py) = (sx(markers[i].x), sy(markers[i].y)); + let (lx, ly) = entries[k]; + let label_line = py + ly as f64 - line_h as f64; + let tx = px + lx as f64 - widths[k] as f64; + let ty = label_line - 3.0; + #[allow(deprecated)] + ctx.set_fill_style(&wasm_bindgen::JsValue::from_str("rgba(0, 0, 0, 0.85)")); + ctx.fill_text(&markers[i].name, tx + 1.0, ty + 1.0).ok(); + #[allow(deprecated)] + ctx.set_fill_style(&wasm_bindgen::JsValue::from_str("white")); + ctx.fill_text(&markers[i].name, tx, ty).ok(); + } + } + }, + ); + } + + // screen (client) -> center-relative image coordinates + let to_img = { + let canvas_ref = props.canvas_ref.clone(); + let view = props.view.clone(); + let bitmap = props.bitmap.clone(); + let w = bitmap.as_ref().map(|b| b.width() as f64).unwrap_or(0.0); + let h = bitmap.as_ref().map(|b| b.height() as f64).unwrap_or(0.0); + move |client_x: f64, client_y: f64| -> (f64, f64) { + let rect = canvas_ref + .cast::() + .map(|c| c.get_bounding_client_rect()); + let (rx, ry) = match rect { + Some(r) => (client_x - r.left(), client_y - r.top()), + None => (client_x, client_y), + }; + ( + (rx - view.ox) / view.scale - w / 2.0, + (ry - view.oy) / view.scale - h / 2.0, + ) + } + }; + + let on_pointerdown = { + let drag = drag.clone(); + let canvas_ref = props.canvas_ref.clone(); + let markers = props.markers.clone(); + let view = props.view.clone(); + let bitmap = props.bitmap.clone(); + Callback::from(move |e: PointerEvent| { + e.prevent_default(); + if let Some(c) = canvas_ref.cast::() { + let _ = c.set_pointer_capture(e.pointer_id()); + } + let rect = canvas_ref + .cast::() + .map(|c| c.get_bounding_client_rect()); + let (rx, ry) = match rect { + Some(r) => (e.client_x() as f64 - r.left(), e.client_y() as f64 - r.top()), + None => (e.client_x() as f64, e.client_y() as f64), + }; + // marker hit-test (screen space, 12 px radius) + let mut mode = DragMode::Pan; + if let Some(bmp) = &bitmap { + let hw = bmp.width() as f64 / 2.0; + let hh = bmp.height() as f64 / 2.0; + for (i, m) in markers.iter().enumerate().rev() { + let px = (m.x + hw) * view.scale + view.ox; + let py = (m.y + hh) * view.scale + view.oy; + if (rx - px).hypot(ry - py) < 12.0 { + mode = DragMode::Marker(i); + break; + } + } + } + let pos = (e.client_x() as f64, e.client_y() as f64); + let mut d = drag.borrow_mut(); + d.mode = Some(mode); + d.last = pos; + d.start = pos; + d.moved = false; + }) + }; + + let on_pointermove = { + let drag = drag.clone(); + let pan_cb = props.callbacks.pan.clone(); + let marker_drag = props.callbacks.marker_drag.clone(); + let hover = props.callbacks.hover.clone(); + let to_img = to_img.clone(); + let scale = props.view.scale; + Callback::from(move |e: PointerEvent| { + let mut d = drag.borrow_mut(); + let mode = match &d.mode { + Some(m) => m.clone(), + None => { + // free hover: report position for peak identification + let (ix, iy) = to_img(e.client_x() as f64, e.client_y() as f64); + hover.emit((ix, iy)); + return; + } + }; + let pos = (e.client_x() as f64, e.client_y() as f64); + let dx = pos.0 - d.last.0; + let dy = pos.1 - d.last.1; + d.last = pos; + if (pos.0 - d.start.0).hypot(pos.1 - d.start.1) > 3.0 { + d.moved = true; + } + if !d.moved { + return; + } + match mode { + DragMode::Pan => pan_cb.emit((dx, dy)), + DragMode::Marker(i) => marker_drag.emit((i, dx / scale, dy / scale)), + } + }) + }; + + let on_pointerleave = { + let hover_end = props.callbacks.hover_end.clone(); + Callback::from(move |_: PointerEvent| hover_end.emit(())) + }; + + let on_pointerup = { + let drag = drag.clone(); + let canvas_ref = props.canvas_ref.clone(); + let click = props.callbacks.click.clone(); + let drag_end = props.callbacks.drag_end.clone(); + let to_img = to_img.clone(); + Callback::from(move |e: PointerEvent| { + let mode = drag.borrow_mut().mode.take(); + if let Some(c) = canvas_ref.cast::() { + let _ = c.release_pointer_capture(e.pointer_id()); + } + let moved = drag.borrow().moved; + match mode { + Some(DragMode::Pan) if !moved => { + let (ix, iy) = to_img(e.client_x() as f64, e.client_y() as f64); + click.emit((ix, iy)); + } + Some(DragMode::Marker(_)) if moved => drag_end.emit(()), + _ => {} + } + }) + }; + + let on_pointercancel = { + let drag = drag.clone(); + Callback::from(move |_: PointerEvent| { + drag.borrow_mut().mode = None; + }) + }; + + let on_contextmenu = { + let context = props.callbacks.context.clone(); + let to_img = to_img.clone(); + Callback::from(move |e: MouseEvent| { + e.prevent_default(); + let (ix, iy) = to_img(e.client_x() as f64, e.client_y() as f64); + context.emit((ix, iy)); + }) + }; + + let on_wheel = { + let zoom = props.callbacks.zoom.clone(); + let canvas_ref = props.canvas_ref.clone(); + Callback::from(move |e: WheelEvent| { + e.prevent_default(); + let cx = e.client_x() as f64 + - canvas_ref + .cast::() + .map(|c| c.get_bounding_client_rect().left()) + .unwrap_or(0.0); + let cy = e.client_y() as f64 + - canvas_ref + .cast::() + .map(|c| c.get_bounding_client_rect().top()) + .unwrap_or(0.0); + let factor = 1.0015f64.powf(-(e.delta_y() as f64)); + zoom.emit((cx, cy, factor)); + }) + }; + + html! { + + } +} + +/// Port of the desktop `viewport::layout_label_y`: place labels right of +/// their crosses, pushing colliding ones up; iterate to a fixed point +/// (the C single pass can leave overlaps). Inputs must be sorted by x. +fn layout_label_y( + xs: &[f32], + ys: &[f32], + widths: &[f32], + in_img: &[bool], + line_h: f32, +) -> Vec<(f32, f32)> { + let n = xs.len(); + let mut label_x = vec![0.0f32; n]; + let mut label_y = vec![0.0f32; n]; + let cross = 4.0f32; + let overlap = |a1: f32, l1: f32, a2: f32, l2: f32| a1 <= a2 + l2 && a1 + l1 >= a2; + + for i in 0..n { + if !in_img[i] { + continue; + } + label_x[i] = widths[i] + 1.0; + label_y[i] = 0.0; + + let mut colliding: Vec = Vec::new(); + for j in (0..i).rev() { + if !in_img[j] { + continue; + } + if overlap(xs[i], label_x[i], xs[j] - cross, label_x[j]) { + colliding.push(j); + } else { + break; + } + } + colliding.sort_by(|&a, &b| { + let ya = ys[a] + label_y[a]; + let yb = ys[b] + label_y[b]; + yb.total_cmp(&ya) + }); + for _round in 0..64 { + let mut pushed = false; + for &j in &colliding { + if overlap( + ys[i] + label_y[i] - line_h, + line_h, + ys[j] + label_y[j] - line_h, + line_h, + ) || overlap(ys[i] + label_y[i] - line_h, line_h, ys[j] - cross, 2.0 * cross) + { + let ny = (ys[j] + label_y[j] - ys[i] - line_h - 2.0).round(); + if ny < label_y[i] { + label_y[i] = ny; + pushed = true; + } + } + } + if !pushed { + break; + } + } + } + + (0..n).map(|i| (label_x[i], label_y[i])).collect() +} diff --git a/crates/wipfel/src/compass.rs b/crates/wipfel/src/compass.rs new file mode 100644 index 0000000..b539e07 --- /dev/null +++ b/crates/wipfel/src/compass.rs @@ -0,0 +1,349 @@ +//! Compass strip (canvas port of the desktop `compass.rs`, Aligned style): +//! shares the image's horizontal transform so each direction sits above +//! its position in the image; drag horizontally to change the view azimuth. + +use web_sys::{HtmlCanvasElement, PointerEvent};use yew::prelude::*; + +use gipfel_core::projection::{projection_from_type, ProjArgs, Projection, ProjectionType, ViewParams}; + +use crate::bridge; + +pub const STRIP_H: f64 = 56.0; + +/// Damped, clamped Newton iteration for a scalar inverse projection: find +/// `a` such that `f(a) ≈ target` (identical to the desktop solver). +pub fn newton_inverse( + target: f64, + mut f: impl FnMut(f64) -> Option, + seed: f64, + lo: f64, + hi: f64, +) -> f64 { + let mut a = seed.clamp(lo, hi); + for _ in 0..6 { + let Some(y) = f(a) else { break }; + let resid = y - target; + let h = 1e-5; + let (Some(y1), Some(y2)) = (f(a + h), f(a - h)) else { + break; + }; + let d = (y1 - y2) / (2.0 * h); + if !d.is_finite() || d.abs() < 1e-9 { + break; + } + let step = (resid / d).clamp(-0.3, 0.3); + a = (a - step).clamp(lo, hi); + if step.abs() < 1e-10 { + break; + } + } + a +} + +/// azimuth whose image x is `x_img`, measured with `c_ref` as center angle +pub fn alph_at_img_x( + ptype: ProjectionType, + proj: &dyn Projection, + p: &ViewParams, + x_img: f64, + c_ref: f64, +) -> f64 { + let mut p = *p; + p.a_center = c_ref; + let seed = match ptype { + ProjectionType::Rectilinear => c_ref + (x_img / p.scale).atan(), + ProjectionType::Cylindrical => c_ref + x_img / p.scale, + }; + let (lo, hi) = match ptype { + ProjectionType::Rectilinear => (c_ref - 1.55, c_ref + 1.55), + ProjectionType::Cylindrical => (c_ref - 3.1, c_ref + 3.1), + }; + newton_inverse( + x_img, + |a| Some(proj.mac_x(ProjArgs::from_params(&p, a, 0.0))), + seed, + lo, + hi, + ) +} + +const DIRS: [(f64, &str); 8] = [ + (0.0, "N"), + (45.0, "NE"), + (90.0, "E"), + (135.0, "SE"), + (180.0, "S"), + (225.0, "SW"), + (270.0, "W"), + (315.0, "NW"), +]; + +/// everything the strip needs; all plain data so Yew can diff it +#[derive(Clone, Copy, PartialEq)] +pub struct CompassData { + pub ptype: ProjectionType, + pub parms: ViewParams, + pub center_deg: f64, + pub zoom: f64, + /// screen x of the image center (strip shares the image transform) + pub cx: f64, + /// lens FOV half-angle limit, radians (0 = none) + pub max_view_angle: f64, +} + +#[derive(Properties, PartialEq)] +pub struct Props { + pub data: CompassData, + /// bumped on window resize to force a redraw + pub tick: u32, + /// new azimuth in degrees while dragging + pub on_change: Callback, +} + +#[function_component(Compass)] +pub fn compass(props: &Props) -> Html { + let canvas_ref = use_node_ref(); + let drag = use_mut_ref(|| Option::<(f64, f64)>::None); // (press x, center_deg) + + let d = props.data; + + // draw + { + let canvas_ref = canvas_ref.clone(); + use_effect_with((d, props.tick), move |(d, _tick)| { + let Some(canvas) = canvas_ref.cast::() else { + return; + }; + let Some(ctx) = bridge::ctx2d(&canvas) else { + return; + }; + let dpr = bridge::window().device_pixel_ratio(); + let w = canvas.client_width() as f64; + let bw = (w * dpr).max(1.0) as u32; + let bh = (STRIP_H * dpr).max(1.0) as u32; + if canvas.width() != bw || canvas.height() != bh { + canvas.set_width(bw); + canvas.set_height(bh); + } + let _ = ctx.set_transform(dpr, 0.0, 0.0, dpr, 0.0, 0.0); + + let on = "rgb(217, 217, 217)"; + let bg = "rgb(41, 41, 41)"; + let divider = "rgb(82, 82, 82)"; + let red = "rgb(255, 102, 64)"; + + let fill = |c: &str| { + #[allow(deprecated)] + ctx.set_fill_style(&wasm_bindgen::JsValue::from_str(c)); + }; + let stroke = |c: &str, width: f64| { + #[allow(deprecated)] + ctx.set_stroke_style(&wasm_bindgen::JsValue::from_str(c)); + ctx.set_line_width(width); + }; + + fill(bg); + ctx.fill_rect(0.0, 0.0, w, STRIP_H); + stroke(divider, 1.0); + ctx.begin_path(); + ctx.move_to(0.0, 0.5); + ctx.line_to(w, 0.5); + ctx.stroke(); + + let label_y = 17.0f64; // text baseline of the direction row + let y0 = (STRIP_H - 10.0).round(); // baseline of the ticks + let tri_y = 25.0f64; + let z = d.zoom; + let proj = projection_from_type(d.ptype); + let cx = d.cx; + let c = d.parms.a_center; + + let x_img_at = |alph: f64| proj.get_coordinates(alph, 0.0, &d.parms).0; + + // adaptive tick step: first that yields >= 6 px spacing + let ppd = ((x_img_at(c + 1f64.to_radians()) - x_img_at(c - 1f64.to_radians())) + * z + / 2.0) + .abs(); + let step = [1.0f64, 2.0, 5.0, 10.0, 15.0, 30.0, 45.0, 90.0] + .into_iter() + .find(|s| s * ppd >= 6.0) + .unwrap_or(90.0); + + let a_lo = alph_at_img_x(d.ptype, &*proj, &d.parms, -cx / z, c) + .min(c - std::f64::consts::PI); + let a_hi = alph_at_img_x(d.ptype, &*proj, &d.parms, (w - cx) / z, c) + .max(c + std::f64::consts::PI); + // rectilinear folds directions behind the camera onto the same + // pixels; also clamp to the lens FOV (distortion can fold + // out-of-view directions back onto the strip) + let mut fold = match d.ptype { + ProjectionType::Rectilinear => 1.535, + ProjectionType::Cylindrical => std::f64::consts::PI, + }; + if d.max_view_angle > 0.0 { + fold = fold.min(d.max_view_angle); + } + let a_lo = a_lo.max(c - fold); + let a_hi = a_hi.min(c + fold); + + // baseline + stroke(on, 1.0); + ctx.begin_path(); + ctx.move_to(0.0, y0 + 0.5); + ctx.line_to(w, y0 + 0.5); + ctx.stroke(); + + // ticks + let step_rad = step.to_radians(); + let mut a = (a_lo / step_rad).floor() * step_rad; + while a <= a_hi { + let x = cx + x_img_at(a) * z; + if x.is_finite() && x >= -1.0 && x <= w + 1.0 { + let rem = a.to_degrees().rem_euclid(45.0); + let major = rem.min(45.0 - rem) < step / 2.0; + let x = x.round(); + ctx.begin_path(); + ctx.move_to(x, y0); + ctx.line_to(x, y0 - if major { 12.0 } else { 6.0 }); + ctx.stroke(); + } + a += step_rad; + } + + // direction labels + ctx.set_font("13px system-ui, sans-serif"); + ctx.set_text_align("center"); + for (deg, name) in DIRS { + let alph = deg.to_radians(); + let rel = (alph - c + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) + - std::f64::consts::PI; + if rel.abs() > fold { + continue; + } + let x = cx + x_img_at(alph) * z; + if !x.is_finite() || x < -20.0 || x > w + 20.0 { + continue; + } + fill(if deg == 0.0 { red } else { on }); + ctx.fill_text(name, x, label_y).ok(); + } + ctx.set_text_align("start"); + + // center marker: triangle + hairline + azimuth readout + fill(red); + ctx.begin_path(); + ctx.move_to(cx - 6.0, tri_y); + ctx.line_to(cx + 6.0, tri_y); + ctx.line_to(cx, tri_y + 8.0); + ctx.close_path(); + ctx.fill(); + stroke(red, 1.0); + ctx.begin_path(); + ctx.move_to(cx.round(), tri_y + 8.0); + ctx.line_to(cx.round(), y0); + ctx.stroke(); + fill(red); + ctx.fill_text(&format!("{:05.1}°", d.center_deg.rem_euclid(360.0)), cx + 10.0, tri_y + 9.0) + .ok(); + }); + } + + let local_x = { + let canvas_ref = canvas_ref.clone(); + move |client_x: f64| { + client_x + - canvas_ref + .cast::() + .map(|c| c.get_bounding_client_rect().left()) + .unwrap_or(0.0) + } + }; + + let on_pointerdown = { + let drag = drag.clone(); + let canvas_ref = canvas_ref.clone(); + let center_deg = props.data.center_deg; + Callback::from(move |e: PointerEvent| { + e.prevent_default(); + if let Some(c) = canvas_ref.cast::() { + let _ = c.set_pointer_capture(e.pointer_id()); + } + *drag.borrow_mut() = Some((e.client_x() as f64, center_deg)); + }) + }; + let on_pointermove = { + let drag = drag.clone(); + let on_change = props.on_change.clone(); + let d = props.data; + Callback::from(move |e: PointerEvent| { + let Some((x0, c0_deg)) = *drag.borrow() else { + return; + }; + let proj = projection_from_type(d.ptype); + let c0 = c0_deg.to_radians(); + let lx0 = local_x(e.client_x() as f64); + let a0 = alph_at_img_x(d.ptype, &*proj, &d.parms, (x0 - d.cx) / d.zoom, c0); + let a1 = alph_at_img_x(d.ptype, &*proj, &d.parms, (lx0 - d.cx) / d.zoom, c0); + on_change.emit((c0 - (a1 - a0)).to_degrees()); + }) + }; + let on_pointerup = { + let drag = drag.clone(); + let canvas_ref = canvas_ref.clone(); + Callback::from(move |e: PointerEvent| { + *drag.borrow_mut() = None; + if let Some(c) = canvas_ref.cast::() { + let _ = c.release_pointer_capture(e.pointer_id()); + } + }) + }; + + html! { + + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn roundtrip(ptype: ProjectionType, k0: f64, k1: f64, x0: f64) { + let proj = projection_from_type(ptype); + let mut parms = ViewParams::new(); + parms.a_center = 0.3; + parms.scale = 3000.0; + parms.k0 = k0; + parms.k1 = k1; + parms.x0 = x0; + for x in [-2500.0, -800.0, -50.0, 0.0, 120.0, 900.0, 2400.0] { + let a = alph_at_img_x(ptype, &*proj, &parms, x, parms.a_center); + let (x2, _) = proj.get_coordinates(a, 0.0, &parms); + assert!( + (x2 - x).abs() < 1e-6, + "{ptype:?} x={x}: round-trips to {x2} (alph {a})" + ); + } + } + + #[test] + fn inverse_rectilinear() { + roundtrip(ProjectionType::Rectilinear, 0.0, 0.0, 0.0); + } + #[test] + fn inverse_rectilinear_distorted() { + roundtrip(ProjectionType::Rectilinear, 0.002, -0.0003, 0.01); + } + #[test] + fn inverse_cylindrical() { + roundtrip(ProjectionType::Cylindrical, 0.0, 0.0, 0.0); + } +} diff --git a/crates/wipfel/src/main.rs b/crates/wipfel/src/main.rs new file mode 100644 index 0000000..741393b --- /dev/null +++ b/crates/wipfel/src/main.rs @@ -0,0 +1,10 @@ +mod app; +mod bridge; +mod canvas_view; +mod compass; +mod markers; +mod widgets; + +fn main() { + yew::Renderer::::new().render(); +} diff --git a/crates/wipfel/src/markers.rs b/crates/wipfel/src/markers.rs new file mode 100644 index 0000000..d024f2e --- /dev/null +++ b/crates/wipfel/src/markers.rs @@ -0,0 +1,60 @@ +//! Markers: user observations of hills at image positions, plus the +//! refit entry point. Coordinates are center-relative image pixels, +//! matching the projection output space (same convention as the +//! desktop viewport widget). + +use gipfel_core::hill::Hill; +use gipfel_core::panorama::Panorama; + +#[derive(Clone, Debug, PartialEq)] +pub struct Marker { + /// index into `Panorama::hills` (stable: load order is preserved) + pub hill: usize, + pub x: f64, + pub y: f64, +} + +/// Refit the projection parameters to the current markers. +/// Same graduated behavior as the original: 1 marker fits the center +/// angle, 2 add the scale, 4+ the full viewpoint (+ distortion when +/// unlocked and enough markers). +pub fn refit(pan: &mut Panorama, markers: &[Marker], fit_distortion: bool) -> Result<(), String> { + if markers.is_empty() { + return Ok(()); + } + let mut obs: Vec = Vec::with_capacity(markers.len()); + for m in markers { + let mut h = pan.hills[m.hill].clone(); + h.x = m.x; + h.y = m.y; + obs.push(h); + } + let known: Vec = (0..markers.len()).collect(); + pan.comp_params_with(&obs, &known, fit_distortion) +} + +/// Nearest visible hill to image position `(x, y)`, within `max_dist` +/// image pixels. Used to resolve marker clicks. Hills hidden by the +/// occlusion heuristic are skipped unless `show_hidden`. +pub fn nearest_hill( + pan: &Panorama, + x: f64, + y: f64, + max_dist: f64, + show_hidden: bool, +) -> Option { + let mut best = None; + let mut best_d = max_dist; + for &i in &pan.visible { + if !show_hidden && pan.hills[i].flags & gipfel_core::hill::FLAG_HIDDEN != 0 { + continue; + } + let h = &pan.hills[i]; + let d = (h.x - x).hypot(h.y - y); + if d < best_d { + best_d = d; + best = Some(i); + } + } + best +} diff --git a/crates/wipfel/src/widgets.rs b/crates/wipfel/src/widgets.rs new file mode 100644 index 0000000..1d22bac --- /dev/null +++ b/crates/wipfel/src/widgets.rs @@ -0,0 +1,77 @@ +//! Small form controls: full-width slider with value readout above +//! (mirrors the desktop `slider_item` layout) and a numeric input row. + +use web_sys::{HtmlInputElement, InputEvent}; +use yew::prelude::*; + +#[derive(Properties, PartialEq)] +pub struct SliderProps { + pub label: AttrValue, + /// formatted value shown right of the label + pub display: AttrValue, + pub value: f64, + pub min: f64, + pub max: f64, + pub step: f64, + pub onchange: Callback, +} + +#[function_component(SliderItem)] +pub fn slider_item(p: &SliderProps) -> Html { + // live update while dragging (oninput), not only on release + let oninput = { + let onchange = p.onchange.clone(); + Callback::from(move |e: InputEvent| { + let input: HtmlInputElement = e.target_unchecked_into(); + if let Ok(v) = input.value().parse::() { + onchange.emit(v); + } + }) + }; + html! { +
+
+ { p.label.as_ref().to_string() } + { p.display.as_ref().to_string() } +
+ +
+ } +} + +#[derive(Properties, PartialEq)] +pub struct NumProps { + pub label: AttrValue, + pub value: f64, + pub step: f64, + #[prop_or(2)] + pub decimals: usize, + pub onchange: Callback, +} + +#[function_component(NumItem)] +pub fn num_item(p: &NumProps) -> Html { + let onchange = { + let onchange = p.onchange.clone(); + Callback::from(move |e: Event| { + let input: HtmlInputElement = e.target_unchecked_into(); + if let Ok(v) = input.value().parse::() { + onchange.emit(v); + } + }) + }; + let display = format!("{:.*}", p.decimals, p.value); + html! { + + } +} diff --git a/crates/wipfel/www/style.css b/crates/wipfel/www/style.css new file mode 100644 index 0000000..5122c43 --- /dev/null +++ b/crates/wipfel/www/style.css @@ -0,0 +1,221 @@ +* { + box-sizing: border-box; +} +html, +body { + margin: 0; + height: 100%; + font-family: system-ui, sans-serif; +} +.app { + display: flex; + height: 100vh; + background: #101014; + color: #e8e8ea; +} +.sidebar { + width: 300px; + padding: 16px; + background: #1a1a20; + border-right: 1px solid #2c2c34; + display: flex; + flex-direction: column; + gap: 8px; + overflow-y: auto; +} +.sidebar h1 { + margin: 0; + font-size: 22px; +} +.tag { + margin: 0 0 12px; + color: #8a8a94; + font-size: 12px; + text-transform: uppercase; + letter-spacing: 1px; +} +.sidebar button { + padding: 8px 12px; + background: #3b6fd4; + color: #fff; + border: 0; + border-radius: 6px; + font-size: 14px; + cursor: pointer; +} +.sidebar button:hover { + background: #4a7ee4; +} +.status { + font-size: 13px; + color: #c8c8d0; + word-break: break-word; +} +.hint { + font-size: 12px; + color: #8a8a94; +} +.row { + display: flex; + gap: 6px; + align-items: center; + font-size: 13px; + cursor: pointer; +} +.fitinfo { + font-size: 12px; + color: #9fd09f; + font-variant-numeric: tabular-nums; +} +.hover { + font-size: 14px; + font-weight: 600; + color: #ffffff; +} +.dim { + opacity: 0.6; +} +.hidden-file { + display: none; +} +.main { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; +} +.canvaswrap { + flex: 1; + position: relative; + min-height: 0; +} +canvas.viewport { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + display: block; + touch-action: none; + cursor: grab; +} +canvas.compass { + display: block; + width: 100%; + touch-action: none; + cursor: ew-resize; +} +.section { + margin-top: 14px; + font-size: 11px; + text-transform: uppercase; + letter-spacing: 1px; + color: #8a8a94; + border-bottom: 1px solid #2c2c34; + padding-bottom: 3px; +} +.slider { + display: flex; + flex-direction: column; + gap: 2px; + margin-top: 8px; +} +.sliderhead { + display: flex; + justify-content: space-between; + font-size: 12px; + color: #c8c8d0; +} +.slider input[type="range"] { + width: 100%; +} +.numrow { + display: flex; + justify-content: space-between; + align-items: center; + gap: 8px; + font-size: 13px; + margin-top: 6px; +} +.numrow input { + width: 130px; + padding: 4px 6px; + background: #24242c; + color: #e8e8ea; + border: 1px solid #34343e; + border-radius: 4px; +} +.fpbackdrop { + position: absolute; + inset: 0; + z-index: 9; +} +.findpeak { + position: absolute; + z-index: 10; + width: 280px; + background: #1e1e26; + border: 1px solid #3a3a46; + border-radius: 6px; + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5); + display: flex; + flex-direction: column; +} +.fpsearch { + padding: 8px; + border-bottom: 1px solid #2c2c34; +} +.fpsearch input { + width: 100%; + padding: 5px 8px; + background: #24242c; + border: 1px solid #3a3a46; + border-radius: 4px; + color: #e8e8ea; + font-size: 13px; +} +.fplist { + max-height: 320px; + overflow-y: auto; +} +.fpempty { + padding: 8px 10px; + font-size: 13px; + color: #8a8a94; + margin: 0; +} +.fpfoot { + padding: 6px 8px; + border-top: 1px solid #2c2c34; + text-align: right; +} +.fpcancel { + padding: 4px 12px; + background: #34343e; + color: #e8e8ea; + border: 0; + border-radius: 4px; + font-size: 12px; + cursor: pointer; +} +.fphead { + padding: 6px 10px; + font-size: 11px; + text-transform: uppercase; + letter-spacing: 1px; + color: #8a8a94; + border-bottom: 1px solid #2c2c34; +} +.fpitem { + display: block; + width: 100%; + text-align: left; + padding: 6px 10px; + background: none; + border: 0; + color: #e8e8ea; + font-size: 13px; + cursor: pointer; +} +.fpitem:hover { + background: #2f6fd4; +} -- cgit v1.2.3