Add design persistence, world rendering, metrics overlay and logs
M3: STL/OBJ import with mesh validation, mass/COM/inertia, material database, RON scene with content-addressed blobs and v0->v1 migration. M4: deterministic heightmap terrain, trimesh colliders, wgpu renderer with instancing and depth, winit app with 1 kHz physics, fly camera, on-screen metrics overlay and per-frame CSV/dev logs. Docs: UI, logging, network and headless CLI plans.
This commit is contained in:
parent
878d144b77
commit
190ef9cc4b
111 changed files with 14801 additions and 63 deletions
|
|
@ -1 +1,121 @@
|
|||
//! fabrilis-worldgen :: noise - stub (see docs/ARCHITECTURE.md)
|
||||
//! Deterministic 2D value noise.
|
||||
//!
|
||||
//! Values sit on an integer lattice and are interpolated with a smoothstep curve.
|
||||
//! The lattice value comes from SplitMix64 mixing of the seed and both lattice
|
||||
//! coordinates, so the result uses integer arithmetic only: no floating-point
|
||||
//! hashing, no `std` transcendental functions, the same output on every platform.
|
||||
//! See docs/DETERMINISM.md.
|
||||
|
||||
/// SplitMix64 increment; mixing a seed with it keeps seed `0` from being special.
|
||||
const GAMMA: u64 = 0x9E37_79B9_7F4A_7C15;
|
||||
|
||||
/// Odd multipliers that spread the two lattice axes before the finaliser runs.
|
||||
const X_PRIME: u64 = 0xD6E8_FEB8_6659_FD93;
|
||||
const Y_PRIME: u64 = 0xA076_1D64_78BD_642F;
|
||||
|
||||
/// Scale that turns the top 53 bits of a hash into `[0, 1)`.
|
||||
const UNIT: f64 = 1.0 / (1u64 << 53) as f64;
|
||||
|
||||
/// The SplitMix64 finaliser: a bijective avalanche on 64 bits.
|
||||
#[inline]
|
||||
fn mix(mut z: u64) -> u64 {
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
/// Hashes one lattice point; pure integer arithmetic, so it is portable.
|
||||
#[inline]
|
||||
fn lattice_hash(seed: u64, ix: i64, iy: i64) -> u64 {
|
||||
let horizontal = mix(seed.wrapping_add(GAMMA) ^ (ix as u64).wrapping_mul(X_PRIME));
|
||||
mix(horizontal ^ (iy as u64).wrapping_mul(Y_PRIME))
|
||||
}
|
||||
|
||||
/// Maps a hash to a lattice value in `[-1, 1)`; the 53-bit mantissa is exact.
|
||||
#[inline]
|
||||
fn lattice_value(hash: u64) -> f64 {
|
||||
((hash >> 11) as f64 * UNIT).mul_add(2.0, -1.0)
|
||||
}
|
||||
|
||||
/// Smoothstep: `3t² - 2t³`, with zero first derivative at both ends.
|
||||
#[inline]
|
||||
fn smoothstep(t: f64) -> f64 {
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
/// A seeded 2D value-noise field.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Noise {
|
||||
seed: u64,
|
||||
}
|
||||
|
||||
impl Noise {
|
||||
/// Creates a field from a seed; every seed is valid.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub const fn new(seed: u64) -> Self {
|
||||
Self { seed }
|
||||
}
|
||||
|
||||
/// Samples the field at `(x, y)`, returning a value in `[-1, 1]`.
|
||||
///
|
||||
/// Non-finite coordinates sample as `0`, so callers never see NaN.
|
||||
#[must_use]
|
||||
pub fn sample(&self, x: f64, y: f64) -> f64 {
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
return 0.0;
|
||||
}
|
||||
// `as i64` saturates for coordinates beyond the lattice range, which keeps
|
||||
// the result finite and deterministic instead of wrapping.
|
||||
let base_x = x.floor();
|
||||
let base_y = y.floor();
|
||||
let ix = base_x as i64;
|
||||
let iy = base_y as i64;
|
||||
let tx = smoothstep(x - base_x);
|
||||
let ty = smoothstep(y - base_y);
|
||||
|
||||
let bottom_left = lattice_value(lattice_hash(self.seed, ix, iy));
|
||||
let bottom_right = lattice_value(lattice_hash(self.seed, ix.wrapping_add(1), iy));
|
||||
let top_left = lattice_value(lattice_hash(self.seed, ix, iy.wrapping_add(1)));
|
||||
let top_right = lattice_value(lattice_hash(
|
||||
self.seed,
|
||||
ix.wrapping_add(1),
|
||||
iy.wrapping_add(1),
|
||||
));
|
||||
|
||||
let bottom = bottom_left + (bottom_right - bottom_left) * tx;
|
||||
let top = top_left + (top_right - top_left) * tx;
|
||||
bottom + (top - bottom) * ty
|
||||
}
|
||||
}
|
||||
|
||||
/// Fractal Brownian motion: octaves summed low to high, each one `lacunarity`
|
||||
/// times denser and `gain` times weaker.
|
||||
///
|
||||
/// The sum is divided by the total amplitude, so the result stays in `[-1, 1]`
|
||||
/// for every gain and octave count. Octaves are added in a fixed order, which
|
||||
/// makes the result bit-reproducible.
|
||||
///
|
||||
/// Six arguments are the natural shape of the call; bundling octaves and both
|
||||
/// multipliers into a struct would only add a type at every call site.
|
||||
#[allow(
|
||||
clippy::too_many_arguments,
|
||||
reason = "noise coordinates plus three independent fBm parameters; a params struct adds no clarity"
|
||||
)]
|
||||
#[must_use]
|
||||
pub fn fbm(noise: &Noise, x: f64, y: f64, octaves: u8, lacunarity: f64, gain: f64) -> f64 {
|
||||
let mut frequency = 1.0;
|
||||
let mut amplitude = 1.0;
|
||||
let mut total = 0.0;
|
||||
let mut weight = 0.0;
|
||||
for _ in 0..octaves {
|
||||
total += amplitude * noise.sample(x * frequency, y * frequency);
|
||||
weight += amplitude;
|
||||
frequency *= lacunarity;
|
||||
amplitude *= gain;
|
||||
}
|
||||
if weight > 0.0 { total / weight } else { 0.0 }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
|
|
|||
96
crates/worldgen/src/noise/tests.rs
Normal file
96
crates/worldgen/src/noise/tests.rs
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sample_stays_in_range() {
|
||||
let noise = Noise::new(7);
|
||||
for j in -32..=32 {
|
||||
for i in -32..=32 {
|
||||
let x = f64::from(i) * 0.37;
|
||||
let y = f64::from(j) * 0.41;
|
||||
let value = noise.sample(x, y);
|
||||
assert!((-1.0..=1.0).contains(&value), "value {value} at ({x}, {y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_seed_repeats_exactly() {
|
||||
let a = Noise::new(1234);
|
||||
let b = Noise::new(1234);
|
||||
for step in 0..100 {
|
||||
let x = f64::from(step) * 0.13;
|
||||
let y = f64::from(step) * 0.29;
|
||||
assert_eq!(a.sample(x, y).to_bits(), b.sample(x, y).to_bits());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_seeds_differ() {
|
||||
let a = Noise::new(1);
|
||||
let b = Noise::new(2);
|
||||
assert_ne!(a.sample(0.5, 0.5), b.sample(0.5, 0.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lattice_points_are_reproducible_by_hash() {
|
||||
let noise = Noise::new(99);
|
||||
assert_eq!(
|
||||
noise.sample(0.0, 0.0),
|
||||
lattice_value(lattice_hash(99, 0, 0))
|
||||
);
|
||||
assert_eq!(
|
||||
noise.sample(-3.0, 5.0),
|
||||
lattice_value(lattice_hash(99, -3, 5))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpolation_is_continuous_across_cells() {
|
||||
// A value-noise field is continuous, so stepping over a lattice boundary
|
||||
// changes the sample only slightly.
|
||||
let noise = Noise::new(5);
|
||||
let left = noise.sample(0.999, 0.25);
|
||||
let right = noise.sample(1.001, 0.25);
|
||||
assert!((left - right).abs() < 1e-2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_finite_coordinates_sample_as_zero() {
|
||||
let noise = Noise::new(3);
|
||||
assert_eq!(noise.sample(f64::NAN, 0.5), 0.0);
|
||||
assert_eq!(noise.sample(0.5, f64::INFINITY), 0.0);
|
||||
assert_eq!(noise.sample(f64::NEG_INFINITY, f64::NAN), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn huge_coordinates_do_not_overflow() {
|
||||
let noise = Noise::new(3);
|
||||
for value in [1e300, -1e300, f64::MAX, f64::MIN] {
|
||||
let sampled = noise.sample(value, value);
|
||||
assert!((-1.0..=1.0).contains(&sampled));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fbm_single_octave_equals_the_field() {
|
||||
let noise = Noise::new(11);
|
||||
assert_eq!(fbm(&noise, 0.7, -1.3, 1, 2.0, 0.5), noise.sample(0.7, -1.3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fbm_stays_in_range_for_many_octaves() {
|
||||
let noise = Noise::new(21);
|
||||
for j in 0..16 {
|
||||
for i in 0..16 {
|
||||
let x = f64::from(i) * 0.31;
|
||||
let y = f64::from(j) * 0.17;
|
||||
let value = fbm(&noise, x, y, 8, 2.0, 0.5);
|
||||
assert!((-1.0..=1.0).contains(&value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fbm_with_zero_octaves_is_zero() {
|
||||
assert_eq!(fbm(&Noise::new(1), 0.3, 0.4, 0, 2.0, 0.5), 0.0);
|
||||
}
|
||||
|
|
@ -1 +1,349 @@
|
|||
//! fabrilis-worldgen :: terrain - stub (see docs/ARCHITECTURE.md)
|
||||
//! Terrain heightmap and its render/collider mesh.
|
||||
//!
|
||||
//! The world is Z-up, so terrain is a height field `z = f(x, y)` sampled on a
|
||||
//! square grid centred at the origin: `x` and `y` cover `[-extent/2, extent/2]`
|
||||
//! and `z` covers `[0, height_scale]`. Row-major storage keeps `i` along X and
|
||||
//! `j` along Y. One map feeds both the renderer and the colliders (D14).
|
||||
//! See docs/COORDINATES.md.
|
||||
|
||||
use fabrilis_core::vec::Vec3;
|
||||
|
||||
use crate::noise::{Noise, fbm};
|
||||
|
||||
/// Smallest accepted grid resolution; two nodes still form one cell.
|
||||
const MIN_SIZE: usize = 2;
|
||||
|
||||
/// Largest accepted grid resolution; `size²` vertices still fit `u32` indices.
|
||||
const MAX_SIZE: usize = 4096;
|
||||
|
||||
/// Octave bounds; more octaves cost more and add little below one sample per cell.
|
||||
const MIN_OCTAVES: u8 = 1;
|
||||
const MAX_OCTAVES: u8 = 8;
|
||||
|
||||
/// Terrain generation parameters.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct TerrainConfig {
|
||||
/// Seed of the noise field; the same seed gives the same heights.
|
||||
pub seed: u64,
|
||||
/// Nodes per axis, in `2..=4096`.
|
||||
pub size: usize,
|
||||
/// Side length of the map, m.
|
||||
pub extent: f64,
|
||||
/// Vertical span, m; `0` makes a flat map.
|
||||
pub height_scale: f64,
|
||||
/// Noise cycles across the map; larger values mean smaller features.
|
||||
pub frequency: f64,
|
||||
/// Octaves of fractal noise, in `1..=8`.
|
||||
pub octaves: u8,
|
||||
/// Frequency multiplier between octaves; must be greater than one.
|
||||
pub lacunarity: f64,
|
||||
/// Amplitude multiplier between octaves, in `[0, 1]`.
|
||||
pub gain: f64,
|
||||
}
|
||||
|
||||
impl Default for TerrainConfig {
|
||||
/// A 64 x 64 grid over 100 m, up to 10 m tall.
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
seed: 0,
|
||||
size: 64,
|
||||
extent: 100.0,
|
||||
height_scale: 10.0,
|
||||
frequency: 2.0,
|
||||
octaves: 4,
|
||||
lacunarity: 2.0,
|
||||
gain: 0.5,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TerrainConfig {
|
||||
/// Distance between neighbouring nodes, m.
|
||||
#[must_use]
|
||||
fn spacing(&self) -> f64 {
|
||||
self.extent / (self.size - 1) as f64
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a [`Heightmap`] could not be generated.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum TerrainError {
|
||||
/// The grid resolution is outside `2..=4096`.
|
||||
SizeOutOfRange(usize),
|
||||
/// The map side is not finite and positive.
|
||||
InvalidExtent(f64),
|
||||
/// The height scale is not finite and non-negative.
|
||||
InvalidHeightScale(f64),
|
||||
/// The noise frequency is not finite and positive.
|
||||
InvalidFrequency(f64),
|
||||
/// The octave count is outside `1..=8`.
|
||||
OctavesOutOfRange(u8),
|
||||
/// The octave frequency multiplier is not finite and greater than one.
|
||||
InvalidLacunarity(f64),
|
||||
/// The octave amplitude multiplier is outside `[0, 1]`.
|
||||
InvalidGain(f64),
|
||||
}
|
||||
|
||||
impl core::fmt::Display for TerrainError {
|
||||
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
Self::SizeOutOfRange(size) => write!(
|
||||
formatter,
|
||||
"terrain size {size} is outside {MIN_SIZE}..={MAX_SIZE}"
|
||||
),
|
||||
Self::InvalidExtent(extent) => {
|
||||
write!(
|
||||
formatter,
|
||||
"terrain extent {extent} is not finite and positive"
|
||||
)
|
||||
}
|
||||
Self::InvalidHeightScale(scale) => write!(
|
||||
formatter,
|
||||
"terrain height scale {scale} is not finite and non-negative"
|
||||
),
|
||||
Self::InvalidFrequency(frequency) => write!(
|
||||
formatter,
|
||||
"terrain frequency {frequency} is not finite and positive"
|
||||
),
|
||||
Self::OctavesOutOfRange(octaves) => write!(
|
||||
formatter,
|
||||
"terrain octaves {octaves} is outside {MIN_OCTAVES}..={MAX_OCTAVES}"
|
||||
),
|
||||
Self::InvalidLacunarity(value) => write!(
|
||||
formatter,
|
||||
"terrain lacunarity {value} is not finite and greater than one"
|
||||
),
|
||||
Self::InvalidGain(value) => {
|
||||
write!(formatter, "terrain gain {value} is not in [0, 1]")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for TerrainError {}
|
||||
|
||||
/// Rejects parameters that would panic or produce a meaningless map.
|
||||
fn validate(config: &TerrainConfig) -> Result<(), TerrainError> {
|
||||
if !(MIN_SIZE..=MAX_SIZE).contains(&config.size) {
|
||||
return Err(TerrainError::SizeOutOfRange(config.size));
|
||||
}
|
||||
if !positive_finite(config.extent) {
|
||||
return Err(TerrainError::InvalidExtent(config.extent));
|
||||
}
|
||||
if !(config.height_scale.is_finite() && config.height_scale >= 0.0) {
|
||||
return Err(TerrainError::InvalidHeightScale(config.height_scale));
|
||||
}
|
||||
if !positive_finite(config.frequency) {
|
||||
return Err(TerrainError::InvalidFrequency(config.frequency));
|
||||
}
|
||||
if !(MIN_OCTAVES..=MAX_OCTAVES).contains(&config.octaves) {
|
||||
return Err(TerrainError::OctavesOutOfRange(config.octaves));
|
||||
}
|
||||
if !(config.lacunarity.is_finite() && config.lacunarity > 1.0) {
|
||||
return Err(TerrainError::InvalidLacunarity(config.lacunarity));
|
||||
}
|
||||
if !(config.gain.is_finite() && (0.0..=1.0).contains(&config.gain)) {
|
||||
return Err(TerrainError::InvalidGain(config.gain));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn positive_finite(value: f64) -> bool {
|
||||
value.is_finite() && value > 0.0
|
||||
}
|
||||
|
||||
/// A generated heightmap with bilinear sampling and a triangle mesh.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Heightmap {
|
||||
config: TerrainConfig,
|
||||
heights: Vec<f64>,
|
||||
}
|
||||
|
||||
impl Heightmap {
|
||||
/// Generates the map, or reports the first invalid parameter.
|
||||
pub fn generate(config: TerrainConfig) -> Result<Self, TerrainError> {
|
||||
validate(&config)?;
|
||||
let noise = Noise::new(config.seed);
|
||||
let half = config.extent * 0.5;
|
||||
let spacing = config.spacing();
|
||||
let noise_scale = config.frequency / config.extent;
|
||||
let mut heights = Vec::with_capacity(config.size * config.size);
|
||||
for j in 0..config.size {
|
||||
let y = j as f64 * spacing - half;
|
||||
for i in 0..config.size {
|
||||
let x = i as f64 * spacing - half;
|
||||
let value = fbm(
|
||||
&noise,
|
||||
x * noise_scale,
|
||||
y * noise_scale,
|
||||
config.octaves,
|
||||
config.lacunarity,
|
||||
config.gain,
|
||||
);
|
||||
heights.push((value * 0.5 + 0.5).clamp(0.0, 1.0) * config.height_scale);
|
||||
}
|
||||
}
|
||||
Ok(Self { config, heights })
|
||||
}
|
||||
|
||||
/// Nodes per axis.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn size(&self) -> usize {
|
||||
self.config.size
|
||||
}
|
||||
|
||||
/// Side length of the map, m.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn extent(&self) -> f64 {
|
||||
self.config.extent
|
||||
}
|
||||
|
||||
/// Distance between neighbouring nodes, m.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn spacing(&self) -> f64 {
|
||||
self.config.spacing()
|
||||
}
|
||||
|
||||
/// Heights in row-major order, `size × size`, `i` along X and `j` along Y.
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn heights(&self) -> &[f64] {
|
||||
&self.heights
|
||||
}
|
||||
|
||||
/// Bilinearly interpolates the height at world `(x, y)`.
|
||||
///
|
||||
/// Coordinates outside the map clamp to its border; non-finite coordinates
|
||||
/// clamp to the nearest edge (`NaN` to the low edge) instead of panicking.
|
||||
#[must_use]
|
||||
pub fn height_at(&self, x: f64, y: f64) -> f64 {
|
||||
self.height_at_grid(self.grid_coordinate(x), self.grid_coordinate(y))
|
||||
}
|
||||
|
||||
/// The surface normal at world `(x, y)`, pointing up.
|
||||
///
|
||||
/// Uses central differences, one-sided at the border, and returns `+Z` when
|
||||
/// the gradient is degenerate.
|
||||
#[must_use]
|
||||
pub fn normal_at(&self, x: f64, y: f64) -> Vec3 {
|
||||
let gx = self.grid_coordinate(x);
|
||||
let gy = self.grid_coordinate(y);
|
||||
let last = (self.config.size - 1) as f64;
|
||||
let (xm, xp) = neighbours(gx, last);
|
||||
let (ym, yp) = neighbours(gy, last);
|
||||
let dx = (xp - xm) * self.spacing();
|
||||
let dy = (yp - ym) * self.spacing();
|
||||
let slope_x = (self.height_at_grid(xp, gy) - self.height_at_grid(xm, gy)) / dx;
|
||||
let slope_y = (self.height_at_grid(gx, yp) - self.height_at_grid(gx, ym)) / dy;
|
||||
Vec3::new(-slope_x, -slope_y, 1.0)
|
||||
.normalized()
|
||||
.unwrap_or(Vec3::Z)
|
||||
}
|
||||
|
||||
/// A triangle mesh at full resolution; see [`Self::mesh_with_step`].
|
||||
#[must_use]
|
||||
pub fn mesh(&self) -> TerrainMesh {
|
||||
self.mesh_with_step(1)
|
||||
}
|
||||
|
||||
/// A triangle mesh that keeps every `step`-th node, for cheap colliders.
|
||||
///
|
||||
/// `step` is clamped to at least one; the grid keeps the first and last node,
|
||||
/// so a step of two on an odd-sized map halves the node count.
|
||||
#[must_use]
|
||||
pub fn mesh_with_step(&self, step: usize) -> TerrainMesh {
|
||||
let step = step.max(1);
|
||||
let nodes = (self.config.size - 1) / step + 1;
|
||||
let vertices = self.build_vertices(nodes, step);
|
||||
let indices = build_indices(nodes);
|
||||
TerrainMesh { vertices, indices }
|
||||
}
|
||||
|
||||
fn build_vertices(&self, nodes: usize, step: usize) -> Vec<Vec3> {
|
||||
let half = self.config.extent * 0.5;
|
||||
let spacing = self.spacing();
|
||||
let mut vertices = Vec::with_capacity(nodes * nodes);
|
||||
for j in 0..nodes {
|
||||
let grid_j = j * step;
|
||||
let y = grid_j as f64 * spacing - half;
|
||||
for i in 0..nodes {
|
||||
let grid_i = i * step;
|
||||
let x = grid_i as f64 * spacing - half;
|
||||
vertices.push(Vec3::new(x, y, self.node(grid_i, grid_j)));
|
||||
}
|
||||
}
|
||||
vertices
|
||||
}
|
||||
|
||||
/// The stored height at a grid node; both indices are below `size`.
|
||||
#[inline]
|
||||
fn node(&self, i: usize, j: usize) -> f64 {
|
||||
self.heights[j * self.config.size + i]
|
||||
}
|
||||
|
||||
/// World coordinate to a fractional grid coordinate in `[0, size - 1]`.
|
||||
fn grid_coordinate(&self, value: f64) -> f64 {
|
||||
let last = (self.config.size - 1) as f64;
|
||||
if value.is_nan() {
|
||||
return 0.0;
|
||||
}
|
||||
let offset = value + self.config.extent * 0.5;
|
||||
(offset / self.spacing()).clamp(0.0, last)
|
||||
}
|
||||
|
||||
/// Bilinear interpolation in grid coordinates, which must be clamped.
|
||||
fn height_at_grid(&self, gx: f64, gy: f64) -> f64 {
|
||||
let last = self.config.size - 1;
|
||||
let i0 = (gx.floor() as usize).min(last - 1);
|
||||
let j0 = (gy.floor() as usize).min(last - 1);
|
||||
let tx = gx - i0 as f64;
|
||||
let ty = gy - j0 as f64;
|
||||
let bottom_left = self.node(i0, j0);
|
||||
let bottom_right = self.node(i0 + 1, j0);
|
||||
let top_left = self.node(i0, j0 + 1);
|
||||
let top_right = self.node(i0 + 1, j0 + 1);
|
||||
// Exact at `t = 0` and `t = 1`, so node samples match the stored heights.
|
||||
let bottom = bottom_left * (1.0 - tx) + bottom_right * tx;
|
||||
let top = top_left * (1.0 - tx) + top_right * tx;
|
||||
bottom * (1.0 - ty) + top * ty
|
||||
}
|
||||
}
|
||||
|
||||
/// The grid positions used for a difference at `position`, clamped to the map.
|
||||
fn neighbours(position: f64, last: f64) -> (f64, f64) {
|
||||
((position - 1.0).max(0.0), (position + 1.0).min(last))
|
||||
}
|
||||
|
||||
/// Two counter-clockwise triangles per cell, joined into `u32` indices.
|
||||
fn build_indices(nodes: usize) -> Vec<[u32; 3]> {
|
||||
let cells = nodes.saturating_sub(1);
|
||||
let mut indices = Vec::with_capacity(2 * cells * cells);
|
||||
let row = nodes as u32;
|
||||
for j in 0..cells {
|
||||
for i in 0..cells {
|
||||
let bottom_left = (j * nodes + i) as u32;
|
||||
let bottom_right = bottom_left + 1;
|
||||
let top_left = bottom_left + row;
|
||||
let top_right = top_left + 1;
|
||||
indices.push([bottom_left, bottom_right, top_right]);
|
||||
indices.push([bottom_left, top_right, top_left]);
|
||||
}
|
||||
}
|
||||
indices
|
||||
}
|
||||
|
||||
/// A triangle mesh of the terrain surface, ready for a renderer or a collider.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct TerrainMesh {
|
||||
/// Vertex positions in world space, metres.
|
||||
pub vertices: Vec<Vec3>,
|
||||
/// Triangles, wound counter-clockwise when viewed from above (`+Z`).
|
||||
pub indices: Vec<[u32; 3]>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
|
|
|||
330
crates/worldgen/src/terrain/tests.rs
Normal file
330
crates/worldgen/src/terrain/tests.rs
Normal file
|
|
@ -0,0 +1,330 @@
|
|||
use fabrilis_core::vec::Vec3;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// FNV-1a over the little-endian bit patterns of the heights.
|
||||
///
|
||||
/// The bit patterns are used so the hash does not depend on the host endianness
|
||||
/// or on formatting, only on the exact `f64` values (docs/DETERMINISM.md).
|
||||
fn hash_heights(heights: &[f64]) -> u64 {
|
||||
let mut hash: u64 = 0xCBF2_9CE4_8422_2325;
|
||||
for height in heights {
|
||||
for byte in height.to_bits().to_le_bytes() {
|
||||
hash ^= u64::from(byte);
|
||||
hash = hash.wrapping_mul(0x0000_0100_0000_01B3);
|
||||
}
|
||||
}
|
||||
hash
|
||||
}
|
||||
|
||||
/// The reference map used by the sampling and mesh tests; its spacing (3.125 m)
|
||||
/// and half extent (50 m) are exact binary values, so grid nodes land exactly.
|
||||
fn reference_map() -> Heightmap {
|
||||
let config = TerrainConfig {
|
||||
seed: 42,
|
||||
size: 33,
|
||||
extent: 100.0,
|
||||
height_scale: 10.0,
|
||||
frequency: 2.0,
|
||||
octaves: 4,
|
||||
..TerrainConfig::default()
|
||||
};
|
||||
Heightmap::generate(config).expect("the reference config is valid")
|
||||
}
|
||||
|
||||
fn flat_map() -> Heightmap {
|
||||
let config = TerrainConfig {
|
||||
height_scale: 0.0,
|
||||
..TerrainConfig::default()
|
||||
};
|
||||
Heightmap::generate(config).expect("a zero height scale is valid")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_terrain_has_zero_height_and_up_normals() {
|
||||
let map = flat_map();
|
||||
assert_eq!(map.heights().len(), map.size() * map.size());
|
||||
for height in map.heights() {
|
||||
assert_eq!(*height, 0.0);
|
||||
}
|
||||
for j in -5..=5 {
|
||||
for i in -5..=5 {
|
||||
let x = f64::from(i) * 12.5;
|
||||
let y = f64::from(j) * 7.25;
|
||||
assert_eq!(map.height_at(x, y), 0.0);
|
||||
assert_eq!(map.normal_at(x, y), Vec3::Z);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_config_has_the_documented_values() {
|
||||
let config = TerrainConfig::default();
|
||||
assert_eq!(config.size, 64);
|
||||
assert_eq!(config.extent, 100.0);
|
||||
assert_eq!(config.height_scale, 10.0);
|
||||
assert_eq!(config.frequency, 2.0);
|
||||
assert_eq!(config.octaves, 4);
|
||||
assert_eq!(config.lacunarity, 2.0);
|
||||
assert_eq!(config.gain, 0.5);
|
||||
assert_eq!(config.spacing(), 100.0 / 63.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_seed_reproduces_heights_bitwise() {
|
||||
let first = reference_map();
|
||||
let second = reference_map();
|
||||
let left: Vec<u64> = first.heights().iter().map(|h| h.to_bits()).collect();
|
||||
let right: Vec<u64> = second.heights().iter().map(|h| h.to_bits()).collect();
|
||||
assert_eq!(left, right);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_seed_changes_heights() {
|
||||
let other = Heightmap::generate(TerrainConfig {
|
||||
seed: 43,
|
||||
..reference_map().config
|
||||
})
|
||||
.expect("the config is valid");
|
||||
assert_ne!(reference_map().heights(), other.heights());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn golden_height_hash_is_pinned() {
|
||||
// This hash covers every height of the reference map. If it changes, the
|
||||
// generator changed: regenerate the whole terrain, not just this constant.
|
||||
// A deliberate algorithm change requires updating this value in the same
|
||||
// commit and noting why in the commit message.
|
||||
const GOLDEN: u64 = 0x9C4F_677D_8BE3_CCB8;
|
||||
let actual = hash_heights(reference_map().heights());
|
||||
assert_eq!(
|
||||
actual, GOLDEN,
|
||||
"golden height hash changed to {actual:#018x}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn height_at_grid_nodes_returns_stored_heights_exactly() {
|
||||
let map = reference_map();
|
||||
let spacing = map.spacing();
|
||||
let half = map.extent() * 0.5;
|
||||
for j in 0..map.size() {
|
||||
for i in 0..map.size() {
|
||||
let x = i as f64 * spacing - half;
|
||||
let y = j as f64 * spacing - half;
|
||||
assert_eq!(map.height_at(x, y), map.heights()[j * map.size() + i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midpoints_interpolate_bilinearly() {
|
||||
let map = reference_map();
|
||||
let spacing = map.spacing();
|
||||
let half = map.extent() * 0.5;
|
||||
let size = map.size();
|
||||
for j in [0, 1, 15, size - 2] {
|
||||
for i in [0, 1, 15, size - 2] {
|
||||
let x = (i as f64 + 0.5) * spacing - half;
|
||||
let y = (j as f64 + 0.5) * spacing - half;
|
||||
let corners = map.heights()[j * size + i]
|
||||
+ map.heights()[j * size + i + 1]
|
||||
+ map.heights()[(j + 1) * size + i]
|
||||
+ map.heights()[(j + 1) * size + i + 1];
|
||||
let expected = corners * 0.25;
|
||||
let actual = map.height_at(x, y);
|
||||
assert!((actual - expected).abs() < 1e-12, "{actual} != {expected}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sampling_clamps_borders_and_non_finite_coordinates() {
|
||||
let map = reference_map();
|
||||
let last = map.size() - 1;
|
||||
let low = map.height_at(-1e9, -1e9);
|
||||
let high = map.height_at(1e9, 1e9);
|
||||
assert_eq!(low, map.heights()[0]);
|
||||
assert_eq!(high, map.heights()[last * map.size() + last]);
|
||||
assert_eq!(map.height_at(f64::NAN, f64::NAN), low);
|
||||
assert_eq!(map.height_at(f64::INFINITY, 0.0), map.height_at(1e9, 0.0));
|
||||
assert_eq!(map.normal_at(f64::NAN, f64::NAN), map.normal_at(-1e9, -1e9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_points_against_the_gradient_and_is_a_unit_vector() {
|
||||
let map = reference_map();
|
||||
let spacing = map.spacing();
|
||||
let half = map.extent() * 0.5;
|
||||
let size = map.size();
|
||||
// Find an interior node with a clear slope; flat spots have a zero gradient
|
||||
// and would not exercise the direction check.
|
||||
let (i, j) = (1..size - 1)
|
||||
.flat_map(|j| (1..size - 1).map(move |i| (i, j)))
|
||||
.find(|&(i, j)| {
|
||||
let dx = map.heights()[j * size + i + 1] - map.heights()[j * size + i - 1];
|
||||
let dy = map.heights()[(j + 1) * size + i] - map.heights()[(j - 1) * size + i];
|
||||
dx.abs() + dy.abs() > 0.5
|
||||
})
|
||||
.expect("the reference map has a slope somewhere");
|
||||
let x = i as f64 * spacing - half;
|
||||
let y = j as f64 * spacing - half;
|
||||
let slope_x =
|
||||
(map.heights()[j * size + i + 1] - map.heights()[j * size + i - 1]) / (2.0 * spacing);
|
||||
let slope_y =
|
||||
(map.heights()[(j + 1) * size + i] - map.heights()[(j - 1) * size + i]) / (2.0 * spacing);
|
||||
let normal = map.normal_at(x, y);
|
||||
assert!((normal.length() - 1.0).abs() < 1e-12);
|
||||
assert!(normal.z > 0.0);
|
||||
assert!(
|
||||
(normal.x + slope_x / (1.0 + slope_x * slope_x + slope_y * slope_y).sqrt()).abs() < 1e-12
|
||||
);
|
||||
assert!(
|
||||
(normal.y + slope_y / (1.0 + slope_x * slope_x + slope_y * slope_y).sqrt()).abs() < 1e-12
|
||||
);
|
||||
assert!(normal.x * slope_x <= 0.0);
|
||||
assert!(normal.y * slope_y <= 0.0);
|
||||
}
|
||||
|
||||
fn triangle_z(vertices: &[Vec3], indices: &[u32; 3]) -> f64 {
|
||||
let a = vertices[indices[0] as usize];
|
||||
let b = vertices[indices[1] as usize];
|
||||
let c = vertices[indices[2] as usize];
|
||||
(b - a).cross(c - a).z
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_has_grid_vertices_and_upward_triangles() {
|
||||
let map = Heightmap::generate(TerrainConfig {
|
||||
size: 9,
|
||||
height_scale: 2.0,
|
||||
..TerrainConfig::default()
|
||||
})
|
||||
.expect("the config is valid");
|
||||
let mesh = map.mesh();
|
||||
assert_eq!(mesh.vertices.len(), map.size() * map.size());
|
||||
assert_eq!(mesh.indices.len(), 2 * (map.size() - 1) * (map.size() - 1));
|
||||
for triangle in &mesh.indices {
|
||||
assert!(triangle_z(&mesh.vertices, triangle) > 0.0);
|
||||
}
|
||||
for (index, vertex) in mesh.vertices.iter().enumerate() {
|
||||
let i = index % map.size();
|
||||
let j = index / map.size();
|
||||
assert_eq!(vertex.z, map.heights()[j * map.size() + i]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_with_step_halves_the_grid_and_keeps_winding() {
|
||||
let map = reference_map();
|
||||
let mesh = map.mesh_with_step(2);
|
||||
let nodes = 17;
|
||||
assert_eq!(mesh.vertices.len(), nodes * nodes);
|
||||
assert_eq!(mesh.indices.len(), 2 * (nodes - 1) * (nodes - 1));
|
||||
for triangle in &mesh.indices {
|
||||
assert!(triangle_z(&mesh.vertices, triangle) > 0.0);
|
||||
}
|
||||
assert_eq!(map.mesh_with_step(0), map.mesh());
|
||||
}
|
||||
|
||||
fn config_with(mutate: impl FnOnce(&mut TerrainConfig)) -> TerrainConfig {
|
||||
let mut config = TerrainConfig::default();
|
||||
mutate(&mut config);
|
||||
config
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_extent_and_scale_errors_are_rejected() {
|
||||
let cases = [
|
||||
(
|
||||
config_with(|config| config.size = 1),
|
||||
TerrainError::SizeOutOfRange(1),
|
||||
),
|
||||
(
|
||||
config_with(|config| config.size = MAX_SIZE + 1),
|
||||
TerrainError::SizeOutOfRange(MAX_SIZE + 1),
|
||||
),
|
||||
(
|
||||
config_with(|config| config.extent = 0.0),
|
||||
TerrainError::InvalidExtent(0.0),
|
||||
),
|
||||
(
|
||||
config_with(|config| config.extent = -5.0),
|
||||
TerrainError::InvalidExtent(-5.0),
|
||||
),
|
||||
(
|
||||
config_with(|config| config.height_scale = -1.0),
|
||||
TerrainError::InvalidHeightScale(-1.0),
|
||||
),
|
||||
];
|
||||
for (config, expected) in cases {
|
||||
assert_eq!(Heightmap::generate(config).unwrap_err(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_parameter_errors_are_rejected() {
|
||||
let cases = [
|
||||
(
|
||||
config_with(|config| config.frequency = 0.0),
|
||||
TerrainError::InvalidFrequency(0.0),
|
||||
),
|
||||
(
|
||||
config_with(|config| config.frequency = f64::INFINITY),
|
||||
TerrainError::InvalidFrequency(f64::INFINITY),
|
||||
),
|
||||
(
|
||||
config_with(|config| config.octaves = 0),
|
||||
TerrainError::OctavesOutOfRange(0),
|
||||
),
|
||||
(
|
||||
config_with(|config| config.octaves = 9),
|
||||
TerrainError::OctavesOutOfRange(9),
|
||||
),
|
||||
(
|
||||
config_with(|config| config.lacunarity = 1.0),
|
||||
TerrainError::InvalidLacunarity(1.0),
|
||||
),
|
||||
(
|
||||
config_with(|config| config.gain = -0.5),
|
||||
TerrainError::InvalidGain(-0.5),
|
||||
),
|
||||
(
|
||||
config_with(|config| config.gain = 1.5),
|
||||
TerrainError::InvalidGain(1.5),
|
||||
),
|
||||
];
|
||||
for (config, expected) in cases {
|
||||
assert_eq!(Heightmap::generate(config).unwrap_err(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_finite_parameter_payloads_are_rejected() {
|
||||
// `NaN` is never equal to itself, so its payload is checked separately.
|
||||
let nan_extent = Heightmap::generate(config_with(|config| config.extent = f64::NAN));
|
||||
assert!(matches!(
|
||||
nan_extent,
|
||||
Err(TerrainError::InvalidExtent(value)) if value.is_nan()
|
||||
));
|
||||
let nan_gain = Heightmap::generate(config_with(|config| config.gain = f64::NAN));
|
||||
assert!(matches!(
|
||||
nan_gain,
|
||||
Err(TerrainError::InvalidGain(value)) if value.is_nan()
|
||||
));
|
||||
let infinite_lacunarity =
|
||||
Heightmap::generate(config_with(|config| config.lacunarity = f64::INFINITY));
|
||||
assert!(matches!(
|
||||
infinite_lacunarity,
|
||||
Err(TerrainError::InvalidLacunarity(value)) if value.is_infinite()
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_implement_display_and_error() {
|
||||
let error = TerrainError::SizeOutOfRange(0);
|
||||
let text = error.to_string();
|
||||
assert!(text.contains('0'));
|
||||
let dynamic: &dyn std::error::Error = &error;
|
||||
assert_eq!(dynamic.to_string(), text);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue