Skip to main content

re_core/
terrain.rs

1//! Heightfield-style terrain: a subdivided grid mesh in the XZ plane whose
2//! vertex heights (local Y) are edited by radial brush operations.
3//!
4//! A terrain is a plain `MeshInstance` node, so rendering, undo, saving and
5//! glTF export work without any special cases. The brush functions operate
6//! on mesh-local positions; callers with transformed nodes must convert the
7//! brush center into local space first.
8
9use crate::id::{MaterialId, MeshId, NodeId};
10use crate::material::Material;
11use crate::mesh::Mesh;
12use crate::ops;
13use crate::project::Project;
14use crate::transform::Transform;
15
16/// Smooth falloff 1.0 at the brush center, 0.0 at (and beyond) the radius.
17pub fn falloff(dist: f32, radius: f32) -> f32 {
18    let t = (dist / radius.max(1e-6)).clamp(0.0, 1.0);
19    let w = 1.0 - t;
20    w * w * (3.0 - 2.0 * w)
21}
22
23/// How a brush stroke changes the heights inside its radius.
24#[derive(Copy, Clone, Debug, PartialEq, Eq)]
25pub enum BrushMode {
26    /// Push heights up along +Y (hills, mountains).
27    Raise,
28    /// Pull heights down along -Y (trenches, river beds).
29    Lower,
30    /// Pull heights towards the disk average (smoothing).
31    Smooth,
32    /// Move heights towards a fixed target plane (terraces, plateaus).
33    /// The target is the Y of the brush center.
34    Flatten,
35}
36
37impl BrushMode {
38    pub fn parse(s: &str) -> Option<Self> {
39        Some(match s.to_ascii_lowercase().as_str() {
40            "raise" | "anheben" | "up" => Self::Raise,
41            "lower" | "absenken" | "down" | "dig" => Self::Lower,
42            "smooth" | "glaetten" | "glätten" => Self::Smooth,
43            "flatten" | "abflachen" | "planieren" => Self::Flatten,
44            _ => return None,
45        })
46    }
47
48    pub fn name(&self) -> &'static str {
49        match self {
50            Self::Raise => "raise",
51            Self::Lower => "lower",
52            Self::Smooth => "smooth",
53            Self::Flatten => "flatten",
54        }
55    }
56}
57
58/// Subdivided terrain grid centred on the origin, lying on the XZ plane at
59/// y = 0 with normals pointing up. Shared vertices (indexed), so brushes
60/// deform the surface without seams.
61pub fn grid_mesh(name: &str, size_x: f32, size_z: f32, segments: u32) -> Mesh {
62    let seg = segments.clamp(1, 512) as usize;
63    let (hx, hz) = (size_x.max(0.01) / 2.0, size_z.max(0.01) / 2.0);
64    let mut mesh = Mesh {
65        name: name.to_string(),
66        ..Default::default()
67    };
68    for z in 0..=seg {
69        for x in 0..=seg {
70            let fx = x as f32 / seg as f32;
71            let fz = z as f32 / seg as f32;
72            mesh.positions
73                .push([-hx + fx * 2.0 * hx, 0.0, -hz + fz * 2.0 * hz]);
74        }
75    }
76    let stride = seg + 1;
77    let mut idx = Vec::with_capacity(seg * seg * 6);
78    for z in 0..seg {
79        for x in 0..seg {
80            let a = (z * stride + x) as u32;
81            let b = a + 1;
82            let c = a + stride as u32;
83            let d = c + 1;
84            // winding chosen so the face normal points +Y
85            idx.extend_from_slice(&[a, c, b, b, c, d]);
86        }
87    }
88    mesh.indices = Some(idx);
89    mesh.compute_normals();
90    mesh
91}
92
93/// Flat quad on the XZ plane at the given height, for a water surface.
94pub fn water_mesh(name: &str, size_x: f32, size_z: f32) -> Mesh {
95    let (hx, hz) = (size_x.max(0.01) / 2.0, size_z.max(0.01) / 2.0);
96    let mut mesh = Mesh {
97        name: name.to_string(),
98        positions: vec![
99            [-hx, 0.0, -hz],
100            [hx, 0.0, -hz],
101            [hx, 0.0, hz],
102            [-hx, 0.0, hz],
103        ],
104        normals: Some(vec![[0.0, 1.0, 0.0]; 4]),
105        uvs: Some(vec![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]),
106        indices: Some(vec![0, 2, 1, 0, 3, 2]), // +Y facing, but double-sided anyway
107        ..Default::default()
108    };
109    mesh.compute_normals();
110    mesh
111}
112
113/// Apply one brush step to a terrain grid mesh in mesh-local space.
114///
115/// `center` is the local-space brush position (its Y is the flatten target,
116/// distances are measured in XZ). `amount` is the displacement in meters at
117/// full falloff (raise/lower) or the blend factor 0..1 (smooth/flatten).
118/// Returns the number of vertices touched; normals are recomputed on change.
119pub fn brush(
120    mesh: &mut Mesh,
121    center: [f32; 3],
122    radius: f32,
123    amount: f32,
124    mode: BrushMode,
125) -> usize {
126    let r = radius.max(0.001);
127    let touched: Vec<(usize, f32)> = mesh
128        .positions
129        .iter()
130        .enumerate()
131        .filter_map(|(i, p)| {
132            let dx = p[0] - center[0];
133            let dz = p[2] - center[2];
134            let d = (dx * dx + dz * dz).sqrt();
135            let w = falloff(d, r);
136            (w > 0.0).then_some((i, w))
137        })
138        .collect();
139    if touched.is_empty() {
140        return 0;
141    }
142    match mode {
143        BrushMode::Raise | BrushMode::Lower => {
144            let sign = if mode == BrushMode::Raise { 1.0 } else { -1.0 };
145            for (i, w) in &touched {
146                mesh.positions[*i][1] += sign * amount * w;
147            }
148        }
149        BrushMode::Smooth => {
150            let mut acc = 0.0;
151            let mut wsum = 0.0;
152            for (i, w) in &touched {
153                acc += mesh.positions[*i][1] * w;
154                wsum += w;
155            }
156            let avg = if wsum > 1e-6 { acc / wsum } else { 0.0 };
157            let k = amount.clamp(0.0, 1.0);
158            for (i, w) in &touched {
159                let y = mesh.positions[*i][1];
160                mesh.positions[*i][1] = y + (avg - y) * k * w;
161            }
162        }
163        BrushMode::Flatten => {
164            let target = center[1];
165            let k = amount.clamp(0.0, 1.0);
166            for (i, w) in &touched {
167                let y = mesh.positions[*i][1];
168                mesh.positions[*i][1] = y + (target - y) * k * w;
169            }
170        }
171    }
172    mesh.compute_normals();
173    mesh.touch();
174    touched.len()
175}
176
177/// Find or create a named material so repeated calls don't pile up duplicates.
178pub fn material_by_name(
179    p: &mut Project,
180    name: &str,
181    make: impl FnOnce() -> Material,
182) -> MaterialId {
183    if let Some((id, _)) = p.library.materials.iter().find(|(_, m)| m.name == name) {
184        return *id;
185    }
186    p.library.add_material(make())
187}
188
189/// Ground material for freshly created maps.
190pub fn soil_material() -> Material {
191    let mut m = Material::colored("Boden", [0.36, 0.45, 0.26, 1.0]);
192    m.roughness = 0.95;
193    m
194}
195
196/// Translucent blue material for water surfaces.
197pub fn water_material() -> Material {
198    let mut m = Material::colored("Wasser", [0.10, 0.35, 0.60, 0.45]);
199    m.roughness = 0.15;
200    m.double_sided = true;
201    m
202}
203
204/// Create a terrain grid node with the soil material attached.
205pub fn add_terrain(
206    p: &mut Project,
207    parent: Option<NodeId>,
208    name: &str,
209    size_x: f32,
210    size_z: f32,
211    segments: u32,
212    transform: Transform,
213) -> (NodeId, MeshId) {
214    let mesh = grid_mesh(name, size_x, size_z, segments);
215    let mesh_id = p.library.add_mesh(mesh);
216    let soil = material_by_name(p, "Boden", soil_material);
217    let node = ops::add_node(
218        p,
219        parent,
220        name,
221        transform,
222        crate::scene::NodeKind::MeshInstance {
223            mesh: mesh_id,
224            material: Some(soil),
225            skeleton_node: None,
226        },
227    );
228    (node, mesh_id)
229}
230
231/// Create a translucent water surface node at world height `height`.
232pub fn add_water(
233    p: &mut Project,
234    parent: Option<NodeId>,
235    name: &str,
236    size_x: f32,
237    size_z: f32,
238    height: f32,
239) -> (NodeId, MeshId, MaterialId) {
240    let mesh = water_mesh(name, size_x, size_z);
241    let mesh_id = p.library.add_mesh(mesh);
242    let mat = material_by_name(p, "Wasser", water_material);
243    let node = ops::add_node(
244        p,
245        parent,
246        name,
247        Transform {
248            translation: [0.0, height, 0.0],
249            ..Default::default()
250        },
251        crate::scene::NodeKind::MeshInstance {
252            mesh: mesh_id,
253            material: Some(mat),
254            skeleton_node: None,
255        },
256    );
257    // a still lake looks frozen — give the surface a gentle ripple by default
258    if let Some(n) = p.scene.get_mut(node) {
259        n.motion = crate::motion::Motion::Waves {
260            amp: 0.05,
261            speed: 1.1,
262        };
263    }
264    (node, mesh_id, mat)
265}
266
267/// Detect a grid produced by [`grid_mesh`]: `(s+1)²` shared vertices on a
268/// regular XZ lattice plus `s²·6` indices in the builder's winding pattern.
269/// Returns the segment count `s`.
270pub fn grid_segments(mesh: &Mesh) -> Option<usize> {
271    let n = mesh.positions.len();
272    if n < 4 {
273        return None;
274    }
275    let side = (n as f64).sqrt();
276    let s = side.round() as usize;
277    if s * s != n || s < 2 {
278        return None;
279    }
280    let seg = s - 1;
281    let idx = mesh.indices.as_ref()?;
282    if idx.len() != seg * seg * 6 {
283        return None;
284    }
285    let stride = s as u32;
286    // first two triangles of row 0: [0, stride, 1] then [1, stride, stride+1]
287    if idx[0..3] != [0, stride, 1] {
288        return None;
289    }
290    let (min, max) = mesh.aabb();
291    let dx = (max[0] - min[0]) / seg as f32;
292    let dz = (max[2] - min[2]) / seg as f32;
293    if dx <= 1e-6 || dz <= 1e-6 {
294        return None;
295    }
296    for z in 0..s {
297        for x in 0..s {
298            let p = &mesh.positions[z * s + x];
299            if (p[0] - (min[0] + x as f32 * dx)).abs() > dx * 0.02 {
300                return None;
301            }
302            if (p[2] - (min[2] + z as f32 * dz)).abs() > dz * 0.02 {
303                return None;
304            }
305        }
306    }
307    Some(seg)
308}
309
310/// Resample a terrain grid to `new_segments` per axis by bilinearly sampling
311/// the height field; XZ extents are preserved, normals recomputed.
312/// Returns false when the mesh is not a [`grid_mesh`] lattice.
313pub fn resample_grid(mesh: &mut Mesh, new_segments: usize) -> bool {
314    let Some(s_old) = grid_segments(mesh) else {
315        return false;
316    };
317    if !(1..=512).contains(&new_segments) {
318        return false;
319    }
320    let (min, max) = mesh.aabb();
321    let (sx, sz) = (max[0] - min[0], max[2] - min[2]);
322    let stride = s_old + 1;
323    let h = |x: usize, z: usize| -> f32 { mesh.positions[z * stride + x][1] };
324    let mut out = grid_mesh(&mesh.name, sx, sz, new_segments as u32);
325    let n = new_segments;
326    for z in 0..=n {
327        for x in 0..=n {
328            let gx = x as f32 * s_old as f32 / n as f32;
329            let gz = z as f32 * s_old as f32 / n as f32;
330            let x0 = gx.floor() as usize;
331            let z0 = gz.floor() as usize;
332            let x1 = (x0 + 1).min(s_old);
333            let z1 = (z0 + 1).min(s_old);
334            let fx = gx - x0 as f32;
335            let fz = gz - z0 as f32;
336            let y = h(x0, z0) * (1.0 - fx) * (1.0 - fz)
337                + h(x1, z0) * fx * (1.0 - fz)
338                + h(x0, z1) * (1.0 - fx) * fz
339                + h(x1, z1) * fx * fz;
340            out.positions[z * (n + 1) + x][1] = y;
341        }
342    }
343    out.compute_normals();
344    *mesh = out;
345    mesh.touch();
346    true
347}
348
349#[cfg(test)]
350mod tests {
351    use super::*;
352
353    #[test]
354    fn grid_topology_is_a_closed_seamless_surface() {
355        let m = grid_mesh("t", 10.0, 10.0, 8);
356        assert_eq!(m.positions.len(), 9 * 9);
357        assert_eq!(m.triangle_count(), 8 * 8 * 2);
358        // all vertices start on y = 0, normals point up
359        assert!(m.positions.iter().all(|p| p[1].abs() < 1e-6));
360        let n = m.normals.clone().unwrap();
361        assert!(n.iter().all(|v| v[1] > 0.99));
362    }
363
364    #[test]
365    fn raise_and_lower_respect_the_brush_radius() {
366        let mut m = grid_mesh("t", 10.0, 10.0, 10);
367        let hit = brush(&mut m, [0.0, 0.0, 0.0], 2.0, 1.0, BrushMode::Raise);
368        assert!(hit > 0);
369        // center pushed up the most, far corners untouched
370        let y_at = |m: &Mesh, x: usize, z: usize| m.positions[z * 11 + x][1];
371        assert!(y_at(&m, 5, 5) > 0.99);
372        assert!(y_at(&m, 0, 0).abs() < 1e-6);
373        // a monotonic profile from center to edge
374        assert!(y_at(&m, 4, 5) > y_at(&m, 3, 5));
375        brush(&mut m, [0.0, 0.0, 0.0], 2.0, 0.5, BrushMode::Lower);
376        assert!(y_at(&m, 5, 5) < 0.6 && y_at(&m, 5, 5) > 0.0);
377    }
378
379    #[test]
380    fn flatten_moves_heights_to_the_target_plane() {
381        let mut m = grid_mesh("t", 10.0, 10.0, 8);
382        brush(&mut m, [0.0, 0.0, 0.0], 8.0, 2.0, BrushMode::Raise);
383        let center = 4 * 9 + 4; // stride is segments+1
384        assert!(m.positions[center][1] > 1.9, "dome under the brush");
385        let far_before = m.positions[center + 4][1]; // world x = 5 m, outside r = 4
386        assert!(far_before > 0.0);
387        brush(&mut m, [0.0, 0.25, 0.0], 4.0, 1.0, BrushMode::Flatten);
388        // dead center (falloff 1, blend 1) lands exactly on the target plane
389        assert!((m.positions[center][1] - 0.25).abs() < 1e-5);
390        // towards the rim the pull is only partial
391        let mid = &m.positions[center + 2];
392        assert!(
393            mid[1] > 0.25 && mid[1] < 1.9,
394            "partial blend, got {}",
395            mid[1]
396        );
397        // outside the brush radius nothing changes
398        assert!((m.positions[center + 4][1] - far_before).abs() < 1e-6);
399    }
400
401    #[test]
402    fn smooth_reduces_variance() {
403        let mut m = grid_mesh("t", 10.0, 10.0, 8);
404        brush(&mut m, [0.0, 0.0, 0.0], 2.0, 2.0, BrushMode::Raise);
405        let variance = |m: &Mesh| {
406            let ys: Vec<f32> = m.positions.iter().map(|p| p[1]).collect();
407            let mean = ys.iter().sum::<f32>() / ys.len() as f32;
408            ys.iter().map(|y| (y - mean).powi(2)).sum::<f32>()
409        };
410        let before = variance(&m);
411        brush(&mut m, [0.0, 0.0, 0.0], 4.0, 1.0, BrushMode::Smooth);
412        assert!(variance(&m) < before);
413    }
414
415    #[test]
416    fn terrain_and_water_nodes_roundtrip_through_json() {
417        let mut p = Project::new("welt");
418        let (node, mesh) = add_terrain(&mut p, None, "Karte", 30.0, 30.0, 16, Transform::default());
419        assert!(matches!(
420            p.scene.get(node).unwrap().kind,
421            crate::scene::NodeKind::MeshInstance { .. }
422        ));
423        // brush through the asset, like the GUI does
424        brush(
425            p.library.meshes.get_mut(&mesh).unwrap(),
426            [1.0, 0.0, 1.0],
427            3.0,
428            0.5,
429            BrushMode::Raise,
430        );
431        let (wnode, _, wmat) = add_water(&mut p, None, "Wasser", 30.0, 30.0, -0.2);
432        assert!(
433            p.library.materials[&wmat].base_color[3] < 1.0,
434            "water must be translucent"
435        );
436        assert_eq!(p.scene.get(wnode).unwrap().transform.translation[1], -0.2);
437
438        let json = serde_json::to_string(&p).unwrap();
439        let back: Project = serde_json::from_str(&json).unwrap();
440        assert_eq!(back, p);
441    }
442
443    #[test]
444    fn materials_are_reused_not_duplicated() {
445        let mut p = Project::new("welt");
446        add_terrain(&mut p, None, "a", 10.0, 10.0, 4, Transform::default());
447        add_terrain(&mut p, None, "b", 10.0, 10.0, 4, Transform::default());
448        add_water(&mut p, None, "w", 10.0, 10.0, 0.0);
449        assert_eq!(p.library.materials.len(), 2, "one Boden + one Wasser");
450    }
451
452    #[test]
453    fn grid_detection_and_resample_keep_the_heights() {
454        let mut m = grid_mesh("t", 10.0, 10.0, 16);
455        assert_eq!(grid_segments(&m), Some(16));
456        brush(&mut m, [0.0, 0.0, 0.0], 3.0, 2.0, BrushMode::Raise);
457        let peak_before = m.positions.iter().map(|p| p[1]).fold(0.0f32, f32::max);
458
459        assert!(resample_grid(&mut m, 8));
460        assert_eq!(grid_segments(&m), Some(8));
461        assert_eq!(m.triangle_count(), 8 * 8 * 2);
462        let peak_after = m.positions.iter().map(|p| p[1]).fold(0.0f32, f32::max);
463        // bilinear coarsening keeps most of the dome
464        assert!(
465            peak_after > peak_before * 0.7,
466            "{peak_after} vs {peak_before}"
467        );
468        // extents preserved
469        let (min, max) = m.aabb();
470        assert!((max[0] - min[0] - 10.0).abs() < 1e-4);
471
472        // a non-grid mesh is refused
473        let mut boxy =
474            crate::primitives::generate(crate::primitives::PrimitiveKind::Box, 1.0, 1.0, 4);
475        boxy.compute_normals();
476        assert_eq!(grid_segments(&boxy), None);
477        assert!(!resample_grid(&mut boxy, 4));
478    }
479}