ttui 2.0.0

A terminal UI framework built from first principles: direct control over text rendering, color, pane layout, and multiplexing.
Documentation
//! A simple particle system for bursts and impacts — one straight-line
//! velocity per particle, no gravity or collision.

use crate::buffer::{Buffer, Cell};
use crossterm::style::Color;
use std::time::Duration;

/// One glyph moving in a straight line with a finite lifetime.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Particle {
    /// Current x position (cells).
    pub x: f32,
    /// Current y position (cells).
    pub y: f32,
    /// x velocity (cells/second).
    pub vx: f32,
    /// y velocity (cells/second).
    pub vy: f32,
    /// Glyph to render.
    pub symbol: char,
    /// Foreground color.
    pub color: Color,
    /// Total time the particle lives before despawning.
    pub lifetime: Duration,
    /// Time elapsed since spawn.
    pub age: Duration,
}

impl Particle {
    /// Whether this particle is still within its `lifetime`.
    pub fn is_alive(&self) -> bool {
        self.age < self.lifetime
    }
}

/// A collection of `Particle`s: spawn, `update` each tick, `render`
/// each frame; dead particles are dropped automatically.
#[derive(Clone, Debug, Default)]
pub struct ParticleSystem {
    particles: Vec<Particle>,
}

impl ParticleSystem {
    /// Creates an empty particle system.
    pub fn new() -> Self {
        ParticleSystem::default()
    }

    /// Adds a particle to the system.
    pub fn spawn(&mut self, p: Particle) {
        self.particles.push(p);
    }

    /// Advances every particle's position and age by `elapsed`,
    /// dropping any that have expired.
    pub fn update(&mut self, elapsed: Duration) {
        let dt = elapsed.as_secs_f32();
        for p in &mut self.particles {
            p.x += p.vx * dt;
            p.y += p.vy * dt;
            p.age += elapsed;
        }
        self.particles.retain(|p| p.is_alive());
    }

    /// Draws every particle's glyph at its rounded position, skipping
    /// any that have moved out of bounds.
    pub fn render(&self, buf: &mut Buffer) {
        for p in &self.particles {
            let x = p.x.round();
            let y = p.y.round();
            if x >= 0.0 && y >= 0.0 && (x as u16) < buf.width && (y as u16) < buf.height {
                buf.set(
                    x as u16,
                    y as u16,
                    Cell {
                        symbol: p.symbol,
                        fg: p.color,
                        bg: Color::Reset,
                        alpha: 1.0,
                        ..Default::default()
                    },
                );
            }
        }
    }

    /// Number of currently-alive particles.
    pub fn len(&self) -> usize {
        self.particles.len()
    }

