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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
//! Efficient ASCII frame building and presentation: a flat [`Canvas`] of
//! colored [`Cell`]s with damage tracking, multi-frame [`Sprite`]s, and
//! three present paths (full, incremental, patch-only).
//!
//! This is the rendering layer game developers reach for, but nothing here
//! assumes a game: a dashboard, a terminal monitor, a video compositor, or
//! a static screen all drive the same API.
//!
//! # Techniques
//!
//! The design applies the standard realtime-rendering toolbox to a
//! character grid:
//!
//! - **Flat storage.** One `Vec<Cell>`, no per-cell allocation;
//!   `(0, 0)` is the top-left cell and every draw clips.
//! - **Damage tracking (dirty rows).** Writes mark their row dirty; a
//!   render visits only dirty rows. See [`Canvas::dirty_rows`] /
//!   [`Canvas::dirty_fraction`].
//! - **Back buffer + snapshot dedupe.** Rows are rendered into a reusable
//!   byte cache, and a `clear()` + identical redraw compares equal to the
//!   snapshot, so a static frame re-renders *nothing*
//!   ([`Canvas::last_recomputed_rows`]).
//! - **Zero-allocation frame paths.** [`Canvas::write_into`] and
//!   [`Canvas::write_dirty_into`] append into a caller-owned `String`, so a
//!   frame loop allocates once, not once per frame.
//! - **Cell-space patches with span merging.** [`Canvas::present_dirty_into`]
//!   emits cursor-addressed updates straight from the cell snapshot — no
//!   string diffing at all — merging changed spans separated by a few
//!   unchanged cells, because one cursor move plus a color escape costs more
//!   bytes than rewriting a short gap.
//! - **Compositing.** Sprites and parsed ANSI frames (video frames,
//!   dithered hit-effects) blit onto the canvas with a transparent glyph,
//!   and scale with nearest-neighbor sampling for perspective.
//!
//! A typical frame loop is therefore:
//!
//! ```rust,no_run
//! use eger::canvas::{screen, Canvas};
//!
//! let mut canvas = Canvas::new(80, 24);
//! let mut frame = String::new();
//! print!("{}{}", screen::ENTER_ALT, screen::HIDE_CURSOR);
//! loop {
//!     // ... update state, canvas.clear(), draw ...
//!     frame.clear();
//!     if canvas.present_dirty_into(&mut frame) {
//!         print!("{frame}");
//!         // flush stdout here
//!     }
//! }
//! # #[allow(unreachable_code)] { print!("{}", screen::SHOW_CURSOR); }
//! ```

#[cfg(feature = "colorize")]
use crate::colorize::{animation_color, PixelAnimation};
use crate::rgb::Rgb;
use std::fmt::Write as _;

// ---------------------------------------------------------------------------
// Cells
// ---------------------------------------------------------------------------

/// One drawable cell: a glyph plus an optional foreground color (`None`
/// renders as a bare character with no escape — the fast path for
/// walls, floors, and HUD chrome).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cell {
    pub ch: char,
    pub color: Option<Rgb>,
}

impl Cell {
    pub const fn new(ch: char, color: Option<Rgb>) -> Self {
        Self { ch, color }
    }
    pub const fn blank() -> Self {
        Self {
            ch: ' ',
            color: None,
        }
    }
}

// ---------------------------------------------------------------------------
// Canvas
// ---------------------------------------------------------------------------

/// A drawable character grid in *screen* space: `(0, 0)` is the top-left
/// cell, `x` grows right, `y` grows down. All drawing operations clip to
/// the canvas, so world/camera math can happily go out of bounds.
///
/// The buffer is one flat `Vec<Cell>` (cache-friendly, no per-cell
/// allocation); each row is emitted as run-merged TrueColor escapes into a
/// single byte buffer, so presenting a full 4K-grid canvas costs one
/// allocation, not one per cell.
///
/// The canvas also tracks *dirty rows* so it can emit only the rows that
/// changed since the last render — the incremental-generation primitive that
/// keeps frame cost proportional to what actually moved, not to canvas size.
/// See [`Canvas::mark_row_dirty`], `Canvas::render_cache`, and
/// [`Canvas::to_string_dirty`].
#[derive(Debug, Clone)]
pub struct Canvas {
    width: u32,
    height: u32,
    cells: Vec<Cell>,
    /// Per-row dirty flag: `true` when any cell in that row has been written
    /// since the last full render. `clear()` marks every row dirty.
    row_dirty: Vec<bool>,
    /// Cached rendered output from the last render: one `Vec<u8>` per row
    /// (run-merged escapes included). Rows whose dirty flag is false are
    /// byte-copied from here instead of re-rendered. `None` before the first
    /// dirty render (nothing cached yet).
    render_cache: Option<Vec<Vec<u8>>>,
    /// The cells as of the last rendered row — the snapshot a dirty row is
    /// compared against, so a `clear()` + identical-redraw frame re-renders
    /// nothing even though every row was written.
    rendered: Vec<Cell>,
    /// Rows actually re-rendered (vs. byte-copied from the cache) by the
    /// last render.
    last_recomputed: usize,
}

impl Canvas {
    /// Blank canvas of `width x height` cells (every row starts dirty, so
    /// the first render is a full one).
    pub fn new(width: u32, height: u32) -> Self {
        Self {
            width,
            height,
            cells: vec![Cell::blank(); width as usize * height as usize],
            row_dirty: vec![true; height as usize],
            render_cache: None,
            rendered: vec![Cell::blank(); width as usize * height as usize],
            last_recomputed: 0,
        }
    }

    pub fn width(&self) -> u32 {
        self.width
    }
    pub fn height(&self) -> u32 {
        self.height
    }

    #[inline]
    fn index(&self, x: i32, y: i32) -> Option<usize> {
        if x < 0 || y < 0 || x >= self.width as i32 || y >= self.height as i32 {
            return None;
        }
        Some(y as usize * self.width as usize + x as usize)
    }

    /// Marks row `y` dirty so it gets re-rendered on the next
    /// [`Canvas::to_string_dirty`]. Out-of-range rows are ignored; writes
    /// through [`Canvas::put`] call this automatically.
    #[inline]
    pub fn mark_row_dirty(&mut self, y: i32) {
        if y >= 0 && (y as usize) < self.row_dirty.len() {
            self.row_dirty[y as usize] = true;
        }
    }

    /// Number of rows currently marked dirty.
    pub fn dirty_rows(&self) -> usize {
        self.row_dirty.iter().filter(|&&d| d).count()
    }

    /// Rows actually re-rendered by the last [`Canvas::to_string_dirty`]
    /// (the rest were byte-copied from the cache). `0` right after a render
    /// that changed nothing — the number to watch when tuning a game loop.
    pub fn last_recomputed_rows(&self) -> usize {
        self.last_recomputed
    }

    /// Fraction of rows currently dirty, `0.0..=1.0` — cheap telemetry for
    /// deciding whether incremental rendering is worth it this frame.
    pub fn dirty_fraction(&self) -> f32 {
        if self.row_dirty.is_empty() {
            return 0.0;
        }
        self.dirty_rows() as f32 / self.row_dirty.len() as f32
    }

