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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! One-knob color treatments for ASCII rendering.
//!
//! [`Style`] picks *how* a converted [`Grid`] is
//! painted, orthogonally to the terminal's [`ColorDepth`]:
//!
//! | Variant | Look | Escapes? |
//! |---|---|---|
//! | [`Style::Plain`] | basic ASCII text | none — smallest output, fastest |
//! | [`Style::Full`] | per-cell source colors (the classic render) | yes |
//! | [`Style::Gray`] | black-and-white photo (luminance grays) | yes |
//! | [`Style::Mono`] | one color of your choice, shaded by luminance ("green terminal" look) | yes |
//! | [`Style::BlackWhite`] | 1-bit bilevel: pure black or white per cell | two codes only |
//!
//! `Plain` is the game-dev / embedded default (no escape parsing needed,
//! output is pure text). `BlackWhite` is the next cheapest: only two SGR
//! codes (`\x1b[30m` / `\x1b[97m`) ever appear, so output stays tiny even
//! at huge grid sizes.
//!
//! `Full` renders byte-identically to `iascii::render::render_ansi` (spaces
//! included, exactly like before). The other color styles leave blank cells
//! as bare spaces instead of wrapping them in color escapes — same visible
//! result, smaller output, which matters at 4K grid sizes.
//!
//! Set it once on [`crate::config::ConfigBuilder::style`]; the image, batch,
//! GIF, and (via `video::ColorMode::Styled`) video pipelines all
//! honor it. Depth still comes from
//! [`crate::config::ConfigBuilder::color_depth`] and applies to `Full`,
//! `Gray`, and `Mono` (`Plain` and `BlackWhite` are depth-independent).

use iascii::grid::{Cell, Grid};
use iascii::render::ColorDepth;

use crate::fast_ansi;

/// How a converted grid should be painted.
///
/// `Copy` so video-frame loops and game loops can pass it by value per
/// frame without cloning. See the [module docs](self) for the lineup.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Style {
    /// Basic ASCII text: glyphs only, no ANSI escapes. Fastest to render,
    /// smallest output, trivially parseable (game sprites, logs, tests).
    Plain,
    /// Per-cell source colors — the classic full-color render.
    Full,
    /// Black-and-white photo: each cell's luminance drawn as gray.
    Gray,
    /// Monocolor of your choice, shaded per-cell by luminance. Any `Rgb`
    /// works — brand color, amber/green phosphor, heat-map red, ...
    Mono(crate::rgb::Rgb),
    /// 1-bit bilevel: cells at or above `threshold` luminance draw white,
    /// the rest black. Only two escape codes ever appear.
    BlackWhite {
        /// Luminance cutoff in `0..=255` (`128` is the natural default).
        threshold: u8,
    },
}

impl Default for Style {
    /// The historical behavior: full per-cell color.
    fn default() -> Self {
        Style::Full
    }
}

impl Style {
    /// Renders `grid` under this style (depth from the caller) to one
    /// `\n`-terminated-rows `String`. See [`render`].
    pub fn render(self, grid: &Grid, depth: ColorDepth) -> String {
        render(self, grid, depth)
    }

    /// Renders `grid` under this style to one `String` per row. See
    /// [`render_lines`].
    pub fn render_lines(self, grid: &Grid, depth: ColorDepth) -> Vec<String> {
        render_lines(self, grid, depth)
    }
}

/// Integer BT.601 luma (`0.299R + 0.587G + 0.114B` as
/// `(77R + 150G + 29B) >> 8`), matching the core grayscale weights to
/// within a level per channel without any float math.
#[inline]
pub(crate) fn luma(r: u8, g: u8, b: u8) -> u8 {
    ((77u32 * r as u32 + 150u32 * g as u32 + 29u32 * b as u32) >> 8) as u8
}

/// Shades `color` by `luma` (`0` = black, `255` = `color` unchanged) with
/// integer math.
#[inline]
fn shade(color: crate::rgb::Rgb, luma: u8) -> (u8, u8, u8) {
    let l = luma as u32;
    (
        (color.0 as u32 * l / 255) as u8,
        (color.1 as u32 * l / 255) as u8,
        (color.2 as u32 * l / 255) as u8,
    )
}

fn bytes_to_string(buf: Vec<u8>) -> String {
    // Safe: escapes are ASCII and glyphs are pushed as valid UTF-8.
    unsafe { String::from_utf8_unchecked(buf) }
}

