1use crate::{Error, Result, WindField};
12use nalgebra::Vector3;
13
14const EARTH_RADIUS_M: f64 = 6_371_000.0;
16
17fn 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#[derive(Debug, Clone, Copy, PartialEq)]
26pub struct Monitor {
27 pub x_m: f64,
29 pub z_m: f64,
31 pub speed_mps: f64,
33 pub direction_from_deg: f64,
36}
37
38impl Monitor {
39 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 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
72pub 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
83pub 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#[derive(Debug, Clone)]
156pub struct HeightGrid {
157 pub origin_x: f64,
159 pub origin_y: f64,
161 pub dx: f64,
163 pub dy: f64,
165 pub ncols: usize,
167 pub nrows: usize,
169 pub heights: Vec<f64>,
171}
172
173impl HeightGrid {
174 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 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 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 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 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
300type 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
336pub 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
382pub enum SrtmResolution {
383 OneArcSecond,
385 ThreeArcSeconds,
387}
388
389impl SrtmResolution {
390 pub fn samples(self) -> usize {
392 match self {
393 Self::OneArcSecond => 3601,
394 Self::ThreeArcSeconds => 1201,
395 }
396 }
397}
398
399pub 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 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 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#[derive(Debug, Clone, Copy, PartialEq)]
450pub struct GeoTransform {
451 pub origin_x: f64,
453 pub origin_y: f64,
456 pub pixel_scale_x: f64,
458 pub pixel_scale_y: f64,
460}
461
462#[cfg(feature = "tiff")]
468pub fn geotransform<R: std::io::Read + std::io::Seek>(
469 decoder: &mut tiff::decoder::Decoder<R>,
470) -> Result<GeoTransform> {
471 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 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 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#[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 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 let geot = geotransform(&mut decoder);
598 match geot {
599 Ok(geot) => {
600 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#[derive(Debug, Clone)]
619pub struct TerrainFlowField {
620 grid: HeightGrid,
621 levels_agl: Vec<f64>,
623 u: Vec<f64>,
626 v: Vec<f64>,
627}
628
629impl TerrainFlowField {
630 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 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 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 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 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 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}