    /// Drops the render cache and marks every row dirty, forcing the next
    /// [`Canvas::to_string_dirty`] to emit a full frame. Necessary after
    /// external state the canvas can't see changes (e.g. the terminal was
    /// resized or another writer touched the screen).
    pub fn reset_render_cache(&mut self) {
        self.render_cache = None;
        self.row_dirty.iter_mut().for_each(|d| *d = true);
    }

    /// Reads a cell; `None` when out of bounds.
    pub fn get(&self, x: i32, y: i32) -> Option<Cell> {
        self.index(x, y).map(|i| self.cells[i])
    }

    /// Writes one cell; silently clipped when out of bounds. Marks the row
    /// dirty for [`Canvas::to_string_dirty`].
    pub fn put(&mut self, x: i32, y: i32, ch: char, color: Option<Rgb>) {
        if let Some(i) = self.index(x, y) {
            self.cells[i] = Cell::new(ch, color);
            self.row_dirty[y as usize] = true;
        }
    }

    /// Fills every cell with blanks (marks every row dirty — if the canvas
    /// was already blank, [`Canvas::to_string_dirty`] still notices via its
    /// cell snapshot and re-renders nothing).
    pub fn clear(&mut self) {
        self.cells.fill(Cell::blank());
        self.row_dirty.iter_mut().for_each(|d| *d = true);
    }

    /// Fills every cell with the same glyph/color (same dirty semantics as
    /// [`Canvas::clear`]).
    pub fn fill(&mut self, ch: char, color: Option<Rgb>) {
        self.cells.fill(Cell::new(ch, color));
        self.row_dirty.iter_mut().for_each(|d| *d = true);
    }

    /// Draws text left-to-right from `(x, y)`; clipped horizontally and
    /// vertically. One color for the whole run; spaces are drawn as bare
    /// blanks (they still advance the cursor).
    pub fn text(&mut self, x: i32, y: i32, s: &str, color: Option<Rgb>) {
        for (i, ch) in s.chars().enumerate() {
            self.put(x + i as i32, y, ch, color);
        }
    }

    /// Draws text centered on row `y` across the full canvas width.
    pub fn text_centered(&mut self, y: i32, s: &str, color: Option<Rgb>) {
        let len = s.chars().count() as i32;
        self.text((self.width as i32 - len) / 2, y, s, color);
    }

    /// Bresenham line, clipped per cell.
    pub fn line(&mut self, x0: i32, y0: i32, x1: i32, y1: i32, ch: char, color: Option<Rgb>) {
        let (mut x, mut y) = (x0, y0);
        let dx = (x1 - x0).abs();
        let dy = -(y1 - y0).abs();
        let sx = if x0 < x1 { 1 } else { -1 };
        let sy = if y0 < y1 { 1 } else { -1 };
        loop {
            self.put(x, y, ch, color);
            if x == x1 && y == y1 {
                break;
            }
            let e2 = 2 * (dx + dy);
            if e2 >= dy {
                x += sx;
            }
            if e2 <= dx {
                y += sy;
            }
        }
    }

    /// Filled rectangle, clipped.
    pub fn rect_fill(&mut self, x: i32, y: i32, w: u32, h: u32, ch: char, color: Option<Rgb>) {
        for dy in 0..h as i32 {
            for dx in 0..w as i32 {
                self.put(x + dx, y + dy, ch, color);
            }
        }
    }

    /// Rectangle outline (`+` corners, `-` top/bottom, `|` sides), clipped.
    pub fn rect_outline(&mut self, x: i32, y: i32, w: u32, h: u32, color: Option<Rgb>) {
        if w == 0 || h == 0 {
            return;
        }
        let (w, h) = (w as i32, h as i32);
        for dx in 0..w {
            let (top, bottom) = if dx == 0 || dx == w - 1 {
                ('+', '+')
            } else {
                ('-', '-')
            };
            self.put(x + dx, y, top, color);
            if h > 1 {
                self.put(x + dx, y + h - 1, bottom, color);
            }
        }
        for dy in 1..h - 1 {
            self.put(x, y + dy, '|', color);
            if w > 1 {
                self.put(x + w - 1, y + dy, '|', color);
            }
        }
    }

    /// Framed panel with an optional title centered on the top border —
    /// dialog boxes, menus, HUD frames.
    pub fn panel(
        &mut self,
        x: i32,
        y: i32,
        w: u32,
        h: u32,
        title: Option<&str>,
        color: Option<Rgb>,
    ) {
        self.rect_outline(x, y, w, h, color);
        if let Some(title) = title {
            if w as usize > title.chars().count() + 2 {
                self.text(x + 2, y, title, color);
            }
        }
    }

    /// Horizontal progress/health/mana bar: `frac` in `[0.0, 1.0]` of `w`
    /// cells drawn with `full_ch`, the rest with `empty_ch`.
    #[allow(clippy::too_many_arguments)] // flat positional drawing API, no options struct by design
    pub fn bar(
        &mut self,
        x: i32,
        y: i32,
        w: u32,
        frac: f32,
        full_ch: char,
        empty_ch: char,
        color: Option<Rgb>,
    ) {
        let frac = frac.clamp(0.0, 1.0);
        let filled = (w as f32 * frac).round() as u32;
        for dx in 0..w {
            let ch = if dx < filled { full_ch } else { empty_ch };
            self.put(x + dx as i32, y, ch, color);
        }
    }

    /// Circle outline (`fill == false`) or filled disc (`fill == true`)
    /// around `(cx, cy)` with radius `r`, clipped.
    pub fn circle(&mut self, cx: i32, cy: i32, r: u32, ch: char, color: Option<Rgb>, fill: bool) {
        let r = r as i32;
        for dy in -r..=r {
            for dx in -r..=r {
                let d = ((dx * dx + dy * dy) as f32).sqrt();
                let on = if fill {
                    d <= r as f32 + 0.5
                } else {
                    (d - r as f32).abs() < 0.5
                };
                if on {
                    self.put(cx + dx, cy + dy, ch, color);
                }
            }
        }
    }

    /// Blits one text frame with its top-left corner at `(x, y)`, clipped.
    /// Cells holding `transparent` are skipped (whatever is underneath
    /// shows through — the standard sprite compositing rule); every other
    /// cell is painted with `color`.
    pub fn blit<S: AsRef<str>>(
        &mut self,
        frame: &[S],
        x: i32,
        y: i32,
        color: Option<Rgb>,
        transparent: char,
    ) {
        for (dy, row) in frame.iter().enumerate() {
            for (dx, ch) in row.as_ref().chars().enumerate() {
                if ch == transparent {
                    continue;
                }
                self.put(x + dx as i32, y + dy as i32, ch, color);
            }
        }
    }

    /// [`Canvas::blit`] for a [`Sprite`]: picks the frame for `tick` first.
    ///
    /// `color` overrides every inked cell when `Some` — the hit-flash /
    /// tint primitive (blit the same sprite with `Some(WHITE)` for a few
    /// ticks after a strike). Pass `None` to keep each cell's own color
    /// (what [`Sprite::from_grid`] captured from the picture).
    pub fn blit_sprite(
        &mut self,
        sprite: &Sprite,
        tick: u64,
        x: i32,
        y: i32,
        color: Option<Rgb>,
        transparent: char,
    ) {
        self.blit_cells(sprite.frame(tick), x, y, color, transparent);
    }

