eger 1.2.0

A high-level, parallel ASCII-art media pipeline built on top of iascii: images, video, GIFs, dithering, animated text/banners, and procedural illusions, all rendered to ANSI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Realtime ASCII game layer: input, a fixed-timestep clock, the [`Game`]
//! trait, and a headless runner — the loop side of building an ASCII game
//! on top of this crate's rendering.
//!
//! Frame drawing lives in [`crate::canvas`] ([`Canvas`], [`Sprite`], cell
//! damage tracking, present paths); this module owns *time and input* and
//! re-exports the canvas items so `eger::game::{Canvas, Sprite, ...}` keeps
//! working.
//!
//! The design is deliberately backend-free (no terminal-control or input
//! dependency): `eger` owns the *frame* (a [`Canvas`]), you own the
//! *terminal* (print the strings, feed [`Input`] from crossterm, termion,
//! winit, or a test script). That keeps games portable and testable:
//!
//! ```rust
//! use eger::game::{Canvas, Control, Game, Input, Key, run_headless};
//! use std::time::Duration;
//!
//! struct Ball { x: i32 }
//! impl Game for Ball {
//!     fn update(&mut self, inputs: &[Input], _dt: Duration) -> Control {
//!         for i in inputs {
//!             if matches!(i, Input::Key(Key::Esc) | Input::Quit) {
//!                 return Control::Quit;
//!             }
//!         }
//!         self.x += 1;
//!         Control::Continue
//!     }
//!     fn render(&self, canvas: &mut Canvas) {
//!         canvas.clear();
//!         canvas.put(self.x, 1, 'O', None);
//!     }
//! }
//!
//! let mut ball = Ball { x: 0 };
//! let script = [vec![], vec![], vec![Input::Quit]];
//! let frames = run_headless(&mut ball, 8, 3, Duration::from_millis(16), &script);
//! assert_eq!(frames.len(), 2); // third tick quits before rendering
//! assert!(frames[1].contains('O'));
//! ```
//!
//! A typical realtime shell around this looks like:
//!
//! ```text
//! print!(ENTER_ALT + HIDE_CURSOR);          // canvas::screen constants
//! let mut frame = String::new();
//! loop clock.accumulate(elapsed) {          // TickClock fixed step
//!     game.update(&drain_backend_input(), dt)
//!     game.render(&mut canvas)              // clear() + redraw is fine
//!     frame.clear();
//!     if canvas.present_dirty_into(&mut frame) {
//!         print!("{frame}");                // only what changed
//!     }
//! }
//! print!(SHOW_CURSOR + LEAVE_ALT);
//! ```
//!
//! The frame half of that loop is incremental end to end: a `clear()` +
//! identical redraw re-renders *nothing* (see
//! [`Canvas::last_recomputed_rows`]), and
//! [`Canvas::present_dirty_into`] emits cursor-addressed patches for the
//! cells that actually moved — a mostly-static 4K HUD frame costs a
//! row-snapshot comparison plus a handful of patched cells.
//!
//! # Timing
//!
//! [`TickClock`] is the standard fixed-timestep accumulator: feed it the
//! real elapsed time, run the simulation the number of whole steps it
//! reports, render once per frame. Gameplay stays speed-independent of
//! frame rate, and [`TickClock::accumulate_capped`] provides the
//! anti-spiral guard after a hitch.
//!
//! # Pictures, video, and effects
//!
//! [`Sprite`]s are full-color character cells (see [`crate::canvas`] for
//! the full story): make them from a converted picture
//! ([`Sprite::from_grid`]) or from any rendered ANSI frame
//! ([`Canvas::blit_ansi`]), give them per-tick animation frames, and add
//! the stock effects this module provides:
//!
//! - **Jump arcs**: [`jump_arc`] gives a unit parabola for hops.
//! - **3D-ish perspective**: [`perspective_scale`] +
//!   [`Canvas::blit_sprite_scaled`] grow/shrink sprites with distance.
//! - **Side effects**: [`shake_offset`] turns a trauma value into a
//!   deterministic screen-shake offset — add it to the [`Camera`] each
//!   frame after explosions or hard landings.
//! - **Hit effects**: [`Canvas::blit_sprite`] takes an override color —
//!   pass `Some(WHITE)` for a few ticks for a classic hit-flash, or blit a
//!   more strongly dithered render for a "glitching" dissolve.
//!
//! [`rects_overlap`] covers hit-testing.

