physics_sandbox 0.1.4

Small rigid-body physics sandbox with pluggable integrators, environments, collisions and an event bus. Optional retro ASCII terminal visualization.
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
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
//! Tiny terminal "retro scope" for visualizing the simulation.
//!
//! Two projection modes:
//!
//! * [`Projection::Ortho2D`] — flat XY plot, Y grows upward (physics
//!   convention, not screen convention).
//! * [`Projection::Perspective`] — true 3D camera with depth buffer, ground
//!   reference grid (depth-shaded), and motion trails that stay visible
//!   across frames.
//!
//! Render priority per cell is `Live > Trail > Ground`, so motion trails
//! always read against the grid and the live marker always reads against
//! its own trail.
//!
//! Enabled with the `viz` feature.

use std::io::{Write, stdout};

use crossterm::{
    QueueableCommand, cursor,
    style::{Color, Print, ResetColor, SetForegroundColor},
    terminal::{Clear, ClearType},
};

use crate::math::Vec3;

/// A single body to draw on the scope. `z` is ignored in 2D ortho mode.
#[derive(Debug, Clone, Copy)]
pub struct Marker {
    pub x: f64,
    pub y: f64,
    pub z: f64,
    pub glyph: char,
    pub color: Color,
}

impl Marker {
    /// 2D constructor (z = 0). Back-compat with the original API.
    pub fn new(x: f64, y: f64, glyph: char) -> Self {
        Self { x, y, z: 0.0, glyph, color: Color::White }
    }

    /// 3D constructor.
    pub fn new3(pos: Vec3, glyph: char) -> Self {
        Self { x: pos.x, y: pos.y, z: pos.z, glyph, color: Color::White }
    }

    pub fn with_color(mut self, color: Color) -> Self {
        self.color = color;
        self
    }

    pub fn pos(&self) -> Vec3 { Vec3::new(self.x, self.y, self.z) }
}

/// A perspective camera. `up` is whatever you call up in your world
/// (typically `Vec3::new(0.0, 1.0, 0.0)`).
#[derive(Debug, Clone, Copy)]
pub struct Camera {
    pub eye: Vec3,
    pub target: Vec3,
    pub up: Vec3,
    /// Vertical field of view, in radians.
    pub fov_y: f64,
    /// Near clipping distance (anything closer is culled).
    pub near: f64,
    /// Far clipping distance (anything further is culled).
    pub far: f64,
    /// Character aspect compensation. Terminal cells are taller than wide
    /// (~2:1), so set this to `2.0` to keep proportions roughly right.
    pub char_aspect: f64,
}

impl Camera {
    pub fn looking_at(eye: Vec3, target: Vec3) -> Self {
        Self {
            eye,
            target,
            up: Vec3::new(0.0, 1.0, 0.0),
            fov_y: 60.0_f64.to_radians(),
            near: 0.1,
            far: 1.0e9,
            char_aspect: 2.0,
        }
    }

    pub fn with_fov_deg(mut self, deg: f64) -> Self {
        self.fov_y = deg.to_radians();
        self
    }

    fn basis(&self) -> (Vec3, Vec3, Vec3) {
        let forward = (self.target - self.eye).normalize();
        let right = forward.cross(self.up).normalize();
        let up = right.cross(forward);
        (right, up, forward)
    }
}

/// Optional reference grid drawn on the world's y=0 plane (3D only).
/// Drawn with `+` at intersections plus `-` along x-lines and `:` along
/// z-lines so the perspective is readable. Color is depth-shaded.
#[derive(Debug, Clone, Copy)]
pub struct GroundGrid {
    pub half_extent: f64,
    pub step: f64,
    /// Near color (closer to camera). Defaults to a soft cyan.
    pub near_color: Color,
    /// Far color (toward the horizon). Defaults to a dim blue-grey.
    pub far_color: Color,
}

impl GroundGrid {
    pub fn new(half_extent: f64, step: f64) -> Self {
        Self {
            half_extent,
            step,
            near_color: Color::Rgb { r: 110, g: 170, b: 210 },
            far_color: Color::Rgb { r: 40, g: 60, b: 90 },
        }
    }
}

/// How world coordinates map onto the character grid.
#[derive(Debug, Clone, Copy)]
pub enum Projection {
    Ortho2D { x_range: (f64, f64), y_range: (f64, f64) },
    Perspective { camera: Camera },
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Kind {
    Empty,
    Ground,
    Trail,
    Live,
}

#[derive(Clone, Copy)]
struct Cell {
    glyph: char,
    color: Color,
    kind: Kind,
    /// Frames since this cell was last "Live". 0 while live; >=1 once it
    /// has aged into a trail.
    age: u8,
}

impl Cell {
    const EMPTY: Cell = Cell {
        glyph: ' ',
        color: Color::Reset,
        kind: Kind::Empty,
        age: 0,
    };
}

/// Maximum age (in frames) a trail cell stays visible before being cleared.
const TRAIL_MAX_AGE: u8 = 12;

/// ASCII oscilloscope-style plotter. 2D or 3D depending on [`Projection`].
pub struct AsciiScope {
    pub width: u16,
    pub height: u16,
    pub projection: Projection,
    pub trails: bool,
    pub ground: Option<GroundGrid>,
    draw_ground_line_2d: bool,
    cells: Vec<Cell>,
    depth: Vec<f64>,
}

impl AsciiScope {
    /// 2D ortho scope (back-compat).
    pub fn new(width: u16, height: u16, x_range: (f64, f64), y_range: (f64, f64)) -> Self {
        let n = (width as usize) * (height as usize);
        Self {
            width,
            height,
            projection: Projection::Ortho2D { x_range, y_range },
            trails: true,
            ground: None,
            draw_ground_line_2d: true,
            cells: vec![Cell::EMPTY; n],
            depth: vec![f64::INFINITY; n],
        }
    }

    /// 3D perspective scope.
    pub fn new_3d(width: u16, height: u16, camera: Camera) -> Self {
        let n = (width as usize) * (height as usize);
        Self {
            width,
            height,
            projection: Projection::Perspective { camera },
            trails: true,
            ground: None,
            draw_ground_line_2d: false,
            cells: vec![Cell::EMPTY; n],
            depth: vec![f64::INFINITY; n],
        }
    }

    pub fn with_trails(mut self, trails: bool) -> Self {
        self.trails = trails;
        self
    }

    pub fn with_ground(mut self, draw_ground: bool) -> Self {
        self.draw_ground_line_2d = draw_ground;
        self
    }

    pub fn with_ground_grid(mut self, grid: GroundGrid) -> Self {
        self.ground = Some(grid);
        self
    }

    pub fn set_camera(&mut self, camera: Camera) {
        if let Projection::Perspective { camera: c } = &mut self.projection {
            *c = camera;
        }
    }

    fn idx(&self, col: u16, row: u16) -> usize {
        (row as usize) * (self.width as usize) + (col as usize)
    }

