Skip to main content

winds_engine/
terrain.rs

1//! Diagnostic mass-consistent terrain wind (NOABL/CONMESS-style).
2//!
3//! A terrain height grid (in metres) plus a background [`WindField`] and
4//! optional surface wind monitors become a terrain-adjusted field: each
5//! fixed above-ground level is adjusted independently to satisfy 2-D
6//! horizontal mass conservation (`div(u) = 0` with `u = u0 − ∇φ`), so flow
7//! is deflected over and around terrain. This is the cheap diagnostic tier
8//! of terrain flow, not a full CFD solve. Entirely offline and
9//! deterministic.
10
11use crate::{Error, Result, WindField};
12use nalgebra::Vector3;
13
14/// Earth's mean radius for the local-tangent metre projection.
15const EARTH_RADIUS_M: f64 = 6_371_000.0;
16
17/// Horizontal wind vector from a speed and a wind-FROM direction in the frame
18/// convention (0° = from +x, a headwind; 90° = from +z, the right).
19fn horizontal(speed_mps: f64, direction_from_deg: f64) -> Vector3<f64> {
20    let toward = (direction_from_deg + 180.0).to_radians();
21    Vector3::new(speed_mps * toward.cos(), 0.0, speed_mps * toward.sin())
22}
23
24/// One surface wind observation, in the terrain grid's frame (metres).
25#[derive(Debug, Clone, Copy, PartialEq)]
26pub struct Monitor {
27    /// Easting (frame x), metres.
28    pub x_m: f64,
29    /// Northing (frame z), metres.
30    pub z_m: f64,
31    /// Wind speed, metres per second.
32    pub speed_mps: f64,
33    /// Wind-FROM direction in the frame convention: 0° = from +x (a
34    /// headwind), 90° = from +z, the right.
35    pub direction_from_deg: f64,
36}
37
38impl Monitor {
39    /// An observation already in the grid's metre frame.
40    pub fn at(x_m: f64, z_m: f64, speed_mps: f64, direction_from_deg: f64) -> Self {
41        Self {
42            x_m,
43            z_m,
44            speed_mps,
45            direction_from_deg,
46        }
47    }
48
49    /// A geographic reading, projected into local metres and rotated from
50    /// compass degrees into the frame. `ref_lat`/`ref_lon` is the point
51    /// that maps to the frame's origin, and `north_azimuth_deg` is the
52    /// compass direction of the frame's +x axis.
53    pub fn from_geo(
54        lat_deg: f64,
55        lon_deg: f64,
56        speed_mps: f64,
57        dir_compass_from_deg: f64,
58        ref_lat_deg: f64,
59        ref_lon_deg: f64,
60        north_azimuth_deg: f64,
61    ) -> Self {
62        let (x_m, z_m) = local_en_m(lat_deg, lon_deg, ref_lat_deg, ref_lon_deg);
63        Self {
64            x_m,
65            z_m,
66            speed_mps,
67            direction_from_deg: (dir_compass_from_deg - north_azimuth_deg).rem_euclid(360.0),
68        }
69    }
70}
71
72/// Local equirectangular projection: `(east, north)` metres from the
73/// reference point, for the small domains a wind network covers. Not for
74/// continental scales.
75pub fn local_en_m(lat_deg: f64, lon_deg: f64, ref_lat_deg: f64, ref_lon_deg: f64) -> (f64, f64) {
76    let dlat = (lat_deg - ref_lat_deg).to_radians();
77    let dlon = (lon_deg - ref_lon_deg).to_radians();
78    let east = EARTH_RADIUS_M * dlon * ref_lat_deg.to_radians().cos();
79    let north = EARTH_RADIUS_M * dlat;
80    (east, north)
81}
82
83/// Parse a monitor file of one reading per line:
84/// `latitude,longitude,speed_ms,direction_compass_from_deg`, `#` comments
85/// and a header line are skipped. Coordinates are projected via
86/// [`local_en_m`] and directions rotated into the frame.
87pub fn monitors_from_geo_csv(
88    text: &str,
89    ref_lat_deg: f64,
90    ref_lon_deg: f64,
91    north_azimuth_deg: f64,
92) -> Result<Vec<Monitor>> {
93    let mut monitors = Vec::new();
94    for (number, line) in text.lines().enumerate() {
95        let line = line.trim();
96        if line.is_empty() || line.starts_with('#') {
97            continue;
98        }
99        let fields: Vec<&str> = line.split(',').collect();
100        if fields.len() < 4 {
101            return Err(Error::invalid(
102                "monitor csv",
103                format!(
104                    "line {}: expected lat,lon,speed_ms,dir_compass_deg",
105                    number + 1
106                ),
107            ));
108        }
109        let num = |token: &str, what: &str| -> Result<f64> {
110            token.trim().parse().map_err(|_| {
111                Error::invalid(
112                    "monitor csv",
113                    format!("line {}: {what} '{token}' is not numeric", number + 1),
114                )
115            })
116        };
117        let (lat, lon) = (num(fields[0], "lat")?, num(fields[1], "lon")?);
118        let speed = num(fields[2], "speed")?;
119        let dir = num(fields[3], "direction")?;
120        if !lat.is_finite()
121            || lat.abs() > 90.0
122            || !lon.is_finite()
123            || !speed.is_finite()
124            || speed < 0.0
125            || !dir.is_finite()
126        {
127            return Err(Error::invalid(
128                "monitor csv",
129                format!(
130                    "line {}: readings must be finite with nonnegative speed",
131                    number + 1
132                ),
133            ));
134        }
135        monitors.push(Monitor::from_geo(
136            lat,
137            lon,
138            speed,
139            dir,
140            ref_lat_deg,
141            ref_lon_deg,
142            north_azimuth_deg,
143        ));
144    }
145    Ok(monitors)
146}
147
148/// Terrain heights on an axis-aligned, uniform grid in metres. Row-major,
149/// **south-to-north**: `heights[i * ncols + j]` is column `j` (east) of row
150/// `i`, where row 0 is the southernmost row and `i` increases northward,
151/// matching the frame's `+z = north` convention shared by monitors and
152/// [`local_en_m`]. `origin_y` is the south edge; sampling `height_at` moves
153/// north as `z` increases. Position `y` is up; the grid lies in the `x`–`z`
154/// plane.
155#[derive(Debug, Clone)]
156pub struct HeightGrid {
157    /// Frame-x of the western (first) column.
158    pub origin_x: f64,
159    /// Frame-z of the southern (first) row.
160    pub origin_y: f64,
161    /// Column spacing, metres.
162    pub dx: f64,
163    /// Row spacing, metres.
164    pub dy: f64,
165    /// Number of columns (east).
166    pub ncols: usize,
167    /// Number of rows (south→north).
168    pub nrows: usize,
169    /// Row-major height samples, `ncols * nrows`, south→north.
170    pub heights: Vec<f64>,
171}
172
173impl HeightGrid {
174    /// Build and validate a grid.
175    pub fn new(
176        origin_x: f64,
177        origin_y: f64,
178        dx: f64,
179        dy: f64,
180        ncols: usize,
181        nrows: usize,
182        heights: Vec<f64>,
183    ) -> Result<Self> {
184        if dx <= 0.0 || dy <= 0.0 || !dx.is_finite() || !dy.is_finite() {
185            return Err(Error::invalid("height grid", "spacing must be positive"));
186        }
187        if ncols < 2 || nrows < 2 {
188            return Err(Error::invalid("height grid", "needs at least 2x2 cells"));
189        }
190        if heights.len() != ncols * nrows {
191            return Err(Error::invalid(
192                "height grid",
193                "height count does not match the grid shape",
194            ));
195        }
196        if !heights.iter().all(|h| h.is_finite()) {
197            return Err(Error::invalid("height grid", "heights must be finite"));
198        }
199        Ok(Self {
200            origin_x,
201            origin_y,
202            dx,
203            dy,
204            ncols,
205            nrows,
206            heights,
207        })
208    }
209
210    /// Terrain height at a horizontal position, bilinear between samples;
211    /// clamps at the grid edges.
212    pub fn height_at(&self, x: f64, z: f64) -> f64 {
213        let fx = ((x - self.origin_x) / self.dx).clamp(0.0, self.ncols as f64 - 1.0);
214        let fy = ((z - self.origin_y) / self.dy).clamp(0.0, self.nrows as f64 - 1.0);
215        let (j, i) = (fx.floor() as usize, fy.floor() as usize);
216        let (rx, ry) = (fx - j as f64, fy - i as f64);
217        let j1 = (j + 1).min(self.ncols - 1);
218        let i1 = (i + 1).min(self.nrows - 1);
219        let f = |i: usize, j: usize| self.heights[i * self.ncols + j];
220        (1.0 - ry) * ((1.0 - rx) * f(i, j) + rx * f(i, j1))
221            + ry * ((1.0 - rx) * f(i1, j) + rx * f(i1, j1))
222    }
223
224    /// A grid from an ASCII ESRI `.asc` raster (projected, metres): header
225    /// `ncols/nrows/xllcorner/yllcorner/cellsize`, then row-major heights
226    /// (north-to-south, west-to-east, i.e. "English reading order": the first
227    /// row is the north edge). Rows are reversed into the grid's
228    /// south-to-north storage so `+z` points north.
229    pub fn from_ascii(text: &str) -> Result<Self> {
230        let mut ncols = None;
231        let mut nrows = None;
232        let mut xll = None;
233        let mut yll = None;
234        let mut cellsize = None;
235        let mut file_rows = Vec::new();
236        for line in text.lines() {
237            let line = line.trim();
238            if line.is_empty() {
239                continue;
240            }
241            let mut parts = line.split_whitespace();
242            match parts.next().unwrap_or("").to_ascii_lowercase().as_str() {
243                "ncols" => ncols = parse_asc_num(parts.next()),
244                "nrows" => nrows = parse_asc_num(parts.next()),
245                "xllcorner" | "xllcenter" => xll = parse_asc_num(parts.next()),
246                "yllcorner" | "yllcenter" => yll = parse_asc_num(parts.next()),
247                "cellsize" => cellsize = parse_asc_num(parts.next()),
248                "nodata_value" => continue,
249                _ => {
250                    for token in line.split_whitespace() {
251                        if let Ok(v) = token.parse::<f64>() {
252                            file_rows.push(v);
253                        }
254                    }
255                }
256            }
257        }
258        let ncols = ncols.ok_or_else(|| Error::invalid("ascii dem", "missing ncols"))? as usize;
259        let nrows = nrows.ok_or_else(|| Error::invalid("ascii dem", "missing nrows"))? as usize;
260        let cellsize = cellsize.ok_or_else(|| Error::invalid("ascii dem", "missing cellsize"))?;
261        let (xll, yll) = (
262            xll.ok_or_else(|| Error::invalid("ascii dem", "missing xllcorner"))?,
263            yll.ok_or_else(|| Error::invalid("ascii dem", "missing yllcorner"))?,
264        );
265        if file_rows.len() != ncols * nrows {
266            return Err(Error::invalid(
267                "ascii dem",
268                "height count does not match header",
269            ));
270        }
271        // File is north-first; reverse to south-first. xll/yll is the
272        // lower-left (south-west) corner, matching our origin_y = south edge.
273        let mut heights = Vec::with_capacity(file_rows.len());
274        for row in file_rows.chunks_exact(ncols).rev() {
275            heights.extend_from_slice(row);
276        }
277        Self::new(xll, yll, cellsize, cellsize, ncols, nrows, heights)
278    }
279
280    /// A grid from raw metres data already in the grid's south-to-north
281    /// row-major order (row 0 = south), with the origin at the south-west
282    /// sample corner.
283    pub fn from_south_up(
284        origin_x: f64,
285        origin_south_y: f64,
286        dx: f64,
287        dy: f64,
288        ncols: usize,
289        nrows: usize,
290        heights: Vec<f64>,
291    ) -> Result<Self> {
292        Self::new(origin_x, origin_south_y, dx, dy, ncols, nrows, heights)
293    }
294}
295
296fn parse_asc_num(token: Option<&str>) -> Option<f64> {
297    token.and_then(|s| s.parse().ok())
298}
299
300/// Parse the shared `flt`/`.asc` six-key header lines into
301/// `(ncols, nrows, xll, yll, cellsize, nodata, msb_first)`. `text` may be an
302/// `.asc` header (no `BYTEORDER`) or a `.hdr` sidecar (with `BYTEORDER`).
303type Header = (usize, usize, f64, f64, f64, Option<f64>, bool);
304
305fn parse_header(text: &str) -> Result<Header> {
306    let mut ncols = None;
307    let mut nrows = None;
308    let mut xll = None;
309    let mut yll = None;
310    let mut cellsize = None;
311    let mut nodata = None;
312    let mut msb = true;
313    for line in text.lines() {
314        let mut parts = line.split_whitespace();
315        let key = parts.next().unwrap_or("").to_ascii_lowercase();
316        let val = parts.next();
317        match key.as_str() {
318            "ncols" => ncols = val.and_then(|s| s.parse().ok()),
319            "nrows" => nrows = val.and_then(|s| s.parse().ok()),
320            "xllcorner" | "xllcenter" => xll = val.and_then(|s| s.parse().ok()),
321            "yllcorner" | "yllcenter" => yll = val.and_then(|s| s.parse().ok()),
322            "cellsize" => cellsize = val.and_then(|s| s.parse().ok()),
323            "nodata_value" | "nodata" => nodata = val.and_then(|s| s.parse().ok()),
324            "byteorder" => msb = val.is_none_or(|s| s.eq_ignore_ascii_case("msbfirst")),
325            _ => {}
326        }
327    }
328    let ncols = ncols.ok_or_else(|| Error::invalid("header", "missing ncols"))?;
329    let nrows = nrows.ok_or_else(|| Error::invalid("header", "missing nrows"))?;
330    let cellsize = cellsize.ok_or_else(|| Error::invalid("header", "missing cellsize"))?;
331    let xll = xll.ok_or_else(|| Error::invalid("header", "missing xllcorner"))?;
332    let yll = yll.ok_or_else(|| Error::invalid("header", "missing yllcorner"))?;
333    Ok((ncols, nrows, xll, yll, cellsize, nodata, msb))
334}
335
336/// Load an ESRI binary floating-point raster (`.flt` raw float32 + `.hdr`
337/// sidecar header). Both the row order (north-first, "English reading
338/// order") and the lower-left-corner origin are handled the same way as
339/// [`HeightGrid::from_ascii`].
340pub fn from_flt(flt: &[u8], hdr_text: &str) -> Result<HeightGrid> {
341    let (ncols, nrows, xll, yll, cellsize, nodata, msb) = parse_header(hdr_text)?;
342    let expected = ncols * nrows * 4;
343    if flt.len() != expected {
344        return Err(Error::invalid(
345            "flt",
346            format!("expected {expected} bytes, got {}", flt.len()),
347        ));
348    }
349    let mut heights = Vec::with_capacity(ncols * nrows);
350    for chunk in flt.as_chunks::<4>().0 {
351        let value = if msb {
352            f32::from_be_bytes(*chunk)
353        } else {
354            f32::from_le_bytes(*chunk)
355        };
356        heights.push(f64::from(value));
357    }
358    // A mass-consistent terrain field needs a dense height grid, so NODATA
359    // cells are an error, not silent holes.
360    if let Some(nodata) = nodata {
361        if heights.contains(&nodata) {
362            return Err(Error::invalid(
363                "flt",
364                "raster contains NODATA cells; terrain wind needs a dense DEM",
365            ));
366        }
367    }
368    // File rows are north-first; reverse to the grid's south-first storage.
369    // yllcorner is the lower-left (south-west) corner = our origin.
370    let mut south_first = Vec::with_capacity(heights.len());
371    for row in heights.chunks_exact(ncols).rev() {
372        south_first.extend_from_slice(row);
373    }
374    HeightGrid::new(xll, yll, cellsize, cellsize, ncols, nrows, south_first)
375}
376
377/// A 1°×1° SRTM tile: 1201² samples for SRTM-3 (3 arc-sec ≈ 90 m), 3601²
378/// for SRTM-1 (1 arc-sec ≈ 30 m). `.hgt` files are 16-bit big-endian
379/// signed metres, recorded north→south (top row is the northern edge),
380/// west→east, sample values at the tile's corners (not centres).
381#[derive(Debug, Clone, Copy, PartialEq, Eq)]
382pub enum SrtmResolution {
383    /// 3601 samples per side (~30 m), SRTM-1.
384    OneArcSecond,
385    /// 1201 samples per side (~90 m), SRTM-3.
386    ThreeArcSeconds,
387}
388
389impl SrtmResolution {
390    /// Samples per tile side: 3601 (SRTM-1) or 1201 (SRTM-3).
391    pub fn samples(self) -> usize {
392        match self {
393            Self::OneArcSecond => 3601,
394            Self::ThreeArcSeconds => 1201,
395        }
396    }
397}
398
399/// Load an SRTM `.hgt` tile into a [`HeightGrid`] on a local equirectangular
400/// projection (metres), with `(north_lat, west_lon)` as the tile's corner
401/// and the given point mapping to the frame origin.
402///
403/// The tile's own north-west corner is the natural reference, but a caller
404/// with a launch site in mind can recentre with `ref_lat`/`ref_lon`.
405pub fn hgt_grid(
406    data: &[u8],
407    resolution: SrtmResolution,
408    north_lat: f64,
409    west_lon: f64,
410    ref_lat: f64,
411    ref_lon: f64,
412) -> Result<HeightGrid> {
413    let samples = resolution.samples();
414    let expected = samples * samples * 2;
415    if data.len() != expected {
416        return Err(Error::invalid(
417            "hgt",
418            format!("expected {expected} bytes, got {}", data.len()),
419        ));
420    }
421    // File is north→south; reverse to the grid's south-first storage.
422    let mut file_rows = Vec::with_capacity(samples * samples);
423    for chunk in data.as_chunks::<2>().0 {
424        file_rows.push(f64::from(i16::from_be_bytes(*chunk)));
425    }
426    let mut heights = Vec::with_capacity(file_rows.len());
427    for row in file_rows.chunks_exact(samples).rev() {
428        heights.extend_from_slice(row);
429    }
430    // Project the corners and the reference into local metres. Origin is the
431    // south-west corner (matches `origin_y` = south edge, `+z` north).
432    let sw = local_en_m(north_lat - 1.0, west_lon, north_lat, west_lon);
433    let ne = local_en_m(north_lat, west_lon + 1.0, north_lat, west_lon);
434    let dx = (ne.0 - sw.0) / (samples - 1) as f64;
435    let dy = (ne.1 - sw.1) / (samples - 1) as f64;
436    let (ref_x, ref_z) = local_en_m(ref_lat, ref_lon, north_lat, west_lon);
437    HeightGrid::new(
438        sw.0 - ref_x,
439        sw.1 - ref_z,
440        dx,
441        dy,
442        samples,
443        samples,
444        heights,
445    )
446}
447
448/// The georeferencing parsed from a GeoTIFF's model tags.
449#[derive(Debug, Clone, Copy, PartialEq)]
450pub struct GeoTransform {
451    /// Easting (model) coordinate of the west edge.
452    pub origin_x: f64,
453    /// Northing (model) coordinate of the **north** (top) edge. `geotiff_grid`,
454    /// which knows the raster height, shifts this to the south edge.
455    pub origin_y: f64,
456    /// Pixel size in x (east-west).
457    pub pixel_scale_x: f64,
458    /// Pixel size in y (north-south magnitude, positive).
459    pub pixel_scale_y: f64,
460}
461
462/// Extract the geotransform from a linear (non-rotated) GeoTIFF:
463/// `ModelTiepointTag` (I,J,K → X,Y,Z) and `ModelPixelScaleTag` (ScaleX,Y,Z).
464/// `ModelTransformationTag` (a full 16-term affine) is accepted only when it
465/// is axis-aligned (off-diagonal terms zero); rotated rasters are rejected
466/// because [`HeightGrid`] is axis-aligned.
467#[cfg(feature = "tiff")]
468pub fn geotransform<R: std::io::Read + std::io::Seek>(
469    decoder: &mut tiff::decoder::Decoder<R>,
470) -> Result<GeoTransform> {
471    // A model transform (4x4 affine, 16 doubles) overrides pixel-scale+ tiepoint.
472    if let Ok(transform) = decoder.get_tag_f64_vec(tiff::tags::Tag::ModelTransformationTag) {
473        if transform.len() != 16 {
474            return Err(Error::invalid(
475                "geotiff",
476                "model transform must be 16 values",
477            ));
478        }
479        let is_axis_aligned = [
480            transform[1],
481            transform[2],
482            transform[4],
483            transform[6],
484            transform[8],
485            transform[9],
486        ]
487        .iter()
488        .all(|v| v.abs() < 1e-12);
489        if !is_axis_aligned {
490            return Err(Error::invalid(
491                "geotiff",
492                "rotated model transform is not supported by a HeightGrid",
493            ));
494        }
495        let (sx, sy) = (transform[0], transform[5]);
496        // Raster (0,0) is the top-left pixel; its corner is at (X, Y) minus
497        // half a pixel when PixelIsArea, i.e. X0 = transform[3], Y0 = transform[7]
498        // for a pixel-corner tie (the transform maps pixel (0,0) center to X0,Y0).
499        // GeoTIFF's model transform maps raster *point* (0,0) to (X0, Y0); for a
500        // north-up raster sy is negative, so the NW corner (top-left) is
501        // (X0, Y0) and the NS spacing is -sy.
502        return Ok(GeoTransform {
503            origin_x: transform[3],
504            origin_y: transform[7],
505            pixel_scale_x: sx,
506            pixel_scale_y: -sy,
507        });
508    }
509
510    let tiepoint = decoder
511        .get_tag_f64_vec(tiff::tags::Tag::ModelTiepointTag)
512        .map_err(|_| Error::invalid("geotiff", "missing ModelTiepointTag"))?;
513    let scale = decoder
514        .get_tag_f64_vec(tiff::tags::Tag::ModelPixelScaleTag)
515        .map_err(|_| Error::invalid("geotiff", "missing ModelPixelScaleTag"))?;
516    if scale.len() != 3 {
517        return Err(Error::invalid("geotiff", "pixel scale must be 3 values"));
518    }
519    let (sx, sy) = (scale[0], scale[1]);
520    if sx <= 0.0 {
521        return Err(Error::invalid("geotiff", "pixel scale x must be positive"));
522    }
523    if sy.abs() <= 0.0 {
524        return Err(Error::invalid("geotiff", "pixel scale y must be nonzero"));
525    }
526    // ModelTiepoint maps raster (I, J, 0) to model (X, Y, Z). The conventional
527    // single tiepoint is at raster (0, 0) = the top-left pixel centre, so its
528    // model X/Y is the top-left corner. Pixel scale y is signed by the CRS
529    // (negative in north-up projected CRSs, positive in y-up CRSs like Web
530    // Mercator); the spacing magnitude is |sy|. `origin_y` here is the
531    // **top** (north) edge; `geotiff_grid` shifts it to the south edge using
532    // the raster height.
533    let tie_model_x = tiepoint
534        .get(3)
535        .copied()
536        .ok_or_else(|| Error::invalid("geotiff", "tiepoint must have 6 values (I J K X Y Z)"))?;
537    let tie_model_y = *tiepoint
538        .get(4)
539        .ok_or_else(|| Error::invalid("geotiff", "tiepoint must have 6 values (I J K X Y Z)"))?;
540    Ok(GeoTransform {
541        origin_x: tie_model_x,
542        origin_y: tie_model_y,
543        pixel_scale_x: sx,
544        pixel_scale_y: sy.abs(),
545    })
546}
547
548/// Load a GeoTIFF DEM into a georeferenced [`HeightGrid`]. Uses the
549/// lightweight `tiff` crate behind a `tiff` feature (off by default, keeping
550/// the core zero-dependency). The geotransform is read from the tags, so a
551/// projected (metre) single-band DEM arrives with real origin and spacing;
552/// a geographic (degree) grid is read as-is (degree units) with no proj — the
553/// caller decides the map projection.
554#[cfg(feature = "tiff")]
555pub fn geotiff_grid(data: &[u8]) -> Result<HeightGrid> {
556    let mut decoder = tiff::decoder::Decoder::new(std::io::Cursor::new(data))
557        .map_err(|e| Error::invalid("geotiff", format!("cannot open: {e}")))?;
558    let (width, height) = decoder
559        .dimensions()
560        .map_err(|e| Error::invalid("geotiff", format!("cannot read dimensions: {e}")))?;
561    let (width, height) = (width as usize, height as usize);
562    let values = match decoder
563        .read_image()
564        .map_err(|e| Error::invalid("geotiff", format!("cannot decode: {e}")))?
565    {
566        tiff::decoder::DecodingResult::F32(data) => data.into_iter().map(f64::from).collect(),
567        tiff::decoder::DecodingResult::F64(data) => data,
568        tiff::decoder::DecodingResult::U8(data) => data.into_iter().map(f64::from).collect(),
569        tiff::decoder::DecodingResult::U16(data) => data.into_iter().map(f64::from).collect(),
570        tiff::decoder::DecodingResult::U32(data) => data.into_iter().map(f64::from).collect(),
571        tiff::decoder::DecodingResult::I8(data) => data.into_iter().map(f64::from).collect(),
572        tiff::decoder::DecodingResult::I16(data) => data.into_iter().map(f64::from).collect(),
573        tiff::decoder::DecodingResult::I32(data) => data.into_iter().map(f64::from).collect(),
574        tiff::decoder::DecodingResult::U64(data) => data.into_iter().map(|v| v as f64).collect(),
575        tiff::decoder::DecodingResult::I64(data) => data.into_iter().map(|v| v as f64).collect(),
576        _ => {
577            return Err(Error::invalid(
578                "geotiff",
579                "unsupported sample format (expected integer or float samples)",
580            ))
581        }
582    };
583    if values.len() != width * height {
584        return Err(Error::invalid(
585            "geotiff",
586            "decoded size does not match header",
587        ));
588    }
589    // Raster rows are north→south (top-left origin); reverse into the grid's
590    // south-first storage.
591    let mut south_first = Vec::with_capacity(values.len());
592    for row in values.chunks_exact(width).rev() {
593        south_first.extend_from_slice(row);
594    }
595    // Read the geotransform. A bare (unreferenced) TIFF is indexed from (0,0)
596    // with unit spacing, origin at the south-west corner.
597    let geot = geotransform(&mut decoder);
598    match geot {
599        Ok(geot) => {
600            // geotransform gives the north (top) edge; the grid's origin is
601            // the south edge, |dy| per row below that.
602            let south_y = geot.origin_y - (height as f64 - 1.0) * geot.pixel_scale_y;
603            HeightGrid::new(
604                geot.origin_x,
605                south_y,
606                geot.pixel_scale_x,
607                geot.pixel_scale_y,
608                width,
609                height,
610                south_first,
611            )
612        }
613        Err(_) => HeightGrid::new(0.0, 0.0, 1.0, 1.0, width, height, south_first),
614    }
615}
616
617/// A diagnostic terrain-adjusted wind field.
618#[derive(Debug, Clone)]
619pub struct TerrainFlowField {
620    grid: HeightGrid,
621    /// Fixed above-ground sampling levels, ascending.
622    levels_agl: Vec<f64>,
623    /// Adjusted horizontal wind per level, row-major `u` and `v` (frame x
624    /// and z), `levels * ncols * nrows` each.
625    u: Vec<f64>,
626    v: Vec<f64>,
627}
628
629impl TerrainFlowField {
630    /// Build a terrain-adjusted field. `base` seeds the first guess;
631    /// `monitors` are surface wind observations `(x, z, speed_mps,
632    /// from_deg)` blended near the ground and relaxed toward the base field
633    /// with height. `obs_length_m` sets the horizontal influence radius,
634    /// `surface_decay_m` the vertical relaxation of monitor influence, and
635    /// `terrain_scale_m` the depth over which the terrain forcing (flow
636    /// rising over the ground) decays.
637    pub fn adjust(
638        grid: HeightGrid,
639        base: &dyn WindField,
640        monitors: &[Monitor],
641        levels_agl: &[f64],
642        obs_length_m: f64,
643        surface_decay_m: f64,
644        terrain_scale_m: f64,
645    ) -> Result<Self> {
646        if levels_agl.is_empty() || levels_agl.iter().any(|h| !h.is_finite() || *h < 0.0) {
647            return Err(Error::invalid(
648                "levels_agl",
649                "must be finite and nonnegative",
650            ));
651        }
652        if obs_length_m <= 0.0 || surface_decay_m <= 0.0 || terrain_scale_m <= 0.0 {
653            return Err(Error::invalid("terrain", "length scales must be positive"));
654        }
655        if levels_agl.is_empty() || levels_agl.iter().any(|h| !h.is_finite() || *h < 0.0) {
656            return Err(Error::invalid(
657                "levels_agl",
658                "must be finite and nonnegative",
659            ));
660        }
661        if obs_length_m <= 0.0 || surface_decay_m <= 0.0 {
662            return Err(Error::invalid("terrain", "length scales must be positive"));
663        }
664        for m in monitors {
665            if !m.x_m.is_finite() || !m.z_m.is_finite() || !m.direction_from_deg.is_finite() {
666                return Err(Error::invalid("monitor", "must be finite"));
667            }
668            if !m.speed_mps.is_finite() || m.speed_mps < 0.0 {
669                return Err(Error::invalid("monitor", "speed must be nonnegative"));
670            }
671        }
672        let (ncols, nrows) = (grid.ncols, grid.nrows);
673        let n = ncols * nrows;
674        let inv_dx2 = 1.0 / (grid.dx * grid.dx);
675        let inv_dy2 = 1.0 / (grid.dy * grid.dy);
676        let diag = -2.0 * (inv_dx2 + inv_dy2);
677        let omega = 1.6;
678        let mut u = Vec::with_capacity(levels_agl.len() * n);
679        let mut v = Vec::with_capacity(levels_agl.len() * n);
680        let mut phi = vec![0.0; n];
681        for &level in levels_agl {
682            // First guess: base field + monitor correction, relaxed with height.
683            let mut u0 = vec![0.0; n];
684            let mut v0 = vec![0.0; n];
685            for i in 0..nrows {
686                for j in 0..ncols {
687                    let x = grid.origin_x + j as f64 * grid.dx;
688                    let z = grid.origin_y + i as f64 * grid.dy;
689                    let height = grid.heights[i * ncols + j] + level;
690                    let bg = base.wind(0.0, Vector3::new(x, height, z));
691                    let (mut cx, mut cz, mut wsum) = (0.0, 0.0, 0.0);
692                    for m in monitors {
693                        let mw = horizontal(m.speed_mps, m.direction_from_deg);
694                        let bg_m = base.wind(
695                            0.0,
696                            Vector3::new(m.x_m, grid.height_at(m.x_m, m.z_m), m.z_m),
697                        );
698                        let dx = x - m.x_m;
699                        let dz = z - m.z_m;
700                        let weight = (-(dx * dx + dz * dz) / (obs_length_m * obs_length_m)).exp()
701                            * (-level / surface_decay_m).exp();
702                        cx += weight * (mw.x - bg_m.x);
703                        cz += weight * (mw.z - bg_m.z);
704                        wsum += weight;
705                    }
706                    if wsum > 0.0 {
707                        // A regularizer keeps a lone distant monitor from
708                        // overriding the background everywhere.
709                        let w_floor = 0.1;
710                        cx /= wsum + w_floor;
711                        cz /= wsum + w_floor;
712                    }
713                    u0[i * ncols + j] = bg.x + cx;
714                    v0[i * ncols + j] = bg.z + cz;
715                }
716            }
717            // Solve div(u) = 0, u = u0 - grad(phi), including the
718            // terrain-induced vertical divergence: air forced up a slope
719            // converges horizontally, air descending into a lee diverges.
720            // laplacian(phi) = div_h(u0) - (u0 . grad(h)) * exp(-z / H) / H.
721            let level_decay = (-level / terrain_scale_m).exp() / terrain_scale_m;
722            let slopes = |u0x: f64, u0z: f64, i: usize, j: usize| -> f64 {
723                let dhdx = (grid.heights[i * ncols + (j + 1).min(ncols - 1)]
724                    - grid.heights[i * ncols + j.saturating_sub(1)])
725                    / (2.0 * grid.dx);
726                let dhdz = (grid.heights[(i + 1).min(nrows - 1) * ncols + j]
727                    - grid.heights[i.saturating_sub(1) * ncols + j])
728                    / (2.0 * grid.dy);
729                u0x * dhdx + u0z * dhdz
730            };
731            phi.fill(0.0);
732            for _ in 0..4000 {
733                let mut max_step = 0.0_f64;
734                for i in 1..nrows - 1 {
735                    for j in 1..ncols - 1 {
736                        let ip = (i + 1).min(nrows - 1);
737                        let im = i.saturating_sub(1);
738                        let jp = (j + 1).min(ncols - 1);
739                        let jm = j.saturating_sub(1);
740                        let lap = (phi[i * ncols + jp] + phi[i * ncols + jm]) * inv_dx2
741                            + (phi[ip * ncols + j] + phi[im * ncols + j]) * inv_dy2
742                            + diag * phi[i * ncols + j];
743                        let div = (u0[i * ncols + jp] - u0[i * ncols + jm]) / (2.0 * grid.dx)
744                            + (v0[ip * ncols + j] - v0[im * ncols + j]) / (2.0 * grid.dy);
745                        let rhs =
746                            div - slopes(u0[i * ncols + j], v0[i * ncols + j], i, j) * level_decay;
747                        let updated = phi[i * ncols + j] + omega * (rhs - lap) / diag;
748                        max_step = max_step.max((updated - phi[i * ncols + j]).abs());
749                        phi[i * ncols + j] = updated;
750                    }
751                }
752                if max_step < 1e-6 {
753                    break;
754                }
755            }
756            for i in 0..nrows {
757                for j in 0..ncols {
758                    let edge = i == 0 || i == nrows - 1 || j == 0 || j == ncols - 1;
759                    if edge {
760                        // The domain is embedded in a larger uniform field: the
761                        // boundary holds the background wind.
762                        u.push(u0[i * ncols + j]);
763                        v.push(v0[i * ncols + j]);
764                        continue;
765                    }
766                    let jp = (j + 1).min(ncols - 1);
767                    let jm = j.saturating_sub(1);
768                    let ip = (i + 1).min(nrows - 1);
769                    let im = i.saturating_sub(1);
770                    let gx = (phi[i * ncols + jp] - phi[i * ncols + jm]) / (2.0 * grid.dx);
771                    let gz = (phi[ip * ncols + j] - phi[im * ncols + j]) / (2.0 * grid.dy);
772                    u.push(u0[i * ncols + j] - gx);
773                    v.push(v0[i * ncols + j] - gz);
774                }
775            }
776        }
777        Ok(Self {
778            grid,
779            levels_agl: levels_agl.to_vec(),
780            u,
781            v,
782        })
783    }
784
785    fn sample_level(&self, level: usize, x: f64, z: f64) -> (f64, f64) {
786        let (ncols, nrows) = (self.grid.ncols, self.grid.nrows);
787        let fx = ((x - self.grid.origin_x) / self.grid.dx).clamp(0.0, ncols as f64 - 1.0);
788        let fy = ((z - self.grid.origin_y) / self.grid.dy).clamp(0.0, nrows as f64 - 1.0);
789        let (j, i) = (fx.floor() as usize, fy.floor() as usize);
790        let (rx, ry) = (fx - j as f64, fy - i as f64);
791        let j1 = (j + 1).min(ncols - 1);
792        let i1 = (i + 1).min(nrows - 1);
793        let base = level * ncols * nrows;
794        let g = |arr: &[f64], i: usize, j: usize| arr[base + i * ncols + j];
795        let sample = |arr: &[f64]| {
796            (1.0 - ry) * ((1.0 - rx) * g(arr, i, j) + rx * g(arr, i, j1))
797                + ry * ((1.0 - rx) * g(arr, i1, j) + rx * g(arr, i1, j1))
798        };
799        (sample(&self.u), sample(&self.v))
800    }
801
802    /// Horizontal wind at a world position: nearest above-ground level.
803    pub fn horizontal_at(&self, x: f64, y: f64, z: f64) -> (f64, f64) {
804        let agl = y - self.grid.height_at(x, z);
805        let mut level = 0;
806        for (k, &h) in self.levels_agl.iter().enumerate() {
807            if agl <= h {
808                level = k;
809                break;
810            }
811            level = k;
812        }
813        self.sample_level(level, x, z)
814    }
815}
816
817impl WindField for TerrainFlowField {
818    fn wind(&self, _time_s: f64, position_m: Vector3<f64>) -> Vector3<f64> {
819        let (u, v) = self.horizontal_at(position_m.x, position_m.y, position_m.z);
820        Vector3::new(u, 0.0, v)
821    }
822}