use std::time::Duration;

pub use crate::canvas::{present_diff, screen, Canvas, Cell, Sprite};

// ---------------------------------------------------------------------------
// Input
// ---------------------------------------------------------------------------

/// A keyboard key, in backend-neutral form. Map your input backend
/// (crossterm, termion, winit, ...) onto this once, and game logic never
/// touches backend types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Key {
    Up,
    Down,
    Left,
    Right,
    Enter,
    Esc,
    Space,
    Tab,
    Backspace,
    /// Printable character key.
    Char(char),
    /// Function key `F1`..`F12` (`0` means "some other Fn key").
    F(u8),
    /// Anything the backend couldn't classify.
    Unknown,
}

/// One input event delivered to [`Game::update`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Input {
    /// A key press.
    Key(Key),
    /// Terminal resized to `(cols, rows)` — a good moment to rebuild or
    /// re-clamp the [`Canvas`].
    Resize(u16, u16),
    /// Backend asked to quit (Ctrl-C, window close, ...).
    Quit,
}

// ---------------------------------------------------------------------------
// Camera and overlap
// ---------------------------------------------------------------------------

/// World-to-screen offset. Keep entities in world coordinates, subtract the
/// camera when blitting: `canvas.blit_sprite(&s, tick, cam.screen_x(wx), ...)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Camera {
    pub x: i32,
    pub y: i32,
}

impl Camera {
    pub const fn new(x: i32, y: i32) -> Self {
        Self { x, y }
    }

    /// Centers the camera so world point `(wx, wy)` lands in the middle of
    /// a `view_w x view_h` viewport.
    pub fn center_on(&mut self, wx: i32, wy: i32, view_w: i32, view_h: i32) {
        self.x = wx - view_w / 2;
        self.y = wy - view_h / 2;
    }

    pub fn screen_x(&self, world_x: i32) -> i32 {
        world_x - self.x
    }
    pub fn screen_y(&self, world_y: i32) -> i32 {
        world_y - self.y
    }
}

/// Axis-aligned bounding-box overlap in cell coordinates — hit-testing,
/// pickups, tile collision. Edges that merely touch do *not* overlap.
#[allow(clippy::too_many_arguments)] // two rects = eight flat numbers, no options struct by design
pub fn rects_overlap(
    ax: i32,
    ay: i32,
    aw: u32,
    ah: u32,
    bx: i32,
    by: i32,
    bw: u32,
    bh: u32,
) -> bool {
    ax < bx + bw as i32 && bx < ax + aw as i32 && ay < by + bh as i32 && by < ay + ah as i32
}

/// Jump-arc height at time `t` (`0..=duration`) for a hop that peaks at
/// `height`: `0` at liftoff and landing, `height` at mid-jump. Draw the
/// actor at `ground_y - jump_arc(...)` (y grows downward) and optionally
/// squash-and-stretch via [`Canvas::blit_sprite_scaled`] using the same
/// curve. Out-of-range `t` clamps to the endpoints.
pub fn jump_arc(t: f32, duration: f32, height: f32) -> f32 {
    if duration <= 0.0 || height <= 0.0 {
        return 0.0;
    }
    let u = (t / duration).clamp(0.0, 1.0);
    4.0 * height * u * (1.0 - u)
}

/// Pseudo-perspective scale for something `distance` away from the camera
/// (`distance >= 0`, same units as `focal`): `1.0` up close, shrinking
/// toward `0.0` far away. Multiply a sprite's base draw size by this and
/// feed it to [`Canvas::blit_sprite_scaled`] for approaching enemies,
/// items popping toward the camera, or floor tiles receding to a horizon.
pub fn perspective_scale(distance: f32, focal: f32) -> f32 {
    if focal <= 0.0 {
        return 1.0;
    }
    (focal / (focal + distance.max(0.0))).clamp(0.0, 1.0)
}

