alice-sdf 6.0.0

ALICE-SDF: 3D/Spatial Data Specialist — Store laws, not polygons. GLSL/WGSL/HLSL transpile, SVO, GPU marching cubes, texture-fit, procedural CSG. Optional bridges to alice-physics / alice-codec / libasp / alice-cache behind features.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Erosion Simulation: Hydraulic + Thermal erosion (Deep Fried Edition)
//!
//! Particle-based hydraulic erosion: raindrops flow downhill, erode terrain,
//! carry sediment, and deposit it. Thermal erosion smooths steep slopes.
//!
//! Author: Moroya Sakamoto

use super::Heightmap;
use crate::compiled::real::LawMinMax;
use crate::crispy::fast_normalize_2d;

/// Configuration for erosion simulation
#[derive(Debug, Clone)]
pub struct ErosionConfig {
    /// Number of raindrop iterations
    pub iterations: u32,
    /// Amount of rain per drop
    pub rain_amount: f32,
    /// Maximum sediment a drop can carry (capacity factor)
    pub sediment_capacity: f32,
    /// Rate of erosion
    pub erosion_rate: f32,
    /// Rate of deposition
    pub deposition_rate: f32,
    /// Evaporation rate per step
    pub evaporation_rate: f32,
    /// Gravity influence on speed
    pub gravity: f32,
    /// Maximum angle for thermal erosion (radians)
    pub thermal_angle: f32,
    /// Rate of thermal erosion
    pub thermal_rate: f32,
    /// Maximum steps per raindrop
    pub max_steps: u32,
    /// Minimum water volume to keep simulating
    pub min_water: f32,
    /// Random seed
    pub seed: u64,
}

impl Default for ErosionConfig {
    fn default() -> Self {
        Self {
            iterations: 10000,
            rain_amount: 1.0,
            sediment_capacity: 4.0,
            erosion_rate: 0.3,
            deposition_rate: 0.3,
            evaporation_rate: 0.01,
            gravity: 4.0,
            thermal_angle: 0.6, // ~34 degrees
            thermal_rate: 0.5,
            max_steps: 64,
            min_water: 0.01,
            seed: 42,
        }
    }
}

/// Apply hydraulic and thermal erosion to a heightmap
pub fn erode(heightmap: &mut Heightmap, config: &ErosionConfig) {
    // Hydraulic erosion
    hydraulic_erosion(heightmap, config);

    // Thermal erosion pass
    if config.thermal_rate > 0.0 {
        thermal_erosion(heightmap, config);
    }
}

/// Particle-based hydraulic erosion
fn hydraulic_erosion(heightmap: &mut Heightmap, config: &ErosionConfig) {
    let w = heightmap.width as f32;
    let d = heightmap.depth as f32;
    let mut rng = config.seed;

    for _ in 0..config.iterations {
        // Random starting position
        rng = lcg_next(rng);
        let mut px = lcg_float(rng) * (w - 2.0) + 1.0;
        rng = lcg_next(rng);
        let mut pz = lcg_float(rng) * (d - 2.0) + 1.0;

        let mut water = config.rain_amount;
        let mut sediment = 0.0f32;
        let mut speed = 1.0f32;

        for _ in 0..config.max_steps {
            if water < config.min_water {
                break;
            }

            let ix = px.floor() as i32;
            let iz = pz.floor() as i32;

            if ix < 1
                || ix >= (heightmap.width as i32 - 1)
                || iz < 1
                || iz >= (heightmap.depth as i32 - 1)
            {
                break;
            }

            // Compute gradient
            let (gx, gz) = compute_gradient(heightmap, px, pz);

            let (nx, nz) = fast_normalize_2d(gx, gz);
            if nx == 0.0 && nz == 0.0 {
                break;
            }

            // Move droplet
            let new_px = px - nx;
            let new_pz = pz - nz;

            // Height difference
            let old_h = sample_height(heightmap, px, pz);
            let new_h = sample_height(heightmap, new_px, new_pz);
            let dh = new_h - old_h;

            // Sediment capacity based on speed and water volume
            let capacity = (-dh).law_max(0.0) * speed * water * config.sediment_capacity;

            if sediment > capacity || dh > 0.0 {
                // Deposit sediment
                let deposit = if dh > 0.0 {
                    // Uphill: deposit all or height difference
                    (sediment).law_min(dh)
                } else {
                    (sediment - capacity) * config.deposition_rate
                };
                deposit_at(heightmap, px, pz, deposit);
                sediment -= deposit;
            } else {
                // Erode terrain
                let erode_amount = ((capacity - sediment) * config.erosion_rate).law_min(-dh);
                erode_at(heightmap, px, pz, erode_amount);
                sediment += erode_amount;
            }

            // Update speed (acceleration from gravity on slope)
            speed = (speed * speed + (dh * config.gravity)).abs().sqrt();

            // Evaporate
            water *= 1.0 - config.evaporation_rate;

            px = new_px;
            pz = new_pz;
        }
    }
}

