1pub const FIXED_8_24_SCALE: i64 = 1 << 24;
12
13#[inline]
15pub fn f32_to_fixed824(val: f32) -> i64 {
16 (val * (FIXED_8_24_SCALE as f32)).round() as i64
17}
18
19#[inline]
21pub fn fixed824_to_f32(val: i64) -> f32 {
22 val as f32 / (FIXED_8_24_SCALE as f32)
23}
24
25pub fn step_hydraulic_pipe_fixed824(
28 height_q24: &mut [i64],
29 water_q24: &mut [i64],
30 sediment_q24: &mut [i64],
31 flux_nesw_q24: &mut [[i64; 4]],
32 width: usize,
33 height: usize,
34 rain_q24: i64,
35 evap_shift: u32,
36 capacity_shift: u32,
37) -> Result<i64, &'static str> {
38 if width == 0 || height == 0 { return Err("Grid dimensions must be non-zero"); }
39 let total = width.checked_mul(height).ok_or("Grid dimensions overflow")?;
40 if height_q24.len() != total || water_q24.len() != total || sediment_q24.len() != total || flux_nesw_q24.len() != total {
41 return Err("Slice length does not match width * height");
42 }
43
44 let mut mass_before: i64 = 0;
45 for i in 0..total { mass_before = mass_before.wrapping_add(height_q24[i]).wrapping_add(sediment_q24[i]); }
46 if rain_q24 > 0 { for w in water_q24.iter_mut() { *w = w.saturating_add(rain_q24); } }
47
48 for y in 0..height {
50 for x in 0..width {
51 let idx = y * width + x;
52 let total_h = height_q24[idx].saturating_add(water_q24[idx]);
53 let n_idx = [y.checked_sub(1).map(|py| py * width + x), (x + 1 < width).then_some(y * width + x + 1), (y + 1 < height).then_some((y + 1) * width + x), x.checked_sub(1).map(|px| y * width + px)];
54
55 for d in 0..4 {
56 flux_nesw_q24[idx][d] = match n_idx[d] {
57 Some(ni) => (flux_nesw_q24[idx][d] + ((total_h - height_q24[ni].saturating_add(water_q24[ni])) >> 1)).max(0),
58 None => 0,
59 };
60 }
61
62 let sum_flux = flux_nesw_q24[idx][0] + flux_nesw_q24[idx][1] + flux_nesw_q24[idx][2] + flux_nesw_q24[idx][3];
63 let cur_w = water_q24[idx];
64 if cur_w <= 0 {
65 flux_nesw_q24[idx] = [0; 4];
66 } else if sum_flux > cur_w {
67 let mut sum_scaled = 0i64;
68 for d in 0..3 {
69 let scaled = ((flux_nesw_q24[idx][d] as i128 * cur_w as i128) / sum_flux as i128) as i64;
70 flux_nesw_q24[idx][d] = scaled;
71 sum_scaled += scaled;
72 }
73 flux_nesw_q24[idx][3] = (cur_w - sum_scaled).max(0);
74 }
75 }
76 }
77
78 for y in 0..height {
80 for x in 0..width {
81 let idx = y * width + x;
82 let outflow = flux_nesw_q24[idx][0] + flux_nesw_q24[idx][1] + flux_nesw_q24[idx][2] + flux_nesw_q24[idx][3];
83 let inflow = (if y > 0 { flux_nesw_q24[(y - 1) * width + x][2] } else { 0 }) + (if x + 1 < width { flux_nesw_q24[y * width + x + 1][3] } else { 0 })
84 + (if y + 1 < height { flux_nesw_q24[(y + 1) * width + x][0] } else { 0 }) + (if x > 0 { flux_nesw_q24[y * width + x - 1][1] } else { 0 });
85
86 let new_w = (water_q24[idx] + (inflow - outflow)).max(0);
87 let evap = if evap_shift < 64 { new_w >> evap_shift } else { 0 };
88 water_q24[idx] = new_w.saturating_sub(evap);
89
90 let flow_mag = (inflow + outflow) >> 1;
91 let capacity = if capacity_shift < 64 { flow_mag >> capacity_shift } else { 0 };
92 let s = sediment_q24[idx];
93 if s < capacity {
94 let erode = ((capacity - s) >> 2).min(height_q24[idx]);
95 height_q24[idx] -= erode;
96 sediment_q24[idx] += erode;
97 } else if s > capacity {
98 let deposit = (s - capacity) >> 2;
99 height_q24[idx] += deposit;
100 sediment_q24[idx] -= deposit;
101 }
102 }
103 }
104
105 let mut mass_after: i64 = 0;
106 for i in 0..total { mass_after = mass_after.wrapping_add(height_q24[i]).wrapping_add(sediment_q24[i]); }
107 Ok(mass_after.wrapping_sub(mass_before))
108}
109
110#[repr(C)]
112#[derive(Debug, Clone, Copy, Default)]
113pub struct StrataCell6 {
114 pub bedrock: f32, pub saprolite: f32, pub regolith: f32, pub sand: f32,
115 pub silt: f32, pub snow_ice: f32, pub water: f32, pub suspended_sediment: f32,
116}
117
118impl StrataCell6 {
119 #[inline] pub fn surface_elevation(&self) -> f32 { self.bedrock + self.saprolite + self.regolith + self.sand + self.silt + self.snow_ice }
121 #[inline] pub fn total_solid_mass(&self) -> f32 { self.bedrock + self.saprolite + self.regolith + self.sand + self.silt + self.snow_ice }
123}
124
125#[derive(Debug, Clone, Copy)]
127pub struct CoupledErosionParams {
128 pub dt: f32, pub cell_size: f32, pub rainfall_rate: f32, pub evaporation_rate: f32,
129 pub kc_transport: f32, pub ks_silt: f32, pub ks_sand: f32, pub ks_regolith: f32,
130 pub ks_saprolite: f32, pub ks_bedrock: f32, pub kd_deposition: f32,
131}
132
133impl Default for CoupledErosionParams {
134 fn default() -> Self {
135 Self {
136 dt: 0.1, cell_size: 1.0, rainfall_rate: 0.01, evaporation_rate: 0.005,
137 kc_transport: 1.0, ks_silt: 0.8, ks_sand: 0.5, ks_regolith: 0.2,
138 ks_saprolite: 0.08, ks_bedrock: 0.02, kd_deposition: 0.1,
139 }
140 }
141}
142
143pub fn step_coupled_6species_erosion(
145 cells: &mut [StrataCell6],
146 flux_scratch: &mut [[f32; 4]],
147 width: usize,
148 height: usize,
149 params: &CoupledErosionParams,
150) -> Result<f32, &'static str> {
151 if width == 0 || height == 0 { return Err("Grid dimensions must be non-zero"); }
152 let total = width.checked_mul(height).ok_or("Grid dimensions overflow")?;
153 if cells.len() != total || flux_scratch.len() != total { return Err("Slice length mismatch"); }
154 if params.cell_size <= 0.0 || params.dt <= 0.0 { return Err("Invalid parameters"); }
155
156 let rain_vol = params.rainfall_rate * params.dt;
157 if rain_vol > 0.0 { for c in cells.iter_mut() { c.water += rain_vol; } }
158
159 let g = 9.81f32;
160 for y in 0..height {
161 for x in 0..width {
162 let idx = y * width + x;
163 let total_h = cells[idx].surface_elevation() + cells[idx].water;
164 let n_idx = [y.checked_sub(1).map(|py| py * width + x), (x + 1 < width).then_some(y * width + x + 1), (y + 1 < height).then_some((y + 1) * width + x), x.checked_sub(1).map(|px| y * width + px)];
165
166 for d in 0..4 {
167 flux_scratch[idx][d] = match n_idx[d] {
168 Some(ni) => (flux_scratch[idx][d] + params.dt * (g * (total_h - (cells[ni].surface_elevation() + cells[ni].water)) / params.cell_size)).max(0.0),
169 None => 0.0,
170 };
171 }
172
173 let sum_flux = flux_scratch[idx][0] + flux_scratch[idx][1] + flux_scratch[idx][2] + flux_scratch[idx][3];
174 let max_flux = cells[idx].water / params.dt;
175 if max_flux <= 0.0 {
176 flux_scratch[idx] = [0.0; 4];
177 } else if sum_flux > max_flux && sum_flux > 1e-7 {
178 let scale = max_flux / sum_flux;
179 for d in 0..4 { flux_scratch[idx][d] *= scale; }
180 }
181 }
182 }
183
184 let mut total_mobilized = 0.0f32;
185 for y in 0..height {
186 for x in 0..width {
187 let idx = y * width + x;
188 let outflow = flux_scratch[idx][0] + flux_scratch[idx][1] + flux_scratch[idx][2] + flux_scratch[idx][3];
189 let inflow = (if y > 0 { flux_scratch[(y - 1) * width + x][2] } else { 0.0 }) + (if x + 1 < width { flux_scratch[y * width + x + 1][3] } else { 0.0 })
190 + (if y + 1 < height { flux_scratch[(y + 1) * width + x][0] } else { 0.0 }) + (if x > 0 { flux_scratch[y * width + x - 1][1] } else { 0.0 });
191
192 let new_w = (cells[idx].water + (inflow - outflow) * params.dt).max(0.0);
193 cells[idx].water = (new_w - params.evaporation_rate * params.dt).max(0.0);
194
195 let cur_elev = cells[idx].surface_elevation();
196 let mut max_dh = 0.0f32;
197 if y > 0 { max_dh = max_dh.max(cur_elev - cells[(y - 1) * width + x].surface_elevation()); } if x + 1 < width { max_dh = max_dh.max(cur_elev - cells[y * width + x + 1].surface_elevation()); }
198 if y + 1 < height { max_dh = max_dh.max(cur_elev - cells[(y + 1) * width + x].surface_elevation()); } if x > 0 { max_dh = max_dh.max(cur_elev - cells[y * width + x - 1].surface_elevation()); }
199 let slope = (max_dh / params.cell_size).max(0.01);
200
201 let capacity = params.kc_transport * 0.5 * (inflow + outflow) * slope;
202 let suspended = cells[idx].suspended_sediment;
203
204 if suspended < capacity {
205 let mut deficit = (capacity - suspended) * params.dt;
206 let layers: [(&mut f32, f32); 5] = [
207 (&mut cells[idx].silt, params.ks_silt),
208 (&mut cells[idx].sand, params.ks_sand),
209 (&mut cells[idx].regolith, params.ks_regolith),
210 (&mut cells[idx].saprolite, params.ks_saprolite),
211 (&mut cells[idx].bedrock, params.ks_bedrock),
212 ];
213 for (layer, rate) in layers {
214 if deficit <= 0.0 { break; }
215 if *layer > 0.0 {
216 let take = (deficit * rate).min(*layer);
217 *layer -= take;
218 cells[idx].suspended_sediment += take;
219 deficit -= take;
220 total_mobilized += take;
221 }
222 }
223 } else if suspended > capacity {
224 let dep = ((suspended - capacity) * params.kd_deposition * params.dt).min(cells[idx].suspended_sediment);
225 let dep_sand = dep * 0.7;
226 cells[idx].sand += dep_sand;
227 cells[idx].silt += dep - dep_sand;
228 cells[idx].suspended_sediment -= dep;
229 }
230 }
231 }
232
233 Ok(total_mobilized)
234}
235
236pub fn trace_erosion_droplet(
238 dem: &mut [f32],
239 width: usize,
240 height: usize,
241 start_x: f32,
242 start_y: f32,
243 inertia: f32,
244 capacity_mult: f32,
245 deposition_rate: f32,
246 erosion_rate: f32,
247 evaporation: f32,
248 max_steps: u32,
249) -> Result<f32, &'static str> {
250 if width < 2 || height < 2 { return Err("Grid dimensions must be at least 2x2"); }
251 if dem.len() != width * height { return Err("DEM length mismatch"); }
252
253 let (mut px, mut py) = (start_x, start_y);
254 let (mut dir_x, mut dir_y) = (0.0f32, 0.0f32);
255 let (mut speed, mut water, mut sediment) = (1.0f32, 1.0f32, 0.0f32);
256 let mut total_eroded = 0.0f32;
257
258 for _ in 0..max_steps {
259 let (ix, iy) = (px.floor() as usize, py.floor() as usize);
260 if ix >= width - 1 || iy >= height - 1 || px < 0.0 || py < 0.0 { break; }
261
262 let (u, v) = (px - ix as f32, py - iy as f32);
263 let idx00 = iy * width + ix;
264 let (h00, h10, h01, h11) = (dem[idx00], dem[idx00 + 1], dem[idx00 + width], dem[idx00 + width + 1]);
265 let cur_h = (1.0 - u) * (1.0 - v) * h00 + u * (1.0 - v) * h10 + (1.0 - u) * v * h01 + u * v * h11;
266 let gx = (h10 - h00) * (1.0 - v) + (h11 - h01) * v;
267 let gy = (h01 - h00) * (1.0 - u) + (h11 - h10) * u;
268
269 dir_x = dir_x * inertia - gx * (1.0 - inertia);
270 dir_y = dir_y * inertia - gy * (1.0 - inertia);
271 let len_sq = dir_x * dir_x + dir_y * dir_y;
272 if len_sq < 1e-8 { break; }
273 let inv_len = 1.0 / len_sq.sqrt();
274 dir_x *= inv_len; dir_y *= inv_len;
275
276 let (next_px, next_py) = (px + dir_x, py + dir_y);
277 let (nix, niy) = (next_px.floor() as usize, next_py.floor() as usize);
278 if nix >= width - 1 || niy >= height - 1 || next_px < 0.0 || next_py < 0.0 { break; }
279
280 let (nu, nv) = (next_px - nix as f32, next_py - niy as f32);
281 let nidx00 = niy * width + nix;
282 let next_h = (1.0 - nu) * (1.0 - nv) * dem[nidx00] + nu * (1.0 - nv) * dem[nidx00 + 1]
283 + (1.0 - nu) * nv * dem[nidx00 + width] + nu * nv * dem[nidx00 + width + 1];
284 let dh = next_h - cur_h;
285
286 let w = [(1.0 - u) * (1.0 - v), u * (1.0 - v), (1.0 - u) * v, u * v];
287 let c = [idx00, idx00 + 1, idx00 + width, idx00 + width + 1];
288
289 if dh > 0.0 {
290 let dep = dh.min(sediment);
291 for i in 0..4 { dem[c[i]] += dep * w[i]; }
292 sediment -= dep;
293 if sediment < 1e-5 { break; }
294 } else {
295 let capacity = (-dh).max(0.01) * speed * water * capacity_mult;
296 if sediment > capacity {
297 let dep = (sediment - capacity) * deposition_rate;
298 for i in 0..4 { dem[c[i]] += dep * w[i]; }
299 sediment -= dep;
300 } else {
301 let erode = ((capacity - sediment) * erosion_rate).min(-dh);
302 for i in 0..4 { dem[c[i]] -= erode * w[i]; }
303 sediment += erode;
304 total_eroded += erode;
305 }
306 }
307
308 speed = (speed * speed + (-dh) * 9.81).max(0.0).sqrt();
309 water *= (1.0 - evaporation).max(0.0);
310 if water < 1e-4 { break; }
311 px = next_px; py = next_py;
312 }
313 Ok(total_eroded)
314}
315
316pub fn carve_meander_channel(
318 dem: &mut [f32],
319 width: usize,
320 height: usize,
321 centerline_xy: &[[f32; 2]],
322 bankfull_width_cells: f32,
323 thalweg_depth: f32,
324 point_bar_asymmetry: f32,
325) -> Result<(), &'static str> {
326 if width == 0 || height == 0 { return Err("Grid dimensions must be non-zero"); }
327 if dem.len() != width * height { return Err("DEM slice length mismatch"); }
328 if centerline_xy.len() < 2 { return Err("Centerline must have at least 2 points"); }
329 if bankfull_width_cells <= 0.0 || thalweg_depth <= 0.0 { return Err("Invalid channel geometry"); }
330
331 for y in 0..height {
332 let cy = y as f32;
333 for x in 0..width {
334 let cx = x as f32;
335 let mut min_dist_sq = f32::MAX;
336 let mut best_signed_lat = 0.0f32;
337 let mut best_kappa = 0.0f32;
338
339 for i in 0..(centerline_xy.len() - 1) {
340 let (p0, p1) = (centerline_xy[i], centerline_xy[i + 1]);
341 let (vx, vy) = (p1[0] - p0[0], p1[1] - p0[1]);
342 let len_sq = vx * vx + vy * vy;
343 if len_sq < 1e-8 { continue; }
344 let inv_len = 1.0 / len_sq.sqrt();
345 let (tx, ty) = (vx * inv_len, vy * inv_len);
346 let (nx, ny) = (-ty, tx);
347
348 let (wx, wy) = (cx - p0[0], cy - p0[1]);
349 let t_clamped = ((wx * tx + wy * ty) * inv_len).clamp(0.0, 1.0);
350 let (dx, dy) = (cx - (p0[0] + vx * t_clamped), cy - (p0[1] + vy * t_clamped));
351 let d_sq = dx * dx + dy * dy;
352
353 if d_sq < min_dist_sq {
354 min_dist_sq = d_sq;
355 best_signed_lat = dx * nx + dy * ny;
356 let k0 = if i > 0 { let (ux, uy) = (p0[0] - centerline_xy[i - 1][0], p0[1] - centerline_xy[i - 1][1]); (ux * vy - uy * vx) / ((ux * ux + uy * uy).sqrt() * len_sq.sqrt() + 1e-6) } else { 0.0 };
357 let k1 = if i + 2 < centerline_xy.len() { let (nx2, ny2) = (centerline_xy[i + 2][0] - p1[0], centerline_xy[i + 2][1] - p1[1]); (vx * ny2 - vy * nx2) / (len_sq.sqrt() * (nx2 * nx2 + ny2 * ny2).sqrt() + 1e-6) } else { 0.0 };
358 best_kappa = ((1.0 - t_clamped) * k0 + t_clamped * k1).clamp(-1.0, 1.0);
359 }
360 }
361
362 let min_dist = min_dist_sq.sqrt();
363 if min_dist <= bankfull_width_cells {
364 let xi = (best_signed_lat / bankfull_width_cells).clamp(-1.0, 1.0);
365 let thalweg_shift = (point_bar_asymmetry * best_kappa).clamp(-0.7, 0.7);
366 let xi_rel = if xi < thalweg_shift { (xi - thalweg_shift) / (1.0 + thalweg_shift) } else { (xi - thalweg_shift) / (1.0 - thalweg_shift) };
367 let profile = (1.0 - xi_rel * xi_rel).max(0.0);
368 dem[y * width + x] -= thalweg_depth * profile * profile;
369 }
370 }
371 }
372 Ok(())
373}
374
375#[cfg(test)]
376mod tests {
377 use super::*;
378
379 #[test]
380 fn test_step_hydraulic_pipe_fixed824_conservation_and_determinism() {
381 let (mut height1, mut water1, mut sediment1, mut flux1) = ([0i64; 16], [0i64; 16], [0i64; 16], [[0i64; 4]; 16]);
382 for i in 0..16 { height1[i] = f32_to_fixed824((16 - i) as f32 * 5.0); }
383 water1[0] = f32_to_fixed824(10.0);
384
385 let (mut height2, mut water2, mut sediment2, mut flux2) = (height1, water1, sediment1, flux1);
386
387 for _ in 0..5 {
388 let delta1 = step_hydraulic_pipe_fixed824(
389 &mut height1, &mut water1, &mut sediment1, &mut flux1,
390 4, 4, f32_to_fixed824(0.05), 3, 2,
391 ).unwrap();
392 assert_eq!(delta1, 0, "Mass delta must be zero (mass conserved)");
393
394 let delta2 = step_hydraulic_pipe_fixed824(
395 &mut height2, &mut water2, &mut sediment2, &mut flux2,
396 4, 4, f32_to_fixed824(0.05), 3, 2,
397 ).unwrap();
398 assert_eq!(delta2, 0);
399 }
400
401 assert_eq!(height1, height2, "Bit-exact determinism across identical runs");
402 assert_eq!(water1, water2);
403 assert_eq!(sediment1, sediment2);
404 assert_eq!(flux1, flux2);
405 }
406
407 #[test]
408 fn test_step_coupled_6species_differential_erodibility() {
409 let (mut cells, mut flux) = ([StrataCell6::default(); 4], [[0.0f32; 4]; 4]);
410 cells[0].silt = 20.0; cells[0].sand = 10.0; cells[0].regolith = 5.0; cells[0].saprolite = 5.0; cells[0].bedrock = 50.0; cells[0].water = 5.0;
411 cells[1].bedrock = 20.0; cells[2].bedrock = 10.0; cells[3].bedrock = 0.0;
412
413 let params = CoupledErosionParams {
414 dt: 0.1, cell_size: 1.0, rainfall_rate: 0.1, evaporation_rate: 0.01,
415 kc_transport: 5.0, ks_silt: 0.9, ks_sand: 0.5, ks_regolith: 0.2,
416 ks_saprolite: 0.08, ks_bedrock: 0.01, kd_deposition: 0.1,
417 };
418
419 let mass_before: f32 = cells.iter().map(|c| c.total_solid_mass() + c.suspended_sediment).sum();
420 let initial_silt = cells[0].silt;
421 let initial_bedrock = cells[0].bedrock;
422
423 let mobilized = step_coupled_6species_erosion(&mut cells, &mut flux, 2, 2, ¶ms).unwrap();
424 assert!(mobilized > 0.0, "Erosion should mobilize mass");
425
426 let mass_after: f32 = cells.iter().map(|c| c.total_solid_mass() + c.suspended_sediment).sum();
427 assert!((mass_after - mass_before).abs() < 1e-4, "Solid mass + sediment strictly conserved");
428
429 let silt_lost = initial_silt - cells[0].silt;
430 let bedrock_lost = initial_bedrock - cells[0].bedrock;
431 assert!(silt_lost > bedrock_lost, "Silt must erode faster than bedrock");
432 }
433
434 #[test]
435 fn test_trace_erosion_droplet_16x16() {
436 let mut dem = [0.0f32; 256];
437 for y in 0..16 {
438 for x in 0..16 { dem[y * 16 + x] = 100.0 - (x + y) as f32 * 2.5; }
439 }
440
441 let initial_elev = dem[2 * 16 + 2];
442 let eroded = trace_erosion_droplet(
443 &mut dem, 16, 16, 2.0, 2.0, 0.2, 2.0, 0.1, 0.3, 0.01, 40,
444 ).unwrap();
445
446 assert!(eroded > 0.0, "Droplet must erode terrain on downhill slope");
447 assert!(dem[2 * 16 + 2] <= initial_elev, "Elevation at start path should be eroded");
448 }
449
450 #[test]
451 fn test_carve_meander_channel_16x16() {
452 let mut dem = [60.0f32; 256];
453 let centerline = [[2.0, 8.0], [8.0, 4.0], [14.0, 8.0]];
454
455 carve_meander_channel(&mut dem, 16, 16, ¢erline, 3.0, 12.0, 0.7).unwrap();
456
457 assert_eq!(dem[0], 60.0, "Corner far from centerline must be untouched");
458 assert!(dem[4 * 16 + 8] < 60.0, "Channel center must be carved");
459
460 let depth_point_bar = 60.0 - dem[6 * 16 + 8];
461 let depth_cutbank = 60.0 - dem[2 * 16 + 8];
462 assert!(depth_cutbank != depth_point_bar, "Meander channel cross-section must be asymmetric");
463 }
464}