omatrix 0.1.1

A Matrix-style terminal rain animation for Omarchy users
Documentation
use rand::{RngExt, SeedableRng, rngs::StdRng};

use crate::charset::{Charset, Script};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Size {
    pub width: u16,
    pub height: u16,
}

impl Size {
    pub const fn new(width: u16, height: u16) -> Self {
        Self { width, height }
    }

    pub fn area(self) -> usize {
        self.width as usize * self.height as usize
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Cell {
    pub glyph: char,
    pub ttl: u16,
    pub max_ttl: u16,
    pub is_head: bool,
}

impl Default for Cell {
    fn default() -> Self {
        Self {
            glyph: ' ',
            ttl: 0,
            max_ttl: 0,
            is_head: false,
        }
    }
}

impl Cell {
    fn head(glyph: char, ttl: u16) -> Self {
        Self {
            glyph,
            ttl,
            max_ttl: ttl,
            is_head: true,
        }
    }
}

#[derive(Debug)]
pub struct Simulation {
    size: Size,
    cells: Vec<Cell>,
    columns: Vec<Column>,
    charset: Charset,
    rng: StdRng,
}

#[derive(Clone, Copy, Debug, Default)]
struct Column {
    stream: Option<Stream>,
}

#[derive(Clone, Copy, Debug)]
struct Stream {
    head_row: i16,
    step_every: u8,
    ticks_until_step: u8,
    remaining_steps: u16,
    trail_length: u16,
    script_cycle: [Script; 5],
    next_script_index: u8,
}

impl Simulation {
    pub fn new(size: Size, charset: Charset, seed: Option<u64>) -> Self {
        let mut simulation = Self {
            size,
            cells: vec![Cell::default(); size.area()],
            columns: vec![Column::default(); size.width as usize],
            charset,
            rng: StdRng::seed_from_u64(seed.unwrap_or_else(rand::random)),
        };

        simulation.bootstrap();
        simulation
    }

    pub fn tick(&mut self) {
        for cell in &mut self.cells {
            if cell.ttl > 0 {
                cell.ttl -= 1;
                cell.is_head = false;
                if cell.ttl == 0 {
                    cell.glyph = ' ';
                    cell.max_ttl = 0;
                }
            }
        }

        if self.size.width == 0 || self.size.height == 0 {
            return;
        }

        let spawn_probability =
            (1.0 / (f64::from(self.size.height.max(1)) * 12.0)).clamp(0.001, 0.02);
        let size = self.size;
        let cells = &mut self.cells;
        let charset = &self.charset;
        let rng = &mut self.rng;

        for (x, column) in self.columns.iter_mut().enumerate() {
            if let Some(stream) = column.stream.as_mut() {
                if stream.ticks_until_step > 0 {
                    stream.ticks_until_step -= 1;
                }

                if stream.ticks_until_step == 0 {
                    stream.ticks_until_step = stream.step_every;
                    stream.head_row += 1;
                    stream.remaining_steps = stream.remaining_steps.saturating_sub(1);

                    if let Ok(y) = usize::try_from(stream.head_row) {
                        if y < size.height as usize {
                            let glyph = charset.random_glyph(rng, stream.next_script());
                            let index = cell_index(size, x, y);
                            let ttl = stream
                                .trail_length
                                .saturating_mul(u16::from(stream.step_every));
                            cells[index] = Cell::head(glyph, ttl.max(1));
                        }
                    }

                    maybe_mutate_trail(cells, size, x, stream, charset, rng);
                }

                if stream.remaining_steps == 0 {
                    column.stream = None;
                }
            } else if rng.random_bool(spawn_probability) {
                column.stream = Some(Stream::spawn(size, rng));
            }
        }
    }

    pub fn resize(&mut self, size: Size) {
        self.size = size;
        self.cells = vec![Cell::default(); size.area()];
        self.columns = vec![Column::default(); size.width as usize];
        self.bootstrap();
    }

    pub fn size(&self) -> Size {
        self.size
    }

    pub fn cells(&self) -> &[Cell] {
        &self.cells
    }

    fn bootstrap(&mut self) {
        if self.columns.is_empty() || self.size.height == 0 {
            return;
        }

        let initial_streams = (self.columns.len() / 5).max(1);
        for _ in 0..initial_streams {
            let index = self.rng.random_range(0..self.columns.len());
            self.columns[index].stream = Some(Stream::spawn(self.size, &mut self.rng));
        }
    }
}

impl Stream {
    fn spawn<R: RngExt + ?Sized>(size: Size, rng: &mut R) -> Self {
        let lead_in = rng.random_range(0..=size.height.max(1) / 3) as i16;
        let step_every = rng.random_range(1..=3);
        let (min_trail, max_trail) = trail_length_bounds(size.height);
        let trail_length = rng.random_range(min_trail..=max_trail);

        Self {
            head_row: -lead_in,
            step_every,
            ticks_until_step: rng.random_range(0..=step_every),
            remaining_steps: size
                .height
                .saturating_add(lead_in as u16)
                .saturating_add(trail_length),
            trail_length,
            script_cycle: shuffled_scripts(rng),
            next_script_index: 0,
        }
    }

    fn next_script(&mut self) -> Script {
        let index = self.next_script_index as usize;
        self.next_script_index = (self.next_script_index + 1) % self.script_cycle.len() as u8;
        self.script_cycle[index]
    }
}

fn maybe_mutate_trail<R: RngExt + ?Sized>(
    cells: &mut [Cell],
    size: Size,
    column: usize,
    stream: &mut Stream,
    charset: &Charset,
    rng: &mut R,
) {
    if !rng.random_bool(1.0) || size.height == 0 {
        return;
    }

    let start = (stream.head_row - stream.trail_length as i16 - 2).max(0);
    let end = stream.head_row.min(size.height as i16 - 1);
    if start > end {
        return;
    }

    let row = rng.random_range(start..=end) as usize;
    let index = cell_index(size, column, row);
    if cells[index].ttl > 0 {
        cells[index].glyph = charset.random_glyph(rng, stream.next_script());
    }
}

fn shuffled_scripts<R: RngExt + ?Sized>(rng: &mut R) -> [Script; 5] {
    let mut scripts = [
        Script::Latin,
        Script::Cyrillic,
        Script::Digits,
        Script::Katakana,
        Script::Symbols,
    ];

    for index in (1..scripts.len()).rev() {
        let swap_index = rng.random_range(0..=index);
        scripts.swap(index, swap_index);
    }

    scripts
}

fn trail_length_bounds(height: u16) -> (u16, u16) {
    let max_trail = ((u32::from(height) * 5 + 2) / 4).max(1) as u16;
    let min_trail = (height / 5).max(4).min(max_trail);
    (min_trail, max_trail)
}

fn cell_index(size: Size, x: usize, y: usize) -> usize {
    y * size.width as usize + x
}

#[cfg(test)]
mod tests {
    use rand::{SeedableRng, rngs::StdRng};

    use super::{Size, Stream, trail_length_bounds};
    use crate::charset::Script;

    #[test]
    fn trail_lengths_scale_with_viewport_height() {
        assert_eq!(trail_length_bounds(24), (4, 30));
        assert_eq!(trail_length_bounds(80), (16, 100));
        assert_eq!(trail_length_bounds(3), (4, 4));
    }

    #[test]
    fn streams_cycle_evenly_through_all_scripts() {
        let mut rng = StdRng::seed_from_u64(9);
        let mut stream = Stream::spawn(Size::new(80, 24), &mut rng);
        let mut seen = [false; 5];

        for _ in 0..5 {
            match stream.next_script() {
                Script::Latin => seen[0] = true,
                Script::Cyrillic => seen[1] = true,
                Script::Digits => seen[2] = true,
                Script::Katakana => seen[3] = true,
                Script::Symbols => seen[4] = true,
            }
        }

        assert!(seen.into_iter().all(|script_seen| script_seen));
    }
}