/// Thermal erosion: smooth steep slopes
fn thermal_erosion(heightmap: &mut Heightmap, config: &ErosionConfig) {
    let w = heightmap.width;
    let d = heightmap.depth;
    let cell_size = heightmap.world_width * (1.0 / w as f32);
    let max_slope = alice_det_math::tan(config.thermal_angle) * cell_size;
    let passes = (config.iterations / 100).max(1);

    for _ in 0..passes {
        for z in 1..(d - 1) {
            for x in 1..(w - 1) {
                let h = heightmap.get_height(x, z);
                let mut max_diff = 0.0f32;
                let mut total_diff = 0.0f32;
                let mut lower_count = 0u32;

                // Check 4 neighbors
                let neighbors = [
                    (x.wrapping_sub(1), z),
                    (x + 1, z),
                    (x, z.wrapping_sub(1)),
                    (x, z + 1),
                ];

                for &(nx, nz) in &neighbors {
                    if nx < w && nz < d {
                        let nh = heightmap.get_height(nx, nz);
                        let diff = h - nh;
                        if diff > max_slope {
                            max_diff = max_diff.law_max(diff);
                            total_diff += diff - max_slope;
                            lower_count += 1;
                        }
                    }
                }

                if lower_count > 0 && total_diff > 0.0 {
                    let transfer = (max_diff - max_slope) * 0.5 * config.thermal_rate;
                    heightmap.set_height(x, z, h - transfer);

                    let inv_total_diff = 1.0 / total_diff;

                    // Distribute to lower neighbors
                    for &(nx, nz) in &neighbors {
                        if nx < w && nz < d {
                            let nh = heightmap.get_height(nx, nz);
                            let diff = h - nh;
                            if diff > max_slope {
                                let ratio = (diff - max_slope) * inv_total_diff;
                                heightmap.set_height(nx, nz, nh + transfer * ratio);
                            }
                        }
                    }
                }
            }
        }
    }
}

/// Sample height with bilinear interpolation using grid coords
fn sample_height(hm: &Heightmap, gx: f32, gz: f32) -> f32 {
    let x0 = gx.floor() as u32;
    let z0 = gz.floor() as u32;
    let x1 = (x0 + 1).min(hm.width - 1);
    let z1 = (z0 + 1).min(hm.depth - 1);
    let tx = gx - gx.floor();
    let tz = gz - gz.floor();

    let h00 = hm.get_height(x0, z0);
    let h10 = hm.get_height(x1, z0);
    let h01 = hm.get_height(x0, z1);
    let h11 = hm.get_height(x1, z1);

    let h0 = (h10 - h00) * tx + h00;
    let h1 = (h11 - h01) * tx + h01;
    (h1 - h0) * tz + h0
}

/// Compute gradient at a position using finite differences
fn compute_gradient(hm: &Heightmap, gx: f32, gz: f32) -> (f32, f32) {
    let x0 = (gx - 0.5).law_max(0.0);
    let x1 = (gx + 0.5).law_min((hm.width - 1) as f32);
    let z0 = (gz - 0.5).law_max(0.0);
    let z1 = (gz + 0.5).law_min((hm.depth - 1) as f32);

    let dx = sample_height(hm, x1, gz) - sample_height(hm, x0, gz);
    let dz = sample_height(hm, gx, z1) - sample_height(hm, gx, z0);

    (dx, dz)
}

/// Deposit sediment at a position (bilinear distribution)
fn deposit_at(hm: &mut Heightmap, gx: f32, gz: f32, amount: f32) {
    let x0 = gx.floor() as u32;
    let z0 = gz.floor() as u32;
    let x1 = (x0 + 1).min(hm.width - 1);
    let z1 = (z0 + 1).min(hm.depth - 1);
    let tx = gx - gx.floor();
    let tz = gz - gz.floor();

    let w00 = (1.0 - tx) * (1.0 - tz);
    let w10 = tx * (1.0 - tz);
    let w01 = (1.0 - tx) * tz;
    let w11 = tx * tz;

    hm.set_height(x0, z0, amount * w00 + hm.get_height(x0, z0));
    hm.set_height(x1, z0, amount * w10 + hm.get_height(x1, z0));
    hm.set_height(x0, z1, amount * w01 + hm.get_height(x0, z1));
    hm.set_height(x1, z1, amount * w11 + hm.get_height(x1, z1));
}

/// Erode terrain at a position (bilinear distribution)
fn erode_at(hm: &mut Heightmap, gx: f32, gz: f32, amount: f32) {
    deposit_at(hm, gx, gz, -amount);
}