    fn project(&self, p: Vec3) -> Option<(u16, u16, f64)> {
        match self.projection {
            Projection::Ortho2D { x_range, y_range } => {
                let (xmin, xmax) = x_range;
                let (ymin, ymax) = y_range;
                if p.x < xmin || p.x > xmax || p.y < ymin || p.y > ymax {
                    return None;
                }
                let nx = (p.x - xmin) / (xmax - xmin);
                let ny = (p.y - ymin) / (ymax - ymin);
                let col = (nx * (self.width as f64 - 1.0)).round() as i32;
                let row = ((1.0 - ny) * (self.height as f64 - 1.0)).round() as i32;
                Some((
                    col.clamp(0, self.width as i32 - 1) as u16,
                    row.clamp(0, self.height as i32 - 1) as u16,
                    0.0,
                ))
            }
            Projection::Perspective { camera } => {
                let (right, up, forward) = camera.basis();
                let rel = p - camera.eye;
                let depth = rel.dot(forward);
                if depth < camera.near || depth > camera.far {
                    return None;
                }
                let rx = rel.dot(right);
                let ry = rel.dot(up);
                let focal_y = 1.0 / (camera.fov_y * 0.5).tan();
                let focal_x = focal_y / camera.char_aspect;
                let nx = (rx / depth) * focal_x;
                let ny = (ry / depth) * focal_y;
                if !(-1.0..=1.0).contains(&nx) || !(-1.0..=1.0).contains(&ny) {
                    return None;
                }
                let col = ((nx * 0.5 + 0.5) * (self.width as f64 - 1.0)).round() as i32;
                let row = (((-ny) * 0.5 + 0.5) * (self.height as f64 - 1.0)).round() as i32;
                Some((
                    col.clamp(0, self.width as i32 - 1) as u16,
                    row.clamp(0, self.height as i32 - 1) as u16,
                    depth,
                ))
            }
        }
    }

    /// Wipe everything.
    pub fn clear(&mut self) {
        for c in &mut self.cells {
            *c = Cell::EMPTY;
        }
        for d in &mut self.depth {
            *d = f64::INFINITY;
        }
    }

    /// Begin-frame: age live cells into trails, fade trails, drop the
    /// oldest, and reset transient buffers (depth + ground cells).
    fn tick(&mut self) {
        for c in &mut self.cells {
            match c.kind {
                Kind::Empty => {}
                Kind::Ground => {
                    // Ground is regenerated each frame; clear it now so the
                    // depth buffer starts clean and ground priority is reset.
                    *c = Cell::EMPTY;
                }
                Kind::Live => {
                    // Last frame's live marker becomes a fresh trail.
                    c.kind = Kind::Trail;
                    c.age = 1;
                    let (g, col) = trail_style(c.age);
                    c.glyph = g;
                    c.color = col;
                }
                Kind::Trail => {
                    c.age = c.age.saturating_add(1);
                    if c.age > TRAIL_MAX_AGE {
                        *c = Cell::EMPTY;
                    } else {
                        let (g, col) = trail_style(c.age);
                        c.glyph = g;
                        c.color = col;
                    }
                }
            }
        }
        for d in &mut self.depth {
            *d = f64::INFINITY;
        }
    }

    /// Plot a cell with priority + depth resolution.
    fn put(&mut self, col: u16, row: u16, depth: f64, glyph: char, color: Color, kind: Kind) {
        let i = self.idx(col, row);
        let existing = self.cells[i].kind;
        let priority = |k: Kind| match k {
            Kind::Empty => 0,
            Kind::Ground => 1,
            Kind::Trail => 2,
            Kind::Live => 3,
        };
        let pn = priority(kind);
        let pe = priority(existing);
        if pn > pe {
            self.cells[i] = Cell { glyph, color, kind, age: 0 };
            self.depth[i] = depth;
        } else if pn == pe && depth <= self.depth[i] {
            self.cells[i] = Cell { glyph, color, kind, age: 0 };
            self.depth[i] = depth;
        }
    }

    fn draw_ground(&mut self) {
        match self.projection {
            Projection::Ortho2D { x_range, .. } if self.draw_ground_line_2d => {
                if let Some((_, row, _)) =
                    self.project(Vec3::new(x_range.0, 0.0, 0.0))
                {
                    for col in 0..self.width {
                        self.put(col, row, f64::INFINITY, '=', Color::DarkYellow, Kind::Ground);
                    }
                }
            }
            Projection::Perspective { camera } => {
                if let Some(grid) = self.ground {
                    let h = grid.half_extent;
                    let step = grid.step.max(1e-3);
                    // Used for depth shading.
                    let cam_dist = (camera.eye - camera.target).magnitude().max(1.0);

                    // Walk along Z-lines (constant x) sampling fine points,
                    // alternating glyphs for perspective readability:
                    // `+` at integer-grid intersections, `:` between them on
                    // a Z-line, `-` between them on an X-line.
                    let fine = step / 4.0;

                    // Z-direction lines (each at constant x = i*step):
                    let nx = (h / step).floor() as i32;
                    for ix in -nx..=nx {
                        let x = ix as f64 * step;
                        let mut z = -h;
                        while z <= h + 1e-9 {
                            let on_intersection = (z / step).round() * step;
                            let is_int = (z - on_intersection).abs() < fine * 0.5;
                            let glyph = if is_int { '+' } else { ':' };
                            if let Some((col, row, depth)) =
                                self.project(Vec3::new(x, 0.0, z))
                            {
                                let color = ground_color(depth, cam_dist, &grid);
                                self.put(col, row, depth, glyph, color, Kind::Ground);
                            }
                            z += fine;
                        }
                    }

                    // X-direction lines (each at constant z = j*step), using
                    // `-` between intersections so x and z lines look different.
                    let nz = (h / step).floor() as i32;
                    for iz in -nz..=nz {
                        let z = iz as f64 * step;
                        let mut x = -h;
                        while x <= h + 1e-9 {
                            let on_intersection = (x / step).round() * step;
                            let is_int = (x - on_intersection).abs() < fine * 0.5;
                            let glyph = if is_int { '+' } else { '-' };
                            if let Some((col, row, depth)) =
                                self.project(Vec3::new(x, 0.0, z))
                            {
                                let color = ground_color(depth, cam_dist, &grid);
                                self.put(col, row, depth, glyph, color, Kind::Ground);
                            }
                            x += fine;
                        }
                    }
                }
            }
            _ => {}
        }
    }

    /// Update buffers without flushing to stdout. Useful when compositing
    /// multiple scopes side by side (see [`MultiView`]).
    pub fn update(&mut self, markers: &[Marker]) {
        if self.trails {
            self.tick();
        } else {
            self.clear();
        }

        self.draw_ground();

        for m in markers {
            if let Some((col, row, depth)) = self.project(m.pos()) {
                self.put(col, row, depth, m.glyph, m.color, Kind::Live);
            }
        }
    }

    /// Render one frame to stdout.
    pub fn draw(&mut self, markers: &[Marker]) -> std::io::Result<()> {
        self.update(markers);
        self.flush()
    }

    /// Render the framed scope to a `Vec` of ANSI-colored lines, *without*
    /// any cursor movement. Each line has visible width `self.width + 2`
    /// (left + right border). Length = `self.height + 2`. Used by
    /// [`MultiView`] to stitch panels together.
    pub fn render_lines(&self) -> Vec<String> {
        let mut buf: Vec<u8> = Vec::new();
        self.write_frame(&mut buf).expect("writing to Vec is infallible");
        let s = String::from_utf8(buf).expect("valid utf8");
        s.lines().map(|l| l.to_string()).collect()
    }

    fn write_frame<W: Write>(&self, out: &mut W) -> std::io::Result<()> {
        out.queue(SetForegroundColor(Color::DarkGrey))?;
        out.queue(Print(format!("+{}+\n", "-".repeat(self.width as usize))))?;
        for row in 0..self.height {
            out.queue(SetForegroundColor(Color::DarkGrey))?;
            out.queue(Print("|"))?;
            let mut current = Color::Reset;
            for col in 0..self.width {
                let cell = self.cells[self.idx(col, row)];
                if cell.color != current {
                    out.queue(SetForegroundColor(cell.color))?;
                    current = cell.color;
                }
                out.queue(Print(cell.glyph))?;
            }
            out.queue(SetForegroundColor(Color::DarkGrey))?;
            out.queue(Print("|\n"))?;
        }
        out.queue(SetForegroundColor(Color::DarkGrey))?;
        out.queue(Print(format!("+{}+\n", "-".repeat(self.width as usize))))?;
        out.queue(ResetColor)?;
        Ok(())
    }