    /// Blits pre-colored cells with the same compositing rule as
    /// [`Canvas::blit`]. `color` overrides every inked cell when `Some`
    /// (see [`Canvas::blit_sprite`]); `None` keeps each cell's own color.
    pub fn blit_cells(
        &mut self,
        rows: &[Vec<Cell>],
        x: i32,
        y: i32,
        color: Option<Rgb>,
        transparent: char,
    ) {
        for (dy, row) in rows.iter().enumerate() {
            for (dx, cell) in row.iter().enumerate() {
                if cell.ch == transparent {
                    continue;
                }
                self.put(x + dx as i32, y + dy as i32, cell.ch, color.or(cell.color));
            }
        }
    }

    /// Nearest-neighbor scaled blit of pre-colored cells into a
    /// `w x h` box at `(x, y)` — the perspective primitive: draw the same
    /// sprite bigger as it approaches (`game::perspective_scale` gives the
    /// factor), or squash-and-stretch it during a jump (`game::jump_arc`
    /// gives the height curve). `color`/
    /// `transparent` behave like [`Canvas::blit_cells`].
    #[allow(clippy::too_many_arguments)] // uniform with `blit_sprite`'s shape
    pub fn blit_cells_scaled(
        &mut self,
        rows: &[Vec<Cell>],
        x: i32,
        y: i32,
        w: u32,
        h: u32,
        color: Option<Rgb>,
        transparent: char,
    ) {
        let (sw, sh) = (sprite_cells_width(rows) as f32, rows.len() as f32);
        if sw == 0.0 || sh == 0.0 || w == 0 || h == 0 {
            return;
        }
        for dy in 0..h as i32 {
            for dx in 0..w as i32 {
                let sx = ((dx as f32 / w as f32) * sw) as usize;
                let sy = ((dy as f32 / h as f32) * sh) as usize;
                let Some(row) = rows.get(sy) else {
                    continue;
                };
                let Some(cell) = row.get(sx) else {
                    continue;
                };
                if cell.ch == transparent {
                    continue;
                }
                self.put(x + dx, y + dy, cell.ch, color.or(cell.color));
            }
        }
    }

    /// [`Canvas::blit_cells_scaled`] for a [`Sprite`].
    #[allow(clippy::too_many_arguments)] // uniform with `blit_sprite`'s shape
    pub fn blit_sprite_scaled(
        &mut self,
        sprite: &Sprite,
        tick: u64,
        x: i32,
        y: i32,
        w: u32,
        h: u32,
        color: Option<Rgb>,
        transparent: char,
    ) {
        self.blit_cells_scaled(sprite.frame(tick), x, y, w, h, color, transparent);
    }

    /// Blits one already-rendered ANSI frame (a video frame string, a
    /// dithered hit-effect, a [`Style`](crate::style::Style)-rendered
    /// picture — anything this crate renders) with its top-left corner at
    /// `(x, y)`, clipped. SGR color escapes (`38;2;r;g;b`, `38;5;n`,
    /// `30-37`/`90-97`, `0` reset) are parsed back into cell colors;
    /// anything else (bold, cursor moves, OSC, ...) is ignored. Cells
    /// holding `transparent` are skipped. This is the decoupled bridge
    /// between the render pipelines and the canvas: no shared types,
    /// just strings.
    pub fn blit_ansi(&mut self, frame: &str, x: i32, y: i32, transparent: char) {
        for (dy, row) in parse_ansi_rows(frame).iter().enumerate() {
            for (dx, cell) in row.iter().enumerate() {
                if cell.ch == transparent {
                    continue;
                }
                self.put(x + dx as i32, y + dy as i32, cell.ch, cell.color);
            }
        }
    }

    /// Recolors every non-blank cell under `animation` at time `tick`,
    /// evaluated in canvas-local coordinates — one call per frame turns a
    /// static scene into a plasma/rainbow/wave animation with no extra
    /// allocations beyond the color pass itself.
    ///
    /// Requires the `colorize` feature (for the animation types).
    #[cfg(feature = "colorize")]
    pub fn apply_animation(&mut self, animation: &PixelAnimation, tick: u64) {
        let (w, h) = (self.width as usize, self.height as usize);
        if w == 0 {
            return;
        }
        for y in 0..h {
            let start = y * w;
            let mut changed = false;
            for (x, cell) in self.cells[start..start + w].iter_mut().enumerate() {
                if cell.ch == ' ' {
                    continue;
                }
                let color = Some(animation_color(animation, x, y, tick, cell.ch, w, h));
                if cell.color != color {
                    cell.color = color;
                    changed = true;
                }
            }
            if changed {
                self.row_dirty[y] = true;
            }
        }
    }

    /// Renders one row of cells into `buf`: run-merged TrueColor escapes,
    /// bare blanks, `\x1b[0m` at the end if the row ends colored (no
    /// trailing newline — callers add those). Rows are rendered
    /// independently (each starts with no active color), which is what lets
    /// the render cache reuse them byte-for-byte.
    fn render_row(row: &[Cell], buf: &mut Vec<u8>) {
        let mut run: Option<Rgb> = None;
        for cell in row {
            match cell.color {
                None => {
                    if run.take().is_some() {
                        buf.extend_from_slice(b"\x1b[0m");
                    }
                    crate::fast_ansi::push_char(buf, cell.ch);
                }
                Some(c) => {
                    if run != Some(c) {
                        if run.is_some() {
                            buf.extend_from_slice(b"\x1b[0m");
                        }
                        crate::fast_ansi::push_truecolor_escape(buf, c.0, c.1, c.2);
                        run = Some(c);
                    }
                    crate::fast_ansi::push_char(buf, cell.ch);
                }
            }
        }
        if run.is_some() {
            buf.extend_from_slice(b"\x1b[0m");
        }
    }

    /// Appends the full frame (`\n`-joined rows) to `out`, re-rendering
    /// every row — the zero-allocation counterpart of [`Canvas::to_string`]:
    /// keep one `String` for the life of the loop and
    /// `frame.clear(); canvas.write_into(&mut frame);`.
    ///
    /// See [`Canvas::write_dirty_into`] for the incremental version and
    /// [`Canvas::present_dirty_into`] for emitting only terminal patches.
    pub fn write_into(&self, out: &mut String) {
        let (w, h) = (self.width as usize, self.height as usize);
        if self.cells.is_empty() {
            return;
        }
        out.reserve(h * (w * 8 + 5));
        // Safe: only ASCII escapes and valid UTF-8 glyphs are appended.
        let buf = unsafe { out.as_mut_vec() };
        for y in 0..h {
            Self::render_row(&self.cells[y * w..y * w + w], buf);
            buf.push(b'\n');
        }
    }