/// Deterministic screen-shake offset for a `trauma` value in `0.0..=1.0`
/// (add to the [`Camera`] position each frame; decay trauma in game logic,
/// e.g. `trauma = (trauma - dt * 1.5).max(0.0)`). Offset magnitude scales
/// with `trauma²` (small hits barely nudge, big ones kick) inside a
/// `±magnitude` box; `trauma <= 0.0` returns `(0, 0)` exactly. Pure
/// function of `(trauma, tick)` — replays stay frame-perfect.
pub fn shake_offset(trauma: f32, tick: u64, magnitude: i32) -> (i32, i32) {
    if trauma <= 0.0 || magnitude <= 0 {
        return (0, 0);
    }
    let amp = magnitude as f32 * trauma * trauma;
    // Integer-hash noise in [-1.0, 1.0): cheap, stable, no tables.
    let noise = |seed: u64| {
        let mut h = seed.wrapping_mul(0x9E3779B97F4A7C15);
        h ^= h >> 30;
        h = h.wrapping_mul(0xBF58476D1CE4E5B9);
        h ^= h >> 27;
        h = h.wrapping_mul(0x94D049BB133111EB);
        h ^= h >> 31;
        (h as f64 / u64::MAX as f64 * 2.0 - 1.0) as f32
    };
    (
        (noise(tick.wrapping_mul(2).wrapping_add(1)) * amp).round() as i32,
        (noise(tick.wrapping_mul(2).wrapping_add(0x9E37)) * amp).round() as i32,
    )
}

// ---------------------------------------------------------------------------
// Loop: fixed step, game trait, headless runner
// ---------------------------------------------------------------------------

/// What [`Game::update`] returns: keep going, or tear the loop down.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Control {
    Continue,
    Quit,
}

/// The game itself: pure logic plus drawing. The loop around it (input
/// backend, terminal, pacing) is the host's job; [`run_headless`] is the
/// backend-free reference loop for tests, bots, and replays.
pub trait Game {
    /// Advances simulation by `dt`, consuming this tick's `inputs`.
    /// Return [`Control::Quit`] to stop the loop (also on
    /// [`Input::Quit`]).
    fn update(&mut self, inputs: &[Input], dt: Duration) -> Control;
    /// Draws the current state. Called once per tick after `update`
    /// (not called for the tick that returns `Quit`).
    fn render(&self, canvas: &mut Canvas);
}

/// Fixed-step accumulator: call [`TickClock::accumulate`] with the real
/// elapsed time each frame; it reports how many simulation ticks to run so
/// gameplay stays speed-independent while rendering runs free.
#[derive(Debug, Clone)]
pub struct TickClock {
    step: Duration,
    acc: Duration,
}

impl TickClock {
    /// `ticks_per_second` simulation steps, e.g. `60`.
    pub fn new(ticks_per_second: u32) -> Self {
        Self {
            step: Duration::from_secs_f64(1.0 / ticks_per_second.max(1) as f64),
            acc: Duration::ZERO,
        }
    }

    /// Adds `elapsed` and returns the number of whole steps now due
    /// (usually 0 or 1; more after a hitch — clamp upstream with
    /// [`TickClock::accumulate_capped`] to avoid spiral of death).
    pub fn accumulate(&mut self, elapsed: Duration) -> u32 {
        self.acc += elapsed;
        let mut n = 0;
        while self.acc >= self.step {
            self.acc -= self.step;
            n += 1;
        }
        n
    }

    /// Like [`TickClock::accumulate`] but never reports more than `max`
    /// ticks, dropping surplus time (standard anti-spiral guard).
    pub fn accumulate_capped(&mut self, elapsed: Duration, max: u32) -> u32 {
        self.accumulate(elapsed).min(max)
    }

    pub fn step(&self) -> Duration {
        self.step
    }
}