    fn flush(&self) -> std::io::Result<()> {
        let mut out = stdout();
        out.queue(cursor::MoveTo(0, 0))?;
        self.write_frame(&mut out)?;
        out.flush()
    }

    pub fn hud(&self, line: &str) -> std::io::Result<()> {
        let mut out = stdout();
        out.queue(Clear(ClearType::CurrentLine))?;
        out.queue(Print(line))?;
        out.queue(Print("\n"))?;
        out.flush()
    }
}

/// Trail glyph + color by age. Newer trails are brighter and use blockier
/// glyphs; older ones fade to dim dots so the live marker pops.
fn trail_style(age: u8) -> (char, Color) {
    match age {
        0 | 1 => ('o', Color::Rgb { r: 200, g: 200, b: 200 }),
        2 | 3 => ('*', Color::Rgb { r: 150, g: 150, b: 150 }),
        4..=6 => ('.', Color::Rgb { r: 110, g: 110, b: 110 }),
        _    => ('.', Color::Rgb { r: 70,  g: 70,  b: 70 }),
    }
}

/// Linearly fade between `near_color` and `far_color` over a sensible
/// distance (proportional to camera distance).
fn ground_color(depth: f64, cam_dist: f64, grid: &GroundGrid) -> Color {
    let max_d = cam_dist * 2.5;
    let t = (depth / max_d).clamp(0.0, 1.0);
    fn rgb(c: Color) -> (u8, u8, u8) {
        match c {
            Color::Rgb { r, g, b } => (r, g, b),
            _ => (128, 128, 128),
        }
    }
    let (nr, ng, nb) = rgb(grid.near_color);
    let (fr, fg, fb) = rgb(grid.far_color);
    let lerp = |a: u8, b: u8| (a as f64 * (1.0 - t) + b as f64 * t).round() as u8;
    Color::Rgb { r: lerp(nr, fr), g: lerp(ng, fg), b: lerp(nb, fb) }
}

/// Convenience: clear screen, home cursor, hide cursor.
pub fn prepare_terminal() -> std::io::Result<()> {
    let mut out = stdout();
    out.queue(Clear(ClearType::All))?;
    out.queue(cursor::MoveTo(0, 0))?;
    out.queue(cursor::Hide)?;
    out.flush()
}

/// Restore cursor visibility.
pub fn restore_terminal() -> std::io::Result<()> {
    let mut out = stdout();
    out.queue(cursor::Show)?;
    out.queue(ResetColor)?;
    out.flush()
}

// ---------------------------------------------------------------------------
// Multi-view (instrument cluster): three 2D ortho panels side-by-side.
// ---------------------------------------------------------------------------

/// Which world axis a panel maps onto its X or Y screen direction.
#[derive(Debug, Clone, Copy)]
pub enum Axis {
    X,
    Y,
    Z,
}

impl Axis {
    fn pick(self, p: Vec3) -> f64 {
        match self {
            Axis::X => p.x,
            Axis::Y => p.y,
            Axis::Z => p.z,
        }
    }
    fn label(self) -> &'static str {
        match self {
            Axis::X => "X",
            Axis::Y => "Y",
            Axis::Z => "Z",
        }
    }
}

struct Panel {
    title: String,
    x_axis: Axis,
    y_axis: Axis,
    x_range: (f64, f64),
    y_range: (f64, f64),
    scope: AsciiScope,
}

/// Three side-by-side 2D ortho panels (SIDE / TOP / FRONT) — like an
/// engineering instrument cluster. Avoids perspective-projection illegibility
/// while still surfacing all three world axes.
pub struct MultiView {
    panels: Vec<Panel>,
    /// Horizontal gap between panels, in characters.
    pub gap: u16,
}

impl MultiView {
    /// Standard three-view layout:
    ///
    /// * SIDE  — X (range) horizontal, Y (altitude) vertical
    /// * TOP   — X (range) horizontal, Z (cross-range) vertical
    /// * FRONT — Z (cross-range) horizontal, Y (altitude) vertical
    pub fn three_view(
        panel_w: u16,
        panel_h: u16,
        x_range: (f64, f64),
        y_range: (f64, f64),
        z_range: (f64, f64),
    ) -> Self {
        let panels = vec![
            Panel {
                title: "SIDE  X->range  Y^alt".into(),
                x_axis: Axis::X,
                y_axis: Axis::Y,
                x_range,
                y_range,
                scope: AsciiScope::new(panel_w, panel_h, x_range, y_range)
                    .with_trails(true)
                    .with_ground(true),
            },
            Panel {
                title: "TOP   X->range  Z^cross".into(),
                x_axis: Axis::X,
                y_axis: Axis::Z,
                x_range,
                y_range: z_range,
                scope: AsciiScope::new(panel_w, panel_h, x_range, z_range)
                    .with_trails(true)
                    .with_ground(false),
            },
            Panel {
                title: "FRONT Z->cross  Y^alt".into(),
                x_axis: Axis::Z,
                y_axis: Axis::Y,
                x_range: z_range,
                y_range,
                scope: AsciiScope::new(panel_w, panel_h, z_range, y_range)
                    .with_trails(true)
                    .with_ground(true),
            },
        ];
        Self { panels, gap: 2 }
    }

    /// Update + render all three panels in one composited frame.
    pub fn draw(&mut self, markers: &[Marker]) -> std::io::Result<()> {
        // Project each marker onto each panel's two world axes and update.
        for panel in &mut self.panels {
            let projected: Vec<Marker> = markers
                .iter()
                .map(|m| {
                    let p = m.pos();
                    Marker {
                        x: panel.x_axis.pick(p),
                        y: panel.y_axis.pick(p),
                        z: 0.0,
                        glyph: m.glyph,
                        color: m.color,
                    }
                })
                .collect();
            panel.scope.update(&projected);
        }

        let renders: Vec<Vec<String>> =
            self.panels.iter().map(|p| p.scope.render_lines()).collect();

        let mut out = stdout();
        out.queue(cursor::MoveTo(0, 0))?;

        // Title row.
        for (i, panel) in self.panels.iter().enumerate() {
            if i > 0 {
                out.queue(Print(" ".repeat(self.gap as usize)))?;
            }
            let total_w = panel.scope.width as usize + 2;
            out.queue(SetForegroundColor(Color::Yellow))?;
            out.queue(Print(center(&panel.title, total_w)))?;
        }
        out.queue(ResetColor)?;
        out.queue(Print("\n"))?;

        // Panel rows.
        let nrows = renders[0].len();
        for r in 0..nrows {
            for (i, lines) in renders.iter().enumerate() {
                if i > 0 {
                    out.queue(Print(" ".repeat(self.gap as usize)))?;
                }
                out.queue(Print(&lines[r]))?;
            }
            out.queue(Print("\n"))?;
        }

        // Axis-range label row (printed under each panel).
        for (i, panel) in self.panels.iter().enumerate() {
            if i > 0 {
                out.queue(Print(" ".repeat(self.gap as usize)))?;
            }
            let total_w = panel.scope.width as usize + 2;
            let lo = fmt_si(panel.x_range.0);
            let hi = fmt_si(panel.x_range.1);
            let mid = format!("{} ({})", panel.x_axis.label(), short_axis_label(panel.x_axis));
            // Build " lo ────── mid ────── hi " padded to total_w.
            let inner = total_w.saturating_sub(2);
            let raw = format!("{} {} {}", lo, mid, hi);
            let line = if raw.len() >= inner {
                raw[..inner].to_string()
            } else {
                let pad = inner - raw.len();
                let left_dashes = pad / 2;
                let right_dashes = pad - left_dashes;
                format!(
                    " {}{}{} {} {}{}{} ",
                    lo,
                    " ",
                    "-".repeat(left_dashes.saturating_sub(2)),
                    mid,
                    "-".repeat(right_dashes.saturating_sub(2)),
                    " ",
                    hi
                )
            };
            out.queue(SetForegroundColor(Color::DarkGrey))?;
            out.queue(Print(truncate_pad(&line, total_w)))?;
        }
        out.queue(ResetColor)?;
        out.queue(Print("\n"))?;

        // y-range label row (just min/max on the left + label on the right).
        for (i, panel) in self.panels.iter().enumerate() {
            if i > 0 {
                out.queue(Print(" ".repeat(self.gap as usize)))?;
            }
            let total_w = panel.scope.width as usize + 2;
            let txt = format!(
                "{} {} {} .. {}",
                panel.y_axis.label(),
                short_axis_label(panel.y_axis),
                fmt_si(panel.y_range.0),
                fmt_si(panel.y_range.1),
            );
            out.queue(SetForegroundColor(Color::DarkGrey))?;
            out.queue(Print(truncate_pad(&txt, total_w)))?;
        }
        out.queue(ResetColor)?;
        out.queue(Print("\n"))?;

        out.flush()
    }