#[inline]
const fn lcg_next(state: u64) -> u64 {
    state
        .wrapping_mul(6364136223846793005)
        .wrapping_add(1442695040888963407)
}

#[inline]
fn lcg_float(state: u64) -> f32 {
    ((state >> 16) as u32 as f32) / (u32::MAX as f32)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_erosion_modifies_terrain() {
        let mut hm = Heightmap::new(64, 64, 64.0, 64.0);
        hm.generate_fbm(4, 0.5, 2.0, 42);
        hm.scale_heights(10.0);

        let heights_before: Vec<f32> = hm.heights.clone();

        let config = ErosionConfig {
            iterations: 1000,
            ..Default::default()
        };
        erode(&mut hm, &config);

        let mut changed = 0;
        for (a, b) in heights_before.iter().zip(hm.heights.iter()) {
            if (a - b).abs() > 1e-6 {
                changed += 1;
            }
        }

        assert!(changed > 0, "Erosion should modify terrain heights");
    }

    /// Thermal erosion is the pass that smooths: it only ever moves material
    /// from a cell to strictly lower neighbours, so roughness cannot grow.
    ///
    /// oracle: `roughness_after <= roughness_before`. Measured ratios over
    /// seeds 42 / 7 / 2024 and 100 / 1000 / 5000 iterations stay in
    /// [0.9744, 1.0000].
    ///
    /// The previous version of this test asserted `roughness_after >= 0.0` and
    /// dropped `roughness_before` on the floor, with a comment claiming
    /// "erosion should generally reduce roughness". That claim is false for the
    /// default (hydraulic + thermal) pipeline: hydraulic erosion cuts channels,
    /// which is high-frequency detail, and roughness *grows* by 2.70x / 1.86x /
    /// 1.52x at 1000 / 5000 / 20000 iterations. Only the thermal pass smooths,
    /// so that is what this test isolates (`rain_amount = 0.0` makes every
    /// droplet break out immediately on `water < min_water`).
    #[test]
    fn test_thermal_erosion_does_not_increase_roughness() {
        for seed in [42u64, 7, 2024] {
            for iterations in [100u32, 1000, 5000] {
                let mut hm = Heightmap::new(32, 32, 32.0, 32.0);
                hm.generate_fbm(4, 0.5, 2.0, seed);
                hm.scale_heights(10.0);
                let before = compute_roughness(&hm);

                erode(
                    &mut hm,
                    &ErosionConfig {
                        iterations,
                        rain_amount: 0.0,
                        thermal_rate: 1.0,
                        ..Default::default()
                    },
                );

                let after = compute_roughness(&hm);
                assert!(
                    after <= before * (1.0 + 1e-6),
                    "seed={seed} iterations={iterations}: thermal erosion raised roughness {before} -> {after}"
                );
            }
        }
    }

    #[test]
    fn test_erosion_config_default() {
        let config = ErosionConfig::default();
        assert_eq!(config.iterations, 10000);
        assert!(config.erosion_rate > 0.0);
        assert!(config.deposition_rate > 0.0);
    }

    #[test]
    fn test_thermal_only() {
        let mut hm = Heightmap::new(16, 16, 16.0, 16.0);
        // Create a sharp peak
        hm.set_height(8, 8, 10.0);

        let config = ErosionConfig {
            iterations: 100,
            thermal_rate: 1.0,
            erosion_rate: 0.0,
            ..Default::default()
        };
        erode(&mut hm, &config);

        // oracle: one thermal pass takes the isolated peak down by
        //   (h - tan(thermal_angle) * cell_size) * 0.5 * thermal_rate
        // with cell_size = world_width / width = 1.0. `peak < 10.0` accepted
        // any reduction at all, including 9.99.
        let cell_size = 16.0f32 / 16.0;
        let max_slope = alice_det_math::tan(config.thermal_angle) * cell_size;
        let want = 10.0 - (10.0 - max_slope) * 0.5 * config.thermal_rate;
        let peak = hm.get_height(8, 8);
        assert!(
            (peak - want).abs() < 1e-5,
            "Peak after one thermal pass: got {peak}, closed form {want}"
        );
    }

    /// Helper: compute terrain roughness as average height difference with neighbors
    fn compute_roughness(hm: &Heightmap) -> f32 {
        let mut total = 0.0f32;
        let mut count = 0u32;
        for z in 1..(hm.depth - 1) {
            for x in 1..(hm.width - 1) {
                let h = hm.get_height(x, z);
                let avg_neighbor = (hm.get_height(x - 1, z)
                    + hm.get_height(x + 1, z)
                    + hm.get_height(x, z - 1)
                    + hm.get_height(x, z + 1))
                    / 4.0;
                total += (h - avg_neighbor).abs();
                count += 1;
            }
        }
        if count > 0 {
            total / count as f32
        } else {
            0.0
        }
    }
}