use crate::buffer::Cell;
use crate::canvas::Canvas;
use crate::common::{
DEFAULT_SEED, EffectRng, TerminalEffect, normalize_effect_size, seeded_rng,
};
use crate::render::braille::{BrailleGrid, DOTS_X, DOTS_Y};
use crate::render::dither::Dither;
use crate::render::palette::{Palette, presets as palette_presets};
use crate::runtime::FrameContext;
use crate::terrain::noise::PerlinNoise;
use crossterm::style::{self, Color};
use rand::RngExt;
use serde::{Deserialize, Serialize};
const NOISE_HALF_RANGE: f64 = 0.55;
const CELL_ASPECT: f32 = 2.0;
const DOT_WIDTH: f32 = 1.0 / DOTS_X as f32;
const DOT_HEIGHT: f32 = CELL_ASPECT / DOTS_Y as f32;
const FOV_TAN: f32 = 0.45;
const NEAR: f32 = 1.5;
const STEP_GROWTH: f32 = 0.14;
const STEP_MIN: f32 = 1.5;
const FAR: f32 = 260.0;
const FOG_DISTANCE: f32 = 85.0;
const FRINGE_DOTS: f32 = 5.0;
const NORMAL_STEP: f32 = 24.0;
const SUN: [f32; 3] = [-0.45, 0.72, -0.53];
const FOLLOW_RATE: f32 = 1.6;
const OCTAVES: i32 = 4;
#[derive(Debug, Clone, Copy)]
struct Camera {
x: f32,
y: f32,
z: f32,
pitch: f32,
roll: f32,
}
const FOG_STEPS: usize = 1024;
const FOG_RANGE: f32 = FAR * 1.01;
static FOG_LUT: std::sync::LazyLock<[f32; FOG_STEPS]> =
std::sync::LazyLock::new(|| {
std::array::from_fn(|i| {
let depth = i as f32 * FOG_RANGE / FOG_STEPS as f32;
(-depth / FOG_DISTANCE).exp()
})
});
#[inline]
fn fog_at(depth: f32) -> f32 {
let index = (depth * (FOG_STEPS as f32 / FOG_RANGE)) as usize;
FOG_LUT[index.min(FOG_STEPS - 1)]
}
#[inline]
fn cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
[
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
}
impl Camera {
fn basis(&self) -> [[f32; 3]; 3] {
let (sp, cp) = self.pitch.sin_cos();
let (sr, cr) = self.roll.sin_cos();
let forward = [0.0, -sp, cp];
let level_right = [1.0, 0.0, 0.0];
let level_up = cross(forward, level_right);
let right = [
level_right[0] * cr + level_up[0] * sr,
level_right[1] * cr + level_up[1] * sr,
level_right[2] * cr + level_up[2] * sr,
];
let up = [
level_up[0] * cr - level_right[0] * sr,
level_up[1] * cr - level_right[1] * sr,
level_up[2] * cr - level_right[2] * sr,
];
[right, up, forward]
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct FlyoverOptions {
pub speed: f32,
pub relief: f32,
pub flying_height: f32,
pub scale: f32,
pub octaves: i32,
pub persistence: f32,
pub sway: f32,
pub palette: String,
pub seed: u64,
}
impl Default for FlyoverOptions {
fn default() -> Self {
Self {
speed: 26.0,
relief: 26.0,
flying_height: 11.0,
scale: 240.0,
octaves: OCTAVES,
persistence: 0.5,
sway: 34.0,
palette: "depth".to_string(),
seed: DEFAULT_SEED,
}
}
}
pub struct Flyover {
screen_size: (u16, u16),
options: FlyoverOptions,
canvas: Canvas,
grid: BrailleGrid,
camera: Camera,
base_x: f32,
noise: PerlinNoise,
time: f32,
rng: EffectRng,
palette: Palette,
coverage: Vec<f32>,
depth_at_row: Vec<f32>,
column_coverage: Vec<f32>,
silhouette: Vec<usize>,
profiles: Vec<f32>,
cell_colour: Vec<Color>,
sky: Vec<Color>,
}
impl TerminalEffect for Flyover {
fn get_diff(&mut self) -> Vec<(usize, usize, Cell)> {
self.draw();
self.canvas.commit()
}
fn update(&mut self) {
self.advance(1.0 / 60.0);
}
fn update_with_context(&mut self, context: &FrameContext) {
self.advance(context.delta.as_secs_f32());
}
fn update_size(&mut self, width: u16, height: u16) {
self.screen_size = (width, height);
self.reset();
}
fn reset(&mut self) {
self.canvas.resize(self.screen_size.0, self.screen_size.1);
self.grid
.resize(self.screen_size.0 as usize, self.screen_size.1 as usize);
self.coverage = vec![0.0; self.grid.dot_width() * self.grid.dot_height()];
self.depth_at_row = vec![0.0; self.grid.dot_height()];
self.column_coverage = vec![0.0; self.grid.dot_height()];
self.silhouette = vec![usize::MAX; self.grid.dot_width()];
self.profiles = vec![0.0; self.grid.dot_width() * self.grid.dot_height()];
self.cell_colour =
vec![Color::Reset; self.canvas.width() * self.canvas.height()];
self.time = 0.0;
self.rng = seeded_rng(self.options.seed, "flyover");
self.noise = PerlinNoise::new(self.options.seed);
self.base_x = self.rng.random_range(-800.0..800.0);
self.camera = Camera {
x: self.base_x,
y: 0.0,
z: 0.0,
pitch: 0.0,
roll: 0.0,
};
self.camera.y =
self.ground(self.camera.x, self.camera.z) + self.flying_height();
self.build_sky();
}
}
impl Flyover {
pub fn new(options: FlyoverOptions, screen_size: (u16, u16)) -> Self {
let screen_size = normalize_effect_size(screen_size);
let grid = BrailleGrid::new(screen_size.0 as usize, screen_size.1 as usize);
let palette = Palette::new(
palette_presets::by_name(&options.palette)
.unwrap_or(palette_presets::DEPTH)
.to_vec(),
)
.truncated_at_peak();
let mut flyover = Self {
screen_size,
canvas: Canvas::new(screen_size.0, screen_size.1),
coverage: vec![0.0; grid.dot_width() * grid.dot_height()],
depth_at_row: vec![0.0; grid.dot_height()],
column_coverage: vec![0.0; grid.dot_height()],
silhouette: vec![usize::MAX; grid.dot_width()],
profiles: vec![0.0; grid.dot_width() * grid.dot_height()],
cell_colour: vec![
Color::Reset;
screen_size.0 as usize * screen_size.1 as usize
],
sky: Vec::new(),
grid,
camera: Camera {
x: 0.0,
y: 0.0,
z: 0.0,
pitch: 0.0,
roll: 0.0,
},
base_x: 0.0,
noise: PerlinNoise::new(DEFAULT_SEED),
time: 0.0,
rng: seeded_rng(DEFAULT_SEED, "flyover"),
palette,
options,
};
flyover.reset();
flyover
}
fn flying_height(&self) -> f32 {
self.options.flying_height.max(1.0)
}
fn noise_scale(&self) -> f64 {
if self.options.scale > 1.0 {
1.0 / self.options.scale as f64
} else {
1.0
}
}
fn ground(&self, x: f32, z: f32) -> f32 {
let raw = self.noise.octave_noise_2d(
x as f64,
z as f64,
self.options.octaves.clamp(1, 16),
self.options.persistence.max(0.0) as f64,
self.noise_scale(),
);
(raw / NOISE_HALF_RANGE * self.options.relief as f64) as f32
}
pub fn advance(&mut self, delta: f32) {
let delta = delta.clamp(0.0, 0.05);
self.time += delta;
let sway = self.options.sway;
self.camera.x = self.base_x
+ sway * (self.time * 0.11).sin()
+ sway * 0.4 * (self.time * 0.037).sin();
self.camera.roll = 0.045 * (self.time * 0.11 + 0.6).sin();
self.camera.z += self.options.speed.max(0.0) * delta;
let follow = 1.0 - (-FOLLOW_RATE * delta).exp();
let look_ahead = self.flying_height() * 2.0;
let target = self.ground(self.camera.x, self.camera.z + look_ahead)
+ self.flying_height();
self.camera.y += (target - self.camera.y) * follow;
let ahead = self.ground(self.camera.x, self.camera.z + 90.0);
let behind = self.ground(self.camera.x, self.camera.z + 20.0);
let target_pitch = 0.09 + ((ahead - behind) / 70.0).clamp(-0.5, 0.5) * 0.3;
self.camera.pitch += (target_pitch - self.camera.pitch) * follow;
}
pub fn dimensions(&self) -> (usize, usize) {
(self.canvas.width(), self.canvas.height())
}
pub fn cell_symbol(&self, x: usize, y: usize) -> char {
self.canvas.on_screen().get(x, y).symbol
}
pub fn profile_at(&self, dot_x: usize, dot_y: usize) -> f32 {
let dh = self.grid.dot_height();
self.profiles
.get(dot_x * dh + dot_y)
.copied()
.unwrap_or(0.0)
}
pub fn silhouette_of(&self, dot_x: usize) -> usize {
self.silhouette.get(dot_x).copied().unwrap_or(usize::MAX)
}
pub fn coverage_summary(&self) -> (usize, usize, usize) {
let width = self.canvas.width();
let height = self.canvas.height();
let mut inked = 0;
let mut topmost_empty = height;
for y in 0..height {
let row_blank = (0..width).all(|x| self.cell_symbol(x, y) == ' ');
if row_blank {
topmost_empty = topmost_empty.min(y);
} else {
for x in 0..width {
if self.cell_symbol(x, y) != ' ' {
inked += 1;
}
}
}
}
(inked, width * height - inked, topmost_empty)
}
pub fn horizon_row_value(&self) -> f32 {
self.horizon_row()
}
pub fn pitch_value(&self) -> f32 {
self.camera.pitch
}
pub fn roll_value(&self) -> f32 {
self.camera.roll
}
pub fn camera_height(&self) -> f32 {
self.camera.y
}
pub fn camera_depth(&self) -> f32 {
self.camera.z
}
pub fn ground_at(&self, x: f32, z: f32) -> f32 {
self.ground(x, z)
}
pub fn dot_dimensions(&self) -> (usize, usize) {
(self.grid.dot_width(), self.grid.dot_height())
}
pub fn camera_lateral(&self) -> f32 {
self.camera.x
}
pub fn ground_under_camera(&self) -> f32 {
self.ground(self.camera.x, self.camera.z)
}
pub fn column_samples(&self, column: usize) -> Vec<(f32, f32, f32, f32, f32)> {
let (dw, dh) = (self.grid.dot_width(), self.grid.dot_height());
let [right, up, forward] = self.camera.basis();
let aspect = (dw as f32 * DOT_WIDTH) / (dh as f32 * DOT_HEIGHT);
let tan_x = FOV_TAN * aspect;
let centre_row = dh as f32 * 0.5;
let eye = [self.camera.x, self.camera.y, self.camera.z];
let ndc_x = (column as f32 + 0.5 - dw as f32 * 0.5) / (dw as f32 * 0.5);
let slope_x = ndc_x * tan_x;
let mut out = Vec::new();
let mut depth = NEAR;
while out.len() < 40 && depth < FAR {
let wx = eye[0] + right[0] * slope_x * depth + forward[0] * depth;
let wz = eye[2] + right[2] * slope_x * depth + forward[2] * depth;
let height = self.ground(wx, wz);
let dx = wx - eye[0];
let dy = height - eye[1];
let dz = wz - eye[2];
let ahead = forward[0] * dx + forward[1] * dy + forward[2] * dz;
let row = if ahead > 1e-3 {
let vertical = up[0] * dx + up[1] * dy + up[2] * dz;
centre_row - vertical / ahead / FOV_TAN * dh as f32 * 0.5
} else {
f32::NAN
};
out.push((depth, wx, wz, height, row));
depth += (depth * STEP_GROWTH).max(STEP_MIN);
}
out
}
fn horizon_row(&self) -> f32 {
let dh = self.grid.dot_height() as f32;
dh * (0.5 - 0.5 * self.camera.pitch.tan() / FOV_TAN)
}
fn build_sky(&mut self) {
let height = self.canvas.height().max(1);
let horizon_cell =
(self.horizon_row() / DOTS_Y as f32 / height as f32).clamp(0.0, 1.0);
self.sky = (0..height)
.map(|row| {
let t = 1.0 - row as f32 / height as f32;
let k = 1.0
- ((t - horizon_cell) / (1.0 - horizon_cell).max(0.05))
.clamp(0.0, 1.0);
Color::Rgb {
r: (8.0 + 44.0 * k) as u8,
g: (10.0 + 60.0 * k) as u8,
b: (22.0 + 70.0 * k) as u8,
}
})
.collect();
}
fn draw(&mut self) {
self.canvas.clear();
self.build_sky();
self.coverage.fill(0.0);
self.column_coverage.fill(0.0);
self.silhouette.fill(usize::MAX);
let (dw, dh) = (self.grid.dot_width(), self.grid.dot_height());
let [right, up, forward] = self.camera.basis();
let sun = {
let length =
(SUN[0] * SUN[0] + SUN[1] * SUN[1] + SUN[2] * SUN[2]).sqrt();
[SUN[0] / length, SUN[1] / length, SUN[2] / length]
};
let aspect = (dw as f32 * DOT_WIDTH) / (dh as f32 * DOT_HEIGHT);
let tan_x = FOV_TAN * aspect;
let centre_row = dh as f32 * 0.5;
let eye = [self.camera.x, self.camera.y, self.camera.z];
for sx in 0..dw {
let ndc_x = (sx as f32 + 0.5 - dw as f32 * 0.5) / (dw as f32 * 0.5);
let slope_x = ndc_x * tan_x;
let Some(top) =
self.march(&eye, &right, &forward, &up, slope_x, centre_row, dh)
else {
continue;
};
self.silhouette[sx] = top;
let silhouette = self.depth_at_row[top];
let wx = eye[0] + (right[0] * slope_x + forward[0]) * silhouette;
let wz = eye[2] + (right[2] * slope_x + forward[2]) * silhouette;
let hx = self.ground(wx + NORMAL_STEP, wz)
- self.ground(wx - NORMAL_STEP, wz);
let hz = self.ground(wx, wz + NORMAL_STEP)
- self.ground(wx, wz - NORMAL_STEP);
let normal = normal_of(hx, hz);
let lambert =
(normal[0] * sun[0] + normal[1] * sun[1] + normal[2] * sun[2])
.max(0.0)
.clamp(0.0, 1.0);
let edge_on = (1.0 - normal[1]).clamp(0.0, 1.0);
let ink = (0.86 - 0.55 * edge_on) * (0.55 + 0.45 * lambert);
for sy in top..dh {
let below =
((sy as f32 - top as f32) / FRINGE_DOTS).clamp(0.0, 1.0);
let fog = fog_at(self.depth_at_row[sy]);
self.column_coverage[sy] = (below * ink * fog).clamp(0.0, 1.0);
}
let base = sx * dh;
self.profiles[base..base + dh].copy_from_slice(&self.column_coverage);
}
self.transpose();
self.grid
.draw_field(&self.coverage, 0.42, 0.5, Dither::Bayer4);
self.paint();
}
fn transpose(&mut self) {
const TILE: usize = 32;
let (dw, dh) = (self.grid.dot_width(), self.grid.dot_height());
for ty in (0..dh).step_by(TILE) {
for tx in (0..dw).step_by(TILE) {
for y in ty..(ty + TILE).min(dh) {
for x in tx..(tx + TILE).min(dw) {
self.coverage[y * dw + x] = self.profiles[x * dh + y];
}
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn march(
&mut self,
eye: &[f32; 3],
right: &[f32; 3],
forward: &[f32; 3],
up: &[f32; 3],
slope_x: f32,
centre_row: f32,
dh: usize,
) -> Option<usize> {
for depth in self.depth_at_row.iter_mut() {
*depth = f32::NAN;
}
let mut depth = NEAR;
while depth < FAR {
let along_x = right[0] * slope_x * depth + forward[0] * depth;
let along_z = right[2] * slope_x * depth + forward[2] * depth;
let wx = eye[0] + along_x;
let wz = eye[2] + along_z;
let height = self.ground(wx, wz);
let dx = wx - eye[0];
let dy = height - eye[1];
let dz = wz - eye[2];
let ahead = forward[0] * dx + forward[1] * dy + forward[2] * dz;
if ahead > 1e-3 {
let vertical = up[0] * dx + up[1] * dy + up[2] * dz;
let row = centre_row - vertical / ahead / FOV_TAN * dh as f32 * 0.5;
if row >= 0.0 && (row as usize) < dh {
let r = row as usize;
if self.depth_at_row[r].is_nan() {
self.depth_at_row[r] = depth;
}
}
}
depth += (depth * STEP_GROWTH).max(STEP_MIN);
}
let mut top = dh;
for r in (0..dh).rev() {
if self.depth_at_row[r].is_nan() {
if r + 1 < dh && !self.depth_at_row[r + 1].is_nan() {
self.depth_at_row[r] = self.depth_at_row[r + 1];
}
} else if r < top {
top = r;
}
}
(top < dh).then_some(top)
}
fn paint(&mut self) {
let width = self.canvas.width();
let height = self.canvas.height();
let dw = self.grid.dot_width();
let last_sky = self.sky.len().saturating_sub(1);
for cy in 0..height {
let sky = self.sky[cy.min(last_sky)];
for cx in 0..width {
let mut lowest = f32::INFINITY;
for sy in cy * DOTS_Y..(cy + 1) * DOTS_Y {
for sx in cx * DOTS_X..(cx + 1) * DOTS_X {
lowest = lowest.min(self.coverage[sy * dw + sx]);
}
}
let colour = if lowest.is_finite() && lowest > 0.0 {
self.palette.sample((1.0 - lowest).clamp(0.0, 1.0))
} else {
sky
};
self.cell_colour[cy * width + cx] = colour;
}
}
for cy in 0..height {
for cx in 0..width {
let symbol = self.grid.cell_char(cx, cy);
self.canvas.set(
cx,
cy,
Cell::new(
symbol,
self.cell_colour[cy * width + cx],
style::Attribute::Reset,
),
);
}
}
}
}
fn normal_of(hx: f32, hz: f32) -> [f32; 3] {
let length = (hx * hx + hz * hz + 4.0 * NORMAL_STEP * NORMAL_STEP).sqrt();
[-hx / length, 2.0 * NORMAL_STEP / length, -hz / length]
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common::TerminalEffect;
use crate::terrain::noise::PerlinNoise;
fn fixture(seed: u64) -> Flyover {
Flyover::new(
FlyoverOptions {
seed,
..FlyoverOptions::default()
},
(100, 32),
)
}
fn run(flyover: &mut Flyover, frames: u32) {
for _ in 0..frames {
flyover.advance(1.0 / 60.0);
flyover.get_diff();
}
}
fn skyline(flyover: &Flyover) -> Vec<Option<usize>> {
let (width, height) = flyover.dimensions();
(0..width)
.map(|x| (0..height).find(|y| flyover.cell_symbol(x, *y) != ' '))
.collect()
}
#[test]
fn no_column_is_inked_above_its_own_silhouette() {
let mut flyover = fixture(3);
run(&mut flyover, 120);
let (dw, _dh) = flyover.dot_dimensions();
let mut with_ground = 0;
let mut smeared = Vec::new();
for sx in 0..dw {
let top = flyover.silhouette_of(sx);
if top == usize::MAX {
continue; }
with_ground += 1;
if let Some(leaked) =
(0..top).find(|y| flyover.profile_at(sx, *y) > 0.0)
{
smeared.push((sx, leaked, top));
}
}
assert!(
with_ground > dw / 2,
"only {with_ground} of {dw} columns found ground, so this measured \
nothing about the sky"
);
assert!(
smeared.is_empty(),
"{} of {dw} columns carry coverage ABOVE their own skyline -- column \
{} is inked at row {} but its silhouette is row {}, and so on for \
{smeared:?}. The sky is inheriting the neighbouring column's ground, \
which no column of this landscape has ever done.",
smeared.len(),
smeared.first().map(|s| s.0).unwrap_or(0),
smeared.first().map(|s| s.1).unwrap_or(0),
smeared.first().map(|s| s.2).unwrap_or(0),
);
}
#[test]
fn there_is_sky_above_the_ground_and_ground_below_it() {
let mut flyover = fixture(1);
run(&mut flyover, 120);
let (width, height) = flyover.dimensions();
let inked_in = |from: usize, to: usize| {
(from..to)
.flat_map(|y| (0..width).map(move |x| (x, y)))
.filter(|(x, y)| flyover.cell_symbol(*x, *y) != ' ')
.count()
};
let top_eighth = inked_in(0, height / 8);
let bottom_quarter = inked_in(height - height / 4, height);
assert_eq!(
top_eighth, 0,
"the top eighth of the frame has {top_eighth} inked cells; the sky is \
where the ground is not"
);
assert!(
bottom_quarter > width * (height / 4) / 2,
"only {bottom_quarter} of the bottom quarter's cells carry ink, so the \
ground does not reach the bottom of the frame"
);
}
#[test]
fn the_ground_has_a_skyline_rather_than_a_flat_top() {
let mut flyover = fixture(2);
run(&mut flyover, 120);
let skyline = skyline(&flyover);
let ground: Vec<usize> = skyline.iter().flatten().copied().collect();
assert!(
ground.len() > skyline.len() / 2,
"only {} of {} columns have any ground at all",
ground.len(),
skyline.len()
);
let lowest = ground.iter().min().expect("measured above");
let highest = ground.iter().max().expect("measured above");
assert!(
*highest - *lowest >= 4,
"the skyline spans {} rows ({} to {}), so the ground has no shape",
highest - lowest,
lowest,
highest
);
}
#[test]
fn the_horizon_moves_smoothly_rather_than_jumping() {
let mut flyover = fixture(3);
run(&mut flyover, 60);
let mut worst: f32 = 0.0;
let mut previous = flyover.horizon_row_value();
for _ in 0..240 {
flyover.advance(1.0 / 60.0);
flyover.get_diff();
let horizon = flyover.horizon_row_value();
worst = worst.max((horizon - previous).abs());
previous = horizon;
}
let dh = flyover.dot_dimensions().1;
assert!(
worst < dh as f32 * 0.02,
"the horizon moved {worst} rows in one frame on a {dh}-row grid, so \
the camera is lurching rather than flying"
);
}
#[test]
fn the_camera_keeps_flying_forward() {
let mut flyover = fixture(4);
run(&mut flyover, 60);
let start = flyover.camera_depth();
run(&mut flyover, 60);
let travelled = flyover.camera_depth() - start;
assert!(
travelled > 20.0,
"the camera advanced {travelled} world units in a second, which is not \
flying"
);
}
#[test]
fn the_camera_stays_above_the_ground() {
let mut flyover = fixture(5);
for _ in 0..600 {
run(&mut flyover, 1);
let clearance = flyover.camera_height() - flyover.ground_under_camera();
assert!(
clearance > 0.0,
"the camera is {} units below the ground at z {:.1}",
-clearance,
flyover.camera_depth()
);
}
}
#[test]
fn a_point_projects_to_the_row_the_projection_says() {
let mut flyover = fixture(6);
run(&mut flyover, 60);
let (dw, dh) = flyover.dot_dimensions();
let samples = flyover.column_samples(dw / 2);
let (_, wx, wz, height, row) = samples
.iter()
.copied()
.find(|(_, _, _, _, row)| *row >= 0.0 && *row < dh as f32)
.unwrap_or_else(|| {
panic!(
"no sample of the middle column lands on the frame in {} steps",
samples.len()
)
});
let depth = samples[0].0;
let eye_x = flyover.camera_lateral();
let eye_y = flyover.camera_height();
let eye_z = flyover.camera_depth();
let pitch = flyover.pitch_value();
flyover.camera.roll = 0.0;
let forward = [0.0, -pitch.sin(), pitch.cos()];
let up = [0.0, pitch.cos(), pitch.sin()];
assert!(
(forward[0] * up[0] + forward[1] * up[1] + forward[2] * up[2]).abs()
< 1e-5,
"the test's `up` is not perpendicular to its `forward`, so the test \
itself is wrong"
);
let d = [wx - eye_x, height - eye_y, wz - eye_z];
let ahead = forward[0] * d[0] + forward[1] * d[1] + forward[2] * d[2];
let vertical = up[0] * d[0] + up[1] * d[1] + up[2] * d[2];
let expected =
dh as f32 * 0.5 - vertical / ahead / FOV_TAN * dh as f32 * 0.5;
assert!(
ahead > 0.0,
"the sample at depth {depth} is behind the camera, so the test has \
nothing to compare"
);
assert!(
(row - expected).abs() < 0.05,
"the sample at ({wx:.1}, {height:.2}, {wz:.1}) projected to row {row} \
and hand arithmetic says {expected}"
);
}
#[test]
fn more_relief_gives_a_rougher_skyline() {
let skyline_spread = |relief: f32| {
let mut flyover = Flyover::new(
FlyoverOptions {
seed: 8,
relief,
..FlyoverOptions::default()
},
(100, 32),
);
run(&mut flyover, 90);
let skyline: Vec<usize> =
skyline(&flyover).into_iter().flatten().collect();
let lowest = skyline.iter().min().expect("some ground");
let highest = skyline.iter().max().expect("some ground");
highest - lowest
};
let flat = skyline_spread(1.0);
let mountainous = skyline_spread(40.0);
assert!(
mountainous > flat * 2,
"relief 1.0 gave a skyline spanning {flat} rows and relief 40.0 gave \
{mountainous}, so the setting barely reaches the picture"
);
}
#[test]
fn different_seeds_are_different_landscapes() {
let ground_here = |seed: u64| fixture(seed).ground_at(3.7, 1.9);
assert_ne!(
ground_here(100),
ground_here(101),
"the seed did not change the terrain"
);
}
#[test]
fn the_noise_still_spans_the_calibrated_range() {
let mut lowest = f64::INFINITY;
let mut highest = f64::NEG_INFINITY;
for seed in [1u64, 42, 99, 12_345] {
let noise = PerlinNoise::new(seed);
for i in 0..2000 {
for j in 0..4 {
let value = noise.octave_noise_2d(
i as f64 * 3.1,
j as f64 * 7.7,
OCTAVES,
0.5,
1.0 / 240.0,
);
lowest = lowest.min(value);
highest = highest.max(value);
}
}
}
assert!(
lowest.abs() < NOISE_HALF_RANGE && highest.abs() < NOISE_HALF_RANGE,
"the noise now spans {lowest:.3}..{highest:.3}, outside the +/-\
{NOISE_HALF_RANGE} that `relief` is calibrated against"
);
assert!(
highest - lowest > NOISE_HALF_RANGE,
"the noise now spans only {} peak to peak, below the {NOISE_HALF_RANGE} \
half-range that `relief` is calibrated against",
highest - lowest
);
}
#[test]
fn every_emitted_cell_is_inside_the_canvas() {
let mut flyover = fixture(9);
for _ in 0..120 {
flyover.advance(1.0 / 60.0);
for (x, y, _) in flyover.get_diff() {
assert!(x < 100 && y < 32, "({x}, {y}) is outside a 100x32 canvas");
}
}
}
}