    /// Print a one-line HUD below the cluster.
    pub fn hud(&self, line: &str) -> std::io::Result<()> {
        let mut out = stdout();
        out.queue(Clear(ClearType::CurrentLine))?;
        out.queue(Print(line))?;
        out.queue(Print("\n"))?;
        out.flush()
    }
}

fn center(s: &str, width: usize) -> String {
    if s.len() >= width {
        return s[..width].to_string();
    }
    let pad = width - s.len();
    let left = pad / 2;
    let right = pad - left;
    format!("{}{}{}", " ".repeat(left), s, " ".repeat(right))
}

fn truncate_pad(s: &str, width: usize) -> String {
    if s.len() >= width {
        s[..width].to_string()
    } else {
        format!("{}{}", s, " ".repeat(width - s.len()))
    }
}

fn fmt_si(v: f64) -> String {
    let a = v.abs();
    if a >= 1.0e6 {
        format!("{:.1}M", v / 1.0e6)
    } else if a >= 1.0e3 {
        format!("{:.1}k", v / 1.0e3)
    } else {
        format!("{:.0}", v)
    }
}

fn short_axis_label(a: Axis) -> &'static str {
    match a {
        Axis::X => "range",
        Axis::Y => "alt",
        Axis::Z => "cross",
    }
}

// ---------------------------------------------------------------------------
// Recorder + SVG export
// ---------------------------------------------------------------------------

/// Phase tag attached to each recorded sample. Affects color in SVG output.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TracePhase {
    Boost,
    Coast,
    Impact,
}

#[derive(Debug, Clone, Copy)]
pub struct TraceSample {
    pub t: f64,
    pub pos: Vec3,
    pub phase: TracePhase,
}

/// Records body samples over the lifetime of a simulation. Export as a 4-up
/// SVG (SIDE / TOP / FRONT / summary) after the run.
#[derive(Default, Debug, Clone)]
pub struct Recorder {
    pub samples: Vec<TraceSample>,
    pub label: String,
}

impl Recorder {
    pub fn new(label: impl Into<String>) -> Self {
        Self { samples: Vec::new(), label: label.into() }
    }

    pub fn push(&mut self, t: f64, pos: Vec3, phase: TracePhase) {
        self.samples.push(TraceSample { t, pos, phase });
    }

    /// Write a 2x2 SVG summary to `path`. Auto-fits the data range; pads by
    /// 5%. Pure string output, no external SVG crate.
    pub fn export_svg(&self, path: impl AsRef<std::path::Path>) -> std::io::Result<()> {
        self.export_svg_inner(path, false)
    }

    /// Like [`export_svg`], but emits SMIL animations so the trajectory
    /// is drawn progressively (boost segment first, then coast) and a
    /// moving dot follows the body's current position. Animation
    /// duration matches the simulated flight time and loops indefinitely.
    pub fn export_svg_animated(&self, path: impl AsRef<std::path::Path>) -> std::io::Result<()> {
        self.export_svg_inner(path, true)
    }