    /// Whether there are no currently-alive particles.
    pub fn is_empty(&self) -> bool {
        self.particles.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn particle_system_new_is_empty() {
        let ps = ParticleSystem::new();
        assert_eq!(ps.len(), 0);
        assert!(ps.is_empty());
    }

    #[test]
    fn spawn_increases_len_by_one() {
        let mut ps = ParticleSystem::new();
        let p = Particle {
            x: 0.0,
            y: 0.0,
            vx: 0.0,
            vy: 0.0,
            symbol: '*',
            color: Color::Red,
            lifetime: Duration::from_millis(100),
            age: Duration::ZERO,
        };
        ps.spawn(p);
        assert_eq!(ps.len(), 1);
    }

    #[test]
    fn update_moves_particle_by_velocity_times_elapsed() {
        let mut ps = ParticleSystem::new();
        let p = Particle {
            x: 0.0,
            y: 0.0,
            vx: 2.0,
            vy: 0.0,
            symbol: '*',
            color: Color::Red,
            lifetime: Duration::from_millis(1000),
            age: Duration::ZERO,
        };
        ps.spawn(p);
        ps.update(Duration::from_millis(500));
        // With vx=2.0 and elapsed=500ms=0.5s, x should advance by 2.0 * 0.5 = 1.0
        // We need to check through render or by accessing particles directly
        // Since particles is private, we'll check via rendering behavior
        let mut buf = Buffer::new(10, 10);
        ps.render(&mut buf);
        // The particle should be at x=1.0 (rounded to 1), y=0.0
        assert_eq!(
            *buf.get(1, 0),
            Cell {
                symbol: '*',
                fg: Color::Red,
                bg: Color::Reset,
                alpha: 1.0,
                ..Default::default()
            }
        );
    }

    #[test]
    fn update_accumulates_position_across_multiple_calls() {
        let mut ps = ParticleSystem::new();
        let p = Particle {
            x: 0.0,
            y: 0.0,
            vx: 2.0,
            vy: 0.0,
            symbol: '*',
            color: Color::Red,
            lifetime: Duration::from_secs(10),
            age: Duration::ZERO,
        };
        ps.spawn(p);
        ps.update(Duration::from_millis(500));
        ps.update(Duration::from_millis(500));
        // Two 500ms updates at vx=2.0 should accumulate to x = 2.0*0.5 + 2.0*0.5
        // = 2.0, not stay at 1.0 (which a buggy `p.x = p.vx * dt` assignment
        // instead of `p.x += p.vx * dt` accumulation would produce).
        let mut buf = Buffer::new(10, 10);
        ps.render(&mut buf);
        assert_eq!(
            *buf.get(2, 0),
            Cell {
                symbol: '*',
                fg: Color::Red,
                bg: Color::Reset,
                alpha: 1.0,
                ..Default::default()
            }
        );
        assert_eq!(ps.len(), 1);
    }

    #[test]
    fn update_accumulates_age_across_multiple_calls_until_expiry() {
        let mut ps = ParticleSystem::new();
        let p = Particle {
            x: 0.0,
            y: 0.0,
            vx: 0.0,
            vy: 0.0,
            symbol: '*',
            color: Color::Red,
            lifetime: Duration::from_millis(150),
            age: Duration::ZERO,
        };
        ps.spawn(p);
        ps.update(Duration::from_millis(100));
        assert_eq!(ps.len(), 1); // 100ms < 150ms lifetime, still alive
        ps.update(Duration::from_millis(100));
        // Total age = 200ms > 150ms lifetime — only correct if age accumulates
        // across calls (100+100=200) rather than resetting each call.
        assert_eq!(ps.len(), 0);
    }

    #[test]
    fn update_ages_particle_and_removes_when_age_exceeds_lifetime() {
        let mut ps = ParticleSystem::new();
        let p = Particle {
            x: 0.0,
            y: 0.0,
            vx: 0.0,
            vy: 0.0,
            symbol: '*',
            color: Color::Red,
            lifetime: Duration::from_millis(100),
            age: Duration::ZERO,
        };
        ps.spawn(p);
        assert_eq!(ps.len(), 1);
        ps.update(Duration::from_millis(150));
        assert_eq!(ps.len(), 0);
    }

    #[test]
    fn update_retains_particles_with_age_less_than_lifetime() {
        let mut ps = ParticleSystem::new();
        let p = Particle {
            x: 0.0,
            y: 0.0,
            vx: 0.0,
            vy: 0.0,
            symbol: '*',
            color: Color::Red,
            lifetime: Duration::from_millis(100),
            age: Duration::ZERO,
        };
        ps.spawn(p);
        assert_eq!(ps.len(), 1);
        ps.update(Duration::from_millis(50));
        assert_eq!(ps.len(), 1);
    }

    #[test]
    fn render_writes_particle_to_buffer_at_rounded_position() {
        let mut ps = ParticleSystem::new();
        let p = Particle {
            x: 3.4,
            y: 2.6,
            vx: 0.0,
            vy: 0.0,
            symbol: 'X',
            color: Color::Blue,
            lifetime: Duration::from_millis(100),
            age: Duration::ZERO,
        };
        ps.spawn(p);
        let mut buf = Buffer::new(10, 10);
        ps.render(&mut buf);
        // x=3.4 rounds to 3, y=2.6 rounds to 3
        assert_eq!(
            *buf.get(3, 3),
            Cell {
                symbol: 'X',
                fg: Color::Blue,
                bg: Color::Reset,
                alpha: 1.0,
                ..Default::default()
            }
        );
    }

    #[test]
    fn render_skips_particle_outside_buffer_bounds() {
        let mut ps = ParticleSystem::new();
        // Particle at negative x
        let p1 = Particle {
            x: -1.0,
            y: 0.0,
            vx: 0.0,
            vy: 0.0,
            symbol: 'A',
            color: Color::Red,
            lifetime: Duration::from_millis(100),
            age: Duration::ZERO,
        };
        ps.spawn(p1);
        // Particle at x >= width
        let p2 = Particle {
            x: 10.0,
            y: 0.0,
            vx: 0.0,
            vy: 0.0,
            symbol: 'B',
            color: Color::Red,
            lifetime: Duration::from_millis(100),
            age: Duration::ZERO,
        };
        ps.spawn(p2);
        // Particle at negative y
        let p3 = Particle {
            x: 0.0,
            y: -1.0,
            vx: 0.0,
            vy: 0.0,
            symbol: 'C',
            color: Color::Red,
            lifetime: Duration::from_millis(100),
            age: Duration::ZERO,
        };
        ps.spawn(p3);
        // Particle at y >= height
        let p4 = Particle {
            x: 0.0,
            y: 10.0,
            vx: 0.0,
            vy: 0.0,
            symbol: 'D',
            color: Color::Red,
            lifetime: Duration::from_millis(100),
            age: Duration::ZERO,
        };
        ps.spawn(p4);

        let mut buf = Buffer::new(10, 10);
        ps.render(&mut buf);

        // Buffer should still be all default cells
        for y in 0..10 {
            for x in 0..10 {
                assert_eq!(*buf.get(x, y), Cell::default());
            }
        }
    }
}