Skip to main content

sciart_shared/
vortex_advect.rs

1//! Semi-Lagrangian transport of scalar fields (dye, cloud water) by a prescribed,
2//! kinematic velocity on a capped lattice (M13 shared model: `jupiter_storms`,
3//! `hurricane`; ADR-0012 caps).
4//!
5//! The flow is not solved: a scene writes node velocities (lattice cells per second) into
6//! a [`Flow`], usually as differences of a stream function across each cell (the form of
7//! `stream_velocity`, which scenes reproduce with cached factors), which makes the
8//! discrete field exactly divergence-free, and [`advect`] carries a field along it. Each
9//! node traces its departure point back with a midpoint (RK2) step and takes the bilinear
10//! value there, so the scheme is unconditionally stable for any `dt` (GEN-R4) at the price
11//! of a little numerical diffusion, which the scenes counter with their sources.
12//!
13//! Lattice coordinates: node `(i, j)` sits at `(x, y) = (i, j)`, `y` down the screen.
14//! Everything here is allocation-free once the grids are sized (GEN-R11).
15
16use sciart_core::rng::{cell_key, hash01};
17use sciart_core::{Grid, Size};
18
19/// What lies beyond the left and right edges: a planet's longitude wraps round, a storm's
20/// box is clamped (its edge value is repeated). Rows are always clamped.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum XEdge {
23    Wrap,
24    Clamp,
25}
26
27/// Node velocities in lattice cells per second.
28#[derive(Debug, Clone, Default)]
29pub struct Flow {
30    pub u: Grid<f32>,
31    pub v: Grid<f32>,
32}
33
34impl Flow {
35    /// Resize both components to `lattice` (contents are rewritten by the scene).
36    pub fn resize(&mut self, lattice: Size) {
37        self.u.resize(lattice, 0.0);
38        self.v.resize(lattice, 0.0);
39    }
40
41    #[cfg(any(test, feature = "test-support"))]
42    /// Set every node's velocity to `f(x, y)`.
43    pub fn fill_with(&mut self, mut f: impl FnMut(f64, f64) -> (f64, f64)) {
44        let w = usize::from(self.u.width()).max(1);
45        let (us, vs) = (self.u.as_mut_slice(), self.v.as_mut_slice());
46        for (k, (u, v)) in us.iter_mut().zip(vs.iter_mut()).enumerate() {
47            let (a, b) = f((k % w) as f64, (k / w) as f64);
48            *u = a as f32;
49            *v = b as f32;
50        }
51    }
52}
53
54#[cfg(any(test, feature = "test-support"))]
55/// The velocity of stream function `psi` at `(x, y)`: `u = ∂ψ/∂y`, `v = −∂ψ/∂x`, each as
56/// the difference of ψ across a cell of side `h` centred on the point. The discrete
57/// divergence built from the same differences cancels term by term (JUP-A1), so the
58/// sampled flow neither creates nor destroys dye. With `y` down the screen a positive
59/// bump of ψ turns clockwise on screen and a negative one counter-clockwise.
60#[inline]
61pub fn stream_velocity(psi: impl Fn(f64, f64) -> f64, x: f64, y: f64, h: f64) -> (f64, f64) {
62    let e = 0.5 * h;
63    let u = (psi(x, y + e) - psi(x, y - e)) / h;
64    let v = -(psi(x + e, y) - psi(x - e, y)) / h;
65    (u, v)
66}
67
68/// Bilinear value of `g` at lattice point `(x, y)`, clamped in `y` and wrapped or clamped
69/// in `x` by `edge`; 0 for an empty grid or a non-finite point.
70#[inline]
71pub fn sample(g: &Grid<f32>, x: f32, y: f32, edge: XEdge) -> f32 {
72    let (w, h) = (usize::from(g.width()), usize::from(g.height()));
73    if w == 0 || h == 0 || !(x.is_finite() && y.is_finite()) {
74        return 0.0;
75    }
76    let cells = g.as_slice();
77    let (wf, hf) = (w as f32, h as f32);
78    let y = y.clamp(0.0, hf - 1.0);
79    let (y0, fy) = (y.floor(), y - y.floor());
80    let j0 = y0 as usize;
81    let j1 = (j0 + 1).min(h - 1);
82    let (i0, i1, fx) = match edge {
83        XEdge::Wrap => {
84            let x = x.rem_euclid(wf);
85            let x0 = x.floor();
86            // `rem_euclid` can round up to exactly `wf`; fold that back onto node 0.
87            let i0 = (x0 as usize) % w;
88            (i0, (i0 + 1) % w, x - x0)
89        }
90        XEdge::Clamp => {
91            let x = x.clamp(0.0, wf - 1.0);
92            let x0 = x.floor();
93            let i0 = x0 as usize;
94            (i0, (i0 + 1).min(w - 1), x - x0)
95        }
96    };
97    let (r0, r1) = (&cells[j0 * w..][..w], &cells[j1 * w..][..w]);
98    let top = r0[i0] + fx * (r0[i1] - r0[i0]);
99    let bottom = r1[i0] + fx * (r1[i1] - r1[i0]);
100    top + fy * (bottom - top)
101}
102
103/// Call `f(k, x, y)` with the departure point `(x, y)` of every node `k` (row-major):
104/// where the fluid now at the node was `dt` seconds ago, traced back along a midpoint
105/// (RK2) characteristic. A scene carrying several fields samples each of them there.
106pub fn departures(flow: &Flow, dt: f32, edge: XEdge, mut f: impl FnMut(usize, f32, f32)) {
107    let w = usize::from(flow.u.width());
108    if w == 0 || flow.u.size() != flow.v.size() {
109        return;
110    }
111    let (us, vs) = (flow.u.as_slice(), flow.v.as_slice());
112    for (k, (&u, &v)) in us.iter().zip(vs).enumerate() {
113        let (x, y) = ((k % w) as f32, (k / w) as f32);
114        let (xm, ym) = (x - 0.5 * dt * u, y - 0.5 * dt * v);
115        let (um, vm) = (sample(&flow.u, xm, ym, edge), sample(&flow.v, xm, ym, edge));
116        f(k, x - dt * um, y - dt * vm);
117    }
118}
119
120/// Carry `src` along `flow` for `dt` seconds into `dst` (resized to `src`): each node
121/// takes the bilinear value of `src` at its [`departures`] point. `flow` must have
122/// `src`'s size, else `dst` is left zeroed.
123pub fn advect(src: &Grid<f32>, dst: &mut Grid<f32>, flow: &Flow, dt: f32, edge: XEdge) {
124    dst.resize(src.size(), 0.0);
125    if flow.u.size() != src.size() {
126        dst.fill(0.0);
127        return;
128    }
129    let out = dst.as_mut_slice();
130    departures(flow, dt, edge, |k, x, y| out[k] = sample(src, x, y, edge));
131}
132
133/// Value noise that wraps every `period` units in `x` (a planet's longitude), so the
134/// seam never shows: `sciart_core::rng::value_noise` (CORE-R97) with unit cells, except
135/// that the lattice column index is taken modulo `period`, which the core form cannot do.
136#[inline]
137pub fn value_noise_wrap_x(salt: u64, x: f64, y: f64, period: i32) -> f64 {
138    if !(x.is_finite() && y.is_finite()) || period < 1 {
139        return 0.0;
140    }
141    let p = f64::from(period);
142    let x = x.rem_euclid(p);
143    let (x0, y0) = (x.floor(), y.floor());
144    let (fx, fy) = (x - x0, y - y0);
145    let (sx, sy) = (fx * fx * (3.0 - 2.0 * fx), fy * fy * (3.0 - 2.0 * fy));
146    let (i, j) = ((x0 as i32).rem_euclid(period), y0 as i32);
147    let at =
148        |di: i32, dj: i32| hash01(salt ^ cell_key((i + di).rem_euclid(period), j.wrapping_add(dj)));
149    let top = at(0, 0) + sx * (at(1, 0) - at(0, 0));
150    let bottom = at(0, 1) + sx * (at(1, 1) - at(0, 1));
151    top + sy * (bottom - top)
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157    use sciart_core::Trig;
158
159    fn gaussian_psi(x: f64, y: f64) -> f64 {
160        let (dx, dy) = (x - 10.0, y - 6.0);
161        -30.0 * (-(dx * dx / 16.0 + dy * dy / 4.0)).exp() + 0.7 * (0.4 * y).sin_det()
162    }
163
164    #[test]
165    fn stream_velocity_is_discretely_divergence_free() {
166        let h = 1.0;
167        for &(x, y) in &[(3.0, 4.0), (10.2, 6.1), (12.7, 3.3), (0.5, 9.5)] {
168            let e = 0.5 * h;
169            let (ue, _) = stream_velocity(gaussian_psi, x + e, y, h);
170            let (uw, _) = stream_velocity(gaussian_psi, x - e, y, h);
171            let (_, vs) = stream_velocity(gaussian_psi, x, y + e, h);
172            let (_, vn) = stream_velocity(gaussian_psi, x, y - e, h);
173            let div = (ue - uw + vs - vn) / h;
174            assert!(div.abs() < 1e-9, "div {div} at ({x}, {y})");
175        }
176    }
177
178    #[test]
179    fn sample_wraps_and_clamps() {
180        let mut g = Grid::new(Size::new(4, 2), 0.0f32);
181        g.set(3, 0, 1.0);
182        // Halfway from the last column to the first (wrapped) column.
183        assert!((sample(&g, 3.5, 0.0, XEdge::Wrap) - 0.5).abs() < 1e-6);
184        assert!((sample(&g, -0.5, 0.0, XEdge::Wrap) - 0.5).abs() < 1e-6);
185        assert!((sample(&g, 9.0, -3.0, XEdge::Clamp) - 1.0).abs() < 1e-6);
186        assert_eq!(sample(&g, f32::NAN, 0.0, XEdge::Wrap), 0.0);
187        assert_eq!(sample(&Grid::default(), 1.0, 1.0, XEdge::Wrap), 0.0);
188    }
189
190    #[test]
191    fn uniform_flow_translates_a_field() {
192        let size = Size::new(16, 4);
193        let mut src = Grid::new(size, 0.0f32);
194        src.set(5, 2, 1.0);
195        let mut flow = Flow::default();
196        flow.resize(size);
197        flow.fill_with(|_, _| (2.0, 0.0));
198        let mut dst = Grid::default();
199        advect(&src, &mut dst, &flow, 0.5, XEdge::Wrap);
200        assert!((dst.get(6, 2).copied().unwrap_or(0.0) - 1.0).abs() < 1e-6);
201        assert!(dst.get(5, 2).copied().unwrap_or(1.0).abs() < 1e-6);
202    }
203
204    #[test]
205    fn value_noise_wrap_x_is_the_core_noise_made_periodic() {
206        for k in 0..200 {
207            let (x, y) = (f64::from(k) * 0.37, f64::from(k) * 0.11);
208            let xr = x.rem_euclid(8.0);
209            if xr < 7.0 {
210                // Away from the seam column it is CORE-R97's noise exactly.
211                let core = sciart_core::rng::value_noise(3, xr, y, 1.0);
212                assert!((core - value_noise_wrap_x(3, x, y, 8)).abs() < 1e-12);
213            }
214            let a = value_noise_wrap_x(3, x, y, 8);
215            let b = value_noise_wrap_x(3, x + 8.0, y, 8);
216            assert!((a - b).abs() < 1e-12);
217        }
218        assert_eq!(value_noise_wrap_x(1, f64::NAN, 0.0, 8), 0.0);
219    }
220}