    fn export_svg_inner(&self, path: impl AsRef<std::path::Path>, animated: bool) -> std::io::Result<()> {
        if self.samples.is_empty() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "no samples recorded",
            ));
        }

        let (xmin, xmax) = bounds(self.samples.iter().map(|s| s.pos.x));
        let (_ymin, ymax) = bounds(self.samples.iter().map(|s| s.pos.y));
        let (zmin, zmax) = bounds(self.samples.iter().map(|s| s.pos.z));

        // Equalize axis scales: every panel's m-per-pixel must match, so we
        // pick the largest data span across X/Y/Z, snap it up to a nice
        // round number, and use a window of that size for every axis.
        // Each axis is anchored so a 0 tick lands on the grid where
        // possible (Y always anchored at 0; X/Z anchored to the nearest
        // tick step around their data midpoint, which usually lands 0 on
        // the grid too).
        let span_x = (xmax - xmin).max(1.0);
        let span_y = (ymax.max(0.0)).max(1.0);
        let span_z = (zmax - zmin).max(1.0);
        let raw_span = span_x.max(span_y).max(span_z) * 1.1;
        let span = nice_ceil(raw_span);
        let step = span / 5.0;
        let snap = |c: f64| (c / step).round() * step;
        let x_center = snap((xmin + xmax) * 0.5);
        let z_center = snap((zmin + zmax) * 0.5);
        let xr = if xmin >= 0.0 {
            (0.0_f64, span)
        } else {
            (x_center - span * 0.5, x_center + span * 0.5)
        };
        let yr = (0.0_f64, span);
        let zr = if zmin >= 0.0 {
            (0.0_f64, span)
        } else {
            (z_center - span * 0.5, z_center + span * 0.5)
        };

        // Layout: 2 columns x 2 rows of square panels so the plot area is
        // square and 1 pixel = the same number of meters on every axis.
        let pw = 560.0_f64;
        let ph = 560.0_f64;
        let margin = 60.0_f64;
        let total_w = (pw * 2.0 + margin * 3.0) as i32;
        let total_h = (ph * 2.0 + margin * 3.0) as i32;

        let mut s = String::new();
        s.push_str(&format!(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" viewBox=\"0 0 {w} {h}\" width=\"{w}\" height=\"{h}\">\n",
            w = total_w,
            h = total_h
        ));
        s.push_str("<style>\n");
        s.push_str(
            "  .bg { fill: #0c1116; }\n\
             .panel { fill: #11161c; stroke: #2a3340; stroke-width: 1; }\n\
             .grid { stroke: #1c2430; stroke-width: 1; }\n\
             .axis { stroke: #4a5260; stroke-width: 1; }\n\
             .ground { stroke: #6b5a26; stroke-width: 1.5; stroke-dasharray: 4 3; }\n\
             .tick { fill: #7a8290; font: 11px monospace; }\n\
             .title { fill: #d6deea; font: 14px monospace; font-weight: bold; }\n\
             .subtitle { fill: #7a8290; font: 11px monospace; }\n\
             .boost { stroke: #ff5c5c; stroke-width: 2.2; fill: none; }\n\
             .coast { stroke: #5cff90; stroke-width: 2.2; fill: none; }\n\
             .impact { fill: #ffa040; stroke: #ffa040; }\n\
             .summary { fill: #d6deea; font: 13px monospace; }\n\
             .summary-dim { fill: #7a8290; font: 12px monospace; }\n",
        );
        s.push_str("</style>\n");
        s.push_str(&format!("<rect class=\"bg\" width=\"{}\" height=\"{}\" />\n", total_w, total_h));

        let t0 = self.samples.first().unwrap().t;
        let t_end = self.samples.last().unwrap().t;
        let anim_dur = (t_end - t0).max(0.001);
        let mut panel_idx: usize = 0;
        let mut draw_panel = |s: &mut String, px: f64, py: f64, title: &str,
                          xa: Axis, ya: Axis, xr: (f64, f64), yr: (f64, f64),
                          show_ground: bool| {
            s.push_str(&format!(
                "<g transform=\"translate({px},{py})\">\n",
                px = px,
                py = py
            ));
            s.push_str(&format!(
                "<rect class=\"panel\" width=\"{}\" height=\"{}\" />\n",
                pw, ph
            ));
            s.push_str(&format!(
                "<text class=\"title\" x=\"10\" y=\"18\">{}</text>\n",
                xml_escape(title)
            ));
            s.push_str(&format!(
                "<text class=\"subtitle\" x=\"10\" y=\"32\">{} -&gt; {} (horiz),  {} -&gt; {} (vert)</text>\n",
                xa.label(), short_axis_label(xa), ya.label(), short_axis_label(ya),
            ));

            // Plot area inside the panel. Forced square so the same number
            // of meters spans the same number of pixels on both axes.
            let inset_l = 60.0;
            let inset_r = 20.0;
            let inset_t = 50.0;
            let inset_b = 40.0;
            let plot_size = (pw - inset_l - inset_r).min(ph - inset_t - inset_b);
            let plot_l = inset_l;
            let plot_r = plot_l + plot_size;
            let plot_t = inset_t;
            let plot_b = plot_t + plot_size;
            let map_x = |v: f64| plot_l + (v - xr.0) / (xr.1 - xr.0) * (plot_r - plot_l);
            let map_y = |v: f64| plot_b - (v - yr.0) / (yr.1 - yr.0) * (plot_b - plot_t);

            // Gridlines + ticks (5 each axis).
            for i in 0..=5 {
                let t = i as f64 / 5.0;
                let xv = xr.0 + t * (xr.1 - xr.0);
                let yv = yr.0 + t * (yr.1 - yr.0);
                let xpix = map_x(xv);
                let ypix = map_y(yv);
                s.push_str(&format!(
                    "<line class=\"grid\" x1=\"{:.1}\" y1=\"{:.1}\" x2=\"{:.1}\" y2=\"{:.1}\" />\n",
                    xpix, plot_t, xpix, plot_b
                ));
                s.push_str(&format!(
                    "<line class=\"grid\" x1=\"{:.1}\" y1=\"{:.1}\" x2=\"{:.1}\" y2=\"{:.1}\" />\n",
                    plot_l, ypix, plot_r, ypix
                ));
                s.push_str(&format!(
                    "<text class=\"tick\" x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"middle\">{}</text>\n",
                    xpix, plot_b + 14.0, fmt_si(xv)
                ));
                s.push_str(&format!(
                    "<text class=\"tick\" x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"end\">{}</text>\n",
                    plot_l - 4.0, ypix + 4.0, fmt_si(yv)
                ));
            }
            // Axis lines.
            s.push_str(&format!(
                "<line class=\"axis\" x1=\"{:.1}\" y1=\"{:.1}\" x2=\"{:.1}\" y2=\"{:.1}\" />\n",
                plot_l, plot_t, plot_l, plot_b
            ));
            s.push_str(&format!(
                "<line class=\"axis\" x1=\"{:.1}\" y1=\"{:.1}\" x2=\"{:.1}\" y2=\"{:.1}\" />\n",
                plot_l, plot_b, plot_r, plot_b
            ));
            // Ground line where vertical axis = 0 (only meaningful for Y-vertical panels).
            if show_ground && yr.0 <= 0.0 && yr.1 >= 0.0 {
                let yz = map_y(0.0);
                s.push_str(&format!(
                    "<line class=\"ground\" x1=\"{:.1}\" y1=\"{:.1}\" x2=\"{:.1}\" y2=\"{:.1}\" />\n",
                    plot_l, yz, plot_r, yz
                ));
            }

            // Trajectory polylines, segmented by phase. We collect each
            // contiguous (phase, points, t_start, t_end) segment first,
            // then emit them — animated mode needs the timing to schedule
            // each segment's stroke-dashoffset animation.
            #[derive(Clone)]
            struct Seg {
                phase: TracePhase,
                pts: Vec<(f64, f64)>,
                t_start: f64,
                t_end: f64,
            }
            let mut segs: Vec<Seg> = Vec::new();
            let mut cur = Seg {
                phase: self.samples[0].phase,
                pts: Vec::new(),
                t_start: self.samples[0].t,
                t_end: self.samples[0].t,
            };
            for sample in &self.samples {
                let xv = xa.pick(sample.pos);
                let yv = ya.pick(sample.pos);
                let pt = (map_x(xv), map_y(yv));
                if sample.phase != cur.phase {
                    // Carry the join point so segments connect visually.
                    cur.pts.push(pt);
                    cur.t_end = sample.t;
                    if cur.pts.len() >= 2 { segs.push(cur.clone()); }
                    cur = Seg {
                        phase: sample.phase,
                        pts: Vec::new(),
                        t_start: sample.t,
                        t_end: sample.t,
                    };
                }
                cur.pts.push(pt);
                cur.t_end = sample.t;
            }
            if cur.pts.len() >= 2 { segs.push(cur); }

            let mut combined_d = String::new();
            for (si, seg) in segs.iter().enumerate() {
                let class = match seg.phase {
                    TracePhase::Boost => "boost",
                    TracePhase::Coast | TracePhase::Impact => "coast",
                };
                let mut d = String::new();
                for (i, (x, y)) in seg.pts.iter().enumerate() {
                    if i == 0 {
                        d.push_str(&format!("M {:.1} {:.1}", x, y));
                        if combined_d.is_empty() {
                            combined_d.push_str(&format!("M {:.1} {:.1}", x, y));
                        } else {
                            combined_d.push_str(&format!(" L {:.1} {:.1}", x, y));
                        }
                    } else {
                        d.push_str(&format!(" L {:.1} {:.1}", x, y));
                        combined_d.push_str(&format!(" L {:.1} {:.1}", x, y));
                    }
                }
                if animated {
                    let mut len = 0.0_f64;
                    for w in seg.pts.windows(2) {
                        len += ((w[1].0 - w[0].0).powi(2) + (w[1].1 - w[0].1).powi(2)).sqrt();
                    }
                    let len = len.max(1.0);
                    // Map this segment's [t_start, t_end] onto fractions
                    // of the master loop, so all segments share one
                    // dur=anim_dur cycle and stay in sync with the
                    // moving body marker (also dur=anim_dur).
                    let f0 = ((seg.t_start - t0) / anim_dur).clamp(0.0, 1.0);
                    let f1 = ((seg.t_end   - t0) / anim_dur).clamp(0.0, 1.0);
                    // Stay at L until f0; animate L -> 0 between f0..f1;
                    // stay at 0 until 1. Skip degenerate keyTimes if
                    // f0 == 0 or f1 == 1.
                    let mut values: Vec<String> = Vec::new();
                    let mut keys: Vec<String> = Vec::new();
                    if f0 > 0.0 {
                        values.push(format!("{:.1}", len));
                        keys.push("0".to_string());
                    }
                    values.push(format!("{:.1}", len));
                    keys.push(format!("{:.4}", f0));
                    values.push("0".to_string());
                    keys.push(format!("{:.4}", f1));
                    if f1 < 1.0 {
                        values.push("0".to_string());
                        keys.push("1".to_string());
                    }
                    let _ = si;
                    s.push_str(&format!(
                        "<path class=\"{cls}\" d=\"{d}\" pathLength=\"{L:.1}\" \
                         stroke-dasharray=\"{L:.1}\" stroke-dashoffset=\"{L:.1}\">\n\
                         <animate attributeName=\"stroke-dashoffset\" \
                         values=\"{V}\" keyTimes=\"{K}\" \
                         dur=\"{T:.2}s\" repeatCount=\"indefinite\" />\n\
                         </path>\n",
                        cls = class,
                        d = d,
                        L = len,
                        V = values.join(";"),
                        K = keys.join(";"),
                        T = anim_dur,
                    ));
                } else {
                    s.push_str(&format!("<path class=\"{}\" d=\"{}\" />\n", class, d));
                }
            }

            if animated && !combined_d.is_empty() {
                // Hidden combined path drives the animateMotion for the
                // moving body marker. Also acts as the timing master via
                // a sentinel <animate id="loop"> on the panel <g>.
                let path_id = format!("recpath_p{}", panel_idx);
                s.push_str(&format!(
                    "<path id=\"{id}\" d=\"{d}\" fill=\"none\" stroke=\"none\" />\n",
                    id = path_id, d = combined_d,
                ));
                s.push_str(&format!(
                    "<circle r=\"5\" fill=\"#5cff90\" stroke=\"#000\" stroke-width=\"0.6\">\n\
                     <animateMotion dur=\"{T:.2}s\" repeatCount=\"indefinite\" rotate=\"0\">\n\
                     <mpath xlink:href=\"#{id}\" href=\"#{id}\" />\n\
                     </animateMotion>\n\
                     </circle>\n",
                    T = anim_dur, id = path_id,
                ));
            }

            // Impact marker if we recorded one.
            if let Some(last) = self.samples.last() {
                if last.phase == TracePhase::Impact {
                    let xv = xa.pick(last.pos);
                    let yv = ya.pick(last.pos);
                    s.push_str(&format!(
                        "<circle class=\"impact\" cx=\"{:.1}\" cy=\"{:.1}\" r=\"5\" />\n",
                        map_x(xv), map_y(yv)
                    ));
                }
            }

            s.push_str("</g>\n");
            panel_idx += 1;
        };

        let p_side = (margin, margin);
        let p_top = (margin * 2.0 + pw, margin);
        let p_front = (margin, margin * 2.0 + ph);
        let p_summary = (margin * 2.0 + pw, margin * 2.0 + ph);

        draw_panel(&mut s, p_side.0, p_side.1, "SIDE  X x Y", Axis::X, Axis::Y, xr, yr, true);
        draw_panel(&mut s, p_top.0, p_top.1, "TOP   X x Z", Axis::X, Axis::Z, xr, zr, false);
        draw_panel(&mut s, p_front.0, p_front.1, "FRONT Z x Y", Axis::Z, Axis::Y, zr, yr, true);

        // Summary panel.
        let last = self.samples.last().unwrap();
        let max_alt = self
            .samples
            .iter()
            .map(|s| s.pos.y)
            .fold(f64::NEG_INFINITY, f64::max);
        let ground_range = (last.pos.x.powi(2) + last.pos.z.powi(2)).sqrt();
        let label = if self.label.is_empty() {
            "Trajectory".to_string()
        } else {
            self.label.clone()
        };
        s.push_str(&format!(
            "<g transform=\"translate({px},{py})\">\n",
            px = p_summary.0,
            py = p_summary.1
        ));
        s.push_str(&format!(
            "<rect class=\"panel\" width=\"{}\" height=\"{}\" />\n",
            pw, ph
        ));
        s.push_str(&format!(
            "<text class=\"title\" x=\"20\" y=\"38\">{}</text>\n",
            xml_escape(&label)
        ));
        let summary_lines = [
            format!("samples       : {}", self.samples.len()),
            format!("duration      : {:.2} s", last.t),
            format!("max altitude  : {:.1} m", max_alt),
            format!("impact        : ({:.1}, {:.1}, {:.1}) m", last.pos.x, last.pos.y, last.pos.z),
            format!("ground range  : {:.1} m", ground_range),
            String::new(),
            "legend:".to_string(),
        ];
        for (i, line) in summary_lines.iter().enumerate() {
            let class = if line.starts_with("legend") {
                "summary-dim"
            } else {
                "summary"
            };
            s.push_str(&format!(
                "<text class=\"{}\" x=\"20\" y=\"{}\">{}</text>\n",
                class,
                70.0 + i as f64 * 22.0,
                xml_escape(line)
            ));
        }
        // Legend swatches.
        let legend_y = 70.0 + summary_lines.len() as f64 * 22.0;
        s.push_str(&format!(
            "<line class=\"boost\" x1=\"30\" y1=\"{:.1}\" x2=\"60\" y2=\"{:.1}\" />\n\
             <text class=\"summary-dim\" x=\"70\" y=\"{:.1}\">boost (thrust on)</text>\n",
            legend_y, legend_y, legend_y + 4.0
        ));
        s.push_str(&format!(
            "<line class=\"coast\" x1=\"30\" y1=\"{:.1}\" x2=\"60\" y2=\"{:.1}\" />\n\
             <text class=\"summary-dim\" x=\"70\" y=\"{:.1}\">coast (ballistic)</text>\n",
            legend_y + 22.0, legend_y + 22.0, legend_y + 26.0
        ));
        s.push_str(&format!(
            "<circle class=\"impact\" cx=\"45\" cy=\"{:.1}\" r=\"5\" />\n\
             <text class=\"summary-dim\" x=\"70\" y=\"{:.1}\">impact</text>\n",
            legend_y + 44.0, legend_y + 48.0
        ));
        s.push_str("</g>\n");

        s.push_str("</svg>\n");

        std::fs::write(path, s)
    }
}

