summaryrefslogtreecommitdiff
path: root/crates/gipfel-core/src
diff options
context:
space:
mode:
Diffstat (limited to 'crates/gipfel-core/src')
-rw-r--r--crates/gipfel-core/src/hill.rs27
-rw-r--r--crates/gipfel-core/src/metadata.rs119
-rw-r--r--crates/gipfel-core/src/panorama.rs59
-rw-r--r--crates/gipfel-core/src/profile.rs14
-rw-r--r--crates/gipfel-core/src/track.rs33
5 files changed, 224 insertions, 28 deletions
diff --git a/crates/gipfel-core/src/hill.rs b/crates/gipfel-core/src/hill.rs
index a904948..254a9e4 100644
--- a/crates/gipfel-core/src/hill.rs
+++ b/crates/gipfel-core/src/hill.rs
@@ -2,9 +2,6 @@
//!
//! Faithful port of gipfel's `Hill.cxx`.
-use std::fs::File;
-use std::io::{BufRead, BufReader};
-
pub const FLAG_DUPLIC: u32 = 1 << 0;
pub const FLAG_KNOWN: u32 = 1 << 1;
pub const FLAG_HIDDEN: u32 = 1 << 2;
@@ -70,6 +67,9 @@ fn atof(s: &str) -> f64 {
return v;
}
for i in (1..s.len()).rev() {
+ if !s.is_char_boundary(i) {
+ continue;
+ }
if let Ok(v) = s[..i].parse::<f64>() {
return v;
}
@@ -77,16 +77,20 @@ fn atof(s: &str) -> f64 {
0.0
}
-/// Load a hill database. Two line formats are accepted:
+/// Load a hill database from a file path.
+pub fn load(path: &str) -> std::io::Result<Vec<Hill>> {
+ load_from_bytes(&std::fs::read(path)?)
+}
+
+/// Load a hill database from raw bytes. Two line formats are accepted:
/// - `SHORT,NAME,DESC,LAT,LON,HEIGHT` (6 fields)
/// - `LAT,LON,HEIGHT` (3 fields, track point)
-pub fn load(path: &str) -> std::io::Result<Vec<Hill>> {
- let file = File::open(path)?;
+///
+/// Byte-oriented entry point (no filesystem): used by the WASM build and
+/// by tests. The database is Latin-1; bytes decode to Unicode code points.
+pub fn load_from_bytes(raw: &[u8]) -> std::io::Result<Vec<Hill>> {
let mut hills = Vec::new();
-
- // the database is Latin-1; decode to Unicode code points
- for line in BufReader::new(file).split(b'\n') {
- let raw = line?;
+ for raw in raw.split(|b| *b == b'\n') {
let line: String = raw.iter().map(|b| *b as char).collect();
// strsep() semantics: split into at most 10 fields, keeping empties
let vals: Vec<&str> = line.split(',').take(10).collect();
@@ -109,7 +113,6 @@ pub fn load(path: &str) -> std::io::Result<Vec<Hill>> {
hills.push(h);
}
}
-
Ok(hills)
}
@@ -163,6 +166,8 @@ mod tests {
assert_eq!(atof("abc"), 0.0);
assert_eq!(atof("12abc"), 12.0);
assert_eq!(atof(" -3.5x"), -3.5);
+ // prefix cut must not slice through a multi-byte character
+ assert_eq!(atof("12.5\u{b0}"), 12.5);
}
#[test]
diff --git a/crates/gipfel-core/src/metadata.rs b/crates/gipfel-core/src/metadata.rs
index e2a888f..d9c98f9 100644
--- a/crates/gipfel-core/src/metadata.rs
+++ b/crates/gipfel-core/src/metadata.rs
@@ -3,9 +3,6 @@
//!
//! Faithful port of gipfel's `ImageMetaData.cxx`.
-use std::fs::File;
-use std::io::{BufReader, Write};
-
use exif::{In, Tag, Value};
pub const NAN: f64 = f64::NAN;
@@ -28,6 +25,10 @@ pub struct ImageMetaData {
pub x0: f64,
pub focal_length: f64,
pub focal_length_35mm: f64,
+ /// true when focal_length_35mm came from a gipfel JPEG comment rather
+ /// than EXIF; the comment uses a legacy scale encoding (see
+ /// apply_image_metadata)
+ pub focal_from_comment: bool,
pub projection_type: i32,
}
@@ -47,6 +48,7 @@ impl Default for ImageMetaData {
x0: NAN,
focal_length: NAN,
focal_length_35mm: NAN,
+ focal_from_comment: false,
projection_type: 0,
}
}
@@ -66,6 +68,16 @@ impl ImageMetaData {
self.load_image_exif(path);
}
+ /// Like [`ImageMetaData::load_image`] but from raw bytes (no filesystem);
+ /// used by the WASM build.
+ pub fn load_image_from_bytes(&mut self, bytes: &[u8]) {
+ *self = ImageMetaData::new();
+ if let Some(com) = read_jpeg_comment_from_bytes(bytes) {
+ self.parse_gipfel_comment(&com);
+ }
+ self.load_image_exif_bytes(bytes);
+ }
+
/// Write the gipfel comment into a copy of `in_img`, saved as `out_img`.
/// Writes atomically via a temp file, like the C original.
pub fn save_image(&self, in_img: &str, out_img: &str) -> std::io::Result<()> {
@@ -76,6 +88,12 @@ impl ImageMetaData {
Ok(())
}
+ /// Like [`ImageMetaData::save_image`] but bytes in / bytes out (no
+ /// filesystem); used by the WASM build.
+ pub fn save_image_to_bytes(&self, in_bytes: &[u8]) -> std::io::Result<Vec<u8>> {
+ write_jpeg_comment_to_bytes(in_bytes, self.format_comment().as_bytes())
+ }
+
pub fn format_comment(&self) -> String {
format!(
"gipfel: longitude {}, latitude {}, height {}, direction {}, nick {}, tilt {}, focal_length_35mm {}, projection type {}, k0 {}, k1 {}, x0 {}",
@@ -134,6 +152,7 @@ impl ImageMetaData {
self.pitch = pit.unwrap();
self.roll = rol.unwrap();
self.focal_length_35mm = fr.unwrap();
+ self.focal_from_comment = true;
self.projection_type = pt;
// n >= 10: k0 and k1 were matched; x0 defaults to 0.0 when only 10
@@ -149,8 +168,12 @@ impl ImageMetaData {
}
fn load_image_exif(&mut self, path: &str) {
- let Ok(file) = File::open(path) else { return };
- let mut reader = BufReader::new(file);
+ let Ok(bytes) = std::fs::read(path) else { return };
+ self.load_image_exif_bytes(&bytes);
+ }
+
+ fn load_image_exif_bytes(&mut self, bytes: &[u8]) {
+ let mut reader = std::io::Cursor::new(bytes);
let Ok(exif) = exif::Reader::new().read_from_container(&mut reader) else {
return;
};
@@ -209,6 +232,22 @@ impl ImageMetaData {
}
}
}
+ // Phone cameras record the shooting direction as GPSImgDirection.
+ // Used only when no gipfel comment provided a direction. A magnetic
+ // reference ('M') is converted to true north with the current
+ // declination of the Eastern Alps (~+2.4 deg east, IGRF 2020s);
+ // the residual error stays below typical phone compass noise.
+ if self.direction.is_nan() {
+ if let Some(f) = exif.get_field(Tag::GPSImgDirection, In::PRIMARY) {
+ if let Some(v) = field_tofloat(f, 0) {
+ let mut dir = v;
+ if exif_ref_is(&exif, Tag::GPSImgDirectionRef, "M") {
+ dir += 2.4;
+ }
+ self.direction = dir;
+ }
+ }
+ }
}
}
@@ -366,6 +405,11 @@ fn marker_len_ok(marker: u8) -> bool {
/// Return the payload of the first COM segment before SOS, if any.
pub fn read_jpeg_comment(path: &str) -> Option<Vec<u8>> {
let bytes = std::fs::read(path).ok()?;
+ read_jpeg_comment_from_bytes(&bytes)
+}
+
+/// Byte-oriented twin of [`read_jpeg_comment`] (no filesystem; WASM-safe).
+pub fn read_jpeg_comment_from_bytes(bytes: &[u8]) -> Option<Vec<u8>> {
if bytes.len() < 2 || bytes[0] != 0xFF || bytes[1] != 0xD8 {
return None;
}
@@ -406,6 +450,13 @@ pub fn read_jpeg_comment(path: &str) -> Option<Vec<u8>> {
/// fresh COM segment right after SOI.
pub fn write_jpeg_comment(in_img: &str, out_img: &str, comment: &[u8]) -> std::io::Result<()> {
let bytes = std::fs::read(in_img)?;
+ let out = write_jpeg_comment_to_bytes(&bytes, comment)?;
+ std::fs::write(out_img, out)
+}
+
+/// Byte-oriented twin of [`write_jpeg_comment`] (no filesystem; WASM-safe):
+/// drop all COM segments and insert a fresh COM segment after the last APPn.
+pub fn write_jpeg_comment_to_bytes(bytes: &[u8], comment: &[u8]) -> std::io::Result<Vec<u8>> {
if bytes.len() < 2 || bytes[0] != 0xFF || bytes[1] != 0xD8 {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a JPEG file"));
}
@@ -469,9 +520,7 @@ pub fn write_jpeg_comment(in_img: &str, out_img: &str, comment: &[u8]) -> std::i
out.extend_from_slice(&bytes[copy_rest_from..]);
- let mut f = File::create(out_img)?;
- f.write_all(&out)?;
- f.flush()
+ Ok(out)
}
/// Read raw image dimensions (width, height) of a JPEG.
@@ -521,13 +570,20 @@ pub fn apply_image_metadata(
pan.set_roll_angle(md.roll);
}
- // set_focal_length_35mm: scale = fl * max(w, h) / 35
+ // scale = f35 * w / 36: the 35mm film frame is 36 mm wide, so a lens
+ // with 35mm-equivalent focal length f projects with focal length
+ // f * w / 36 in pixels. Exception: the gipfel JPEG comment has always
+ // encoded the focal as scale * 35 / w, so that legacy encoding is
+ // kept for comments to reproduce identical views with annotated
+ // JPEGs written by older gipfel versions.
let w = img_w.max(img_h);
if md.focal_length_35mm.is_nan() || md.focal_length_35mm == 0.0 {
- pan.set_scale(35.0 * w as f64 / 35.0);
+ pan.set_scale(35.0 * w as f64 / 36.0);
have_info = false;
- } else {
+ } else if md.focal_from_comment {
pan.set_scale(md.focal_length_35mm * w as f64 / 35.0);
+ } else {
+ pan.set_scale(md.focal_length_35mm * w as f64 / 36.0);
}
// distortion parameters, C ordering:
@@ -694,4 +750,45 @@ mod tests {
}
let _ = std::fs::remove_dir_all(&dir);
}
+
+ #[test]
+ fn focal_scale_exif_vs_comment() {
+ // EXIF 35mm-equivalent focal: scale = f * w / 36 (film width)
+ let mut md = ImageMetaData::new();
+ md.focal_length_35mm = 50.0;
+ let mut pan = crate::panorama::Panorama::new();
+ apply_image_metadata(&mut pan, &md, 1000, 800);
+ assert!((pan.get_scale() - 50.0 * 1000.0 / 36.0).abs() < 1e-9);
+
+ // gipfel comment: legacy encoding scale = f * w / 35, kept so
+ // annotated JPEGs from older versions reproduce the same view
+ md.focal_from_comment = true;
+ let mut pan = crate::panorama::Panorama::new();
+ apply_image_metadata(&mut pan, &md, 1000, 800);
+ assert!((pan.get_scale() - 50.0 * 1000.0 / 35.0).abs() < 1e-9);
+ }
+}
+
+#[cfg(test)]
+mod save_tests {
+ use super::*;
+
+ #[test]
+ fn comment_roundtrip_preserves_projection_type() {
+ let mut md = ImageMetaData::new();
+ md.longitude = 10.5;
+ md.latitude = 47.0;
+ md.height = 2993.0;
+ md.direction = 57.4;
+ md.pitch = -20.0;
+ md.roll = 0.3;
+ md.focal_length_35mm = 27.0;
+ md.projection_type = 1; // cylindrical
+ // minimal valid JPEG (SOI, empty COM, EOI)
+ let jpg = b"\xff\xd8\xff\xfe\x00\x02\xff\xd9";
+ let out = md.save_image_to_bytes(jpg).unwrap();
+ let mut md2 = ImageMetaData::new();
+ md2.load_image_from_bytes(&out);
+ assert_eq!(md2.projection_type, 1, "projection type lost in comment roundtrip");
+ }
}
diff --git a/crates/gipfel-core/src/panorama.rs b/crates/gipfel-core/src/panorama.rs
index 9e27251..b8ce342 100644
--- a/crates/gipfel-core/src/panorama.rs
+++ b/crates/gipfel-core/src/panorama.rs
@@ -74,6 +74,16 @@ impl Panorama {
Ok(())
}
+ /// Like [`Panorama::load_data`] but from raw bytes (no filesystem);
+ /// used by the WASM build.
+ pub fn load_data_from_bytes(&mut self, raw: &[u8]) -> std::io::Result<()> {
+ let mut hills = crate::hill::load_from_bytes(raw)?;
+ crate::hill::mark_duplicates(&mut hills, 0.00001);
+ self.hills = hills;
+ self.update_angles();
+ Ok(())
+ }
+
pub fn add_hills(&mut self, extra: &[Hill]) {
self.hills.extend_from_slice(extra);
crate::hill::mark_duplicates(&mut self.hills, 0.00001);
@@ -394,7 +404,17 @@ impl Panorama {
}
pub fn is_visible(&self, alph: f64) -> bool {
- let mut center_dist = (alph - self.parms.a_center).abs();
+ // NaN or infinite azimuths (from user input or a diverged fit) must
+ // never count as visible; a NaN center used to make everything so.
+ if !alph.is_finite() || !self.parms.a_center.is_finite() {
+ return false;
+ }
+ // Wrap into [0, 2pi) before the fold: a_center may lie outside
+ // [-pi, pi] (user enters "400 deg", or a fit leaves it unnormalized).
+ // Without this, |alph - a_center| > 2pi turned the single fold below
+ // into a NEGATIVE distance, which passed every comparison and made
+ // hills behind the camera visible (GipfelFind.lean Finding 1).
+ let mut center_dist = (alph - self.parms.a_center).abs() % (2.0 * PI);
if center_dist > PI {
center_dist = 2.0 * PI - center_dist;
}
@@ -448,8 +468,13 @@ impl Panorama {
let mut rows = Vec::new();
for &i in &self.visible {
let m = &self.hills[i];
+ // restricted mode (-e, a curated list such as the photo
+ // index): export every listed entry inside the field of
+ // view. The prominence/occlusion heuristics are meant to
+ // thin out the full 21k peak database, not to second-guess
+ // an explicit list.
if m.flags & crate::hill::FLAG_DUPLIC != 0
- || m.flags & crate::hill::FLAG_HIDDEN != 0
+ || (!require_export && m.flags & crate::hill::FLAG_HIDDEN != 0)
|| (require_export && m.flags & crate::hill::FLAG_EXPORT == 0)
{
continue;
@@ -499,4 +524,34 @@ mod tests {
pan.max_view_angle = 80f64.to_radians();
assert!(!pan.is_visible(a70));
}
+
+ #[test]
+ fn out_of_range_center_angle_stays_safe() {
+ // GipfelFind.lean Finding 1: with |alph - a_center| > 2pi the single
+ // fold produced a negative "distance" that passed every comparison.
+ // Hill azimuths come from atan2, so alph is always in [-pi, pi].
+ let mut raw = Panorama::new();
+ raw.parms.a_center = 400f64.to_radians(); // e.g. left by a fit
+ assert!(!raw.is_visible(-std::f64::consts::PI)); // 220 deg off, behind
+
+ // the setter must agree with the equivalent in-range azimuth
+ let mut pan400 = Panorama::new();
+ pan400.set_center_angle(400.0); // "bearing + full turn" input slip
+ let mut pan40 = Panorama::new();
+ pan40.set_center_angle(40.0);
+ for d in -180..=180 {
+ let a = (d as f64).to_radians();
+ assert_eq!(pan400.is_visible(a), pan40.is_visible(a), "az {d}");
+ }
+
+ // NaN / infinite azimuths are not visible (Finding 1b)
+ assert!(!pan40.is_visible(f64::NAN));
+ assert!(!pan40.is_visible(f64::INFINITY));
+ assert!(!pan40.is_visible(f64::NEG_INFINITY));
+
+ // a NaN camera azimuth hides everything (was: everything visible)
+ let mut bad = Panorama::new();
+ bad.parms.a_center = f64::NAN;
+ assert!(!bad.is_visible(0.0));
+ }
}
diff --git a/crates/gipfel-core/src/profile.rs b/crates/gipfel-core/src/profile.rs
index e8bda68..2eff8f6 100644
--- a/crates/gipfel-core/src/profile.rs
+++ b/crates/gipfel-core/src/profile.rs
@@ -112,7 +112,19 @@ pub fn sanitize_name(name: &str) -> Result<(), Error> {
Ok(())
}
-/// Parse a prefs file into ordered (name, profile) pairs. Tolerant:
+/// Parse a prefs file into ordered (name, profile) pairs. Tolerant: comments
+/// (`;`), the root group `[.]`, blank lines and unknown keys are ignored;
+/// values are parsed with Rust's `f64` (superset of C `%g`).
+pub fn parse_prefs(text: &str) -> Vec<(String, Profile)> {
+ parse(text)
+}
+
+/// Serialize profiles in FLTK's layout so the C version can read our file.
+pub fn serialize_prefs(profiles: &[(String, Profile)]) -> String {
+ serialize(profiles)
+}
+
+/// Parse a prefs file into ordered (name, profile) pairs. Tolerant:
/// comments (`;`), the root group `[.]`, blank lines and unknown keys are
/// ignored; values are parsed with Rust's `f64` (superset of C `%g`).
fn parse(text: &str) -> Vec<(String, Profile)> {
diff --git a/crates/gipfel-core/src/track.rs b/crates/gipfel-core/src/track.rs
index 5450aa8..f7bf755 100644
--- a/crates/gipfel-core/src/track.rs
+++ b/crates/gipfel-core/src/track.rs
@@ -32,7 +32,18 @@ pub fn load_gpx(path: &str, max_points: usize) -> Result<Vec<Hill>, String> {
if size.len() > MAX_GPX_BYTES {
return Err(format!("{path}: file too large ({} bytes)", size.len()));
}
- let data = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?;
+ let data = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
+ load_gpx_from_bytes(&data, max_points).map_err(|e| format!("{path}: {e}"))
+}
+
+/// Parse GPX from raw bytes. Same hardening as [`load_gpx`]: size cap,
+/// no entity expansion, `<ele>` accepted only as direct child of
+/// `<trkpt>`. Used directly by the browser front end.
+pub fn load_gpx_from_bytes(data: &[u8], max_points: usize) -> Result<Vec<Hill>, String> {
+ if data.len() as u64 > MAX_GPX_BYTES {
+ return Err(format!("file too large ({} bytes)", data.len()));
+ }
+ let data = String::from_utf8_lossy(data);
let mut reader = quick_xml::Reader::from_str(&data);
reader.config_mut().trim_text(true);
@@ -55,7 +66,7 @@ pub fn load_gpx(path: &str, max_points: usize) -> Result<Vec<Hill>, String> {
}
loop {
- match reader.read_event().map_err(|e| format!("{path}: {e}"))? {
+ match reader.read_event().map_err(|e| e.to_string())? {
Event::Eof => break,
Event::Empty(e) => {
if e.local_name().as_ref() == b"trkpt" {
@@ -112,7 +123,7 @@ pub fn load_gpx(path: &str, max_points: usize) -> Result<Vec<Hill>, String> {
}
if pts.is_empty() {
- return Err(format!("{path}: no track points"));
+ return Err("no track points".to_string());
}
let stride = pts.len().div_ceil(max_points.max(1));
@@ -173,6 +184,22 @@ mod tests {
}
#[test]
+ fn gpx_from_bytes_matches_path_api() {
+ // the browser front end feeds raw bytes directly
+ let gpx = br#"<?xml version="1.0" encoding="UTF-8"?>
+<gpx version="1.1"><trk><trkseg>
+ <trkpt lat="47.36" lon="11.15"><ele>2100</ele></trkpt>
+ <trkpt lat="47.37" lon="11.16"><ele>2150</ele></trkpt>
+</trkseg></trk></gpx>"#;
+ let hills = load_gpx_from_bytes(gpx, 100).unwrap();
+ assert_eq!(hills.len(), 2);
+ assert!(hills.iter().all(|h| h.is_track_point()));
+ assert!((hills[0].phi - 47.36f64.to_radians()).abs() < 1e-12);
+ assert!((hills[1].height - 2150.0).abs() < 1e-9);
+ assert!(load_gpx_from_bytes(b"<gpx></gpx>", 10).is_err()); // no points
+ }
+
+ #[test]
fn gpx_vendor_extensions_ignored() {
// Garmin-style files are full of vendor extension blocks; they must
// not confuse the parser (and must not contribute elevation).