/// Renders one grid row for every non-`Full` style into `buf`, appending a
/// trailing `\x1b[0m` reset (except `Plain`, which emits glyphs only).
/// State is row-local, so rows stay independent like
/// [`fast_ansi`](crate::fast_ansi)'s row resets.
fn render_row(buf: &mut Vec<u8>, row: &[Cell], style: Style, depth: ColorDepth) {
    match style {
        Style::Plain => {
            for cell in row {
                fast_ansi::push_char(buf, cell.ch);
            }
        }
        Style::Full => {
            // Byte-identical to the historical render: spaces colored too.
            let mut cur = u32::MAX;
            for cell in row {
                let (r, g, b) = (cell.color.r, cell.color.g, cell.color.b);
                let key = match depth {
                    ColorDepth::TrueColor => (r as u32) << 16 | (g as u32) << 8 | b as u32,
                    ColorDepth::Ansi256 => fast_ansi::nearest_ansi256(r, g, b) as u32,
                    ColorDepth::Ansi16 => fast_ansi::nearest_ansi16(r, g, b) as u32,
                };
                if key != cur {
                    match depth {
                        ColorDepth::TrueColor => fast_ansi::push_truecolor_escape(buf, r, g, b),
                        ColorDepth::Ansi256 => fast_ansi::push_ansi256_escape(buf, key as u8),
                        ColorDepth::Ansi16 => fast_ansi::push_ansi16_escape(buf, key as u8),
                    }
                    cur = key;
                }
                fast_ansi::push_char(buf, cell.ch);
            }
            buf.extend_from_slice(b"\x1b[0m");
        }
        Style::Gray => {
            let mut cur = u32::MAX;
            for cell in row {
                if cell.ch == ' ' {
                    if cur != u32::MAX {
                        buf.extend_from_slice(b"\x1b[0m");
                        cur = u32::MAX;
                    }
                    buf.push(b' ');
                    continue;
                }
                let v = luma(cell.color.r, cell.color.g, cell.color.b);
                let key = match depth {
                    ColorDepth::TrueColor => (v as u32) << 16 | (v as u32) << 8 | v as u32,
                    ColorDepth::Ansi256 => fast_ansi::nearest_ansi256(v, v, v) as u32,
                    ColorDepth::Ansi16 => fast_ansi::nearest_ansi16(v, v, v) as u32,
                };
                if key != cur {
                    match depth {
                        ColorDepth::TrueColor => fast_ansi::push_truecolor_escape(buf, v, v, v),
                        ColorDepth::Ansi256 => fast_ansi::push_ansi256_escape(buf, key as u8),
                        ColorDepth::Ansi16 => fast_ansi::push_ansi16_escape(buf, key as u8),
                    }
                    cur = key;
                }
                fast_ansi::push_char(buf, cell.ch);
            }
            buf.extend_from_slice(b"\x1b[0m");
        }
        Style::Mono(tint) => {
            let mut cur = u32::MAX;
            for cell in row {
                if cell.ch == ' ' {
                    if cur != u32::MAX {
                        buf.extend_from_slice(b"\x1b[0m");
                        cur = u32::MAX;
                    }
                    buf.push(b' ');
                    continue;
                }
                let v = luma(cell.color.r, cell.color.g, cell.color.b);
                let (r, g, b) = shade(tint, v);
                let key = match depth {
                    ColorDepth::TrueColor => (r as u32) << 16 | (g as u32) << 8 | b as u32,
                    ColorDepth::Ansi256 => fast_ansi::nearest_ansi256(r, g, b) as u32,
                    ColorDepth::Ansi16 => fast_ansi::nearest_ansi16(r, g, b) as u32,
                };
                if key != cur {
                    match depth {
                        ColorDepth::TrueColor => fast_ansi::push_truecolor_escape(buf, r, g, b),
                        ColorDepth::Ansi256 => fast_ansi::push_ansi256_escape(buf, key as u8),
                        ColorDepth::Ansi16 => fast_ansi::push_ansi16_escape(buf, key as u8),
                    }
                    cur = key;
                }
                fast_ansi::push_char(buf, cell.ch);
            }
            buf.extend_from_slice(b"\x1b[0m");
        }
        Style::BlackWhite { threshold } => {
            let mut cur_white: Option<bool> = None;
            for cell in row {
                if cell.ch == ' ' {
                    if cur_white.take().is_some() {
                        buf.extend_from_slice(b"\x1b[0m");
                    }
                    buf.push(b' ');
                    continue;
                }
                let white = luma(cell.color.r, cell.color.g, cell.color.b) >= threshold;
                if cur_white != Some(white) {
                    if cur_white.is_some() {
                        buf.extend_from_slice(b"\x1b[0m");
                    }
                    buf.extend_from_slice(if white { b"\x1b[97m" } else { b"\x1b[30m" });
                    cur_white = Some(white);
                }
                fast_ansi::push_char(buf, cell.ch);
            }
            buf.extend_from_slice(b"\x1b[0m");
        }
    }
}