fn bounds<I: Iterator<Item = f64>>(it: I) -> (f64, f64) {
    let mut lo = f64::INFINITY;
    let mut hi = f64::NEG_INFINITY;
    for v in it {
        if v < lo { lo = v; }
        if v > hi { hi = v; }
    }
    (lo, hi)
}

/// Round `x` up to a "nice" value of the form k * 10^n where
/// k ∈ {1, 1.5, 2, 2.5, 3, 4, 5, 7.5, 10}. Used for axis-span snapping.
fn nice_ceil(x: f64) -> f64 {
    if x <= 0.0 { return 1.0; }
    let exp = x.log10().floor();
    let base = 10f64.powf(exp);
    let m = x / base;
    let nice = if m <= 1.0 { 1.0 }
        else if m <= 1.5 { 1.5 }
        else if m <= 2.0 { 2.0 }
        else if m <= 2.5 { 2.5 }
        else if m <= 3.0 { 3.0 }
        else if m <= 4.0 { 4.0 }
        else if m <= 5.0 { 5.0 }
        else if m <= 7.5 { 7.5 }
        else { 10.0 };
    nice * base
}


fn xml_escape<S: AsRef<str>>(s: S) -> String {
    s.as_ref()
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

// ---------------------------------------------------------------------------
// MultiRecorder — N independently-labeled tracks rendered on one SVG.
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
pub struct Track {
    pub label: String,
    /// Any valid SVG stroke color (e.g. "#5cff90", "tomato", "rgb(...)").
    pub color: String,
    pub samples: Vec<TraceSample>,
}

/// Records multiple parallel trajectories (e.g. drones in formation) and
/// exports them all to a single SVG with a shared coordinate system. Each
/// track is drawn in its own color; phase information on samples is
/// ignored (use `Recorder` directly if you want boost/coast coloring).
#[derive(Debug, Clone, Default)]
pub struct MultiRecorder {
    pub label: String,
    pub tracks: Vec<Track>,
}

impl MultiRecorder {
    pub fn new(label: impl Into<String>) -> Self {
        Self { label: label.into(), tracks: Vec::new() }
    }

    /// Allocate a new track and return its index. Color is any SVG color
    /// string. Subsequent `push(idx, ..)` calls append samples to it.
    pub fn add_track(&mut self, label: impl Into<String>, color: impl Into<String>) -> usize {
        let idx = self.tracks.len();
        self.tracks.push(Track {
            label: label.into(),
            color: color.into(),
            samples: Vec::new(),
        });
        idx
    }

    pub fn push(&mut self, track: usize, t: f64, pos: Vec3) {
        self.tracks[track].samples.push(TraceSample {
            t,
            pos,
            phase: TracePhase::Coast,
        });
    }

    pub fn export_svg(&self, path: impl AsRef<std::path::Path>) -> std::io::Result<()> {
        self.export_svg_inner(path, false)
    }

    /// Like [`export_svg`], but emits SMIL animations so each track is
    /// drawn progressively in real time and a moving dot follows the
    /// current position. Animation duration matches the longest track
    /// (in simulated seconds = wall-clock seconds, looped indefinitely).
    pub fn export_svg_animated(&self, path: impl AsRef<std::path::Path>) -> std::io::Result<()> {
        self.export_svg_inner(path, true)
    }

    fn export_svg_inner(&self, path: impl AsRef<std::path::Path>, animated: bool) -> std::io::Result<()> {
        if self.tracks.iter().all(|t| t.samples.is_empty()) {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "no samples recorded in any track",
            ));
        }

        let all_samples = || self.tracks.iter().flat_map(|t| t.samples.iter());
        let (xmin, xmax) = bounds(all_samples().map(|s| s.pos.x));
        let (_ymin, ymax) = bounds(all_samples().map(|s| s.pos.y));
        let (zmin, zmax) = bounds(all_samples().map(|s| s.pos.z));

        let span_x = (xmax - xmin).max(1.0);
        let span_y = (ymax.max(0.0)).max(1.0);
        let span_z = (zmax - zmin).max(1.0);
        let raw_span = span_x.max(span_y).max(span_z) * 1.1;
        let span = nice_ceil(raw_span);
        let step = span / 5.0;
        let snap = |c: f64| (c / step).round() * step;
        let x_center = snap((xmin + xmax) * 0.5);
        let z_center = snap((zmin + zmax) * 0.5);
        let xr = if xmin >= 0.0 {
            (0.0_f64, span)
        } else {
            (x_center - span * 0.5, x_center + span * 0.5)
        };
        let yr = (0.0_f64, span);
        let zr = if zmin >= 0.0 {
            (0.0_f64, span)
        } else {
            (z_center - span * 0.5, z_center + span * 0.5)
        };

        let pw = 560.0_f64;
        let ph = 560.0_f64;
        let margin = 60.0_f64;
        let total_w = (pw * 2.0 + margin * 3.0) as i32;
        let total_h = (ph * 2.0 + margin * 3.0) as i32;

        let mut s = String::new();
        s.push_str(&format!(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" viewBox=\"0 0 {w} {h}\" width=\"{w}\" height=\"{h}\">\n",
            w = total_w,
            h = total_h
        ));
        s.push_str("<style>\n");
        s.push_str(
            "  .bg { fill: #0c1116; }\n\
             .panel { fill: #11161c; stroke: #2a3340; stroke-width: 1; }\n\
             .grid { stroke: #1c2430; stroke-width: 1; }\n\
             .axis { stroke: #4a5260; stroke-width: 1; }\n\
             .ground { stroke: #6b5a26; stroke-width: 1.5; stroke-dasharray: 4 3; }\n\
             .tick { fill: #7a8290; font: 11px monospace; }\n\
             .title { fill: #d6deea; font: 14px monospace; font-weight: bold; }\n\
             .subtitle { fill: #7a8290; font: 11px monospace; }\n\
             .summary { fill: #d6deea; font: 13px monospace; }\n\
             .summary-dim { fill: #7a8290; font: 12px monospace; }\n\
             .track { fill: none; stroke-width: 1.8; }\n\
             .start { stroke-width: 1.2; }\n\
             .end { stroke-width: 1.0; }\n",
        );
        s.push_str("</style>\n");
        s.push_str(&format!("<rect class=\"bg\" width=\"{}\" height=\"{}\" />\n", total_w, total_h));

        let tracks = &self.tracks;
        // Animation duration = longest track's elapsed simulated time.
        let anim_dur = self
            .tracks
            .iter()
            .filter_map(|t| {
                let f = t.samples.first()?.t;
                let l = t.samples.last()?.t;
                Some(l - f)
            })
            .fold(0.0_f64, f64::max)
            .max(0.001);
        let mut panel_idx: usize = 0;
        let mut draw_panel = |s: &mut String, px: f64, py: f64, title: &str,
                          xa: Axis, ya: Axis, xr: (f64, f64), yr: (f64, f64),
                          show_ground: bool| {
            s.push_str(&format!("<g transform=\"translate({px},{py})\">\n", px = px, py = py));
            s.push_str(&format!("<rect class=\"panel\" width=\"{}\" height=\"{}\" />\n", pw, ph));
            s.push_str(&format!("<text class=\"title\" x=\"10\" y=\"18\">{}</text>\n", xml_escape(title)));
            s.push_str(&format!(
                "<text class=\"subtitle\" x=\"10\" y=\"32\">{} -&gt; {} (horiz),  {} -&gt; {} (vert)</text>\n",
                xa.label(), short_axis_label(xa), ya.label(), short_axis_label(ya),
            ));

            let inset_l = 60.0;
            let inset_r = 20.0;
            let inset_t = 50.0;
            let inset_b = 40.0;
            let plot_size = (pw - inset_l - inset_r).min(ph - inset_t - inset_b);
            let plot_l = inset_l;
            let plot_r = plot_l + plot_size;
            let plot_t = inset_t;
            let plot_b = plot_t + plot_size;
            let map_x = |v: f64| plot_l + (v - xr.0) / (xr.1 - xr.0) * (plot_r - plot_l);
            let map_y = |v: f64| plot_b - (v - yr.0) / (yr.1 - yr.0) * (plot_b - plot_t);

            for i in 0..=5 {
                let t = i as f64 / 5.0;
                let xv = xr.0 + t * (xr.1 - xr.0);
                let yv = yr.0 + t * (yr.1 - yr.0);
                let xpix = map_x(xv);
                let ypix = map_y(yv);
                s.push_str(&format!("<line class=\"grid\" x1=\"{:.1}\" y1=\"{:.1}\" x2=\"{:.1}\" y2=\"{:.1}\" />\n", xpix, plot_t, xpix, plot_b));
                s.push_str(&format!("<line class=\"grid\" x1=\"{:.1}\" y1=\"{:.1}\" x2=\"{:.1}\" y2=\"{:.1}\" />\n", plot_l, ypix, plot_r, ypix));
                s.push_str(&format!("<text class=\"tick\" x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"middle\">{}</text>\n", xpix, plot_b + 14.0, fmt_si(xv)));
                s.push_str(&format!("<text class=\"tick\" x=\"{:.1}\" y=\"{:.1}\" text-anchor=\"end\">{}</text>\n", plot_l - 4.0, ypix + 4.0, fmt_si(yv)));
            }
            s.push_str(&format!("<line class=\"axis\" x1=\"{:.1}\" y1=\"{:.1}\" x2=\"{:.1}\" y2=\"{:.1}\" />\n", plot_l, plot_t, plot_l, plot_b));
            s.push_str(&format!("<line class=\"axis\" x1=\"{:.1}\" y1=\"{:.1}\" x2=\"{:.1}\" y2=\"{:.1}\" />\n", plot_l, plot_b, plot_r, plot_b));
            if show_ground && yr.0 <= 0.0 && yr.1 >= 0.0 {
                let yz = map_y(0.0);
                s.push_str(&format!("<line class=\"ground\" x1=\"{:.1}\" y1=\"{:.1}\" x2=\"{:.1}\" y2=\"{:.1}\" />\n", plot_l, yz, plot_r, yz));
            }

            // One polyline per track, in track color.
            for (ti, track) in tracks.iter().enumerate() {
                if track.samples.len() < 2 { continue; }
                let mut d = String::new();
                for (i, sample) in track.samples.iter().enumerate() {
                    let xv = xa.pick(sample.pos);
                    let yv = ya.pick(sample.pos);
                    let px = map_x(xv);
                    let py = map_y(yv);
                    if i == 0 {
                        d.push_str(&format!("M {:.1} {:.1}", px, py));
                    } else {
                        d.push_str(&format!(" L {:.1} {:.1}", px, py));
                    }
                }
                let path_id = format!("p{}t{}", panel_idx, ti);
                if animated {
                    // Approximate path length so we can use stroke-dasharray
                    // to reveal the line progressively. SVG also exposes
                    // pathLength; we set it explicitly to the same value
                    // we pass to dasharray so the animation is exact.
                    let mut len = 0.0_f64;
                    let mut prev: Option<(f64, f64)> = None;
                    for sample in &track.samples {
                        let p = (map_x(xa.pick(sample.pos)), map_y(ya.pick(sample.pos)));
                        if let Some(q) = prev {
                            len += ((p.0 - q.0).powi(2) + (p.1 - q.1).powi(2)).sqrt();
                        }
                        prev = Some(p);
                    }
                    let len = len.max(1.0);
                    s.push_str(&format!(
                        "<path id=\"{id}\" class=\"track\" stroke=\"{c}\" d=\"{d}\" \
                         pathLength=\"{L:.1}\" stroke-dasharray=\"{L:.1}\" \
                         stroke-dashoffset=\"{L:.1}\">\n\
                         <animate attributeName=\"stroke-dashoffset\" \
                         values=\"{L:.1};0\" dur=\"{T:.2}s\" repeatCount=\"indefinite\" />\n\
                         </path>\n",
                        id = path_id,
                        c = xml_escape(&track.color),
                        d = d,
                        L = len,
                        T = anim_dur,
                    ));
                } else {
                    s.push_str(&format!(
                        "<path class=\"track\" stroke=\"{}\" d=\"{}\" />\n",
                        xml_escape(&track.color), d,
                    ));
                }
                // Start marker (hollow ring) is always visible.
                let first = track.samples.first().unwrap();
                let (sx, sy) = (map_x(xa.pick(first.pos)), map_y(ya.pick(first.pos)));
                s.push_str(&format!(
                    "<circle cx=\"{:.1}\" cy=\"{:.1}\" r=\"4\" fill=\"none\" stroke=\"{}\" stroke-width=\"1.4\" />\n",
                    sx, sy, xml_escape(&track.color)
                ));
                if animated {
                    // Moving dot follows the same path. animateMotion
                    // walks the path geometry over `anim_dur` seconds.
                    s.push_str(&format!(
                        "<circle r=\"5\" fill=\"{c}\" stroke=\"#000\" stroke-width=\"0.6\">\n\
                         <animateMotion dur=\"{T:.2}s\" repeatCount=\"indefinite\" rotate=\"0\">\n\
                         <mpath xlink:href=\"#{id}\" href=\"#{id}\" />\n\
                         </animateMotion>\n\
                         </circle>\n",
                        c = xml_escape(&track.color),
                        T = anim_dur,
                        id = path_id,
                    ));
                } else {
                    let last = track.samples.last().unwrap();
                    let (ex, ey) = (map_x(xa.pick(last.pos)), map_y(ya.pick(last.pos)));
                    s.push_str(&format!(
                        "<circle cx=\"{:.1}\" cy=\"{:.1}\" r=\"4\" fill=\"{}\" />\n",
                        ex, ey, xml_escape(&track.color)
                    ));
                }
            }

            s.push_str("</g>\n");
            panel_idx += 1;
        };

        let p_side = (margin, margin);
        let p_top = (margin * 2.0 + pw, margin);
        let p_front = (margin, margin * 2.0 + ph);
        let p_summary = (margin * 2.0 + pw, margin * 2.0 + ph);

        draw_panel(&mut s, p_side.0, p_side.1, "SIDE  X x Y", Axis::X, Axis::Y, xr, yr, true);
        draw_panel(&mut s, p_top.0, p_top.1, "TOP   X x Z", Axis::X, Axis::Z, xr, zr, false);
        draw_panel(&mut s, p_front.0, p_front.1, "FRONT Z x Y", Axis::Z, Axis::Y, zr, yr, true);

        // Summary panel.
        let label = if self.label.is_empty() { "Tracks".to_string() } else { self.label.clone() };
        s.push_str(&format!("<g transform=\"translate({px},{py})\">\n", px = p_summary.0, py = p_summary.1));
        s.push_str(&format!("<rect class=\"panel\" width=\"{}\" height=\"{}\" />\n", pw, ph));
        s.push_str(&format!("<text class=\"title\" x=\"20\" y=\"38\">{}</text>\n", xml_escape(&label)));

        let total_samples: usize = self.tracks.iter().map(|t| t.samples.len()).sum();
        let duration = self
            .tracks
            .iter()
            .filter_map(|t| t.samples.last().map(|s| s.t))
            .fold(0.0_f64, f64::max);

        let header = [
            format!("tracks        : {}", self.tracks.len()),
            format!("total samples : {}", total_samples),
            format!("duration      : {:.2} s", duration),
            String::new(),
            "legend:".to_string(),
        ];
        for (i, line) in header.iter().enumerate() {
            let class = if line.starts_with("legend") { "summary-dim" } else { "summary" };
            s.push_str(&format!(
                "<text class=\"{}\" x=\"20\" y=\"{}\">{}</text>\n",
                class, 70.0 + i as f64 * 22.0, xml_escape(line),
            ));
        }
        let mut y = 70.0 + header.len() as f64 * 22.0;
        for track in &self.tracks {
            let last_pos = track.samples.last().map(|s| s.pos).unwrap_or(Vec3::zero());
            s.push_str(&format!(
                "<line x1=\"30\" y1=\"{:.1}\" x2=\"60\" y2=\"{:.1}\" stroke=\"{}\" stroke-width=\"2.2\" />\n",
                y, y, xml_escape(&track.color),
            ));
            s.push_str(&format!(
                "<circle cx=\"45\" cy=\"{:.1}\" r=\"3.5\" fill=\"{}\" />\n",
                y, xml_escape(&track.color),
            ));
            s.push_str(&format!(
                "<text class=\"summary-dim\" x=\"70\" y=\"{:.1}\">{:<9}  end ({:.0}, {:.0}, {:.0}) m  ({} samples)</text>\n",
                y + 4.0,
                xml_escape(&track.label),
                last_pos.x, last_pos.y, last_pos.z,
                track.samples.len(),
            ));
            y += 22.0;
            if y > ph - 20.0 { break; }
        }
        s.push_str("</g>\n");
        s.push_str("</svg>\n");

        std::fs::write(path, s)
    }
}