1use indexmap::IndexMap;
8
9use super::{GeometryError, Point};
10
11pub type ClosedPath = Vec<Point>;
13
14#[derive(Clone, Debug, PartialEq)]
20pub struct ScalarGrid {
21 pub origin: Point,
23 pub cell: f64,
25 pub cols: usize,
27 pub rows: usize,
29 pub values: Vec<f64>,
31}
32
33impl ScalarGrid {
34 pub fn zeros(
41 origin: Point,
42 cell: f64,
43 cols: usize,
44 rows: usize,
45 ) -> Result<Self, GeometryError> {
46 if !(cell.is_finite() && cell > 0.0) {
47 return Err(GeometryError::BadParameter {
48 name: "cell",
49 value: cell,
50 });
51 }
52 for value in [origin.0, origin.1] {
53 if !value.is_finite() {
54 return Err(GeometryError::BadParameter {
55 name: "origin",
56 value,
57 });
58 }
59 }
60 if cols == 0 {
61 return Err(GeometryError::BadParameter {
62 name: "cols",
63 value: 0.0,
64 });
65 }
66 if rows == 0 {
67 return Err(GeometryError::BadParameter {
68 name: "rows",
69 value: 0.0,
70 });
71 }
72 let nodes = cols.checked_mul(rows).ok_or(GeometryError::BadParameter {
73 name: "cols",
74 value: cols as f64,
75 })?;
76 Ok(Self {
77 origin,
78 cell,
79 cols,
80 rows,
81 values: vec![0.0; nodes],
82 })
83 }
84
85 #[must_use]
91 pub fn get(&self, col: usize, row: usize) -> f64 {
92 assert!(col < self.cols && row < self.rows, "node out of range");
93 self.check();
94 self.values[row * self.cols + col]
95 }
96
97 #[must_use]
103 pub fn sample(&self, at: Point) -> Option<f64> {
104 self.check();
105 if self.cols == 0 || self.rows == 0 {
106 return None;
107 }
108 let u = (at.0 - self.origin.0) / self.cell;
109 let v = (at.1 - self.origin.1) / self.cell;
110 if !(u >= 0.0 && u <= (self.cols - 1) as f64 && v >= 0.0 && v <= (self.rows - 1) as f64) {
111 return None;
112 }
113 let c0 = (u.floor() as usize).min(self.cols.saturating_sub(2));
114 let r0 = (v.floor() as usize).min(self.rows.saturating_sub(2));
115 let c1 = (c0 + 1).min(self.cols - 1);
116 let r1 = (r0 + 1).min(self.rows - 1);
117 let (fx, fy) = (u - c0 as f64, v - r0 as f64);
118 let at_node = |c: usize, r: usize| self.values[r * self.cols + c];
119 let top = at_node(c0, r0) + (at_node(c1, r0) - at_node(c0, r0)) * fx;
120 let bottom = at_node(c0, r1) + (at_node(c1, r1) - at_node(c0, r1)) * fx;
121 Some(top + (bottom - top) * fy)
122 }
123
124 fn check(&self) {
125 assert!(
126 self.values.len() == self.cols * self.rows,
127 "grid holds {} numbers, expected {} * {}",
128 self.values.len(),
129 self.cols,
130 self.rows
131 );
132 }
133}
134
135const NONE: usize = usize::MAX;
137
138struct Edges {
142 cols: usize,
143 stride: usize,
144}
145
146impl Edges {
147 fn new(grid: &ScalarGrid) -> Self {
148 Self {
149 cols: grid.cols,
150 stride: 2 * grid.cols + 3,
151 }
152 }
153
154 fn count(&self, grid: &ScalarGrid) -> usize {
155 (grid.rows + 2) * self.stride
156 }
157
158 fn horizontal(&self, c: i64, r: i64) -> usize {
160 ((r + 1) as usize) * self.stride + (c + 1) as usize
161 }
162
163 fn vertical(&self, c: i64, r: i64) -> usize {
165 ((r + 1) as usize) * self.stride + self.cols + 1 + (c + 1) as usize
166 }
167}
168
169fn node_value(grid: &ScalarGrid, c: i64, r: i64) -> Option<f64> {
171 if c < 0 || r < 0 || c >= grid.cols as i64 || r >= grid.rows as i64 {
172 None
173 } else {
174 Some(grid.values[r as usize * grid.cols + c as usize])
175 }
176}
177
178fn is_inside(grid: &ScalarGrid, threshold: f64, c: i64, r: i64) -> bool {
179 node_value(grid, c, r).is_some_and(|v| v > threshold)
180}
181
182fn crossing_fraction(threshold: f64, a: f64, b: f64) -> f64 {
184 let t = (threshold - a) / (b - a);
185 if (0.0..=1.0).contains(&t) {
186 t
187 } else {
188 0.5
189 }
190}
191
192fn edge_vertex(grid: &ScalarGrid, threshold: f64, edges: &Edges, edge: usize) -> Point {
195 let row = (edge / edges.stride) as i64 - 1;
196 let rem = edge % edges.stride;
197 let (ox, oy) = grid.origin;
198 if rem < edges.cols + 1 {
199 let c = rem as i64 - 1;
200 let t = match (node_value(grid, c, row), node_value(grid, c + 1, row)) {
201 (Some(a), Some(b)) => crossing_fraction(threshold, a, b),
202 _ => 0.5,
203 };
204 (ox + (c as f64 + t) * grid.cell, oy + row as f64 * grid.cell)
205 } else {
206 let c = (rem - edges.cols - 1) as i64 - 1;
207 let t = match (node_value(grid, c, row), node_value(grid, c, row + 1)) {
208 (Some(a), Some(b)) => crossing_fraction(threshold, a, b),
209 _ => 0.5,
210 };
211 (ox + c as f64 * grid.cell, oy + (row as f64 + t) * grid.cell)
212 }
213}
214
215fn cell_segments(
222 grid: &ScalarGrid,
223 threshold: f64,
224 edges: &Edges,
225 cc: i64,
226 rr: i64,
227 mut emit: impl FnMut(usize, usize),
228) {
229 let corners = [(cc, rr), (cc + 1, rr), (cc + 1, rr + 1), (cc, rr + 1)];
231 let inside = corners.map(|(c, r)| is_inside(grid, threshold, c, r));
232 let sides = [
233 edges.horizontal(cc, rr),
234 edges.vertical(cc + 1, rr),
235 edges.horizontal(cc, rr + 1),
236 edges.vertical(cc, rr),
237 ];
238 let mut crossings = [(NONE, false); 4];
240 let mut n = 0;
241 for k in 0..4 {
242 let next = (k + 1) % 4;
243 if inside[k] != inside[next] {
244 crossings[n] = (sides[k], inside[k]);
245 n += 1;
246 }
247 }
248 match n {
249 2 => {
250 let (from, to) = if crossings[0].1 {
251 (crossings[0].0, crossings[1].0)
252 } else {
253 (crossings[1].0, crossings[0].0)
254 };
255 emit(from, to);
256 }
257 4 => {
258 let value = |c: i64, r: i64| node_value(grid, c, r).unwrap_or(f64::NEG_INFINITY);
259 let sum =
260 ((value(cc, rr) + value(cc + 1, rr)) + value(cc + 1, rr + 1)) + value(cc, rr + 1);
261 let joined = sum / 4.0 > threshold;
262 for k in 0..4 {
263 if crossings[k].1 {
264 let other = if joined { (k + 1) % 4 } else { (k + 3) % 4 };
265 emit(crossings[k].0, crossings[other].0);
266 }
267 }
268 }
269 _ => {}
270 }
271}
272
273#[must_use]
290pub fn iso_lines(grid: &ScalarGrid, threshold: f64) -> Vec<ClosedPath> {
291 grid.check();
292 let edges = Edges::new(grid);
293 let mut next = vec![NONE; edges.count(grid)];
294 for rr in -1..grid.rows as i64 {
295 for cc in -1..grid.cols as i64 {
296 cell_segments(grid, threshold, &edges, cc, rr, |from, to| next[from] = to);
297 }
298 }
299 let mut paths = Vec::new();
300 for start in 0..next.len() {
301 if next[start] == NONE {
302 continue;
303 }
304 let mut path: Vec<Point> = Vec::new();
305 let mut seen: IndexMap<(u64, u64), usize> = IndexMap::new();
306 let mut edge = start;
307 while next[edge] != NONE {
308 let vertex = edge_vertex(grid, threshold, &edges, edge);
309 let key = ((vertex.0 + 0.0).to_bits(), (vertex.1 + 0.0).to_bits());
311 if let Some(&at) = seen.get(&key) {
315 let cut = path.split_off(at + 1);
316 for dropped in &cut {
317 seen.swap_remove(&((dropped.0 + 0.0).to_bits(), (dropped.1 + 0.0).to_bits()));
318 }
319 keep_loop(&mut paths, std::iter::once(vertex).chain(cut).collect());
320 } else {
321 seen.insert(key, path.len());
322 path.push(vertex);
323 }
324 let following = next[edge];
325 next[edge] = NONE;
326 edge = following;
327 }
328 keep_loop(&mut paths, path);
329 }
330 paths
331}
332
333fn keep_loop(paths: &mut Vec<ClosedPath>, path: Vec<Point>) {
335 if path.len() >= 3 && signed_area(&path) != 0.0 {
336 paths.push(path);
337 }
338}
339
340#[must_use]
342pub fn signed_area(path: &[Point]) -> f64 {
343 let mut twice = 0.0_f64;
344 for (k, p) in path.iter().enumerate() {
345 let q = path[(k + 1) % path.len()];
346 twice += p.0 * q.1 - q.0 * p.1;
347 }
348 twice / 2.0
349}
350
351fn crosses_ray(p: Point, q: Point, at: Point) -> bool {
353 if (p.1 > at.1) == (q.1 > at.1) {
354 return false;
355 }
356 let x = p.0 + (at.1 - p.1) * (q.0 - p.0) / (q.1 - p.1);
357 x > at.0
358}
359
360#[must_use]
362pub fn contains(paths: &[ClosedPath], at: Point) -> bool {
363 let mut inside = false;
364 for path in paths {
365 for (k, p) in path.iter().enumerate() {
366 let q = path[(k + 1) % path.len()];
367 if crosses_ray(*p, q, at) {
368 inside = !inside;
369 }
370 }
371 }
372 inside
373}
374
375pub(crate) fn inside_cell(grid: &ScalarGrid, threshold: f64, at: Point) -> bool {
385 grid.check();
386 let u = ((at.0 - grid.origin.0) / grid.cell).floor();
387 let v = ((at.1 - grid.origin.1) / grid.cell).floor();
388 if !(u >= -1.0 && u < grid.cols as f64 && v >= -1.0 && v < grid.rows as f64) {
390 return false;
391 }
392 let (cc, rr) = (u as i64, v as i64);
393 let edges = Edges::new(grid);
394 let mut crossed = false;
395 cell_segments(grid, threshold, &edges, cc, rr, |from, to| {
396 let p = edge_vertex(grid, threshold, &edges, from);
397 let q = edge_vertex(grid, threshold, &edges, to);
398 if crosses_ray(p, q, at) {
399 crossed = !crossed;
400 }
401 });
402 let below = is_inside(grid, threshold, cc + 1, rr);
404 let above = is_inside(grid, threshold, cc + 1, rr + 1);
405 let at_edge = if below == above {
406 below
407 } else {
408 let y = edge_vertex(grid, threshold, &edges, edges.vertical(cc + 1, rr)).1;
409 if at.1 < y {
410 below
411 } else {
412 above
413 }
414 };
415 at_edge != crossed
416}
417
418#[cfg(test)]
419mod tests {
420 use super::*;
421
422 fn lcg(state: &mut u64) -> f64 {
423 *state = state
424 .wrapping_mul(6_364_136_223_846_793_005)
425 .wrapping_add(1_442_695_040_888_963_407);
426 (*state >> 40) as f64 / (1_u64 << 24) as f64
427 }
428
429 #[test]
430 fn inside_cell_agrees_with_contains() {
431 let mut state = 20_261_121_u64;
432 let mut grid = ScalarGrid::zeros((0.0, 0.0), 1.0, 40, 30).unwrap();
433 for value in &mut grid.values {
434 *value = lcg(&mut state);
435 }
436 let paths = iso_lines(&grid, 0.5);
437 let mut second = 7_u64;
438 let mut inside = 0;
439 for _ in 0..2_000 {
440 let p = (lcg(&mut second) * 39.0, lcg(&mut second) * 29.0);
441 let expected = contains(&paths, p);
442 assert_eq!(inside_cell(&grid, 0.5, p), expected, "at {p:?}");
443 inside += usize::from(expected);
444 }
445 assert!(inside > 300 && inside < 1_700, "{inside} inside");
446 assert!(!inside_cell(&grid, 0.5, (-3.0, 4.0)));
447 }
448}