    /// Appends the full frame to `out`, but re-renders only the rows whose
    /// cells actually changed since the last render; every other row is
    /// byte-copied from the render cache. Appended output is byte-identical
    /// to [`Canvas::write_into`], and the cost is proportional to what
    /// moved, not to canvas size.
    ///
    /// First call (or after [`Canvas::reset_render_cache`]) renders the
    /// whole frame; a `clear()` + redraw-the-same-scene frame re-renders
    /// only rows whose *final* cells differ from the last snapshot, so
    /// static HUD/panel rows cost a comparison, not a render. Consumes the
    /// dirty flags (see [`Canvas::last_recomputed_rows`]).
    pub fn write_dirty_into(&mut self, out: &mut String) {
        let (w, h) = (self.width as usize, self.height as usize);
        if self.cells.is_empty() {
            self.render_cache = None;
            self.row_dirty.iter_mut().for_each(|d| *d = true);
            self.last_recomputed = 0;
            return;
        }
        let mut cache = self
            .render_cache
            .take()
            .unwrap_or_else(|| vec![Vec::new(); h]);
        out.reserve(h * (w * 8 + 5));
        let mut recomputed = 0usize;
        for (y, cached) in cache.iter_mut().enumerate() {
            let start = y * w;
            let row = &self.cells[start..start + w];
            // Untouched rows can't differ; touched rows are re-rendered
            // only if their final content beats the rendered snapshot.
            let changed = self.row_dirty[y] && self.rendered[start..start + w] != *row;
            if changed || cached.is_empty() {
                cached.clear();
                Self::render_row(row, cached);
                self.rendered[start..start + w].copy_from_slice(row);
                recomputed += 1;
            }
            // Safe: cache rows hold only ASCII escapes and UTF-8 glyphs.
            out.push_str(unsafe { std::str::from_utf8_unchecked(cached) });
            out.push('\n');
        }
        self.render_cache = Some(cache);
        self.row_dirty.iter_mut().for_each(|d| *d = false);
        self.last_recomputed = recomputed;
    }

    /// Emits the minimal cursor-addressed updates that bring a terminal
    /// showing the last rendered frame up to date, and reports whether
    /// anything was written. Damage is located on the canvas's own cell
    /// snapshot — nothing is string-diffed — so only changed rows are
    /// visited and, within a row, only changed spans (merged across short
    /// gaps) are re-sent with fresh escapes.
    ///
    /// The first call (right after construction or
    /// [`Canvas::reset_render_cache`]) paints every row in full, absolutely
    /// addressed and newline-free; the caller just writes the produced
    /// bytes. Returns `false` when the frame is identical to the last
    /// present, so the caller can skip the terminal write entirely.
    ///
    /// This and [`Canvas::write_dirty_into`] are alternative present paths —
    /// both consume the dirty flags, so use one per frame:
    ///
    /// ```rust,no_run
    /// # use eger::canvas::Canvas;
    /// # let mut canvas = Canvas::new(8, 2);
    /// # let mut frame = String::new();
    /// frame.clear();
    /// if canvas.present_dirty_into(&mut frame) {
    ///     print!("{frame}"); // only what changed
    /// }
    /// ```
    pub fn present_dirty_into(&mut self, out: &mut String) -> bool {
        let (w, h) = (self.width as usize, self.height as usize);
        if self.cells.is_empty() {
            self.render_cache = None;
            self.row_dirty.iter_mut().for_each(|d| *d = true);
            self.last_recomputed = 0;
            return false;
        }
        let first_paint = self.render_cache.is_none();
        let mut cache = self
            .render_cache
            .take()
            .unwrap_or_else(|| vec![Vec::new(); h]);
        let mut prev_cells: Vec<crate::fast_ansi::ParsedCell> = Vec::new();
        let mut next_cells: Vec<crate::fast_ansi::ParsedCell> = Vec::new();
        let mut recomputed = 0usize;
        let mut emitted = false;
        for (y, cached) in cache.iter_mut().enumerate() {
            let start = y * w;
            let row = &self.cells[start..start + w];
            let changed = self.row_dirty[y] && self.rendered[start..start + w] != *row;
            if !(changed || cached.is_empty()) {
                continue;
            }
            // Keep the row cache coherent for a later full-frame write.
            cached.clear();
            Self::render_row(row, cached);
            recomputed += 1;
            if first_paint {
                // Absolute per-row addressing: no newlines, no clear.
                let _ = write!(out, "\x1b[{};1H", y + 1);
                // Safe: cache rows hold only ASCII escapes and UTF-8 glyphs.
                out.push_str(unsafe { std::str::from_utf8_unchecked(cached.as_slice()) });
                emitted = true;
            } else {
                prev_cells.clear();
                next_cells.clear();
                for (old, new) in self.rendered[start..start + w].iter().zip(row) {
                    prev_cells.push((old.ch, old.color));
                    next_cells.push((new.ch, new.color));
                }
                let before = out.len();
                crate::fast_ansi::diff_cells_into(out, y + 1, &prev_cells, &next_cells);
                emitted |= out.len() != before;
            }
            self.rendered[start..start + w].copy_from_slice(row);
        }
        self.render_cache = Some(cache);
        self.row_dirty.iter_mut().for_each(|d| *d = false);
        self.last_recomputed = recomputed;
        emitted
    }

    /// Renders the canvas to one `\n`-joined ANSI string (TrueColor cells,
    /// run-merged escapes, bare blanks). Pure text when every cell is
    /// uncolored. Always re-renders every row — see
    /// [`Canvas::to_string_dirty`] for the incremental version and
    /// [`Canvas::write_into`] to avoid the allocation.
    #[allow(clippy::inherent_to_string)] // intentional: fast byte-buffer path, no fmt machinery
    pub fn to_string(&self) -> String {
        let mut out = String::new();
        self.write_into(&mut out);
        out
    }

    /// Incremental counterpart to [`Canvas::to_string`]: reuses the render
    /// cache for rows whose cells didn't change and re-renders the rest.
    /// Byte-identical to `to_string()`, but proportional to what moved. See
    /// [`Canvas::write_dirty_into`] for the zero-allocation form.
    pub fn to_string_dirty(&mut self) -> String {
        let mut out = String::new();
        self.write_dirty_into(&mut out);
        out
    }

    /// Renders glyphs only — no escapes at all. Ideal for tests, logs,
    /// bots, and backends that do their own coloring.
    pub fn to_plain(&self) -> String {
        let (w, h) = (self.width as usize, self.height as usize);
        if self.cells.is_empty() {
            return String::new();
        }
        let mut out = String::with_capacity(h * (w + 1));
        for (i, cell) in self.cells.iter().enumerate() {
            if i > 0 && i % w == 0 {
                out.push('\n');
            }
            out.push(cell.ch);
        }
        out.push('\n');
        out
    }
}

// ---------------------------------------------------------------------------
// Sprites
// ---------------------------------------------------------------------------

/// Width of the longest row in pre-colored `rows`, in chars.
fn sprite_cells_width(rows: &[Vec<Cell>]) -> usize {
    rows.iter().map(|r| r.len()).max().unwrap_or(0)
}

/// Parses one rendered ANSI frame back into colored rows (see
/// [`Canvas::blit_ansi`]); `"\n"` separates rows. The inverse of
/// [`Canvas::to_string`]-style rendering — lossy only for styles the canvas
/// can't represent (bold is dropped).
fn parse_ansi_rows(frame: &str) -> Vec<Vec<Cell>> {
    let mut rows = Vec::new();
    let mut cells: Vec<crate::fast_ansi::ParsedCell> = Vec::new();
    for line in frame.split('\n') {
        crate::fast_ansi::parse_sgr_cells(line, &mut cells);
        rows.push(
            cells
                .iter()
                .map(|&(ch, color)| Cell::new(ch, color))
                .collect(),
        );
    }
    // A trailing '\n' (every renderer emits one) would add a phantom empty
    // row — drop it so a 20-row frame parses back to 20 rows.
    if rows.last().is_some_and(|r: &Vec<Cell>| r.is_empty()) {
        rows.pop();
    }
    rows
}