/// Backend-free reference loop: steps `game` through one tick per
/// `script` entry (that tick's inputs), rendering after every
/// non-quitting tick. Returns each rendered frame as a string.
///
/// Deterministic — the same script always yields the same frames — so it
/// doubles as a test harness, replay player, and bot arena.
pub fn run_headless<G: Game>(
    game: &mut G,
    width: u32,
    height: u32,
    dt: Duration,
    script: &[Vec<Input>],
) -> Vec<String> {
    let mut canvas = Canvas::new(width, height);
    let mut frames = Vec::with_capacity(script.len());
    for inputs in script {
        if game.update(inputs, dt) == Control::Quit {
            break;
        }
        game.render(&mut canvas);
        frames.push(canvas.to_string());
    }
    frames
}

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

    #[test]
    fn jump_arc_peaks_midway_and_lands_at_zero() {
        assert_eq!(jump_arc(0.0, 10.0, 8.0), 0.0);
        assert_eq!(jump_arc(10.0, 10.0, 8.0), 0.0);
        assert_eq!(jump_arc(5.0, 10.0, 8.0), 8.0);
        assert!((jump_arc(2.5, 10.0, 8.0) - 6.0).abs() < 1e-5);
        // Degenerate inputs never produce NaN.
        assert_eq!(jump_arc(5.0, 0.0, 8.0), 0.0);
        assert_eq!(jump_arc(-3.0, 10.0, 8.0), 0.0);
    }

    #[test]
    fn perspective_scale_is_one_up_close_and_fades_with_distance() {
        assert_eq!(perspective_scale(0.0, 10.0), 1.0);
        let near = perspective_scale(5.0, 10.0);
        let far = perspective_scale(50.0, 10.0);
        assert!(near > far && far > 0.0);
        assert_eq!(perspective_scale(-4.0, 10.0), 1.0);
        assert_eq!(perspective_scale(5.0, 0.0), 1.0);
    }

    #[test]
    fn shake_offset_is_zero_without_trauma_and_deterministic() {
        assert_eq!(shake_offset(0.0, 99, 4), (0, 0));
        assert_eq!(shake_offset(1.0, 7, 0), (0, 0));
        let a = shake_offset(1.0, 42, 4);
        let b = shake_offset(1.0, 42, 4);
        assert_eq!(a, b, "same (trauma, tick) must shake identically");
        // Full trauma at magnitude 4 stays inside ±4.
        for tick in 0..200u64 {
            let (dx, dy) = shake_offset(1.0, tick, 4);
            assert!(dx.abs() <= 4 && dy.abs() <= 4);
        }
        // Half trauma never exceeds quarter magnitude (trauma² scaling).
        for tick in 0..200u64 {
            let (dx, dy) = shake_offset(0.5, tick, 8);
            assert!(dx.abs() <= 2 && dy.abs() <= 2);
        }
    }

    #[test]
    fn camera_centering_math() {
        let mut cam = Camera::new(0, 0);
        cam.center_on(100, 50, 40, 20);
        assert_eq!((cam.screen_x(100), cam.screen_y(50)), (20, 10));
    }

    #[test]
    fn rects_overlap_cases() {
        assert!(rects_overlap(0, 0, 4, 4, 2, 2, 4, 4));
        assert!(!rects_overlap(0, 0, 2, 2, 2, 0, 2, 2)); // touching edges
        assert!(!rects_overlap(0, 0, 2, 2, 5, 5, 2, 2));
        assert!(rects_overlap(-3, -3, 5, 5, 0, 0, 1, 1));
    }

    #[test]
    fn tick_clock_accumulates_whole_steps() {
        let mut clock = TickClock::new(10); // 100ms steps
        assert_eq!(clock.accumulate(Duration::from_millis(30)), 0);
        assert_eq!(clock.accumulate(Duration::from_millis(80)), 1); // 110 total
        assert_eq!(clock.accumulate(Duration::from_millis(250)), 2);
        assert_eq!(clock.step(), Duration::from_millis(100));
        // Capped variant never exceeds max.
        assert_eq!(clock.accumulate_capped(Duration::from_secs(10), 3), 3);
    }

    #[test]
    fn run_headless_drives_a_toy_game() {
        struct Right {
            x: i32,
        }
        impl Game for Right {
            fn update(&mut self, inputs: &[Input], _dt: Duration) -> Control {
                if inputs.contains(&Input::Quit) {
                    return Control::Quit;
                }
                self.x += 1;
                Control::Continue
            }
            fn render(&self, canvas: &mut Canvas) {
                canvas.clear();
                canvas.put(self.x, 0, '@', None);
            }
        }
        let mut game = Right { x: 0 };
        let script = vec![vec![], vec![Input::Key(Key::Right)], vec![Input::Quit]];
        let frames = run_headless(&mut game, 6, 2, Duration::from_millis(16), &script);
        assert_eq!(frames.len(), 2);
        assert!(frames[0].starts_with(" @"));
        assert!(frames[1].starts_with("  @"));
    }
}