/// Renders `grid` under `style` (depth from the caller's
/// [`ColorDepth`]) to one `\n`-terminated-rows `String`.
pub fn render(style: Style, grid: &Grid, depth: ColorDepth) -> String {
    let w = grid.width() as usize;
    let h = grid.height() as usize;
    if w == 0 || h == 0 {
        return String::new();
    }
    if style == Style::Plain {
        return render_plain(grid);
    }
    let cells = grid.as_slice();
    let per_cell = match (style, depth) {
        (Style::Full, ColorDepth::TrueColor) => 20,
        (Style::Full, ColorDepth::Ansi256) => 13,
        (Style::Full, ColorDepth::Ansi16) => 7,
        (_, ColorDepth::TrueColor) => 20,
        (_, ColorDepth::Ansi256) => 13,
        _ => 7,
    };
    let mut buf = Vec::with_capacity(h * (w * per_cell + 5));
    for row in cells.chunks_exact(w) {
        render_row(&mut buf, row, style, depth);
        buf.push(b'\n');
    }
    bytes_to_string(buf)
}

/// Row-direct variant of [`render`]: one `String` per grid row, each
/// keeping its trailing `\x1b[0m` (`Plain` rows have no reset).
pub fn render_lines(style: Style, grid: &Grid, depth: ColorDepth) -> Vec<String> {
    let w = grid.width() as usize;
    let h = grid.height() as usize;
    if w == 0 || h == 0 {
        return Vec::new();
    }
    if style == Style::Plain {
        return grid
            .rows()
            .map(|row| row.iter().map(|cell| cell.ch).collect())
            .collect();
    }
    let per_cell = match (style, depth) {
        (Style::Full, ColorDepth::TrueColor) => 20,
        (Style::Full, ColorDepth::Ansi256) => 13,
        (Style::Full, ColorDepth::Ansi16) => 7,
        (_, ColorDepth::TrueColor) => 20,
        (_, ColorDepth::Ansi256) => 13,
        _ => 7,
    };
    let mut lines = Vec::with_capacity(h);
    for row in grid.as_slice().chunks_exact(w) {
        let mut buf = Vec::with_capacity(w * per_cell + 4);
        render_row(&mut buf, row, style, depth);
        lines.push(bytes_to_string(buf));
    }
    lines
}