/// ASCII art with one or more frames. Frames are full-color character
/// cells — make them from plain text ([`Sprite::from_lines`], tinted at
/// blit time), from a converted picture ([`Sprite::from_grid`], keeping
/// the picture's own per-cell colors), or parsed back out of any rendered
/// frame ([`Canvas::blit_ansi`]). [`Sprite::frame`] cycles frames by tick
/// for walk cycles, flicker, water, and other full-animation effects.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sprite {
    frames: Vec<Vec<Vec<Cell>>>,
}

impl Sprite {
    /// Single-frame sprite from plain text rows (all cells uncolored —
    /// supply the tint at blit time).
    pub fn from_lines<S: AsRef<str>>(lines: &[S]) -> Self {
        Self {
            frames: vec![lines
                .iter()
                .map(|l| l.as_ref().chars().map(|ch| Cell::new(ch, None)).collect())
                .collect()],
        }
    }

    /// Single-frame sprite from a converted picture grid: glyphs plus the
    /// grid's own per-cell colors. Blit with `color: None` to keep the
    /// picture's colors, or `Some(tint)` for a flat hit-flash/tint.
    pub fn from_grid(grid: &iascii::grid::Grid) -> Self {
        let w = grid.width() as usize;
        if w == 0 || grid.height() == 0 {
            return Self {
                frames: vec![Vec::new()],
            };
        }
        let mut rows = Vec::with_capacity(grid.height() as usize);
        for row in grid.as_slice().chunks_exact(w) {
            rows.push(
                row.iter()
                    .map(|c| Cell::new(c.ch, Some(Rgb::new(c.color.r, c.color.g, c.color.b))))
                    .collect(),
            );
        }
        Self { frames: vec![rows] }
    }

    /// Multi-frame sprite from already-colored rows; every frame should be
    /// the same size for sane animation (not enforced — clipping handles
    /// ragged frames).
    pub fn from_frames(frames: Vec<Vec<Vec<Cell>>>) -> Self {
        Self { frames }
    }

    /// Appends a plain-text frame (same size as the others, by convention).
    pub fn add_frame<S: AsRef<str>>(&mut self, lines: &[S]) {
        self.frames.push(
            lines
                .iter()
                .map(|l| l.as_ref().chars().map(|ch| Cell::new(ch, None)).collect())
                .collect(),
        );
    }

    /// Appends one converted picture grid as a frame.
    pub fn add_frame_grid(&mut self, grid: &iascii::grid::Grid) {
        let mut other = Sprite::from_grid(grid);
        self.frames.append(&mut other.frames);
    }

    /// Frame count.
    pub fn len(&self) -> usize {
        self.frames.len()
    }

    pub fn is_empty(&self) -> bool {
        self.frames.is_empty()
    }

    /// The frame for `tick`, cycling (`tick % len`). Empty sprite yields
    /// an empty slice — blitting it draws nothing.
    pub fn frame(&self, tick: u64) -> &[Vec<Cell>] {
        if self.frames.is_empty() {
            return &[];
        }
        &self.frames[tick as usize % self.frames.len()]
    }

    /// The frame's glyphs as plain text rows (no color) — for logs, tests,
    /// or feeding back into text pipelines.
    pub fn frame_text(&self, tick: u64) -> Vec<String> {
        self.frame(tick)
            .iter()
            .map(|row| row.iter().map(|c| c.ch).collect())
            .collect()
    }

    /// Width (longest row, in chars) of frame `tick`.
    pub fn width(&self, tick: u64) -> usize {
        sprite_cells_width(self.frame(tick))
    }

    /// Row count of frame `tick`.
    pub fn height(&self, tick: u64) -> usize {
        self.frame(tick).len()
    }

    /// Horizontally mirrored copy, colors included (for left/right walk
    /// cycles from one set of frames).
    pub fn flip_h(&self) -> Self {
        Self {
            frames: self
                .frames
                .iter()
                .map(|f| {
                    f.iter()
                        .map(|r| r.iter().rev().copied().collect())
                        .collect()
                })
                .collect(),
        }
    }
}

// ---------------------------------------------------------------------------
// Terminal presentation helpers
// ---------------------------------------------------------------------------

/// Escape-string building blocks for hosts that present frames on a real
/// terminal: print `ENTER_ALT` + `HIDE_CURSOR` once, one patch per frame,
/// then `SHOW_CURSOR` + `LEAVE_ALT`. Raw `&str` constants (not functions)
/// so `no_std`-ish hosts and FFI callers can use them without allocation.
pub mod screen {
    /// Switches to the alternate screen (restores the shell's scrollback
    /// on exit).
    pub const ENTER_ALT: &str = "\x1b[?1049h";
    /// Leaves the alternate screen.
    pub const LEAVE_ALT: &str = "\x1b[?1049l";
    /// Hides the cursor (games draw their own).
    pub const HIDE_CURSOR: &str = "\x1b[?25l";
    /// Shows the cursor again.
    pub const SHOW_CURSOR: &str = "\x1b[?25h";
    /// Clears the screen and homes the cursor (initial paint).
    pub const CLEAR: &str = "\x1b[H\x1b[2J";
    /// Homes the cursor without clearing.
    pub const HOME: &str = "\x1b[H";
}

