use crate::aquarium::art;
use crate::aquarium::charart;
use crate::buffer::Cell;
use crate::canvas::Canvas;
use crate::common::{
DEFAULT_SEED, EffectRng, TerminalEffect, normalize_effect_size, seeded_rng,
};
use crate::render::palette;
use crate::runtime::{FrameContext, InputEvent, PointerPhase};
use crossterm::style::{Attribute, Color};
use rand::RngExt;
use serde::{Deserialize, Serialize};
const SPECIES_MIX: &[(f32, f32)] = &[
(0.30, 0.0), (0.52, 1.0), (0.63, 2.0), (0.72, 3.0), (0.80, 4.0), (0.88, 5.0), (1.01, 6.0), ];
const SEPARATION_DEPTH: f32 = 0.28;
const SEP_GAP: f32 = 1.0;
const SHOAL_RADIUS: f32 = 15.0;
const COHESION: f32 = 0.30;
const ALIGNMENT: f32 = 0.60;
const ROW_PULL: f32 = 0.55;
const SEP_GAIN: f32 = 0.33;
const FLAKE_PULL: f32 = 3.0;
const HOME_SPREAD: f32 = 0.7;
const STEER: f32 = 2.6;
const MAX_SPEED_FACTOR: f32 = 2.6;
const PARALLAX: f32 = 0.45;
const BANK: f32 = 0.05;
const STARTLE_RADIUS: f32 = 7.0;
const STARTLE_IMPULSE: f32 = 9.0;
fn tail_advance(tail: f32, moved: f32, poses: usize) -> f32 {
if poses <= 1 {
return 0.0;
}
(tail + moved * TAIL_RATE) % poses as f32
}
const FACING_EPSILON: f32 = 0.02;
const TAIL_RATE: f32 = 0.9;
const RESOLVE_GAP_X: f32 = 1.0;
const RESOLVE_GAP_Y: f32 = 1.0;
const RESOLVE_PASSES: usize = 5;
fn pick_species(roll: f32) -> usize {
SPECIES_MIX
.iter()
.position(|(bound, _)| roll < *bound)
.unwrap_or(0)
}
const PHASES_X: usize = 2;
const PHASES_Y: usize = 4;
const GRAVEL: &[char] = &['.', ':', '-', '~', '.', '-'];
fn gravel_depth(column: usize) -> usize {
1 + (column % 5 == 0) as usize
}
struct Fish {
x: f32,
y: f32,
vx: f32,
vy: f32,
facing_left: bool,
z: f32,
species: usize,
pose: usize,
tail: f32,
phase: f32,
home: f32,
}
struct Bubble {
x: f32,
y: f32,
phase: f32,
}
const MAX_FLAKES: usize = 24;
struct Flake {
x: f32,
y: f32,
vy: f32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AquariumOptions {
pub fish: u16,
pub speed: f32,
pub surface: Color,
pub deep: Color,
pub gravel_color: Color,
pub bubble_rate: u16,
pub show_gravel: bool,
pub seed: u64,
}
impl Default for AquariumOptions {
fn default() -> Self {
Self {
fish: 12,
speed: 6.0,
surface: Color::Rgb {
r: 26,
g: 92,
b: 108,
},
deep: Color::Rgb { r: 4, g: 16, b: 40 },
gravel_color: Color::Rgb {
r: 62,
g: 58,
b: 48,
},
bubble_rate: 18,
show_gravel: true,
seed: DEFAULT_SEED,
}
}
}
#[derive(Debug, Clone, Copy)]
struct Slot {
base: usize,
poses: usize,
chars: bool,
depth: f32,
chroma: f32,
cruise: f32,
color: Color,
}
pub struct Aquarium {
screen_size: (u16, u16),
options: AquariumOptions,
canvas: Canvas,
fish: Vec<Fish>,
bubbles: Vec<Bubble>,
bubbles_spawned: f32,
flakes: Vec<Flake>,
art: Vec<art::Sprite>,
slots: Vec<Slot>,
art_scale_applied: f32,
fish_cells: usize,
water: Vec<Color>,
time: f32,
rng: EffectRng,
}
impl TerminalEffect for Aquarium {
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 = normalize_effect_size((width, height));
self.canvas.resize(self.screen_size.0, self.screen_size.1);
self.rebuild_water();
let scale = self.art_scale();
if (scale - self.art_scale_applied).abs() > 1e-3 {
let (art, slots) = build_sprites(scale);
self.art = art;
self.slots = slots;
self.art_scale_applied = scale;
}
}
fn handle_input(&mut self, event: &InputEvent) {
if let InputEvent::Pointer {
position,
phase: PointerPhase::Pressed,
..
} = event
&& self.flakes.len() < MAX_FLAKES
{
let (fx, fy) = (position.0 as f32, position.1 as f32);
self.flakes.push(Flake {
x: fx,
y: fy,
vy: 1.6 + self.time.sin().abs() * 1.4,
});
self.startle(fx, fy);
}
}
fn reset(&mut self) {
let options = self.options.clone();
let size = self.screen_size;
*self = Self::new(options, size);
}
}
impl Aquarium {
pub fn new(options: AquariumOptions, screen_size: (u16, u16)) -> Self {
let screen_size = normalize_effect_size(screen_size);
let mut effect = Self {
screen_size,
canvas: Canvas::new(screen_size.0, screen_size.1),
fish: Vec::new(),
bubbles: Vec::new(),
bubbles_spawned: 0.0,
flakes: Vec::new(),
art: build_sprites(1.0).0,
slots: build_sprites(1.0).1,
art_scale_applied: 1.0,
water: Vec::new(),
fish_cells: 0,
time: 0.0,
rng: seeded_rng(options.seed, "aquarium"),
options,
};
effect.rebuild_water();
effect.art_scale_applied = effect.art_scale();
if (effect.art_scale_applied - 1.0).abs() > 1e-3 {
let (art, slots) = build_sprites(effect.art_scale_applied);
effect.art = art;
effect.slots = slots;
}
effect.populate();
effect
}
fn rows(&self) -> usize {
self.screen_size.1 as usize
}
fn cols(&self) -> usize {
self.screen_size.0 as usize
}
fn art_index(
&self,
species: usize,
facing_left: bool,
pose: usize,
px: usize,
py: usize,
) -> usize {
let slot = self.slots[species];
if slot.chars {
slot.base + usize::from(facing_left)
} else {
(((pose % slot.poses) * 2 + usize::from(facing_left)) * PHASES_Y + py)
* PHASES_X
+ px
}
}
fn art_of(
&self,
species: usize,
facing_left: bool,
pose: usize,
px: usize,
py: usize,
) -> &art::Sprite {
&self.art[self.art_index(species, facing_left, pose, px, py)]
}
fn rebuild_water(&mut self) {
let rows = self.rows();
let _ = &mut self.art;
self.water = (0..rows)
.map(|y| {
let t = if rows <= 1 {
0.0
} else {
(y as f32 / (rows - 1) as f32).sqrt()
};
palette::lerp(self.options.surface, self.options.deep, t)
})
.collect();
}
fn populate(&mut self) {
let count = self.shoal_size();
self.fish = (0..count).map(|i| self.spawn_fish(i)).collect();
self.bubbles.clear();
self.bubbles_spawned = 0.0;
self.flakes.clear();
}
fn art_scale(&self) -> f32 {
const REFERENCE_AREA: f32 = 80.0 * 24.0;
let area = self.cols() as f32 * self.rows() as f32;
(area / REFERENCE_AREA).sqrt().sqrt().clamp(1.0, 2.0)
}
fn shoal_size(&self) -> usize {
const REFERENCE_AREA: f32 = 80.0 * 24.0;
const CEILING: f32 = 400.0;
let area = self.cols() as f32 * self.rows() as f32;
let factor = (area / REFERENCE_AREA).sqrt().clamp(1.0, 4.0);
((self.options.fish as f32) * factor)
.clamp(1.0, CEILING)
.round() as usize
}
fn spawn_fish(&mut self, index: usize) -> Fish {
let cols = self.cols() as f32;
let species = pick_species(self.rng.random::<f32>());
let band = self.slots[species].depth;
let z = (band + (self.rng.random::<f32>() - 0.5) * 0.44).clamp(0.0, 1.0);
let angle = self.rng.random::<f32>() * std::f32::consts::TAU;
let speed = self.options.speed * (0.7 + 0.6 * self.rng.random::<f32>());
let home = (self.row_for_depth(self.slots[species].depth)
+ (self.rng.random::<f32>() - 0.5) * HOME_SPREAD)
.clamp(top_of_water(), self.rows() as f32 - 1.0);
Fish {
x: self.rng.random::<f32>() * cols,
y: home + (self.rng.random::<f32>() - 0.5) * 1.5,
home,
vx: angle.cos() * speed,
vy: angle.sin() * speed * 0.25,
facing_left: angle.cos() < 0.0,
z,
species,
pose: index % self.slots[species].poses,
tail: (index % self.slots[species].poses) as f32,
phase: self.rng.random::<f32>() * std::f32::consts::TAU,
}
}
fn row_for_depth(&self, z: f32) -> f32 {
let rows = self.rows() as f32;
let gravel = self.gravel_rows() as f32;
let usable = (rows - gravel - 1.0).max(1.0);
(1.0 - z) * usable + 1.0
}
fn gravel_rows(&self) -> usize {
if self.options.show_gravel { 2 } else { 0 }
}
pub fn advance_for_picture(&mut self, dt: f32) {
self.advance(dt);
}
pub fn fish_snapshot(&self) -> Vec<(f32, f32, f32, usize, f32, f32)> {
self.fish
.iter()
.map(|f| (f.x, f.y, f.z, f.species, f.vx, f.vy))
.collect()
}
pub fn colour_at(&self, z: f32, species: usize) -> Color {
self.colour_at_row(z, species, self.rows() / 2)
}
pub fn colour_at_row(&self, z: f32, species: usize, row: usize) -> Color {
Self::shade_into_water(
art::shade_colour(self.slots[species].color, 0.5),
&self.water,
z,
self.slots[species].chroma,
row.min(self.rows() - 1),
)
}
fn advance(&mut self, dt: f32) {
let dt = if dt.is_finite() {
dt.clamp(0.0, 0.25)
} else {
0.0
};
self.time += dt;
self.step_fish(dt);
self.step_flakes(dt);
self.step_bubbles(dt);
}
fn step_fish(&mut self, dt: f32) {
let (cols, rows) = (self.cols() as f32, self.rows() as f32);
let gravel = self.gravel_rows() as f32;
let top = 1.0f32;
let bottom = (rows - gravel - 1.0).max(1.0);
let lag = 1.0 - (-STEER * dt).exp();
for i in 0..self.fish.len() {
let (x, y, vx, vy, z, species, phase, home) = {
let f = &self.fish[i];
(f.x, f.y, f.vx, f.vy, f.z, f.species, f.phase, f.home)
};
let slot = self.slots[species];
let art = self.art_of(species, false, 0, 0, 0);
let (cw, ch) = (art.cells_wide() as f32, art.cells_tall() as f32);
let half_w = cw * 0.5;
let half_h = ch * 0.5;
let cruise = self.options.speed * slot.cruise * (1.0 - PARALLAX * z);
let mut ux = 0.0f32;
let mut uy = 0.0f32;
let (left, right) = (half_w + 0.5, cols - half_w - 0.5);
let (ceil, floor) = (top + half_h, bottom - half_h);
if x < left {
ux += (left - x) / cruise;
} else if x > right {
ux -= (x - right) / cruise;
}
if y < ceil {
uy += (ceil - y) / cruise;
} else if y > floor {
uy -= (y - floor) / cruise;
}
let mut sep_x = 0.0f32;
let mut sep_y = 0.0f32;
let mut coh_x = 0.0f32;
let mut coh_y = 0.0f32;
let mut ali_x = 0.0f32;
let mut ali_y = 0.0f32;
let mut kin = 0.0f32;
for (j, other) in self.fish.iter().enumerate() {
if i == j {
continue;
}
let odx = x - other.x;
let ody = (y - other.y) * 0.5;
let d2 = odx * odx + ody * ody;
if d2 < 1e-4 {
continue;
}
let dz = (z - other.z).abs();
if dz < SEPARATION_DEPTH {
let other_art = self.art_of(other.species, false, 0, 0, 0);
let radius =
(cw + other_art.cells_wide() as f32) * 0.5 + SEP_GAP;
if d2 < radius * radius {
let d = d2.sqrt();
let push =
(radius - d) / radius * (1.0 - dz / SEPARATION_DEPTH);
sep_x += odx / d * push;
sep_y += ody / d * push;
}
}
if other.species == species && d2 < SHOAL_RADIUS * SHOAL_RADIUS {
kin += 1.0;
coh_x += other.x;
coh_y += other.y;
ali_x += other.vx;
ali_y += other.vy;
}
}
if kin > 0.0 {
coh_x = coh_x / kin - x;
coh_y = coh_y / kin - y;
ali_x /= kin;
ali_y /= kin;
}
ux += sep_x * SEP_GAIN;
uy += sep_y * SEP_GAIN;
let chasing = self.nearest_flake(x, y);
if let Some(flake) = chasing {
let fdx = flake.0 - x;
let fdy = (flake.1 - y) * 0.5;
let d = (fdx * fdx + fdy * fdy).sqrt().max(0.5);
ux += fdx / d * FLAKE_PULL;
uy += fdy / d * FLAKE_PULL * 0.5;
}
if kin > 0.0 {
let d = (coh_x * coh_x + coh_y * coh_y).sqrt().max(0.5);
ux += coh_x / d * COHESION;
uy += coh_y / d * COHESION;
let a = (ali_x * ali_x + ali_y * ali_y).sqrt();
if a > 1e-3 {
ux += ali_x / a * ALIGNMENT;
uy += ali_y / a * ALIGNMENT;
}
}
uy += (home - y) * ROW_PULL / cruise
* if chasing.is_some() { 0.1 } else { 1.0 };
ux += (self.time * 0.7 + phase).cos();
uy += (self.time * 0.5 + phase).sin() * 0.35;
let (mut wx, mut wy) = (ux * cruise, uy * cruise);
let lateral = (wx * vy - wy * vx).abs();
let bank = 1.0 + BANK * lateral / cruise.max(0.01);
wx += sep_x * SEP_GAIN * cruise * (bank - 1.0);
wy += sep_y * SEP_GAIN * cruise * (bank - 1.0);
let max = cruise * MAX_SPEED_FACTOR;
let f = &mut self.fish[i];
f.vx += (wx - f.vx) * lag;
f.vy += (wy - f.vy) * lag;
let sp = (f.vx * f.vx + f.vy * f.vy).sqrt();
if sp > max {
f.vx = f.vx / sp * max;
f.vy = f.vy / sp * max;
}
f.x += f.vx * dt;
f.y += f.vy * dt;
if f.vx.abs() > FACING_EPSILON {
f.facing_left = f.vx < 0.0;
}
let moved = (f.vx * dt).abs() + (f.vy * dt).abs();
let poses = self.slots[f.species].poses;
f.tail = tail_advance(f.tail, moved, poses);
f.pose = f.tail as usize;
}
for i in 0..self.fish.len() {
self.clamp_one(i);
}
self.resolve_overlaps();
}
fn clamp_one(&mut self, i: usize) {
let (cols, rows) = (self.cols() as f32, self.rows() as f32);
let gravel = self.gravel_rows() as f32;
let species = self.fish[i].species;
let art = &self.art[self.art_index(species, false, 0, 0, 0)];
let (half_w, half_h) =
(art.cells_wide() as f32 * 0.5, art.cells_tall() as f32 * 0.5);
let f = &mut self.fish[i];
let top = 1.0 + half_h;
let bottom = (rows - gravel - half_h - 0.5).max(top);
f.x =
f.x.clamp(half_w + 0.5, (cols - half_w - 0.5).max(half_w + 0.5));
f.y = f.y.clamp(top, bottom);
}
fn resolve_overlaps(&mut self) {
for _ in 0..RESOLVE_PASSES {
for i in 0..self.fish.len() {
for j in (i + 1)..self.fish.len() {
if (self.fish[i].z - self.fish[j].z).abs() > SEPARATION_DEPTH {
continue; }
let (wi, hi) = {
let a = self.art_of(self.fish[i].species, false, 0, 0, 0);
(a.cells_wide() as f32, a.cells_tall() as f32)
};
let (wj, hj) = {
let a = self.art_of(self.fish[j].species, false, 0, 0, 0);
(a.cells_wide() as f32, a.cells_tall() as f32)
};
let dx = (self.fish[j].x - self.fish[i].x).abs();
let dy = (self.fish[j].y - self.fish[i].y).abs();
let into_x = (wi + wj) * 0.5 + RESOLVE_GAP_X - dx;
let into_y = (hi + hj) * 0.5 + RESOLVE_GAP_Y - dy;
if into_x <= 0.0 || into_y <= 0.0 {
continue; }
let sign = if self.fish[j].x >= self.fish[i].x {
1.0
} else {
-1.0
};
if into_x <= into_y {
let push = into_x * 0.5;
self.fish[i].x -= sign * push;
self.fish[j].x += sign * push;
} else {
let push = into_y * 0.5;
let vsign = if self.fish[j].y >= self.fish[i].y {
1.0
} else {
-1.0
};
self.fish[i].y -= vsign * push;
self.fish[j].y += vsign * push;
}
self.clamp_one(i);
self.clamp_one(j);
}
}
}
}
fn startle(&mut self, x: f32, y: f32) {
for f in &mut self.fish {
let dx = f.x - x;
let dy = (f.y - y) * 0.5;
let d = (dx * dx + dy * dy).sqrt();
if !(1e-3..=STARTLE_RADIUS).contains(&d) {
continue;
}
let nearness = 1.0 - d / STARTLE_RADIUS;
let dart = STARTLE_IMPULSE * (0.4 + 0.6 * nearness);
let speed = (f.vx * f.vx + f.vy * f.vy).sqrt();
let out = speed.max(dart);
f.vx = dx / d * out;
f.vy = dy / d * out * 0.5;
}
}
fn nearest_flake(&self, x: f32, y: f32) -> Option<(f32, f32)> {
self.flakes
.iter()
.map(|f| {
let dx = f.x - x;
let dy = f.y - y;
(dx * dx + dy * dy, f.x, f.y)
})
.filter(|(d2, _, _)| *d2 < 900.0)
.min_by(|a, b| {
a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)
})
.map(|(_, fx, fy)| (fx, fy))
}
fn flake_is_in_the_jaw(&self, f: &Fish, flake: &Flake) -> bool {
let art = self.art_of(f.species, f.vx < 0.0, 0, 0, 0);
let half_w = art.cells_wide() as f32 * 0.5;
let half_h = art.cells_tall() as f32 * 0.5;
let reach = 1.0f32.max(half_h * 0.5);
let forward = if f.vx < 0.0 { -1.0 } else { 1.0 };
let dx = (flake.x - f.x) * forward;
let dy = (flake.y - f.y).abs();
dx >= -reach && dx <= half_w + reach && dy * 0.5 <= reach + half_h
}
fn step_flakes(&mut self, dt: f32) {
let (cols, rows) = (self.cols() as f32, self.rows() as f32);
for flake in &mut self.flakes {
flake.y += flake.vy * dt;
}
let mut eaten = vec![false; self.flakes.len()];
for (i, flake) in self.flakes.iter().enumerate() {
for f in &self.fish {
if self.flake_is_in_the_jaw(f, flake) {
eaten[i] = true;
break;
}
}
}
let mut keep = 0usize;
self.flakes.retain(|_| {
let gone = eaten[keep];
keep += 1;
!gone
});
let floor = rows - self.gravel_rows() as f32;
self.flakes
.retain(|f| f.y < floor && f.x > -2.0 && f.x < cols + 2.0);
}
fn step_bubbles(&mut self, dt: f32) {
let cols = self.cols() as f32;
self.bubbles_spawned += dt * f32::from(self.options.bubble_rate) / 100.0
* self.fish.len() as f32;
while self.bubbles_spawned >= 1.0 {
self.bubbles_spawned -= 1.0;
if !self.fish.is_empty() {
let pick = (self.rng.random::<f32>() * self.fish.len() as f32)
as usize
% self.fish.len();
let fish = &self.fish[pick];
let dir = if fish.vx >= 0.0 { 1.0 } else { -1.0 };
self.bubbles.push(Bubble {
x: fish.x - dir * 1.5,
y: fish.y + 0.5,
phase: self.rng.random::<f32>() * std::f32::consts::TAU,
});
}
}
for bubble in &mut self.bubbles {
bubble.y -= 9.0 * dt;
bubble.x += (self.time * 2.0 + bubble.phase).sin() * 2.5 * dt;
}
self.bubbles
.retain(|b| b.y > top_of_water() && b.x > -2.0 && b.x < cols + 2.0);
}
fn draw(&mut self) {
let (cols, rows) = (self.cols(), self.rows());
self.canvas.clear();
self.fish_cells = 0;
for y in 0..rows {
let base = self.water[y];
for x in 0..cols {
self.canvas.set(
x,
y,
Cell::with_bg(' ', Color::Reset, base, Attribute::Reset),
);
}
}
if self.options.show_gravel {
self.draw_gravel();
}
self.draw_flakes();
self.draw_bubbles();
let mut order: Vec<usize> = (0..self.fish.len()).collect();
order.sort_by(|a, b| {
self.fish[*b]
.z
.partial_cmp(&self.fish[*a].z)
.unwrap_or(std::cmp::Ordering::Equal)
});
for i in order {
self.draw_fish(i);
}
}
fn draw_fish(&mut self, index: usize) {
let (x, y, facing_left, z, species, pose) = {
let f = &self.fish[index];
(f.x, f.y, f.facing_left, f.z, f.species, f.pose)
};
let cell_x = x.floor();
let cell_y = y.floor();
let px =
(((x - cell_x) * PHASES_X as f32).round() as usize).min(PHASES_X - 1);
let py =
(((y - cell_y) * PHASES_Y as f32).round() as usize).min(PHASES_Y - 1);
let sprite = &self.art[self.art_index(species, facing_left, pose, px, py)];
let origin_x = (cell_x as i32) - (sprite.cells_wide() as i32) / 2;
let origin_y = (cell_y as i32) - (sprite.cells_tall() as i32) / 2;
let (cols, rows) = (self.cols() as i32, self.rows() as i32);
let base = self.slots[species].color;
let chroma = self.slots[species].chroma;
let water = &self.water;
let canvas = &mut self.canvas;
let mut cells = 0usize;
sprite.for_each_cell(pose, |cx, cy, symbol, shade| {
let (sx, sy) = (origin_x + cx, origin_y + cy);
if sx < 0 || sy < 0 || sx >= cols || sy >= rows {
return;
}
let (sx, sy) = (sx as usize, sy as usize);
let colour = Aquarium::shade_into_water(
art::shade_colour(base, shade),
water,
z,
chroma,
sy,
);
canvas.set(
sx,
sy,
Cell::with_bg(symbol, colour, water[sy], Attribute::Reset),
);
cells += 1;
});
self.fish_cells += cells;
}
fn shade_into_water(
base: Color,
water: &[Color],
z: f32,
chroma: f32,
row: usize,
) -> Color {
let water = water[row.min(water.len().saturating_sub(1))];
let keep = (1.0 - z).clamp(0.0, 1.0) * chroma;
match (base, water) {
(
Color::Rgb {
r: sr,
g: sg,
b: sb,
},
Color::Rgb {
r: wr,
g: wg,
b: wb,
},
) => {
let r = wr as f32 + (sr as f32 - wr as f32) * keep.powi(2);
let g = wg as f32 + (sg as f32 - wg as f32) * keep;
let b = wb as f32 + (sb as f32 - wb as f32) * keep.powf(0.35);
Color::Rgb {
r: r.round().clamp(0.0, 255.0) as u8,
g: g.round().clamp(0.0, 255.0) as u8,
b: b.round().clamp(0.0, 255.0) as u8,
}
}
_ => base,
}
}
fn draw_gravel(&mut self) {
let (cols, rows) = (self.cols(), self.rows());
let base = rows.saturating_sub(2);
for x in 0..cols {
let depth = gravel_depth(x);
for d in 0..depth {
let y = base + d;
if y < rows {
let glyph = GRAVEL[(x + d) % GRAVEL.len()];
let colour = if d == 0 {
self.options.gravel_color
} else {
palette::shade(self.options.gravel_color, 0.6)
};
self.canvas.set(
x,
y,
Cell::with_bg(
glyph,
colour,
self.water[y.min(rows - 1)],
Attribute::Reset,
),
);
}
}
}
}
fn draw_flakes(&mut self) {
for flake in &self.flakes {
let (x, y) = (flake.x.round() as i32, flake.y.round() as i32);
if x < 0 || y < 0 || x >= self.cols() as i32 || y >= self.rows() as i32
{
continue;
}
let (x, y) = (x as usize, y as usize);
self.canvas.set(
x,
y,
Cell::with_bg(
'o',
Color::Rgb {
r: 250,
g: 200,
b: 120,
},
self.water[y],
Attribute::Reset,
),
);
}
}
fn draw_bubbles(&mut self) {
for bubble in &self.bubbles {
let (x, y) = (bubble.x.round() as i32, bubble.y.round() as i32);
if x < 0 || y < 0 {
continue;
}
let (x, y) = (x as usize, y as usize);
if x >= self.cols() || y >= self.rows() {
continue;
}
self.canvas.set(
x,
y,
Cell::with_bg(
'o',
Color::Rgb {
r: 190,
g: 225,
b: 240,
},
self.water[y],
Attribute::Reset,
),
);
}
}
}
fn build_sprites(scale: f32) -> (Vec<art::Sprite>, Vec<Slot>) {
let dot_species = art::SPECIES.len();
let char_species = art::CHAR_SPECIES.len();
let mut all = Vec::with_capacity(
dot_species * art::POSES * 2 * PHASES_X * PHASES_Y + char_species * 2,
);
let mut slots = Vec::with_capacity(dot_species + char_species);
for src in art::sources() {
let base = all.len();
match src {
art::Source::Dots(s) => {
let mut scaled = *s;
scaled.length =
((s.length as f32) * scale).round().max(8.0) as usize;
scaled.girth = s.girth * scale;
for pose in 0..art::POSES {
let master = art::rasterise(&scaled, pose);
for facing in [true, false] {
let posed = if facing {
master.mirrored()
} else {
master.shifted(0, 0)
};
for py in 0..PHASES_Y {
for px in 0..PHASES_X {
all.push(art::Sprite::Dots(Box::new(
posed.shifted(px, py),
)));
}
}
}
}
}
art::Source::Chars(s) => {
let master = charart::species(s);
all.push(art::Sprite::Chars(Box::new(master.mirrored())));
all.push(art::Sprite::Chars(Box::new(master)));
}
}
slots.push(Slot {
base,
poses: src.cycle(),
chars: src.is_chars(),
depth: src.depth(),
chroma: src.chroma(),
cruise: src.cruise(),
color: src.color(),
});
}
(all, slots)
}
fn top_of_water() -> f32 {
1.0
}
#[cfg(test)]
mod tests {
use super::*;
use crate::aquarium::art::SPECIES;
use crate::render::palette::perceptual_distance;
use std::collections::HashSet;
fn settle(tank: &mut Aquarium) {
for _ in 0..180 {
tank.advance(1.0 / 60.0);
}
}
fn fish_ink(tank: &mut Aquarium) -> usize {
let _ = tank.get_diff();
tank.fish_cells
}
#[test]
fn the_fish_are_drawn() {
for (w, h) in [(100usize, 30usize), (80, 24), (200, 50)] {
let mut tank =
Aquarium::new(AquariumOptions::default(), (w as u16, h as u16));
settle(&mut tank);
let mut best = 0usize;
for _ in 0..120 {
tank.advance(1.0 / 60.0);
best = best.max(fish_ink(&mut tank));
}
let fish = tank.fish_snapshot().len();
let wanted = fish * 8; assert!(
best > wanted,
"{w}x{h}: a shoal of {fish} fish never drew more than {best} cells of \\
ink; each should cover at least eight. The tank is water."
);
}
}
#[test]
fn a_fish_does_not_punch_a_hole_in_the_water_behind_it() {
let (w, h) = (100usize, 30usize);
let mut tank = Aquarium::new(
AquariumOptions {
fish: 4,
..AquariumOptions::default()
},
(w as u16, h as u16),
);
settle(&mut tank);
let mut seen: HashSet<Color> = HashSet::new();
for _ in 0..60 {
tank.advance(1.0 / 60.0);
for (_, _, cell) in tank.get_diff() {
if !cell.bg.eq(&Color::Reset) {
seen.insert(cell.bg);
}
}
}
assert!(
seen.iter().all(|c| tank.water.contains(c)),
"a cell carried a background that is not one of the tank's {} water \\
colours; a braille cell written with `Cell::new` resets it to the \\
terminal's own",
tank.water.len()
);
}
#[test]
fn no_two_fish_overlap_on_screen() {
let mut tank = Aquarium::new(
AquariumOptions {
fish: 9,
..AquariumOptions::default()
},
(200, 40),
);
settle(&mut tank);
let fish = tank.fish_snapshot();
let mut worst: f32 = 0.0;
for i in 0..fish.len() {
for j in (i + 1)..fish.len() {
if (fish[i].2 - fish[j].2).abs() > SEPARATION_DEPTH {
continue;
}
let (wi, hi) = {
let a = tank.art_of(fish[i].3, false, 0, 0, 0);
(a.cells_wide() as f32, a.cells_tall() as f32)
};
let (wj, hj) = {
let a = tank.art_of(fish[j].3, false, 0, 0, 0);
(a.cells_wide() as f32, a.cells_tall() as f32)
};
let dx = (fish[i].0 - fish[j].0).abs();
let dy = (fish[i].1 - fish[j].1).abs();
let into_x = (wi + wj) * 0.5 + RESOLVE_GAP_X - dx;
let into_y = (hi + hj) * 0.5 + RESOLVE_GAP_Y - dy;
if into_x > 0.0 && into_y > 0.0 {
worst = worst.max(into_x.min(into_y));
}
}
}
assert!(
worst <= 0.34,
"two sprites overlap by {worst:.2} cells after settling, which is more \
than the blit can show"
);
}
#[test]
fn no_frame_moves_a_fish_more_than_half_a_cell() {
let mut tank = Aquarium::new(AquariumOptions::default(), (100, 30));
settle(&mut tank);
let mut worst: f32 = 0.0;
for _ in 0..600 {
let before = tank.fish_snapshot();
tank.advance(1.0 / 60.0);
let after = tank.fish_snapshot();
for (a, b) in before.iter().zip(after.iter()) {
worst = worst.max((a.0 - b.0).abs().max((a.1 - b.1).abs()));
}
}
assert!(
worst <= 0.5 + 1e-3,
"a fish moved {worst:.3} cells in one frame; the finest step the dot \\
phases give is half a cell and anything more is a fish on a grid"
);
}
#[test]
fn a_large_terminal_gets_a_populated_tank() {
let measure = |w: u16, h: u16| -> (usize, usize) {
let mut tank = Aquarium::new(AquariumOptions::default(), (w, h));
settle(&mut tank);
let count = tank.fish_snapshot().len();
let mut best = 0usize;
for _ in 0..120 {
tank.advance(1.0 / 60.0);
best = best.max(fish_ink(&mut tank));
}
(count, best)
};
let (small_count, small_cells) = measure(80, 24);
let (large_count, large_cells) = measure(400, 200);
let area = |w: u16, h: u16| (w as f32 * h as f32) as usize;
let small = small_cells as f32 / area(80, 24) as f32;
let large = large_cells as f32 / area(400, 200) as f32;
assert!(
small > 0.05,
"the 80x24 tank is only {:.1}% fish; the shoal has collapsed",
small * 100.0
);
assert!(
large_count >= small_count * 3,
"the 400x200 tank holds {large_count} fish against the 80x24 tank's \
{small_count}. A fixed count in a terminal forty times the area is a \
handful of specks in an empty blue screen."
);
assert!(
large > 0.01,
"the 400x200 tank is {:.2}% fish, {large_cells} cells. The fixed-count \
version measured 0.33% and read as an empty screen. Character art \
cannot be scaled, so this floor is 1% rather than 3% -- see the note on \
the test.",
large * 100.0
);
assert!(
large_cells >= small_cells * 3,
"the 400x200 tank has {large_cells} cells of fish and the 80x24 tank has \
{small_cells}. The *fraction* is supposed to fall -- 3.8% against 17.4% \
-- because a character sprite is a fixed number of cells and a bigger \
window is more water. The absolute count is the one that must grow."
);
}
#[test]
fn the_shoal_clusters_without_touching() {
let mut tank = Aquarium::new(
AquariumOptions {
fish: 24,
..AquariumOptions::default()
},
(200, 50),
);
settle(&mut tank);
let fish = tank.fish_snapshot();
let nearest = |i: usize| -> f32 {
fish.iter()
.enumerate()
.filter(|(j, f)| *j != i && f.3 == fish[i].3)
.map(|(_, f)| {
((fish[i].0 - f.0).powi(2) + ((fish[i].1 - f.1) * 0.5).powi(2))
.sqrt()
})
.fold(f32::MAX, f32::min)
};
let distances: Vec<f32> = (0..fish.len()).map(nearest).collect();
let mean = distances.iter().sum::<f32>() / distances.len() as f32;
let closest = *distances
.iter()
.min_by(|a, b| a.partial_cmp(b).unwrap())
.unwrap();
assert!(
closest < mean * 0.55,
"the closest same-species pair is {closest:.1} cells apart and the \
average is {mean:.1}. A shoal is a clump; a uniform spread is a bag."
);
let mut worst: f32 = 0.0;
for i in 0..fish.len() {
for j in (i + 1)..fish.len() {
if (fish[i].2 - fish[j].2).abs() > SEPARATION_DEPTH {
continue;
}
let (wi, hi) = {
let a = tank.art_of(fish[i].3, false, 0, 0, 0);
(a.cells_wide() as f32, a.cells_tall() as f32)
};
let (wj, hj) = {
let a = tank.art_of(fish[j].3, false, 0, 0, 0);
(a.cells_wide() as f32, a.cells_tall() as f32)
};
let into_x =
(wi + wj) * 0.5 + RESOLVE_GAP_X - (fish[i].0 - fish[j].0).abs();
let into_y =
(hi + hj) * 0.5 + RESOLVE_GAP_Y - (fish[i].1 - fish[j].1).abs();
if into_x > 0.0 && into_y > 0.0 {
worst = worst.max(into_x.min(into_y));
}
}
}
assert!(
worst < 1.0,
"a same-depth pair is {worst:.2} cells inside the resolve's gap"
);
}
#[test]
fn depth_is_not_a_stripe() {
let mut tank = Aquarium::new(
AquariumOptions {
fish: 30,
..AquariumOptions::default()
},
(200, 50),
);
settle(&mut tank);
let fish = tank.fish_snapshot();
let rows = tank.rows() as f32;
let mut near = Vec::new();
let mut far = Vec::new();
for f in &fish {
if f.2 < 0.25 {
near.push(f.1);
} else if f.2 > 0.45 {
far.push(f.1);
}
}
assert!(
near.len() >= 3 && far.len() >= 3,
"the fixture needs fish at both ends of the tank; it has {} near and {} far",
near.len(),
far.len()
);
let mean = |v: &Vec<f32>| v.iter().sum::<f32>() / v.len() as f32;
assert!(
mean(&near) > mean(&far),
"the near fish average row {:.1} and the far fish {:.1}. This tank maps \
depth onto height the other way up -- near is the bottom of the frame, \
per `row_for_depth` -- and the fish are not.",
mean(&near),
mean(&far)
);
for (lo, hi, name) in [(0.0f32, 0.2f32, "near"), (0.4, 0.6, "far")] {
let band: Vec<f32> = fish
.iter()
.filter(|f| f.2 >= lo && f.2 < hi)
.map(|f| f.1)
.collect();
if band.len() < 3 {
continue;
}
let m = mean(&band);
let spread = (band.iter().map(|y| (y - m).abs()).fold(0.0, f32::max)
/ rows)
.max(0.001);
assert!(
spread > 0.06,
"the {name} band spans only {:.1}% of the tank's height ({spread:.3}). \
That is a horizontal stripe. `Fish::home` is chosen per fish and is \
never recomputed from `z` precisely so this cannot happen.",
spread * 100.0
);
}
}
#[test]
fn a_far_fish_travels_less_than_a_near_one_within_its_own_species() {
let mut tank = Aquarium::new(
AquariumOptions {
fish: 160,
..AquariumOptions::default()
},
(400, 80),
);
settle(&mut tank);
let n = tank.fish.len();
let mut depth = vec![0.0f32; n];
let mut speed = vec![0.0f32; n];
let mut frames = vec![0.0f32; n];
for _ in 0..180 {
tank.advance(1.0 / 60.0);
for (i, f) in tank.fish_snapshot().iter().enumerate() {
depth[i] = f.2;
speed[i] += (f.4 * f.4 + f.5 * f.5).sqrt();
frames[i] += 1.0;
}
}
for i in 0..n {
speed[i] /= frames[i].max(1.0);
}
const CUE_BOUND: f32 = 0.90;
let mut checked = 0;
for species in 0..tank.slots.len() {
let mut kin: Vec<(f32, f32)> = (0..n)
.filter(|i| tank.fish[*i].species == species)
.map(|i| (depth[i], speed[i]))
.collect();
if kin.len() < 8 {
continue;
}
kin.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
let q = kin.len() / 4;
let mean = |v: &[(f32, f32)]| {
v.iter().map(|p| p.1).sum::<f32>() / v.len() as f32
};
let (shallow, deep) = (mean(&kin[..q]), mean(&kin[kin.len() - q..]));
let ratio = deep / shallow.max(1e-3);
let chars = tank.slots[species].chars;
let wide = tank.art_of(species, false, 0, 0, 0).cells_wide();
if !chars {
assert!(
ratio < CUE_BOUND,
"species {species} is {wide} cells wide and its deepest quarter \
swims at {ratio:.2} of its shallowest quarter ({deep:.2} against \
{shallow:.2} cells a second). PARALLAX is {PARALLAX} and it is \
the only depth cue a screen has."
);
checked += 1;
} else {
assert!(
ratio < 1.0,
"species {species} is {wide} cells wide and its deepest quarter \
swims at {ratio:.2} of its shallowest -- the depth cue is \
running backwards."
);
}
}
assert!(
checked >= 2,
"only {checked} species were small enough to measure the cue on"
);
}
#[test]
fn a_fish_can_come_to_rest() {
let mut tank = Aquarium::new(
AquariumOptions {
fish: 16,
..AquariumOptions::default()
},
(200, 50),
);
settle(&mut tank);
let cory = tank.slots.iter().position(|s| s.cruise < 0.5).unwrap();
let mut slowest = f32::MAX;
for _ in 0..600 {
tank.advance(1.0 / 60.0);
let fish = tank.fish_snapshot();
let speeds: Vec<f32> = fish
.iter()
.filter(|f| f.3 == cory)
.map(|f| (f.4 * f.4 + f.5 * f.5).sqrt())
.collect();
slowest = slowest.min(speeds.iter().cloned().fold(f32::MAX, f32::min));
}
let cruise = tank.options.speed * tank.slots[cory].cruise;
assert!(
slowest < cruise * 0.5,
"the slowest cory never dropped below {slowest:.3} cells/frame against a \
cruise of {cruise:.3}. Every fish in this tank is obliged to move, and \
nothing in the effect is allowed to stop."
);
}
#[test]
fn the_tail_beat_is_proportional_to_distance_travelled() {
const POSES: usize = 4;
for start in [0.0f32, 0.5, 1.5, 3.75] {
assert_eq!(tail_advance(start, 0.0, POSES), start);
}
let mut phase = 0.0f32;
let mut advanced = false;
for _ in 0..100 {
phase = tail_advance(phase, 0.09, POSES);
advanced |= phase >= 1.0;
}
assert!(
advanced,
"a fish covering 0.09 cells a frame never reached a single pose, so it \
never wagged. This is the truncation bug: a beat that advances only on \
whole frames is a beat that does not advance at 60 Hz."
);
let distance = 7.3f32;
let one_step = tail_advance(0.0, distance, POSES);
let many = (0..1000)
.fold(0.0f32, |p, _| tail_advance(p, distance / 1000.0, POSES));
assert!(
(one_step - many).abs() < 1e-3,
"covering {distance} cells in one step gave phase {one_step:.4} and in a \
thousand gave {many:.4}. The beat is reading the frame clock, not the \
distance, so it will run at a different rate on a different terminal."
);
let mut phase = 0.0f32;
for step in 0..100_000 {
phase = tail_advance(phase, 0.25, POSES);
assert!(
(0.0..POSES as f32).contains(&phase),
"phase {phase} left the cycle at step {step}"
);
}
}
#[test]
fn a_braille_fish_wags_its_tail() {
let mut tank = Aquarium::new(
AquariumOptions {
fish: 8,
..AquariumOptions::default()
},
(80, 24),
);
settle(&mut tank);
let braille = tank.slots.iter().filter(|s| !s.chars).count();
assert_eq!(
braille,
art::SPECIES.len(),
"the braille species are missing from the tank, so this would pass on an \
empty set"
);
for i in 0..tank.fish.len() {
let species = tank.fish[i].species;
if tank.slots[species].chars {
continue;
}
let poses = tank.slots[species].poses;
assert_eq!(
poses,
art::POSES,
"a braille species has a cycle of {poses} rather than the art's {}, so \
the table and the effect disagree about how many frames exist",
art::POSES
);
let mut seen = std::collections::BTreeSet::new();
for _ in 0..120 {
tank.advance(1.0 / 60.0);
seen.insert(tank.fish[i].pose);
}
assert!(
seen.len() == poses,
"braille fish {i} showed only {} of its {poses} poses in two \
seconds: {seen:?}. A tail that does not advance through its cycle is \
a fish sliding rather than swimming.",
seen.len()
);
}
}
#[test]
fn a_character_fish_does_not_wag_its_tail() {
let mut tank = Aquarium::new(
AquariumOptions {
fish: 8,
..AquariumOptions::default()
},
(80, 24),
);
settle(&mut tank);
let chars = tank.slots.iter().filter(|s| s.chars).count();
assert_eq!(
chars,
art::CHAR_SPECIES.len(),
"the character species are missing from the tank, so this would pass on an \
empty set"
);
for (i, slot) in tank.slots.iter().enumerate() {
if !slot.chars {
continue;
}
assert_eq!(
slot.poses, 1,
"character species {i} has a cycle of {} poses. They are not meant to \
animate -- see `art::Source::cycle` -- and anything above one puts \
the hand-drawn beat back.",
slot.poses
);
}
for i in 0..tank.fish.len() {
if !tank.slots[tank.fish[i].species].chars {
continue;
}
for _ in 0..180 {
tank.advance(1.0 / 60.0);
assert_eq!(
tank.fish[i].pose, 0,
"character fish {i} advanced to frame {} of a one-frame cycle.",
tank.fish[i].pose
);
}
}
}
#[test]
fn a_fish_faces_the_way_it_travels() {
const UNDECIDABLE: &[&str] = &["fry"];
let tank = Aquarium::new(
AquariumOptions {
fish: 1,
..AquariumOptions::default()
},
(80, 24),
);
let mut checked = 0usize;
let mut exempt = Vec::new();
for (species, source) in art::sources().enumerate() {
let (name, medium) = match source {
art::Source::Dots(s) => (s.name, "braille"),
art::Source::Chars(s) => (s.name, "character"),
};
let as_drawn = tank.art_of(species, true, 0, 0, 0);
match as_drawn.faces_left(0) {
Some(faces_left) => {
checked += 1;
assert!(
faces_left,
"{name} ({medium}): the sprite art_index hands out for a fish \
travelling left has its eye near its **tail**. The facing \
order in the art table is the wrong way round."
);
}
None => {
exempt.push(name);
let mirrored = tank.art_of(species, false, 0, 0, 0);
let cells = |s: &art::Sprite, flip: bool| {
let w = s.cells_wide() as i32;
let mut v: Vec<(i32, i32, char)> = Vec::new();
s.for_each_cell(0, |x, y, ch, _| {
v.push((if flip { w - 1 - x } else { x }, y, ch))
});
v.sort_unstable();
v
};
let (a, b) = (cells(as_drawn, false), cells(mirrored, true));
assert!(!a.is_empty(), "{name} drew no cells to compare.");
assert_eq!(
a, b,
"{name} ({medium}): its two facings are not the same fish \
turned around, so they are two different animals rather than \
one animal facing two ways."
);
}
}
}
assert_eq!(
exempt, UNDECIDABLE,
"the set of species whose art cannot say which end is the head has \
changed. If a species became undecidable it has stopped being checked \
for facing, and if one became decidable it should be asserted like the \
rest -- update the list deliberately rather than letting it drift."
);
assert!(
checked >= 6,
"only {checked} species had a decisive eye, so this test is barely \
asserting anything."
);
}
#[test]
fn a_fish_that_stops_keeps_the_facing_it_had() {
let mut tank = Aquarium::new(
AquariumOptions {
fish: 16,
..AquariumOptions::default()
},
(200, 50),
);
settle(&mut tank);
let cory = tank.slots.iter().position(|s| s.cruise < 0.5).unwrap();
let mut before: Vec<bool> =
tank.fish.iter().map(|f| f.facing_left).collect();
let mut saw_a_rest = false;
for _ in 0..900 {
tank.advance(1.0 / 60.0);
for (i, f) in tank.fish.iter().enumerate() {
if f.species != cory {
continue;
}
if f.vx.abs() <= FACING_EPSILON {
saw_a_rest = true;
assert_eq!(
f.facing_left, before[i],
"fish {i} (a {cory}-species cory, cruise {}) is at rest with \
vx = 0 and has changed which way it faces. A resting fish \
has no direction to read, so the facing has to be kept.",
tank.slots[cory].cruise
);
} else {
assert_eq!(
f.facing_left,
f.vx < 0.0,
"fish {i} is travelling at vx = {:.3} but is drawn facing the \
other way.",
f.vx
);
before[i] = f.facing_left;
}
}
}
assert!(
saw_a_rest,
"no cory was ever at rest in fifteen seconds, so this test never reached \
the case it exists for."
);
}
#[test]
fn a_dropped_flake_starts_a_burst() {
let mut tank = Aquarium::new(
AquariumOptions {
fish: 1,
..AquariumOptions::default()
},
(120, 40),
);
tank.fish.truncate(1);
tank.fish[0].species = 0;
settle(&mut tank);
let (fx, fy, fvx, fvy) = {
let f = &tank.fish[0];
(f.x, f.y, f.vx, f.vy)
};
let speed_before = (fvx * fvx + fvy * fvy).sqrt();
tank.flakes.push(Flake {
x: fx + 0.5,
y: fy,
vy: 2.0,
});
tank.startle(fx + 0.5, fy);
let burst = (tank.fish[0].vx.powi(2) + tank.fish[0].vy.powi(2)).sqrt();
let cruise = tank.options.speed
* tank.slots[tank.fish[0].species].cruise
* (1.0 - PARALLAX * tank.fish[0].z);
assert!(
fvx > 0.0 && tank.fish[0].vx < 0.0,
"the fish was swimming right at {fvx:.2} and is now going {:.2}. A \
flake landed half a cell to its right; it should have turned.",
tank.fish[0].vx
);
assert!(
burst > speed_before,
"a flake half a cell away took the fish from {speed_before:.2} to \
{burst:.2} cells/second. A startle is not a deceleration."
);
assert!(
burst >= cruise,
"a flake half a cell away took the fish to {burst:.2} cells/second \
against a cruise of {cruise:.2}. A startle leaves at speed."
);
for _ in 0..90 {
tank.advance(1.0 / 60.0);
}
let after = (tank.fish[0].vx.powi(2) + tank.fish[0].vy.powi(2)).sqrt();
assert!(
after < burst * 0.6,
"the fish was still at {after:.2} cells/second a second and a half after \
the drop, against a peak of {burst:.2}. That is a new cruise speed, not a \
startle."
);
}
#[test]
fn a_turning_fish_sweeps_wider() {
let straight = 1.0;
let turn_rate = 4.0;
let bank = |lateral: f32, cruise: f32| {
1.0 + BANK * lateral.abs() / cruise.max(0.01)
};
assert!(
bank(turn_rate, 1.0) > bank(0.0, 1.0),
"a fish turning at {turn_rate} sweeps the same width as one going straight"
);
assert!(
bank(4.0, 1.0) < 1.0 + BANK * 4.0 * MAX_SPEED_FACTOR,
"the banking term is unbounded"
);
let _ = straight;
}
#[test]
fn every_fish_is_inside_the_tank_and_above_the_gravel() {
let (w, h) = (120usize, 32usize);
let mut tank =
Aquarium::new(AquariumOptions::default(), (w as u16, h as u16));
settle(&mut tank);
let gravel_rows = tank.gravel_rows() as f32;
for (x, y, _, species, ..) in tank.fish_snapshot() {
let (cw, ch) = {
let a = tank.art_of(species, false, 0, 0, 0);
(a.cells_wide() as f32, a.cells_tall() as f32)
};
let left = (x - cw * 0.5).round();
let right = (x + cw * 0.5).round();
let top = (y - ch * 0.5).round();
let bottom = (y + ch * 0.5).round();
assert!(left >= 0.0, "a {species} sprite starts at x={left}");
assert!(
right <= w as f32,
"a {species} sprite ends at x={right}, past {w}"
);
assert!(top >= 0.0, "a {species} sprite starts at y={top}");
assert!(
bottom <= h as f32 - gravel_rows,
"a {species} sprite ends at y={bottom}, into the gravel which starts \
at {}",
h as f32 - gravel_rows
);
}
}
#[test]
fn depth_costs_red_first_and_so_reads_as_underwater_rather_than_fog() {
let tank = Aquarium::new(AquariumOptions::default(), (100, 30));
let row = tank.rows() / 2;
let (wr, _, wb) = rgb_of(tank.water[row]).unwrap();
let excess = |c: Color| {
let (r, _, b) = rgb_of(c).unwrap();
(r as f32 - wr as f32) / (b as f32 - wb as f32).max(1.0)
};
for (species, s) in SPECIES.iter().enumerate() {
let front = excess(tank.colour_at_row(0.0, species, row));
let back = excess(tank.colour_at_row(0.65, species, row));
assert!(
front > 0.0,
"{}: even at the front it carries no red over the water",
s.name
);
assert!(
back < front * 0.5,
"{}: its red excess falls from {front:.2} at the front to {back:.2} \
at depth. Red is absorbed first -- gone by about twenty feet, \
green by sixty -- and a fish that does not get bluer as it goes \
back is a fish behind fog.",
s.name
);
}
}
#[test]
fn a_far_fish_is_measurably_closer_to_the_water_than_a_near_one() {
let tank = Aquarium::new(AquariumOptions::default(), (100, 30));
let water = tank.water[tank.rows() / 2];
for (species, s) in SPECIES.iter().enumerate() {
let near = tank.colour_at(0.0, species);
let near_gap = perceptual_distance(near, water);
assert!(
near_gap > 0.02,
"{}: even a near fish is only {near_gap:.3} from the water, so there \
is no colour for depth to take away",
s.name
);
assert!(
near_gap > 0.02,
"{}: a far fish is {near_gap:.3} from the water, which is not a \
depth cue",
s.name
);
}
}
#[test]
fn the_species_are_told_apart_by_colour() {
let tank = Aquarium::new(AquariumOptions::default(), (100, 30));
let colours: Vec<Color> = (0..SPECIES.len())
.map(|s| tank.colour_at(0.35, s))
.collect();
for i in 0..colours.len() {
for j in (i + 1)..colours.len() {
let d = perceptual_distance(colours[i], colours[j]);
assert!(
d > 0.05,
"{} and {} are {d:.3} apart at mid depth, which is a shading \
step rather than two fish",
SPECIES[i].name,
SPECIES[j].name
);
}
}
}
#[test]
fn the_water_darkens_monotonically_with_depth() {
let tank = Aquarium::new(AquariumOptions::default(), (80, 30));
assert_eq!(tank.water.len(), 30);
assert_eq!(tank.water[0], tank.options.surface);
assert_eq!(
tank.water[29], tank.options.deep,
"the last row is not the deep colour"
);
for y in 1..tank.water.len() {
let above = palette::luminance(tank.water[y - 1]);
let below = palette::luminance(tank.water[y]);
assert!(
below <= above + 1e-6,
"row {y} is brighter than row {}; the gradient is not monotonic, so \
it reads as a pattern rather than as depth",
y - 1
);
}
}
#[test]
fn the_water_is_static_so_the_encoder_does_not_resend_it() {
let mut tank = Aquarium::new(AquariumOptions::default(), (100, 30));
let before: Vec<Color> = tank.water.clone();
settle(&mut tank);
assert_eq!(
before, tank.water,
"the water gradient moved while time passed"
);
}
#[test]
fn a_settled_frame_reports_far_fewer_cells_than_it_has() {
let (w, h) = (200usize, 50usize);
let mut tank =
Aquarium::new(AquariumOptions::default(), (w as u16, h as u16));
settle(&mut tank);
let _ = tank.get_diff();
let mut worst = 0usize;
for _ in 0..120 {
tank.advance(1.0 / 60.0);
worst = worst.max(tank.get_diff().len());
}
let total = w * h;
assert!(
worst < total / 12,
"a settled frame reported {worst} changed cells out of {total}; the water \
is in the background channel precisely so that this is a few per cent"
);
}
#[test]
fn the_gravel_does_not_churn() {
let mut tank = Aquarium::new(AquariumOptions::default(), (100, 30));
settle(&mut tank);
let _ = tank.get_diff();
let second = tank.get_diff();
let gravel_changes = second.iter().filter(|(_, y, _)| *y >= 28).count();
assert!(
gravel_changes == 0,
"{gravel_changes} gravel cells reported as changed with no time passing"
);
}
#[test]
fn the_picture_keeps_changing() {
let mut tank = Aquarium::new(AquariumOptions::default(), (100, 30));
settle(&mut tank);
let (mut longest, mut run) = (0usize, 0usize);
for _ in 0..600 {
tank.advance(1.0 / 60.0);
if tank.get_diff().len() < 4 {
run += 1;
longest = longest.max(run);
} else {
run = 0;
}
}
assert!(
longest < 12,
"the tank went still for {longest} consecutive frames (a fifth of a second)"
);
}
#[test]
fn bubbles_rise_are_cleared_and_do_not_sit_on_the_fish() {
let mut tank = Aquarium::new(AquariumOptions::default(), (100, 30));
settle(&mut tank);
let mut on_a_fish = 0usize;
for _ in 0..900 {
tank.advance(1.0 / 60.0);
assert!(
tank.bubbles.len() < 4000,
"{} bubbles accumulated",
tank.bubbles.len()
);
for b in &tank.bubbles {
assert!(b.y > 0.0, "a bubble rose above the surface");
for f in &tank.fish {
let dx = f.x - b.x;
let dy = f.y - b.y;
if dx * dx + dy * dy < 2.25 {
on_a_fish += 1;
}
}
}
}
assert!(!tank.bubbles.is_empty(), "no bubbles were ever spawned");
assert!(
on_a_fish < 400,
"{on_a_fish} bubble-frames landed within a cell and a half of a fish's \
centre; bubbles are drawn a pale `o` and one on a fish's back is a \
second eye"
);
}
#[test]
fn a_hostile_config_renders_rather_than_panicking() {
let hostile = AquariumOptions {
fish: 0,
speed: -5.0,
bubble_rate: 9999,
..AquariumOptions::default()
};
for options in [
hostile,
AquariumOptions {
speed: f32::NAN,
..AquariumOptions::default()
},
AquariumOptions {
fish: 5000,
..AquariumOptions::default()
},
] {
let mut tank = Aquarium::new(options, (80, 24));
settle(&mut tank);
let _ = tank.get_diff();
}
}
#[test]
fn extreme_shapes_render() {
for (w, h) in [(6u16, 6u16), (6, 200), (400, 6), (200, 50)] {
let mut tank = Aquarium::new(AquariumOptions::default(), (w, h));
settle(&mut tank);
tank.advance(1.0 / 60.0);
let diff = tank.get_diff();
for (x, y, _) in &diff {
assert!(
*x < w as usize && *y < h as usize,
"({x},{y}) outside {w}x{h}"
);
}
}
}
#[test]
fn a_resized_tank_keeps_its_fish_inside_the_frame() {
let mut tank = Aquarium::new(AquariumOptions::default(), (200, 50));
settle(&mut tank);
tank.update_size(60, 20);
tank.advance(1.0 / 60.0);
for (x, y, _) in tank.get_diff() {
assert!(x < 60 && y < 20, "({x},{y}) outside the resized 60x20");
}
}
#[test]
fn a_seed_reproduces_and_two_seeds_differ() {
let run = |seed: u64| {
let mut tank = Aquarium::new(
AquariumOptions {
seed,
..AquariumOptions::default()
},
(100, 30),
);
settle(&mut tank);
tank.fish_snapshot()
};
assert_eq!(run(99), run(99), "seed 99 diverged");
assert_ne!(run(99), run(100), "two seeds agreed");
}
#[test]
fn a_seed_reproduces_the_picture() {
let run = |seed: u64| {
let mut tank = Aquarium::new(
AquariumOptions {
seed,
..AquariumOptions::default()
},
(80, 24),
);
settle(&mut tank);
tank.advance(1.0 / 60.0);
tank.get_diff()
};
assert_eq!(run(5), run(5), "seed 5 drew two different pictures");
assert_ne!(run(5), run(6), "two seeds drew the same picture");
}
#[test]
fn a_click_drops_a_flake_and_the_flake_is_drawn() {
let mut tank = Aquarium::new(
AquariumOptions {
fish: 1,
..AquariumOptions::default()
},
(100, 30),
);
settle(&mut tank);
assert!(tank.flakes.is_empty(), "food appeared with no click");
let _ = tank.get_diff();
for _ in 0..300 {
tank.advance(1.0 / 60.0);
let _ = tank.get_diff();
}
assert_eq!(tank.flakes.len(), 0, "flakes appeared unbidden");
let fish_x = tank.fish_snapshot()[0].0;
let drop_x = if fish_x > 50.0 { 12 } else { 88 };
tank.handle_input(&InputEvent::Pointer {
position: (drop_x, 10),
phase: PointerPhase::Pressed,
button: crate::runtime::PointerButton::Left,
});
assert_eq!(tank.flakes.len(), 1, "a click did not drop a flake");
assert_eq!((tank.flakes[0].x, tank.flakes[0].y), (drop_x as f32, 10.0));
let diff = tank.get_diff();
let drawn = diff.iter().any(|(x, y, cell)| {
*x == drop_x as usize && *y == 10 && cell.symbol == 'o'
});
assert!(drawn, "the flake is in the list but was not drawn");
}
#[test]
fn the_fish_go_for_the_food_and_eat_it() {
let mut tank = Aquarium::new(
AquariumOptions {
fish: 10,
..AquariumOptions::default()
},
(100, 30),
);
settle(&mut tank);
tank.handle_input(&InputEvent::Pointer {
position: (50, 15),
phase: PointerPhase::Pressed,
button: crate::runtime::PointerButton::Left,
});
let mut closed = 0usize;
for _ in 0..240 {
tank.advance(1.0 / 60.0);
for (x, y, ..) in tank.fish_snapshot() {
let d = ((x - 50.0).powi(2) + (y - 15.0).powi(2)).sqrt();
if d < 20.0 {
closed += 1;
break;
}
}
if tank.flakes.is_empty() {
break;
}
}
assert!(
closed > 0,
"no fish came within twenty cells of a flake that sat for four seconds"
);
assert!(
tank.flakes.is_empty(),
"the flake was never eaten, so the attraction did nothing"
);
}
#[test]
fn food_is_capped_and_cannot_pile_up_on_the_gravel() {
let mut tank = Aquarium::new(AquariumOptions::default(), (100, 30));
settle(&mut tank);
for i in 0..200u16 {
tank.handle_input(&InputEvent::Pointer {
position: (i % 100, 3 + (i / 100) % 25),
phase: PointerPhase::Pressed,
button: crate::runtime::PointerButton::Left,
});
}
assert!(
tank.flakes.len() <= MAX_FLAKES,
"{} flakes after 200 clicks, cap is {MAX_FLAKES}",
tank.flakes.len()
);
for _ in 0..1200 {
tank.advance(1.0 / 60.0);
}
let floor = tank.rows() as f32 - tank.gravel_rows() as f32;
for f in &tank.flakes {
assert!(f.y < floor, "a flake is resting on the gravel at y={}", f.y);
}
}
#[test]
fn the_tank_is_a_seven_species_community_in_two_media() {
let roster: Vec<(&str, bool)> =
art::sources().map(|s| (s.name(), s.is_chars())).collect();
assert_eq!(
roster,
vec![
("neon", false),
("tetra", false),
("longfin", true),
("bigeye", true),
("slashback", true),
("fry", true),
("stipple", true),
],
"the tank's roster changed. If a species was added, dropped or \
reordered, this list is the thing to update -- and note that the \
order is load-bearing, because SPECIES_MIX indexes it."
);
}
#[test]
fn the_species_mix_covers_every_species_and_is_not_one_species() {
let names: Vec<&'static str> = art::sources().map(|s| s.name()).collect();
let mut counts = vec![0usize; names.len()];
for seed in 0..24u64 {
let tank = Aquarium::new(
AquariumOptions {
fish: 40,
seed: seed.wrapping_mul(7919),
..AquariumOptions::default()
},
(100, 30),
);
for (_, _, _, s, ..) in tank.fish_snapshot() {
counts[s] += 1;
}
}
for (i, n) in counts.iter().enumerate() {
assert!(
*n > 0,
"{} never appeared in {} spawns; the mix's cumulative bounds are \
wrong",
names[i],
counts.iter().sum::<usize>()
);
}
let total: usize = counts.iter().sum();
for (i, n) in counts.iter().enumerate() {
let share = *n as f32 / total as f32;
assert!(
share < 0.55,
"{} took {:.0}% of the tank; the mix is not a mix",
names[i],
share * 100.0
);
}
}
fn rgb_of(c: Color) -> Option<(u8, u8, u8)> {
match c {
Color::Rgb { r, g, b } => Some((r, g, b)),
_ => None,
}
}
}