/// Plain basic-ASCII render: glyphs only, no escapes.
fn render_plain(grid: &Grid) -> String {
    let mut out = String::with_capacity((grid.width() as usize + 1) * grid.height() as usize);
    for row in grid.rows() {
        for cell in row {
            out.push(cell.ch);
        }
        out.push('\n');
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use iascii::config::{ConfigBuilder as AsciiConfigBuilder, OutputSizing};
    use iascii::convert::convert_image;

    fn test_grid() -> Grid {
        let cfg = AsciiConfigBuilder::new()
            .output_sizing(OutputSizing::Explicit {
                width: 6,
                height: 4,
            })
            .build()
            .unwrap();
        // Colorful pixels so Full/Gray/Mono/BW all diverge.
        let mut pix = Vec::with_capacity(6 * 4 * 3);
        for y in 0..4u32 {
            for x in 0..6u32 {
                pix.push((x * 51) as u8);
                pix.push((y * 85) as u8);
                pix.push(((x + y) * 36) as u8);
            }
        }
        convert_image(6, 4, &pix, &cfg).unwrap()
    }

    #[test]
    fn plain_has_no_escapes_and_matches_plain_string() {
        let grid = test_grid();
        let out = render(Style::Plain, &grid, ColorDepth::TrueColor);
        assert!(!out.contains('\x1b'));
        assert_eq!(out, crate::render::plain_string(&grid));
        assert_eq!(out.lines().count(), 4);
    }

    #[test]
    fn full_matches_the_historical_renderer() {
        let grid = test_grid();
        for depth in [
            ColorDepth::TrueColor,
            ColorDepth::Ansi256,
            ColorDepth::Ansi16,
        ] {
            assert_eq!(
                render(Style::Full, &grid, depth),
                iascii::render::render_ansi(&grid, depth),
                "Full must stay byte-identical at {depth:?}"
            );
        }
    }

    #[test]
    fn gray_truecolor_uses_equal_channels_only() {
        let grid = test_grid();
        let out = render(Style::Gray, &grid, ColorDepth::TrueColor);
        for line in out.lines() {
            // Every 38;2;r;g;bm triple must have r == g == b.
            let mut rest = line;
            while let Some(start) = rest.find("38;2;") {
                let esc = &rest[start + 5..];
                let end = esc.find('m').unwrap();
                let parts: Vec<&str> = esc[..end].split(';').collect();
                assert_eq!(parts.len(), 3);
                assert_eq!(parts[0], parts[1]);
                assert_eq!(parts[1], parts[2]);
                rest = &esc[end..];
            }
        }
        // But it must still differ from plain (color is present).
        assert!(out.contains('\x1b'));
    }

    #[test]
    fn mono_shades_only_the_chosen_hue() {
        let grid = test_grid();
        // Pure-red tint: every emitted color must have g == b == 0.
        let out = render(
            Style::Mono(crate::rgb::Rgb::new(255, 0, 0)),
            &grid,
            ColorDepth::TrueColor,
        );
        assert!(out.contains('\x1b'));
        let mut rest = out.as_str();
        let mut seen = 0;
        while let Some(start) = rest.find("38;2;") {
            let esc = &rest[start + 5..];
            let end = esc.find('m').unwrap();
            let parts: Vec<&str> = esc[..end].split(';').collect();
            assert_eq!(parts.len(), 3);
            assert_eq!(parts[1], "0");
            assert_eq!(parts[2], "0");
            seen += 1;
            rest = &esc[end..];
        }
        assert!(seen > 0, "mono render should emit its color");
    }

    #[test]
    fn black_white_uses_only_two_codes() {
        let grid = test_grid();
        let out = render(
            Style::BlackWhite { threshold: 128 },
            &grid,
            ColorDepth::Ansi16,
        );
        assert!(out.contains('\x1b'));
        assert!(!out.contains("38;2;"), "no truecolor escapes in BW mode");
        assert!(!out.contains("38;5;"), "no 256-color escapes in BW mode");
        for line in out.lines() {
            let mut rest = line;
            while let Some(start) = rest.find("\x1b[") {
                let esc = &rest[start + 2..];
                let end = esc.find('m').unwrap();
                let code = &esc[..end];
                assert!(
                    code == "30" || code == "97" || code == "0",
                    "unexpected SGR code {code:?}"
                );
                rest = &esc[end..];
            }
        }
    }

    #[test]
    fn black_white_threshold_picks_sides() {
        // threshold 0: everything is white; 255: only pure-white cells.
        let grid = test_grid();
        let all_white = render(
            Style::BlackWhite { threshold: 0 },
            &grid,
            ColorDepth::TrueColor,
        );
        assert!(!all_white.contains("\x1b[30m"));
        assert!(all_white.contains("\x1b[97m"));
    }

    #[test]
    fn styled_spaces_stay_bare() {
        let grid = test_grid();
        for style in [
            Style::Gray,
            Style::Mono(crate::rgb::Rgb::GREEN),
            Style::BlackWhite { threshold: 128 },
        ] {
            let out = render(style, &grid, ColorDepth::TrueColor);
            assert!(
                !out.contains("m \x1b[0m") && !out.contains("\x1b[0m \x1b["),
                "spaces must not be wrapped in escapes for {style:?}"
            );
        }
    }

    #[test]
    fn lines_variant_matches_split_render() {
        let grid = test_grid();
        for style in [
            Style::Plain,
            Style::Full,
            Style::Gray,
            Style::Mono(crate::rgb::Rgb::CYAN),
            Style::BlackWhite { threshold: 128 },
        ] {
            let joined = render(style, &grid, ColorDepth::TrueColor);
            let expected: Vec<String> = joined.lines().map(str::to_owned).collect();
            assert_eq!(
                render_lines(style, &grid, ColorDepth::TrueColor),
                expected,
                "lines mismatch for {style:?}"
            );
        }
    }

    #[test]
    fn luma_matches_bt601_float() {
        for (r, g, b) in [(0, 0, 0), (255, 255, 255), (200, 50, 50), (20, 200, 90)] {
            let expected = (0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32).round() as u8;
            let got = luma(r, g, b);
            assert!(
                (got as i16 - expected as i16).abs() <= 1,
                "luma({r},{g},{b}) = {got}, float BT.601 = {expected}"
            );
        }
    }
}