1use super::*;
2
3impl Default for TerrainConfig {
5 fn default() -> Self {
11 Self::alpine(42)
12 }
13}
14
15impl TerrainConfig {
17 #[must_use]
27 pub fn alpine(seed: u64) -> Self {
28 Self {
29 grid_x: 65,
30 grid_z: 65,
31 world_size_x: 120.0,
32 world_size_z: 120.0,
33 height_scale: 28.0,
34 seed,
35 fbm_octaves: 5,
36 fbm_frequency: 2.2,
37 fbm_lacunarity: 2.05,
38 fbm_persistence: 0.5,
39 ridged_weight: 0.55,
40 canyon_weight: 0.1,
41 terrace_steps: 0,
42 terrace_strength: 0.0,
43 hydraulic_droplets: 1500,
44 thermal_iterations: 8,
45 talus_angle: 0.65,
46 biome: TerrainBiome::Alpine,
47 }
48 }
49
50 #[must_use]
60 pub fn canyon(seed: u64) -> Self {
61 Self {
62 grid_x: 65,
63 grid_z: 65,
64 world_size_x: 120.0,
65 world_size_z: 120.0,
66 height_scale: 24.0,
67 seed,
68 fbm_octaves: 4,
69 fbm_frequency: 2.6,
70 fbm_lacunarity: 2.0,
71 fbm_persistence: 0.48,
72 ridged_weight: 0.2,
73 canyon_weight: 0.72,
74 terrace_steps: 6,
75 terrace_strength: 0.65,
76 hydraulic_droplets: 1200,
77 thermal_iterations: 10,
78 talus_angle: 0.72,
79 biome: TerrainBiome::Canyon,
80 }
81 }
82
83 #[must_use]
93 pub fn archipelago(seed: u64) -> Self {
94 Self {
95 grid_x: 65,
96 grid_z: 65,
97 world_size_x: 140.0,
98 world_size_z: 140.0,
99 height_scale: 18.0,
100 seed,
101 fbm_octaves: 5,
102 fbm_frequency: 2.4,
103 fbm_lacunarity: 2.0,
104 fbm_persistence: 0.52,
105 ridged_weight: 0.3,
106 canyon_weight: 0.05,
107 terrace_steps: 0,
108 terrace_strength: 0.0,
109 hydraulic_droplets: 1000,
110 thermal_iterations: 6,
111 talus_angle: 0.55,
112 biome: TerrainBiome::Archipelago,
113 }
114 }
115
116 #[must_use]
126 pub fn terraced(seed: u64) -> Self {
127 Self {
128 grid_x: 65,
129 grid_z: 65,
130 world_size_x: 120.0,
131 world_size_z: 120.0,
132 height_scale: 22.0,
133 seed,
134 fbm_octaves: 5,
135 fbm_frequency: 2.0,
136 fbm_lacunarity: 2.0,
137 fbm_persistence: 0.5,
138 ridged_weight: 0.25,
139 canyon_weight: 0.15,
140 terrace_steps: 8,
141 terrace_strength: 0.85,
142 hydraulic_droplets: 800,
143 thermal_iterations: 6,
144 talus_angle: 0.62,
145 biome: TerrainBiome::TerracedHighlands,
146 }
147 }
148}
149
150impl HeightfieldTerrain {
152 #[must_use]
162 pub fn generate(config: &TerrainConfig) -> Self {
163 let gx: u32 = config
164 .get_grid_x()
165 .clamp(TERRAIN_MIN_GRID, TERRAIN_MAX_GRID);
166 let gz: u32 = config
167 .get_grid_z()
168 .clamp(TERRAIN_MIN_GRID, TERRAIN_MAX_GRID);
169 let size_x: f32 = sanitize_scalar(config.get_world_size_x(), 100.0)
170 .abs()
171 .max(1.0);
172 let size_z: f32 = sanitize_scalar(config.get_world_size_z(), 100.0)
173 .abs()
174 .max(1.0);
175 let h_scale: f32 = sanitize_scalar(config.get_height_scale(), 20.0)
176 .abs()
177 .max(0.1);
178 let freq: f32 = sanitize_scalar(config.get_fbm_frequency(), 2.0)
179 .abs()
180 .max(0.05);
181 let lac: f32 = sanitize_scalar(config.get_fbm_lacunarity(), 2.0).clamp(1.1, 4.0);
182 let pers: f32 = sanitize_scalar(config.get_fbm_persistence(), 0.5).clamp(0.1, 0.9);
183 let ridge_w: f32 = sanitize_scalar(config.get_ridged_weight(), 0.4).clamp(0.0, 1.0);
184 let canyon_w: f32 = sanitize_scalar(config.get_canyon_weight(), 0.1).clamp(0.0, 1.0);
185 let octaves: u32 = config.get_fbm_octaves().clamp(1, TERRAIN_MAX_OCTAVES);
186 let seed: u64 = config.get_seed();
187 let total_cells: usize = (gx as usize) * (gz as usize);
188 let mut heights: Vec<f32> = Vec::with_capacity(total_cells);
189 for iz in 0..gz {
190 let v: f32 = (iz as f32) / ((gz - 1) as f32);
191 for ix in 0..gx {
192 let u: f32 = (ix as f32) / ((gx - 1) as f32);
193 let nx: f32 = u * freq;
194 let nz: f32 = v * freq;
195 let fbm_val: f32 = fbm_2d(nx, nz, octaves, lac, pers, seed) * 0.5 + 0.5;
196 let ridge_val: f32 =
197 ridged_multifractal_2d(nx * 0.85, nz * 0.85, octaves, lac, pers, seed);
198 let base_h: f32 = fbm_val * (1.0 - ridge_w) + ridge_val * ridge_w;
199 let canyon_mask: f32 =
200 worley_canyon_2d(nx * 1.15, nz * 1.15, seed.wrapping_add(7919));
201 let carved_h: f32 = base_h * (1.0 - canyon_w * (1.0 - canyon_mask));
202 let biome_shaped: f32 = match config.get_biome() {
203 TerrainBiome::Archipelago => {
204 let dx: f32 = (u - 0.5) * 2.0;
205 let dz: f32 = (v - 0.5) * 2.0;
206 let radial: f32 = (dx * dx + dz * dz).sqrt();
207 let falloff: f32 = (1.0 - (radial * 0.95).powi(2)).clamp(0.0, 1.0);
208 carved_h * falloff
209 }
210 TerrainBiome::Canyon => (carved_h * 1.15).clamp(0.0, 1.0),
211 TerrainBiome::Alpine => carved_h.powf(1.25),
212 TerrainBiome::TerracedHighlands => carved_h,
213 };
214 let terraced: f32 = apply_terracing(
215 biome_shaped,
216 config.get_terrace_steps(),
217 config.get_terrace_strength(),
218 );
219 let elev: f32 = sanitize_scalar(terraced * h_scale, 0.0);
220 heights.push(elev);
221 }
222 }
223 let mut terrain: Self = Self {
224 grid_x: gx,
225 grid_z: gz,
226 world_size_x: size_x,
227 world_size_z: size_z,
228 heights,
229 splat_weights: vec![[1.0, 0.0, 0.0, 0.0]; total_cells],
230 vertex_colors: vec![[128, 160, 100, 255]; total_cells],
231 normal_map: vec![[128, 255, 128, 255]; total_cells],
232 min_height: 0.0,
233 max_height: h_scale,
234 };
235 if config.get_hydraulic_droplets() > 0 {
236 terrain
237 .apply_hydraulic_erosion(config.get_hydraulic_droplets(), seed.wrapping_add(31337));
238 }
239 if config.get_thermal_iterations() > 0 {
240 terrain
241 .apply_thermal_erosion(config.get_thermal_iterations(), config.get_talus_angle());
242 }
243 terrain.recompute_surface_maps(config.get_biome());
244 terrain
245 }
246
247 pub fn apply_hydraulic_erosion(&mut self, droplets: u32, seed: u64) {
254 let gx: usize = self.get_grid_x() as usize;
255 let gz: usize = self.get_grid_z() as usize;
256 if gx.min(gz) < 4 || droplets == 0 {
257 return;
258 }
259 let brush: [(i32, i32, f32); 9] = [
260 (-1, -1, 0.0625),
261 (0, -1, 0.125),
262 (1, -1, 0.0625),
263 (-1, 0, 0.125),
264 (0, 0, 0.25),
265 (1, 0, 0.125),
266 (-1, 1, 0.0625),
267 (0, 1, 0.125),
268 (1, 1, 0.0625),
269 ];
270 let mut rng: u64 = seed ^ 0xA5A5_5A5A_1234_5678;
271 let max_x: f32 = (gx - 2) as f32;
272 let max_z: f32 = (gz - 2) as f32;
273 let heights: &mut Vec<f32> = self.get_mut_heights();
274 for _ in 0..droplets {
275 let mut px: f32 = 1.0 + terrain_next_f32(&mut rng) * (max_x - 1.0);
276 let mut pz: f32 = 1.0 + terrain_next_f32(&mut rng) * (max_z - 1.0);
277 let mut dir_x: f32 = 0.0;
278 let mut dir_z: f32 = 0.0;
279 let mut speed: f32 = 1.0;
280 let mut water: f32 = 1.0;
281 let mut sediment: f32 = 0.0;
282 for _ in 0..TERRAIN_DROPLET_MAX_STEPS {
283 let ix: usize = (px.floor() as usize).clamp(0, gx - 2);
284 let iz: usize = (pz.floor() as usize).clamp(0, gz - 2);
285 let tx: f32 = (px - (ix as f32)).clamp(0.0, 1.0);
286 let tz: f32 = (pz - (iz as f32)).clamp(0.0, 1.0);
287 let idx00: usize = iz * gx + ix;
288 let h00: f32 = heights[idx00];
289 let h10: f32 = heights[idx00 + 1];
290 let h01: f32 = heights[idx00 + gx];
291 let h11: f32 = heights[idx00 + gx + 1];
292 let grad_x: f32 = (h10 - h00) * (1.0 - tz) + (h11 - h01) * tz;
293 let grad_z: f32 = (h01 - h00) * (1.0 - tx) + (h11 - h10) * tx;
294 let old_h: f32 =
295 (h00 * (1.0 - tx) + h10 * tx) * (1.0 - tz) + (h01 * (1.0 - tx) + h11 * tx) * tz;
296 dir_x = dir_x * TERRAIN_INERTIA - grad_x * (1.0 - TERRAIN_INERTIA);
297 dir_z = dir_z * TERRAIN_INERTIA - grad_z * (1.0 - TERRAIN_INERTIA);
298 let dlen: f32 = (dir_x * dir_x + dir_z * dir_z).sqrt();
299 if dlen <= 1e-6 || !dlen.is_finite() {
300 break;
301 }
302 dir_x /= dlen;
303 dir_z /= dlen;
304 let next_x: f32 = px + dir_x;
305 let next_z: f32 = pz + dir_z;
306 let out_x: bool = next_x < 1.0 || next_x >= max_x;
307 let out_z: bool = next_z < 1.0 || next_z >= max_z;
308 if out_x || out_z {
309 break;
310 }
311 let nix: usize = (next_x.floor() as usize).clamp(0, gx - 2);
312 let niz: usize = (next_z.floor() as usize).clamp(0, gz - 2);
313 let ntx: f32 = (next_x - (nix as f32)).clamp(0.0, 1.0);
314 let ntz: f32 = (next_z - (niz as f32)).clamp(0.0, 1.0);
315 let nidx: usize = niz * gx + nix;
316 let new_h: f32 = (heights[nidx] * (1.0 - ntx) + heights[nidx + 1] * ntx)
317 * (1.0 - ntz)
318 + (heights[nidx + gx] * (1.0 - ntx) + heights[nidx + gx + 1] * ntx) * ntz;
319 let dh: f32 = new_h - old_h;
320 let capacity: f32 =
321 ((-dh).max(TERRAIN_MIN_SLOPE) * speed * water * TERRAIN_CAPACITY_FACTOR)
322 .clamp(0.0, 20.0);
323 if sediment > capacity || dh > 0.0 {
324 let deposit: f32 = if dh > 0.0 {
325 dh.min(sediment)
326 } else {
327 (sediment - capacity) * TERRAIN_DEPOSITION_RATE
328 };
329 let clean_dep: f32 = sanitize_scalar(deposit, 0.0).max(0.0);
330 sediment = (sediment - clean_dep).max(0.0);
331 heights[idx00] = sanitize_scalar(
332 heights[idx00] + clean_dep * (1.0 - tx) * (1.0 - tz),
333 old_h,
334 );
335 heights[idx00 + 1] =
336 sanitize_scalar(heights[idx00 + 1] + clean_dep * tx * (1.0 - tz), old_h);
337 heights[idx00 + gx] =
338 sanitize_scalar(heights[idx00 + gx] + clean_dep * (1.0 - tx) * tz, old_h);
339 heights[idx00 + gx + 1] =
340 sanitize_scalar(heights[idx00 + gx + 1] + clean_dep * tx * tz, old_h);
341 } else {
342 let erode: f32 =
343 ((capacity - sediment) * TERRAIN_EROSION_RATE).min((-dh).max(0.0));
344 let clean_erode: f32 = sanitize_scalar(erode, 0.0).clamp(0.0, 2.0);
345 let mut actual_eroded: f32 = 0.0;
346 for &(ox, oz, w) in brush.iter() {
347 let bx: i32 = (ix as i32) + ox;
348 let bz: i32 = (iz as i32) + oz;
349 if bx >= 0 && bx < (gx as i32) && bz >= 0 && bz < (gz as i32) {
350 let bidx: usize = (bz as usize) * gx + (bx as usize);
351 let delta: f32 = clean_erode * w;
352 heights[bidx] = sanitize_scalar(heights[bidx] - delta, 0.0);
353 actual_eroded += delta;
354 }
355 }
356 sediment += actual_eroded;
357 }
358 let speed_sq: f32 = (speed * speed + (-dh) * TERRAIN_GRAVITY).clamp(0.0025, 64.0);
359 speed = speed_sq.sqrt();
360 water *= 1.0 - TERRAIN_EVAPORATION_RATE;
361 px = next_x;
362 pz = next_z;
363 if water < 0.02 {
364 break;
365 }
366 }
367 }
368 }
369
370 pub fn apply_thermal_erosion(&mut self, iterations: u32, talus_angle: f32) {
377 let gx: usize = self.get_grid_x() as usize;
378 let gz: usize = self.get_grid_z() as usize;
379 if gx.min(gz) < 3 || iterations == 0 {
380 return;
381 }
382 let step_x: f32 = self.get_world_size_x() / ((gx - 1) as f32);
383 let step_z: f32 = self.get_world_size_z() / ((gz - 1) as f32);
384 let avg_step: f32 = (step_x + step_z) * 0.5;
385 let angle: f32 = sanitize_scalar(talus_angle, 0.6).clamp(0.1, 1.45);
386 let talus_h: f32 = avg_step * angle.tan();
387 let neighbors: [(i32, i32, f32); 8] = [
388 (-1, 0, 1.0),
389 (1, 0, 1.0),
390 (0, -1, 1.0),
391 (0, 1, 1.0),
392 (-1, -1, SQRT_2),
393 (1, -1, SQRT_2),
394 (-1, 1, SQRT_2),
395 (1, 1, SQRT_2),
396 ];
397 let mut deltas: Vec<f32> = vec![0.0; gx * gz];
398 let heights: &mut Vec<f32> = self.get_mut_heights();
399 for _ in 0..iterations {
400 deltas.fill(0.0);
401 for iz in 0..gz {
402 for ix in 0..gx {
403 let idx: usize = iz * gx + ix;
404 let h: f32 = heights[idx];
405 let mut excess_sum: f32 = 0.0;
406 let mut max_diff: f32 = 0.0;
407 let mut local_excess: [f32; 8] = [0.0; 8];
408 for (k, &(ox, oz, dist_mul)) in neighbors.iter().enumerate() {
409 let nx: i32 = (ix as i32) + ox;
410 let nz: i32 = (iz as i32) + oz;
411 if nx >= 0 && nx < (gx as i32) && nz >= 0 && nz < (gz as i32) {
412 let nidx: usize = (nz as usize) * gx + (nx as usize);
413 let diff: f32 = h - heights[nidx];
414 let thresh: f32 = talus_h * dist_mul;
415 if diff > thresh {
416 let exc: f32 = diff - thresh;
417 local_excess[k] = exc;
418 excess_sum += exc;
419 if exc > max_diff {
420 max_diff = exc;
421 }
422 }
423 }
424 }
425 if excess_sum > 1e-6 {
426 let transfer: f32 = 0.45 * max_diff;
427 deltas[idx] -= transfer;
428 for (k, &(ox, oz, _)) in neighbors.iter().enumerate() {
429 if local_excess[k] > 0.0 {
430 let nx: usize = ((ix as i32) + ox) as usize;
431 let nz: usize = ((iz as i32) + oz) as usize;
432 deltas[nz * gx + nx] += transfer * (local_excess[k] / excess_sum);
433 }
434 }
435 }
436 }
437 }
438 for (h_slot, &d) in heights.iter_mut().zip(deltas.iter()) {
439 *h_slot = sanitize_scalar(*h_slot + d, 0.0);
440 }
441 }
442 }
443
444 pub fn recompute_surface_maps(&mut self, biome: TerrainBiome) {
450 let gx: usize = self.get_grid_x() as usize;
451 let gz: usize = self.get_grid_z() as usize;
452 let step_x: f32 = self.get_world_size_x() / ((gx.max(2) - 1) as f32);
453 let step_z: f32 = self.get_world_size_z() / ((gz.max(2) - 1) as f32);
454 let mut min_h: f32 = f32::INFINITY;
455 let mut max_h: f32 = f32::NEG_INFINITY;
456 for &h in self.get_heights().iter() {
457 let clean: f32 = sanitize_scalar(h, 0.0);
458 min_h = min_h.min(clean);
459 max_h = max_h.max(clean);
460 }
461 if !min_h.is_finite() || !max_h.is_finite() {
462 min_h = 0.0;
463 max_h = 1.0;
464 }
465 let span: f32 = (max_h - min_h).max(1e-4);
466 let total: usize = gx * gz;
467 let mut splats: Vec<[f32; 4]> = Vec::with_capacity(total);
468 let mut colors: Vec<[u8; 4]> = Vec::with_capacity(total);
469 let mut nmap: Vec<[u8; 4]> = Vec::with_capacity(total);
470 let heights_ref: &[f32] = self.get_heights();
471 for iz in 0..gz {
472 let z_prev: usize = iz.saturating_sub(1);
473 let z_next: usize = (iz + 1).min(gz - 1);
474 let dz: f32 = ((z_next - z_prev).max(1) as f32) * step_z;
475 for ix in 0..gx {
476 let x_prev: usize = ix.saturating_sub(1);
477 let x_next: usize = (ix + 1).min(gx - 1);
478 let dx: f32 = ((x_next - x_prev).max(1) as f32) * step_x;
479 let h: f32 = heights_ref[iz * gx + ix];
480 let hx0: f32 = heights_ref[iz * gx + x_prev];
481 let hx1: f32 = heights_ref[iz * gx + x_next];
482 let hz0: f32 = heights_ref[z_prev * gx + ix];
483 let hz1: f32 = heights_ref[z_next * gx + ix];
484 let n: Vec3 =
485 safe_unit_normal(Vec3::new(-(hx1 - hx0) / dx, 1.0, -(hz1 - hz0) / dz));
486 nmap.push([
487 ((n.get_x() * 0.5 + 0.5) * 255.0).round().clamp(0.0, 255.0) as u8,
488 ((n.get_y() * 0.5 + 0.5) * 255.0).round().clamp(0.0, 255.0) as u8,
489 ((n.get_z() * 0.5 + 0.5) * 255.0).round().clamp(0.0, 255.0) as u8,
490 255,
491 ]);
492 let alt: f32 = ((h - min_h) / span).clamp(0.0, 1.0);
493 let slope: f32 = (1.0 - n.get_y()).clamp(0.0, 1.0);
494 let mut w_sand: f32 = ((0.22 - alt) * 4.5).clamp(0.0, 1.0);
495 let mut w_snow: f32 = ((alt - 0.72) * 3.8 * (1.0 - slope * 1.4)).clamp(0.0, 1.0);
496 let mut w_rock: f32 = ((slope - 0.14) * 3.5).clamp(0.0, 1.0);
497 let mut w_grass: f32 = (1.0 - w_rock - w_snow - w_sand).clamp(0.0, 1.0);
498 if matches!(biome, TerrainBiome::Canyon) {
499 w_sand = (w_sand + 0.45 * (1.0 - slope)).clamp(0.0, 1.0);
500 w_rock = (w_rock + 0.45 * slope).clamp(0.0, 1.0);
501 w_snow *= 0.05;
502 w_grass *= 0.15;
503 }
504 let w_sum: f32 = (w_grass + w_rock + w_snow + w_sand).max(1e-5);
505 let sw: [f32; 4] = [
506 w_grass / w_sum,
507 w_rock / w_sum,
508 w_snow / w_sum,
509 w_sand / w_sum,
510 ];
511 splats.push(sw);
512 let (c_grass, c_rock, c_snow, c_sand): ([f32; 3], [f32; 3], [f32; 3], [f32; 3]) =
513 match biome {
514 TerrainBiome::Canyon => (
515 [138.0, 122.0, 74.0],
516 [168.0, 92.0, 56.0],
517 [228.0, 198.0, 162.0],
518 [208.0, 146.0, 88.0],
519 ),
520 TerrainBiome::Archipelago => (
521 [74.0, 148.0, 72.0],
522 [112.0, 114.0, 118.0],
523 [235.0, 240.0, 244.0],
524 [226.0, 206.0, 152.0],
525 ),
526 TerrainBiome::TerracedHighlands => (
527 [86.0, 138.0, 68.0],
528 [124.0, 116.0, 108.0],
529 [226.0, 232.0, 236.0],
530 [174.0, 152.0, 112.0],
531 ),
532 TerrainBiome::Alpine => (
533 [76.0, 132.0, 66.0],
534 [118.0, 116.0, 114.0],
535 [242.0, 246.0, 250.0],
536 [184.0, 164.0, 122.0],
537 ),
538 };
539 let rgb_r: f32 =
540 c_grass[0] * sw[0] + c_rock[0] * sw[1] + c_snow[0] * sw[2] + c_sand[0] * sw[3];
541 let rgb_g: f32 =
542 c_grass[1] * sw[0] + c_rock[1] * sw[1] + c_snow[1] * sw[2] + c_sand[1] * sw[3];
543 let rgb_b: f32 =
544 c_grass[2] * sw[0] + c_rock[2] * sw[1] + c_snow[2] * sw[2] + c_sand[2] * sw[3];
545 colors.push([
546 rgb_r.round().clamp(0.0, 255.0) as u8,
547 rgb_g.round().clamp(0.0, 255.0) as u8,
548 rgb_b.round().clamp(0.0, 255.0) as u8,
549 255,
550 ]);
551 }
552 }
553 self.set_min_height(min_h);
554 self.set_max_height(max_h);
555 self.set_splat_weights(splats);
556 self.set_vertex_colors(colors);
557 self.set_normal_map(nmap);
558 }
559
560 #[must_use]
571 pub fn sample_height(&self, world_x: f32, world_z: f32) -> f32 {
572 let gx: usize = self.get_grid_x() as usize;
573 let gz: usize = self.get_grid_z() as usize;
574 let heights: &[f32] = self.get_heights();
575 if gx.min(gz) < 2 || heights.len() < gx * gz {
576 return 0.0;
577 }
578 let u: f32 =
579 (sanitize_scalar(world_x, 0.0) / self.get_world_size_x() + 0.5).clamp(0.0, 1.0);
580 let v: f32 =
581 (sanitize_scalar(world_z, 0.0) / self.get_world_size_z() + 0.5).clamp(0.0, 1.0);
582 let fx: f32 = u * ((gx - 1) as f32);
583 let fz: f32 = v * ((gz - 1) as f32);
584 let ix: usize = (fx.floor() as usize).min(gx - 2);
585 let iz: usize = (fz.floor() as usize).min(gz - 2);
586 let tx: f32 = (fx - (ix as f32)).clamp(0.0, 1.0);
587 let tz: f32 = (fz - (iz as f32)).clamp(0.0, 1.0);
588 let base: usize = iz * gx + ix;
589 let h00: f32 = heights[base];
590 let h10: f32 = heights[base + 1];
591 let h01: f32 = heights[base + gx];
592 let h11: f32 = heights[base + gx + 1];
593 let hx0: f32 = h00 + (h10 - h00) * tx;
594 let hx1: f32 = h01 + (h11 - h01) * tx;
595 sanitize_scalar(hx0 + (hx1 - hx0) * tz, 0.0)
596 }
597
598 #[must_use]
609 pub fn sample_normal(&self, world_x: f32, world_z: f32) -> Vec3 {
610 let gx: usize = self.get_grid_x() as usize;
611 let gz: usize = self.get_grid_z() as usize;
612 let heights: &[f32] = self.get_heights();
613 if gx.min(gz) < 2 || heights.len() < gx * gz {
614 return Vec3::new(0.0, 1.0, 0.0);
615 }
616 let step_x: f32 = self.get_world_size_x() / ((gx - 1) as f32);
617 let step_z: f32 = self.get_world_size_z() / ((gz - 1) as f32);
618 let u: f32 =
619 (sanitize_scalar(world_x, 0.0) / self.get_world_size_x() + 0.5).clamp(0.0, 1.0);
620 let v: f32 =
621 (sanitize_scalar(world_z, 0.0) / self.get_world_size_z() + 0.5).clamp(0.0, 1.0);
622 let fx: f32 = u * ((gx - 1) as f32);
623 let fz: f32 = v * ((gz - 1) as f32);
624 let ix: usize = (fx.floor() as usize).min(gx - 2);
625 let iz: usize = (fz.floor() as usize).min(gz - 2);
626 let tx: f32 = (fx - (ix as f32)).clamp(0.0, 1.0);
627 let tz: f32 = (fz - (iz as f32)).clamp(0.0, 1.0);
628 let base: usize = iz * gx + ix;
629 let h00: f32 = heights[base];
630 let h10: f32 = heights[base + 1];
631 let h01: f32 = heights[base + gx];
632 let h11: f32 = heights[base + gx + 1];
633 let dh_dx: f32 = ((h10 - h00) * (1.0 - tz) + (h11 - h01) * tz) / step_x.max(1e-4);
634 let dh_dz: f32 = ((h01 - h00) * (1.0 - tx) + (h11 - h10) * tx) / step_z.max(1e-4);
635 safe_unit_normal(Vec3::new(-dh_dx, 1.0, -dh_dz))
636 }
637
638 #[must_use]
649 pub fn sample_splat_weights(&self, world_x: f32, world_z: f32) -> [f32; 4] {
650 let gx: usize = self.get_grid_x() as usize;
651 let gz: usize = self.get_grid_z() as usize;
652 let splats: &[[f32; 4]] = self.get_splat_weights();
653 if gx.min(gz) < 2 || splats.len() < gx * gz {
654 return [1.0, 0.0, 0.0, 0.0];
655 }
656 let u: f32 =
657 (sanitize_scalar(world_x, 0.0) / self.get_world_size_x() + 0.5).clamp(0.0, 1.0);
658 let v: f32 =
659 (sanitize_scalar(world_z, 0.0) / self.get_world_size_z() + 0.5).clamp(0.0, 1.0);
660 let fx: f32 = u * ((gx - 1) as f32);
661 let fz: f32 = v * ((gz - 1) as f32);
662 let ix: usize = (fx.floor() as usize).min(gx - 2);
663 let iz: usize = (fz.floor() as usize).min(gz - 2);
664 let tx: f32 = (fx - (ix as f32)).clamp(0.0, 1.0);
665 let tz: f32 = (fz - (iz as f32)).clamp(0.0, 1.0);
666 let base: usize = iz * gx + ix;
667 let s00: [f32; 4] = splats[base];
668 let s10: [f32; 4] = splats[base + 1];
669 let s01: [f32; 4] = splats[base + gx];
670 let s11: [f32; 4] = splats[base + gx + 1];
671 let mut out: [f32; 4] = [0.0; 4];
672 let mut sum: f32 = 0.0;
673 for c in 0..4 {
674 let v0: f32 = s00[c] + (s10[c] - s00[c]) * tx;
675 let v1: f32 = s01[c] + (s11[c] - s01[c]) * tx;
676 out[c] = (v0 + (v1 - v0) * tz).max(0.0);
677 sum += out[c];
678 }
679 if sum > 1e-6 {
680 [out[0] / sum, out[1] / sum, out[2] / sum, out[3] / sum]
681 } else {
682 [1.0, 0.0, 0.0, 0.0]
683 }
684 }
685
686 #[must_use]
697 pub fn to_mesh3d(&self, name: &str, material: PbrMaterial) -> Mesh3D {
698 let gx: usize = self.get_grid_x() as usize;
699 let gz: usize = self.get_grid_z() as usize;
700 let mesh_name: String = if name.is_empty() {
701 TERRAIN_DEFAULT_NAME.to_string()
702 } else {
703 name.to_string()
704 };
705 if gx < 2 || gz < 2 {
706 return Mesh3D::from_parts(mesh_name, Vec::new(), Vec::new(), material);
707 }
708 let size_x: f32 = self.get_world_size_x();
709 let size_z: f32 = self.get_world_size_z();
710 let heights: &[f32] = self.get_heights();
711 let colors: &[[u8; 4]] = self.get_vertex_colors();
712 let nmap: &[[u8; 4]] = self.get_normal_map();
713 let mut vertices: Vec<Vertex3D> = Vec::with_capacity(gx * gz);
714 let mut indices: Vec<[u32; 3]> = Vec::with_capacity((gx - 1) * (gz - 1) * 2);
715 let uv_flags: u32 = VERTEX_FLAG_UV0 | VERTEX_FLAG_UV1;
716 let flags: u32 = uv_flags | VERTEX_FLAG_COLOR0;
717 for iz in 0..gz {
718 let v: f32 = (iz as f32) / ((gz - 1) as f32);
719 let wz: f32 = (v - 0.5) * size_z;
720 for ix in 0..gx {
721 let u: f32 = (ix as f32) / ((gx - 1) as f32);
722 let wx: f32 = (u - 0.5) * size_x;
723 let idx: usize = iz * gx + ix;
724 let wy: f32 = heights.get(idx).copied().unwrap_or(0.0);
725 let nc: [u8; 4] = nmap.get(idx).copied().unwrap_or([128, 255, 128, 255]);
726 let normal: Vec3 = safe_unit_normal(Vec3::new(
727 (nc[0] as f32) / 127.5 - 1.0,
728 (nc[1] as f32) / 127.5 - 1.0,
729 (nc[2] as f32) / 127.5 - 1.0,
730 ));
731 let col: [u8; 4] = colors.get(idx).copied().unwrap_or([128, 160, 100, 255]);
732 vertices.push(Vertex3D::from_full(
733 Vec3::new(wx, wy, wz),
734 normal,
735 [1.0, 0.0, 0.0, 1.0],
736 [u, v],
737 [u * 8.0, v * 8.0],
738 col,
739 flags,
740 ));
741 }
742 }
743 for iz in 0..(gz - 1) {
744 let row0: u32 = (iz * gx) as u32;
745 let row1: u32 = ((iz + 1) * gx) as u32;
746 for ix in 0..(gx - 1) {
747 let jx: u32 = ix as u32;
748 let i00: u32 = row0 + jx;
749 let i10: u32 = row0 + jx + 1;
750 let i01: u32 = row1 + jx;
751 let i11: u32 = row1 + jx + 1;
752 indices.push([i00, i01, i10]);
753 indices.push([i01, i11, i10]);
754 }
755 }
756 let mesh: Mesh3D = Mesh3D::from_parts(mesh_name, vertices, indices, material);
757 compute_tangents(&mesh)
758 }
759}