/// Minimal present for one frame: the full frame when `prev` is empty
/// (first paint), otherwise a cursor-addressed patch touching only changed
/// cells ([`crate::render::DiffGranularity::Cell`]). Updates `prev` to
/// `next` and returns the bytes to write. Near-static scenes (HUDs,
/// puzzles, menus) cost bytes proportional to what *moved*, not to the
/// canvas size.
///
/// Cell granularity is the right choice when damage is sparse (the usual
/// case for a game or dashboard). For a frame where most cells change every
/// frame, the whole-line
/// [`DiffGranularity::Line`](crate::render::DiffGranularity::Line) path is
/// cheaper in CPU — call [`crate::render::diff_frame_into`] directly with it,
/// or better, keep a [`Canvas`] and present it with
/// [`Canvas::present_dirty_into`].
///
/// [`Canvas::present_dirty_into`] is faster still: it derives the patch
/// from the canvas's own cell snapshot instead of diffing two strings.
pub fn present_diff(prev: &mut String, next: &str) -> String {
    let mut out = String::new();
    if !prev.is_empty() {
        crate::render::diff_frame_into(prev, next, crate::render::DiffGranularity::Cell, &mut out);
    } else {
        out.push_str(next);
    }
    prev.clear();
    prev.push_str(next);
    out
}

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

    #[cfg(feature = "colorize")]
    fn plain_canvas() -> Canvas {
        let mut c = Canvas::new(10, 5);
        c.text(0, 0, "hello", None);
        c
    }

    #[test]
    fn put_and_get_round_trip_with_clipping() {
        let mut c = Canvas::new(4, 3);
        c.put(1, 1, '@', Some(Rgb::RED));
        assert_eq!(c.get(1, 1), Some(Cell::new('@', Some(Rgb::RED))));
        assert_eq!(c.get(-1, 0), None);
        assert_eq!(c.get(4, 0), None);
        assert_eq!(c.get(0, 3), None);
        // Out-of-bounds writes are silent no-ops, never panics.
        c.put(-5, -5, 'X', None);
        c.put(99, 99, 'X', None);
        assert_eq!(c.get(0, 0), Some(Cell::blank()));
    }

    #[test]
    fn text_clips_at_edges() {
        let mut c = Canvas::new(5, 2);
        c.text(-2, 0, "abcdef", None);
        // 'a','b' fall off the left; 'c'..'f' land at x=0..3.
        assert_eq!(c.get(0, 0).unwrap().ch, 'c');
        assert_eq!(c.get(3, 0).unwrap().ch, 'f');
        assert_eq!(c.get(4, 0).unwrap().ch, ' ');
        c.text(0, 7, "offscreen", None); // no panic
        let plain = c.to_plain();
        assert_eq!(plain.lines().count(), 2);
    }

    #[test]
    fn text_centered_lands_in_the_middle() {
        let mut c = Canvas::new(10, 1);
        c.text_centered(0, "ab", None);
        assert_eq!(c.get(4, 0).unwrap().ch, 'a');
        assert_eq!(c.get(5, 0).unwrap().ch, 'b');
    }

    #[test]
    fn line_hits_both_endpoints() {
        let mut c = Canvas::new(8, 8);
        c.line(0, 0, 7, 7, '#', None);
        assert_eq!(c.get(0, 0).unwrap().ch, '#');
        assert_eq!(c.get(7, 7).unwrap().ch, '#');
        assert_eq!(c.get(3, 3).unwrap().ch, '#');
        // Degenerate single-point line.
        let mut c2 = Canvas::new(3, 3);
        c2.line(1, 1, 1, 1, 'X', None);
        assert_eq!(c2.get(1, 1).unwrap().ch, 'X');
    }

    #[test]
    fn rect_fill_and_outline_counts() {
        let mut c = Canvas::new(6, 6);
        c.rect_fill(1, 1, 2, 2, '.', None);
        let filled = c.cells.iter().filter(|cell| cell.ch == '.').count();
        assert_eq!(filled, 4);

        let mut o = Canvas::new(6, 6);
        o.rect_outline(0, 0, 4, 3, None);
        // 4x3 outline: 2*(4+3) - 4 corners double-counted = 10.
        let drawn = o.cells.iter().filter(|cell| cell.ch != ' ').count();
        assert_eq!(drawn, 10);
        assert_eq!(o.get(0, 0).unwrap().ch, '+');
    }

    #[test]
    fn panel_draws_frame_and_title() {
        let mut c = Canvas::new(12, 5);
        c.panel(0, 0, 12, 5, Some("menu"), None);
        let plain = c.to_plain();
        assert!(plain.contains("menu"));
        assert!(plain.contains('+'));
    }

    #[test]
    fn bar_scales_with_fraction() {
        let mut c = Canvas::new(10, 1);
        c.bar(0, 0, 10, 0.5, '#', '-', None);
        let row: String = (0..10).map(|x| c.get(x, 0).unwrap().ch).collect();
        assert_eq!(row, "#####-----");
        c.bar(0, 0, 10, 2.0, '#', '-', None); // clamped
        let row: String = (0..10).map(|x| c.get(x, 0).unwrap().ch).collect();
        assert_eq!(row, "##########");
    }

    #[test]
    fn circle_outline_and_fill() {
        let mut outline = Canvas::new(11, 11);
        outline.circle(5, 5, 3, 'o', None, false);
        assert_eq!(outline.get(5, 2).unwrap().ch, 'o'); // top
        assert_eq!(outline.get(5, 5).unwrap().ch, ' '); // hollow
        let mut filled = Canvas::new(11, 11);
        filled.circle(5, 5, 3, 'o', None, true);
        assert_eq!(filled.get(5, 5).unwrap().ch, 'o');
    }

    #[test]
    fn blit_skips_transparent_and_clips() {
        let mut c = Canvas::new(4, 2);
        c.fill('.', None);
        c.blit(&["a b".to_owned()], -1, 0, Some(Rgb::RED), ' ');
        // 'a' at x=-1 is clipped away; 'b' lands at x=1.
        assert_eq!(c.get(0, 0).unwrap().ch, '.');
        assert_eq!(c.get(1, 0).unwrap().ch, 'b');
        assert_eq!(c.get(1, 0).unwrap().color, Some(Rgb::RED));
    }

    #[test]
    fn sprite_cycles_frames_and_flips() {
        let s = Sprite::from_lines(&["->", "  "]);
        assert_eq!(s.frame_text(0), vec!["->".to_owned(), "  ".to_owned()]);
        assert_eq!((s.width(0), s.height(0)), (2, 2));
        // from_lines cells are uncolored; blit tint supplies the color.
        assert!(s.frame(0).iter().flatten().all(|c| c.color.is_none()));
        let two = Sprite::from_frames(vec![
            vec![vec![Cell::new('a', Some(Rgb::RED))]],
            vec![vec![Cell::new('b', None)]],
        ]);
        assert_eq!(two.frame_text(0), vec!["a".to_owned()]);
        assert_eq!(two.frame_text(1), vec!["b".to_owned()]);
        assert_eq!(two.frame_text(2), vec!["a".to_owned()]);
        assert_eq!(two.frame_text(1_000_001), vec!["b".to_owned()]);
        assert_eq!(two.frame(0)[0][0].color, Some(Rgb::RED));
        let flipped = Sprite::from_lines(&["ab>"]).flip_h();
        assert_eq!(flipped.frame_text(0), vec![">ba".to_owned()]);
        assert!(Sprite::from_frames(vec![]).frame(99).is_empty());
    }

    #[test]
    fn sprite_from_grid_keeps_glyphs_and_colors() {
        let grid = test_grid();
        let sprite = Sprite::from_grid(&grid);
        assert_eq!((sprite.width(0), sprite.height(0)), (6, 4));
        // Every inked cell carries the grid's own color.
        assert!(sprite.frame(0).iter().flatten().all(|c| c.color.is_some()));
        assert_eq!(sprite.frame_text(0).len(), 4);
    }

    fn test_grid() -> iascii::grid::Grid {
        let cfg = iascii::config::ConfigBuilder::new()
            .output_sizing(iascii::config::OutputSizing::Explicit {
                width: 6,
                height: 4,
            })
            .build()
            .unwrap();
        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);
            }
        }
        iascii::convert::convert_image(6, 4, &pix, &cfg).unwrap()
    }

    #[test]
    fn blit_sprite_tint_overrides_while_none_keeps_cell_colors() {
        let mut c = Canvas::new(4, 1);
        let sprite = Sprite::from_grid(&test_grid());
        // Tinted: every inked cell becomes the override color.
        c.blit_sprite(&sprite, 0, 0, 0, Some(Rgb::WHITE), ' ');
        assert!(c
            .cells
            .iter()
            .filter(|cell| cell.ch != ' ')
            .all(|cell| cell.color == Some(Rgb::WHITE)));
        // Untinted: the picture's own colors survive on inked cells. The
        // grid's blank cell is transparent, so the canvas keeps its own
        // (uncolored) blank underneath it.
        let mut d = Canvas::new(6, 4);
        d.blit_sprite(&sprite, 0, 0, 0, None, ' ');
        for (i, cell) in sprite.frame(0).iter().flatten().copied().enumerate() {
            if cell.ch == ' ' {
                assert_eq!(
                    d.cells[i],
                    Cell::blank(),
                    "transparent cell must be skipped"
                );
            } else {
                assert_eq!(d.cells[i], cell, "inked cell must keep its own color");
            }
        }
    }

    #[test]
    fn blit_ansi_parses_escapes_and_positions_cells() {
        let mut c = Canvas::new(5, 2);
        c.fill('.', None);
        c.blit_ansi("\x1b[38;2;10;20;30mAB\x1b[0mC\x1b[38;5;196mD", 1, 0, ' ');
        assert_eq!(
            c.get(1, 0).unwrap(),
            Cell::new('A', Some(Rgb::new(10, 20, 30)))
        );
        assert_eq!(
            c.get(2, 0).unwrap(),
            Cell::new('B', Some(Rgb::new(10, 20, 30)))
        );
        // Reset drops the color again.
        assert_eq!(c.get(3, 0).unwrap(), Cell::new('C', None));
        // 256-color index 196 is pure red.
        assert_eq!(c.get(4, 0).unwrap().color, Some(Rgb::new(255, 0, 0)));
        // 16-color code path.
        let mut d = Canvas::new(2, 1);
        d.blit_ansi("\x1b[91mX\x1b[37mY", 0, 0, ' ');
        assert_eq!(d.get(0, 0).unwrap().color, Some(Rgb::new(255, 0, 0)));
        assert_eq!(d.get(1, 0).unwrap().color, Some(Rgb::new(192, 192, 192)));
        // Transparent glyphs leave the canvas alone, whatever their color.
        let mut e = Canvas::new(2, 1);
        e.fill('.', None);
        e.blit_ansi("\x1b[38;2;1;2;3m  ", 0, 0, ' ');
        assert_eq!(e.get(0, 0).unwrap().ch, '.');
    }

    #[test]
    fn blit_scaled_grows_and_shrinks() {
        let sprite = Sprite::from_lines(&["AB", "CD"]);
        let mut big = Canvas::new(4, 4);
        big.blit_sprite_scaled(&sprite, 0, 0, 0, 4, 4, None, ' ');
        assert_eq!(big.get(0, 0).unwrap().ch, 'A');
        assert_eq!(big.get(1, 0).unwrap().ch, 'A');
        assert_eq!(big.get(2, 0).unwrap().ch, 'B');
        assert_eq!(big.get(0, 2).unwrap().ch, 'C');
        assert_eq!(big.get(3, 3).unwrap().ch, 'D');
        let mut small = Canvas::new(4, 4);
        small.blit_sprite_scaled(&sprite, 0, 0, 0, 1, 1, None, ' ');
        assert_eq!(small.get(0, 0).unwrap().ch, 'A');
        assert_eq!(small.get(1, 0).unwrap().ch, ' ');
    }

    #[test]
    fn to_string_dirty_is_byte_identical_to_full_render() {
        let mut c = Canvas::new(6, 3);
        c.fill('.', None);
        c.text(1, 1, "hi", Some(Rgb::RED));
        // First dirty render must equal the full render (cold cache).
        assert_eq!(c.to_string_dirty(), c.to_string());
        assert_eq!(c.last_recomputed_rows(), 3, "cold cache renders every row");
        assert_eq!(c.dirty_rows(), 0, "render consumes the dirty flags");

        // One cell changes -> only that row re-renders, output still equal.
        c.put(2, 1, 'X', Some(Rgb::BLUE));
        assert_eq!(c.dirty_rows(), 1);
        assert_eq!(c.to_string_dirty(), c.to_string());
        assert_eq!(c.last_recomputed_rows(), 1);

        // Nothing changed -> nothing re-renders, output still equal.
        assert_eq!(c.dirty_rows(), 0);
        assert_eq!(c.to_string_dirty(), c.to_string());
        assert_eq!(
            c.last_recomputed_rows(),
            0,
            "clean frame costs zero renders"
        );
    }

    #[test]
    fn to_string_dirty_sees_clear_and_painted_rows() {
        let mut c = Canvas::new(4, 2);
        c.fill('#', Some(Rgb::GREEN));
        let _ = c.to_string_dirty();
        // clear() marks everything dirty; the cleared rows differ from the
        // snapshot, so they must re-render (old '#' output must not survive).
        c.clear();
        assert_eq!(c.dirty_rows(), 2);
        let out = c.to_string_dirty();
        assert_eq!(out, c.to_string());
        assert!(!out.contains('#'));
        assert_eq!(c.last_recomputed_rows(), 2);
    }

    #[test]
    fn to_string_dirty_reuses_rows_after_identical_clear_redraw() {
        let mut c = Canvas::new(4, 2);
        c.text(0, 0, "abcd", Some(Rgb::RED));
        c.text(0, 1, "efgh", Some(Rgb::BLUE));
        let first = c.to_string_dirty();
        assert_eq!(c.last_recomputed_rows(), 2);

        // Classic game loop: clear() + redraw the exact same scene. Every
        // row is written (dirty), but final cells match the rendered
        // snapshot, so not one row needs re-rendering.
        c.clear();
        c.text(0, 0, "abcd", Some(Rgb::RED));
        c.text(0, 1, "efgh", Some(Rgb::BLUE));
        assert_eq!(c.dirty_rows(), 2);
        assert_eq!(c.to_string_dirty(), first);
        assert_eq!(
            c.last_recomputed_rows(),
            0,
            "identical clear+redraw must render nothing"
        );
    }

    #[test]
    fn to_string_dirty_tracks_movement_across_rows() {
        let mut c = Canvas::new(8, 3);
        let _ = c.to_string_dirty();
        // A sprite moving one cell right: its old and new rows both change.
        c.put(1, 1, '@', Some(Rgb::WHITE));
        c.put(2, 1, ' ', None);
        assert_eq!(c.dirty_rows(), 1);
        let out = c.to_string_dirty();
        assert_eq!(out, c.to_string());
        assert_eq!(
            c.last_recomputed_rows(),
            1,
            "one row moved, one row rendered"
        );
    }

    #[test]
    fn reset_render_cache_forces_a_full_render() {
        let mut c = Canvas::new(3, 2);
        let _ = c.to_string_dirty();
        assert_eq!(c.last_recomputed_rows(), 2);
        let _ = c.to_string_dirty();
        assert_eq!(c.last_recomputed_rows(), 0);
        c.reset_render_cache();
        assert_eq!(c.dirty_rows(), 2, "everything dirty after a reset");
        let _ = c.to_string_dirty();
        assert_eq!(c.last_recomputed_rows(), 2, "reset forces full re-render");
    }

    #[test]
    fn write_into_matches_to_string_and_reuses_the_buffer() {
        let mut c = Canvas::new(5, 3);
        c.fill('.', Some(Rgb::BLUE));
        c.text(1, 1, "hi", Some(Rgb::RED));
        let mut buf = String::new();
        c.write_into(&mut buf);
        assert_eq!(buf, c.to_string());
        // Reusing the buffer (append twice) must produce the frame twice.
        c.write_into(&mut buf);
        assert_eq!(buf, format!("{}{}", c.to_string(), c.to_string()));
    }

    #[test]
    fn write_dirty_into_matches_the_string_variant_every_frame() {
        let mut c = Canvas::new(6, 4);
        c.text(0, 0, "score", Some(Rgb::RED));
        let mut buf = String::new();
        for step in 0..4i32 {
            c.clear();
            c.text(0, 0, "score", Some(Rgb::RED));
            c.put(2, step, '@', Some(Rgb::WHITE));
            buf.clear();
            c.write_dirty_into(&mut buf);
            assert_eq!(buf, c.to_string(), "step {step} must match full render");
        }
    }

    #[test]
    fn present_dirty_into_paints_full_then_only_patches() {
        let mut c = Canvas::new(8, 3);
        c.fill('.', None);
        c.text(0, 0, "hi", Some(Rgb::RED));

        // First present: every row, cursor-addressed, no newlines.
        let mut frame = String::new();
        assert!(c.present_dirty_into(&mut frame));
        assert!(frame.contains("\x1b[1;1H"));
        assert!(frame.contains("\x1b[3;1H"));
        assert!(!frame.contains('\n'), "present uses absolute addressing");
        assert_eq!(c.last_recomputed_rows(), 3);

        // Nothing changed: nothing emitted, caller can skip the write.
        frame.clear();
        assert!(!c.present_dirty_into(&mut frame));
        assert_eq!(frame, "");

        // One cell changes: one cursor move, one glyph — no full rows.
        c.put(3, 1, 'X', Some(Rgb::GREEN));
        frame.clear();
        assert!(c.present_dirty_into(&mut frame));
        assert_eq!(c.last_recomputed_rows(), 1, "only the dirty row is visited");
        assert!(
            frame.contains("\x1b[2;4H"),
            "patched the exact cell: {frame:?}"
        );
        assert!(frame.contains('X'));
        assert!(!frame.contains("..."), "static rows must not be re-sent");
    }

    #[test]
    fn present_dirty_patch_stream_replays_to_the_frame() {
        // Tiny "terminal": apply every emitted patch to a glyph grid and
        // check the screen ends up showing the canvas. This is the real
        // guarantee the patch stream must provide, across full paints and
        // incremental damage.
        let (w, h) = (10usize, 3usize);
        let mut c = Canvas::new(w as u32, h as u32);
        c.fill('.', None);
        c.text(1, 1, "hello", Some(Rgb::RED));

        let mut screen = vec![vec![' '; w]; h];
        let mut frame = String::new();
        for step in 0..4i32 {
            c.put(step, 0, '@', Some(Rgb::WHITE));
            c.put(5, 2, (b'0' + step as u8) as char, Some(Rgb::GREEN));
            frame.clear();
            if c.present_dirty_into(&mut frame) {
                apply_patch(&mut screen, &frame, w, h);
            }
            assert_eq!(glyphs(&screen), c.to_plain(), "step {step}");
        }
    }

    /// Applies one patch stream (cursor moves, SGR, glyphs, clear-to-EOL) to
    /// a glyph grid — SGR is ignored, glyphs are what's verified here (the
    /// color channel is covered by the `fast_ansi` cell-diff tests).
    fn apply_patch(screen: &mut [Vec<char>], patch: &str, cols: usize, rows: usize) {
        let (mut r, mut c) = (0usize, 0usize);
        let mut rest = patch;
        while let Some(i) = rest.find('\x1b') {
            for ch in rest[..i].chars() {
                if r < rows && c < cols {
                    screen[r][c] = ch;
                }
                c += 1;
            }
            rest = &rest[i..];
            let Some(end) = rest.find(|ch: char| ch.is_ascii_alphabetic()) else {
                return;
            };
            match rest.as_bytes()[end] {
                b'H' => {
                    let mut it = rest[2..end].split(';');
                    r = it.next().and_then(|s| s.parse().ok()).unwrap_or(1) - 1;
                    c = it.next().and_then(|s| s.parse().ok()).unwrap_or(1) - 1;
                }
                b'K' if r < rows => {
                    if let Some(tail) = screen[r].get_mut(c..cols) {
                        tail.fill(' ');
                    }
                }
                _ => {} // SGR (`m`) and anything else: not a movement
            }
            rest = &rest[end + 1..];
        }
        for ch in rest.chars() {
            if r < rows && c < cols {
                screen[r][c] = ch;
            }
            c += 1;
        }
    }

    fn glyphs(screen: &[Vec<char>]) -> String {
        let mut out: String = screen
            .iter()
            .map(|row| row.iter().collect::<String>())
            .collect::<Vec<_>>()
            .join("\n");
        out.push('\n');
        out
    }

    #[test]
    fn present_dirty_into_reset_forces_a_full_repaint() {
        let mut c = Canvas::new(4, 2);
        let mut frame = String::new();
        assert!(c.present_dirty_into(&mut frame));
        frame.clear();
        assert!(!c.present_dirty_into(&mut frame));
        c.reset_render_cache();
        frame.clear();
        assert!(c.present_dirty_into(&mut frame));
        assert!(frame.contains("\x1b[1;1H") && frame.contains("\x1b[2;1H"));
    }

    #[cfg(feature = "colorize")]
    #[test]
    fn apply_animation_colors_every_inked_cell() {
        let mut c = plain_canvas();
        c.apply_animation(&PixelAnimation::Rainbow { speed: 5.0 }, 0);
        assert!(c
            .cells
            .iter()
            .all(|cell| cell.color.is_some() || cell.ch == ' '));
        assert!(c.to_string().contains("\x1b[38;2;"));
    }

    #[test]
    fn canvas_to_string_merges_runs_and_resets() {
        let mut c = Canvas::new(4, 1);
        c.text(0, 0, "ab", Some(Rgb::RED));
        c.text(2, 0, "cd", Some(Rgb::RED));
        let out = c.to_string();
        // One merged escape + one reset for the whole same-color run.
        assert_eq!(out.matches("\x1b[38;2;255;0;0m").count(), 1);
        assert!(out.ends_with("\x1b[0m\n"));
    }

    #[test]
    fn present_diff_first_paint_is_full_then_patches() {
        let mut prev = String::new();
        let full = present_diff(&mut prev, "ab\n");
        assert_eq!(full, "ab\n");
        let patch = present_diff(&mut prev, "ab\n");
        assert_eq!(patch, "", "identical frame patches to nothing");
        let patch2 = present_diff(&mut prev, "ac\n");
        assert!(patch2.contains('c'));
        assert!(!patch2.contains("\x1b[2J"), "no full clear on patch");
    }

    #[test]
    fn present_diff_is_safe_when_only_colors_change() {
        let mut prev = String::new();
        let _ = present_diff(&mut prev, "\x1b[38;2;255;0;0mab\x1b[0m\n");
        let patch = present_diff(&mut prev, "\x1b[38;2;0;255;0mab\x1b[0m\n");
        assert!(
            patch.contains("\x1b[38;2;0;255;0m"),
            "whole escape: {patch:?}"
        );
        let residue = patch.replace("\x1b[38;2;0;255;0m", "");
        assert!(
            !residue.contains('8'),
            "no escape fragment leaked: {patch:?}"
        );
    }

    #[test]
    fn screen_constants_are_sane_escapes() {
        assert!(screen::ENTER_ALT.starts_with('\x1b'));
        assert!(screen::LEAVE_ALT.starts_with('\x1b'));
        assert_eq!(screen::CLEAR, "\x1b[H\x1b[2J");
    }

    #[test]
    fn zero_sized_canvas_is_harmless() {
        let mut c = Canvas::new(0, 0);
        assert_eq!(c.to_string(), "");
        assert_eq!(c.to_string_dirty(), "");
        let mut out = String::new();
        assert!(!c.present_dirty_into(&mut out));
        assert_eq!(out, "");
    }
}