Skip to main content

unbanished_terrain/river/
water.rs

1//! The water mesh of a river: its vertices and its strip.
2
3use super::*;
4
5// MapComponent +0x1a0 (vertices), +0x1b0 (indices), +0x1c0 / +0x1d0 (the ranges).
6/// The map's water mesh: the strips of the rivers, then the surfaces of the lakes.
7///
8/// A vertex is 16 bytes: `i16 x, y` (1/48 cell), `i16 z` (1/256), `0`, `i16 u, v`, the normal
9/// bytes `0x7f, 0x7f`, an alpha byte, and `0`.
10///
11/// Original: `FUN_1400b0730`.
12#[derive(Debug, Clone, Default, PartialEq)]
13pub struct WaterMesh {
14    /// The vertices.
15    pub vertices: Vec<[u8; 16]>,
16    /// The indices, each relative to the first vertex of its range.
17    pub indices: Vec<u16>,
18    /// The range of each river: first index, first vertex, vertex count, index count.
19    pub rivers: Vec<[i32; 4]>,
20    /// The range of each lake, in the same form as [`rivers`](Self::rivers).
21    pub lakes: Vec<[i32; 4]>,
22}
23
24pub(super) fn water_vertex(x: i16, y: i16, z: i16, u: i16, v: i16, alpha: u8) -> [u8; 16] {
25    let mut out = [0u8; 16];
26    for (k, s) in [x, y, z, 0, u, v].into_iter().enumerate() {
27        out[2 * k..2 * k + 2].copy_from_slice(&s.to_le_bytes());
28    }
29    out[12] = 0x7f;
30    out[13] = 0x7f;
31    out[14] = alpha;
32    out
33}
34
35// Reads MapComponent +0xc0, +0xd0, +0xd8 and the generator's +0x18 (paths), +0x48 (lakes).
36/// The water mesh of a generated map. `paths` and `lakes` are the generator's, `heights` is the
37/// map's `(size + 1)²` height grid, and `size` is its size in cells.
38///
39/// Original: `FUN_1400b0730`.
40pub fn water_mesh(
41    paths: &[Vec<PathPoint>],
42    lakes: &[[f32; 3]],
43    heights: &[i16],
44    size: usize,
45) -> WaterMesh {
46    let mut mesh = WaterMesh::default();
47    // Each river a little lower than the one before (`−192 − i`, 1/256).
48    for (i, path) in paths.iter().enumerate() {
49        let (vertices, indices) = river_strip(path);
50        mesh.rivers.push([
51            mesh.indices.len() as i32,
52            mesh.vertices.len() as i32,
53            vertices.len() as i32,
54            indices.len() as i32,
55        ]);
56        let z = (-192.0 - i as f32) as i32 as i16;
57        mesh.vertices.extend(vertices.iter().map(|v| {
58            water_vertex(
59                (v[0] * 48.0) as i32 as i16,
60                (v[1] * 48.0) as i32 as i16,
61                z,
62                (v[2] * 1024.0) as i32 as i16,
63                (v[3] * 1024.0) as i32 as i16,
64                0xff,
65            )
66        }));
67        mesh.indices.extend_from_slice(&indices);
68    }
69    let width = size + 1;
70    let half = (size >> 1) as i32;
71    let height = |gx: i32, gy: i32| -> f32 {
72        let (x, y) = (gx.clamp(0, width as i32 - 1), gy.clamp(0, width as i32 - 1));
73        heights[y as usize * width + x as usize] as i32 as f32 * 0.00390625
74    };
75    for (i, lake) in lakes.iter().enumerate() {
76        let [cx, cy, r] = *lake;
77        let outer = r + 2.0;
78        let first_index = mesh.indices.len();
79        let first_vertex = mesh.vertices.len();
80        let (x0, y0) = ((cx - outer) as i32, (cy - outer) as i32);
81        let (x1, y1) = ((cx + outer) as i32, (cy + outer) as i32);
82        let fade = outer - r;
83        let z = (i as f32 - 191.0) as i32 as i16;
84        let mut local: Vec<[u8; 16]> = Vec::new();
85        let mut seen: HashMap<[u8; 16], u16> = HashMap::new();
86        let mut indices = Vec::new();
87        for y in y0..y1 {
88            for x in x0..x1 {
89                let corners = [
90                    (x, y, height(half + x, half + y)),
91                    (x + 1, y, height(half + 1 + x, half + y)),
92                    (x + 1, y + 1, height(half + 1 + x, half + 1 + y)),
93                    (x, y + 1, height(half + x, half + 1 + y)),
94                ];
95                let mut above = true;
96                let mut clear = true;
97                let mut alpha = [0.0f32; 4];
98                for (k, &(px, py, pz)) in corners.iter().enumerate() {
99                    if pz <= -0.75 {
100                        above = false;
101                    }
102                    let d = [px as f32 - cx, py as f32 - cy, pz - 0.0];
103                    // `Vector3::Dot`: `(y² + x²) + z²`.
104                    let dist = (d[1] * d[1] + d[0] * d[0] + d[2] * d[2]).sqrt();
105                    let a = 1.0 - (dist - r) / fade;
106                    alpha[k] = if a < 0.0 {
107                        0.0
108                    } else if 1.0 < a {
109                        clear = false;
110                        1.0
111                    } else {
112                        if 0.0 < a {
113                            clear = false;
114                        }
115                        a
116                    };
117                }
118                if clear || above {
119                    continue;
120                }
121                let mut quad = [0u16; 4];
122                for (k, &(px, py, _)) in corners.iter().enumerate() {
123                    let (vx, vy) = (
124                        (px as f32 * 48.0) as i32 as i16,
125                        (py as f32 * 48.0) as i32 as i16,
126                    );
127                    let v = water_vertex(vx, vy, z, vx, vy, (alpha[k] * 255.0) as i64 as u8);
128                    quad[k] = *seen.entry(v).or_insert_with(|| {
129                        local.push(v);
130                        (local.len() - 1) as u16
131                    });
132                }
133                indices.extend_from_slice(&[quad[0], quad[1], quad[2], quad[0], quad[2], quad[3]]);
134            }
135        }
136        mesh.lakes.push([
137            first_index as i32,
138            first_vertex as i32,
139            local.len() as i32,
140            indices.len() as i32,
141        ]);
142        mesh.vertices.extend(local);
143        mesh.indices.extend(indices);
144    }
145    mesh
146}