use crate::buffer::Cell;
use crate::canvas::Canvas;
use crate::common::{DEFAULT_SEED, EffectRng, TerminalEffect, seeded_rng};
use crate::render::glyph_ramp::{GlyphRamp, presets as glyph_presets};
use crate::render::palette::{Palette, luminance, presets as palette_presets};
use crate::runtime::FrameContext;
use crossterm::style;
use rand::RngExt;
use serde::{Deserialize, Serialize};
const SATURATION: f32 = 8.0;
const TRAIL_LUMA_MIDPOINT: f32 = 0.45;
const NORTH: usize = 0;
const EAST: usize = 1;
const SOUTH: usize = 2;
const WEST: usize = 3;
struct Ant {
x: usize,
y: usize,
heading: usize,
}
impl Ant {
fn turn_right(&mut self) {
self.heading = (self.heading + 1) % 4;
}
fn turn_left(&mut self) {
self.heading = (self.heading + 3) % 4;
}
fn step(&mut self, width: usize, height: usize) {
match self.heading {
NORTH => self.y = (self.y + height - 1) % height,
EAST => self.x = (self.x + 1) % width,
SOUTH => self.y = (self.y + 1) % height,
WEST => self.x = (self.x + width - 1) % width,
_ => unreachable!("heading {} is not a direction", self.heading),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AntsOptions {
#[serde(skip)]
pub ants: u16,
pub ant_coeff: f32,
pub steps_per_second: f32,
pub max_steps_per_frame: u16,
pub palette: String,
pub seed: u64,
}
impl Default for AntsOptions {
fn default() -> Self {
Self {
ants: DEFAULT_ANT_COUNT,
ant_coeff: 1.0,
steps_per_second: 240.0,
max_steps_per_frame: 8,
palette: "magma".to_string(),
seed: DEFAULT_SEED,
}
}
}
pub const ANT_DENSITY: f32 = 1.0 / 6000.0;
pub const ANTS_MIN_COUNT: u16 = 1;
pub const ANTS_MAX_COUNT: u16 = 12;
const DEFAULT_ANT_COUNT: u16 = 4;
pub struct Ants {
screen_size: (u16, u16),
options: AntsOptions,
canvas: Canvas,
grid: Vec<u8>,
colony: Vec<Ant>,
step_accumulator: f32,
rng: EffectRng,
ramp: GlyphRamp,
palette: Palette,
}
impl TerminalEffect for Ants {
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) {
let (width, height) = self.size();
self.canvas.resize(self.screen_size.0, self.screen_size.1);
self.grid = vec![0u8; width * height];
self.step_accumulator = 0.0;
self.rng = seeded_rng(self.options.seed, "ants");
self.spawn_colony();
}
}
impl Ants {
pub fn new(options: AntsOptions, screen_size: (u16, u16)) -> Self {
let screen_size = crate::common::normalize_effect_size(screen_size);
let (width, height) = (screen_size.0 as usize, screen_size.1 as usize);
let palette = Palette::new(
palette_presets::by_name(&options.palette)
.unwrap_or(palette_presets::MAGMA)
.to_vec(),
)
.truncated_at_peak();
let mut ants = Self {
screen_size,
canvas: Canvas::new(screen_size.0, screen_size.1),
options,
grid: vec![0u8; width * height],
colony: Vec::new(),
step_accumulator: 0.0,
rng: seeded_rng(DEFAULT_SEED, "ants"),
ramp: GlyphRamp::new_ascii(glyph_presets::SHADE.chars().collect()),
palette,
};
ants.rng = seeded_rng(ants.options.seed, "ants");
ants.spawn_colony();
ants
}
pub fn grid_dimensions(&self) -> (usize, usize) {
self.size()
}
pub fn flipped(&self, x: usize, y: usize) -> u8 {
let (width, height) = self.size();
if x >= width || y >= height {
return 0;
}
self.grid[y * width + x]
}
fn size(&self) -> (usize, usize) {
(
self.screen_size.0.max(1) as usize,
self.screen_size.1.max(1) as usize,
)
}
fn spawn_colony(&mut self) {
let (width, height) = self.size();
self.colony = (0..self.options.ants.max(1))
.map(|_| Ant {
x: self.rng.random_range(0..width),
y: self.rng.random_range(0..height),
heading: self.rng.random_range(0..4),
})
.collect();
}
fn advance(&mut self, delta: f32) {
let rate = self.options.steps_per_second.max(0.0);
if rate <= 0.0 {
return;
}
self.step_accumulator += delta * rate;
let cap = self.options.max_steps_per_frame.max(1) as usize;
let mut steps = 0;
while self.step_accumulator >= 1.0 && steps < cap {
self.step_accumulator -= 1.0;
self.step_once();
steps += 1;
}
if steps == cap {
self.step_accumulator = 0.0;
}
}
pub fn step_once(&mut self) {
let (width, height) = self.size();
for ant in &mut self.colony {
let index = ant.y * width + ant.x;
if self.grid[index] % 2 == 0 {
ant.turn_right();
} else {
ant.turn_left();
}
self.grid[index] = self.grid[index].saturating_add(1);
ant.step(width, height);
}
}
fn draw(&mut self) {
self.canvas.clear();
let (width, height) = self.size();
for y in 0..height {
for x in 0..width {
let flips = self.grid[y * width + x];
if flips == 0 {
continue;
}
let t = (flips as f32 / SATURATION).min(1.0);
let cell = Cell::new(
self.ramp.sample(t),
self.palette.sample(t),
style::Attribute::Reset,
);
self.canvas.set(x, y, cell);
}
}
for (i, ant) in self.colony.iter().enumerate() {
if ant.x >= width || ant.y >= height {
continue;
}
let glyph = if i == 0 { '@' } else { 'o' };
let under = self.grid[ant.y * width + ant.x];
let background = if under == 0 {
style::Color::White
} else {
let trail =
self.palette.sample((under as f32 / SATURATION).min(1.0));
if luminance(trail) > TRAIL_LUMA_MIDPOINT {
style::Color::Black
} else {
style::Color::White
}
};
self.canvas.set(
ant.x,
ant.y,
Cell::new(glyph, background, style::Attribute::Bold),
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::render::palette::luminance;
fn small(seed: u64) -> Ants {
Ants::new(
AntsOptions {
seed,
ants: 1,
..AntsOptions::default()
},
(60, 20),
)
}
fn longest_diagonal(ants: &Ants) -> usize {
let (width, height) = ants.size();
let mut best = 0usize;
for (dx, dy) in [(1isize, 1isize), (-1, 1), (1, -1), (-1, -1)] {
for x0 in 0..width as isize {
for y0 in 0..height as isize {
let (mut x, mut y) = (x0, y0);
let mut run = 0usize;
while x >= 0
&& y >= 0
&& (x as usize) < width
&& (y as usize) < height
&& ants.grid[y as usize * width + x as usize] != 0
{
run += 1;
x += dx;
y += dy;
}
best = best.max(run);
}
}
}
best
}
fn colour_at(ants: &Ants, flips: u8) -> style::Color {
let t = (flips as f32 / SATURATION).min(1.0);
ants.palette.sample(t)
}
#[test]
fn a_busier_cell_is_brighter_than_a_fresh_one() {
let ants = small(1);
let fresh = colour_at(&ants, 1);
let busy = colour_at(&ants, 8);
assert!(
luminance(busy) > luminance(fresh) + 0.2,
"a cell flipped eight times was drawn at {busy:?} (luma \
{:.3}) and a cell flipped once at {fresh:?} (luma {:.3})",
luminance(busy),
luminance(fresh)
);
}
#[test]
fn the_trail_brightness_climbs_monotonically_with_the_flip_count() {
let ants = small(1);
let mut previous = f32::NEG_INFINITY;
for flips in 1..=8u8 {
let color = colour_at(&ants, flips);
let luma = luminance(color);
assert!(
luma >= previous - 1e-4,
"flip count {flips} drew at {color:?}, luma {luma:.3}, \
after {previous:.3}"
);
previous = luma;
}
}
#[test]
fn an_ant_is_always_contrasted_against_its_own_trail() {
let mut ants = Ants::new(
AntsOptions {
seed: 5,
ants: 3,
..AntsOptions::default()
},
(60, 20),
);
for _ in 0..2_000 {
ants.step_once();
}
ants.draw();
let (width, _) = ants.size();
let mut checked = 0usize;
for ant in &ants.colony {
let under = ants.grid[ant.y * width + ant.x];
let drawn = ants.canvas.get(ant.x, ant.y);
let ant_luma = luminance(drawn.color);
let trail_luma = if under == 0 {
0.0
} else {
luminance(colour_at(&ants, under))
};
assert!(
(ant_luma - trail_luma).abs() > 0.2,
"an ant at ({}, {}) is drawn at {ant_luma:.2} on a trail at \
{trail_luma:.2}, so it is invisible",
ant.x,
ant.y
);
checked += 1;
}
assert!(checked >= 3, "the fixture produced {checked} ants");
}
#[test]
fn the_ant_colour_actually_flips_across_the_ramp() {
let ants = small(1);
let dark_ant = if luminance(colour_at(&ants, 1)) > TRAIL_LUMA_MIDPOINT {
style::Color::Black
} else {
style::Color::White
};
let bright_trail = colour_at(&ants, 8);
let bright_ant = if luminance(bright_trail) > TRAIL_LUMA_MIDPOINT {
style::Color::Black
} else {
style::Color::White
};
assert_ne!(
dark_ant,
bright_ant,
"a fresh trail at {:?} and a busy one at {bright_trail:?} pick the same \
ant colour, so one of the two is invisible",
colour_at(&ants, 1)
);
}
#[test]
fn a_configured_palette_is_honoured_and_still_truncated() {
let default_ants = Ants::new(
AntsOptions {
seed: 1,
ants: 1,
..AntsOptions::default()
},
(60, 20),
);
let ocean = Ants::new(
AntsOptions {
seed: 1,
ants: 1,
palette: "ocean".to_string(),
..AntsOptions::default()
},
(60, 20),
);
assert_ne!(
colour_at(&default_ants, 8),
colour_at(&ocean, 8),
"choosing ocean changed nothing, so the option is ignored"
);
let brightest = palette_presets::OCEAN
.iter()
.copied()
.max_by(|a, b| {
luminance(*a)
.partial_cmp(&luminance(*b))
.unwrap_or(std::cmp::Ordering::Equal)
})
.unwrap();
assert_eq!(colour_at(&ocean, 8), brightest);
let bogus = Ants::new(
AntsOptions {
seed: 1,
ants: 1,
palette: "not-a-ramp".to_string(),
..AntsOptions::default()
},
(60, 20),
);
assert_eq!(
colour_at(&bogus, 8),
colour_at(&default_ants, 8),
"an unknown palette name did not fall back to the default"
);
}
#[test]
fn a_highway_forms_and_then_keeps_extending() {
let mut ants = Ants::new(
AntsOptions {
seed: 1,
ants: 1,
..AntsOptions::default()
},
(200, 60),
);
for _ in 0..10_000 {
ants.step_once();
}
let run_at_10k = longest_diagonal(&ants);
let cells_at_10k = ants.grid.iter().filter(|v| **v != 0).count();
for _ in 0..10_000 {
ants.step_once();
}
let run_at_20k = longest_diagonal(&ants);
let cells_at_20k = ants.grid.iter().filter(|v| **v != 0).count();
assert!(
run_at_10k >= 20,
"the longest diagonal run was {run_at_10k} cells at ten thousand steps; \
the chaotic phase ends at about ten thousand, so no highway had formed"
);
assert!(
run_at_20k >= run_at_10k * 2,
"the run went from {run_at_10k} to {run_at_20k} over the second ten \
thousand steps: a highway keeps extending, so this is not one"
);
assert!(
cells_at_20k < cells_at_10k * 3,
"distinct flipped cells went from {cells_at_10k} to {cells_at_20k}; a \
highway retraces the cells it has already made rather than spreading"
);
}
#[test]
fn a_cell_visited_twice_turns_the_ant_the_other_way() {
let mut ants = small(3);
let (width, _) = ants.size();
let ant = &ants.colony[0];
ants.grid[ant.y * width + ant.x] = 2;
let start_heading = ant.heading;
ants.step_once();
assert_eq!(
ants.colony[0].heading,
(start_heading + 1) % 4,
"a cell flipped twice is white again, so the ant must turn right"
);
}
#[test]
fn a_single_step_turns_flips_and_moves() {
let mut ants = small(2);
let (width, height) = ants.size();
let ant = &ants.colony[0];
let (start_x, start_y, start_heading) = (ant.x, ant.y, ant.heading);
ants.step_once();
let ant = &ants.colony[0];
assert_eq!(
ants.grid[start_y * width + start_x],
1,
"the cell the ant was standing on was not flipped"
);
let expected = (start_heading + 1) % 4;
assert_eq!(
ant.heading, expected,
"the ant did not turn right off a light cell"
);
let (expected_x, expected_y) = match expected {
NORTH => (start_x, (start_y + height - 1) % height),
EAST => ((start_x + 1) % width, start_y),
SOUTH => (start_x, (start_y + 1) % height),
_ => ((start_x + width - 1) % width, start_y),
};
assert_eq!((ant.x, ant.y), (expected_x, expected_y));
}
#[test]
fn a_dark_cell_makes_the_ant_turn_left() {
let mut ants = small(4);
let (width, _) = ants.size();
let ant = &ants.colony[0];
ants.grid[ant.y * width + ant.x] = 1;
let start_heading = ant.heading;
ants.step_once();
assert_eq!(
ants.colony[0].heading,
(start_heading + 3) % 4,
"the ant did not turn left off a dark cell"
);
}
#[test]
fn the_grid_wraps_rather_than_killing_the_ant_at_an_edge() {
let (width, height) = (20usize, 10usize);
for (from, heading, expected) in [
((width - 1, height - 1), SOUTH, (width - 1, 0)),
((width - 1, 0), NORTH, (width - 1, height - 1)),
((0, 5), WEST, (width - 1, 5)),
((width - 1, 5), EAST, (0, 5)),
((0, 0), NORTH, (0, height - 1)),
] {
let mut ant = Ant {
x: from.0,
y: from.1,
heading,
};
ant.step(width, height);
assert_eq!(
(ant.x, ant.y),
expected,
"heading {heading} from {from:?} left the grid"
);
}
}
#[test]
fn an_ant_survives_a_long_run_on_the_smallest_board() {
let mut ants = small(6);
for _ in 0..20_000 {
ants.step_once();
}
let (width, height) = ants.size();
for ant in &ants.colony {
assert!(ant.x < width && ant.y < height);
}
}
#[test]
fn flip_counts_saturate_instead_of_overflowing() {
let mut ants = small(5);
let (width, _) = ants.size();
let ant = &ants.colony[0];
ants.grid[ant.y * width + ant.x] = 255;
let index = ant.y * width + ant.x;
ants.step_once();
assert_eq!(
ants.grid[index], 255,
"a saturated cell overflowed rather than clamping"
);
}
#[test]
fn more_than_one_ant_changes_the_picture() {
let mut one = Ants::new(
AntsOptions {
seed: 11,
ants: 1,
..AntsOptions::default()
},
(60, 20),
);
let mut many = Ants::new(
AntsOptions {
seed: 11,
ants: 6,
..AntsOptions::default()
},
(60, 20),
);
for _ in 0..2_000 {
one.step_once();
many.step_once();
}
assert_ne!(
one.grid, many.grid,
"adding ants made no difference, so they are not sharing the board"
);
}
#[test]
fn the_seeded_colony_places_its_ants_differently() {
let a = small(100);
let b = small(101);
let positions = |ants: &Ants| {
ants.colony
.iter()
.map(|a| (a.x, a.y, a.heading))
.collect::<Vec<_>>()
};
assert_ne!(positions(&a), positions(&b));
}
#[test]
fn a_zero_step_rate_freezes_the_colony_rather_than_spinning_it() {
let mut ants = Ants::new(
AntsOptions {
ants: 1,
steps_per_second: 0.0,
..AntsOptions::default()
},
(40, 12),
);
let before: Vec<u8> = ants.grid.clone();
ants.advance(1.0);
ants.advance(1.0);
assert_eq!(ants.grid, before, "the board changed with the rate at zero");
}
#[test]
fn zero_requested_ants_still_puts_one_on_the_board() {
let ants = Ants::new(
AntsOptions {
ants: 0,
..AntsOptions::default()
},
(40, 12),
);
assert_eq!(ants.colony.len(), 1);
}
#[test]
fn every_emitted_cell_is_inside_the_canvas() {
let mut ants = small(9);
for _ in 0..300 {
ants.step_once();
ants.draw();
}
for (x, y, _) in ants.canvas.commit() {
assert!(x < ants.screen_size.0 as usize);
assert!(y < ants.screen_size.1 as usize);
}
}
}