ttui 2.0.0

A terminal UI framework built from first principles: direct control over text rendering, color, pane layout, and multiplexing.
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
//! Fixed-forward pinhole-camera projection — points, lines, and
//! polygons in camera-relative 3D space project to 2D screen
//! coordinates plus a depth-derived scale. Graduated from the depth &
//! perspective projection spike
//! (docs/design/specs/core/2026-08-10-depth-perspective-projection-spike-design.md)
//! per
//! docs/design/specs/core/2026-08-11-perspective-projection-graduation-design.md.
//! No camera position/orientation — see that spec's Non-goals.

/// A point in camera-relative 3D space.
#[derive(Clone, Copy, Debug)]
pub struct Point3 {
    /// Horizontal position, camera-relative.
    pub x: f32,
    /// Vertical position, camera-relative.
    pub y: f32,
    /// Depth (distance along the camera's forward axis).
    pub z: f32,
}

/// A line segment in camera-relative 3D space.
#[derive(Clone, Copy, Debug)]
pub struct Line3 {
    /// The segment's first endpoint.
    pub start: Point3,
    /// The segment's second endpoint.
    pub end: Point3,
}

/// A flat-shaded polygon in camera-relative 3D space — 3+ vertices,
/// in order around the perimeter (not necessarily convex).
#[derive(Clone, Debug)]
pub struct Polygon3 {
    /// Vertices in order around the perimeter.
    pub vertices: Vec<Point3>,
}

/// Screen/subpixel parameters for `Camera::project_line` — bundles
/// everything except the line itself, since Falcon's HUD (the first
/// real consumer beyond the depth/perspective spike) call sites were
/// becoming hard to read with 7 trailing positional `f32`s.
#[derive(Clone, Copy, Debug)]
pub struct ProjectLineParams {
    /// Screen-space projection center, x.
    pub center_x: f32,
    /// Screen-space projection center, y.
    pub center_y: f32,
    /// Visible screen width in cells, for clipping.
    pub screen_w: f32,
    /// Visible screen height in cells, for clipping.
    pub screen_h: f32,
    /// Canvas subpixel columns per cell.
    pub subpixels_x: f32,
    /// Canvas subpixel rows per cell.
    pub subpixels_y: f32,
    /// Minimum projected scale for the line to be drawn at all.
    pub min_scale: f32,
}

/// A fixed-forward pinhole camera: positioned at the origin, looking
/// down `+Z`. No position/orientation fields — general camera
/// movement is out of scope.
#[derive(Clone, Copy, Debug)]
pub struct Camera {
    /// Points at or nearer than this depth are clipped.
    pub near: f32,
    /// Controls field of view: larger = more zoomed in/narrower FOV.
    pub focal_length: f32,
}

/// Corrects for terminal cells being roughly twice as tall as wide —
/// same compensation the `Dial` widget already applies to its ring
/// radius.
pub const ASPECT_COMPENSATION: f32 = 2.0;

impl Camera {
    /// Projects `p` to `(screen_x, screen_y, scale)` in cell
    /// coordinates relative to `(center_x, center_y)`, where `scale`
    /// grows as the point gets nearer (drives size/brightness
    /// falloff). Returns `None` if `p.z <= self.near`.
    pub fn project(&self, p: Point3, center_x: f32, center_y: f32) -> Option<(f32, f32, f32)> {
        if p.z <= self.near {
            return None;
        }
        let ndc_x = p.x / p.z;
        let ndc_y = p.y / p.z;
        let scale = self.focal_length / p.z;
        let screen_x = center_x + ndc_x * self.focal_length * ASPECT_COMPENSATION;
        let screen_y = center_y - ndc_y * self.focal_length;
        Some((screen_x, screen_y, scale))
    }

    /// Projects `line` to `Canvas` subpixel coordinates for a canvas
    /// whose subpixel grid is `subpixels_x`/`subpixels_y` per cell and
    /// `screen_w`/`screen_h` cells wide/tall. Returns `None` if either
    /// endpoint is at/behind the near plane, if every vertex's `scale`
    /// is below `min_scale`, or if the projected segment falls
    /// entirely outside the visible screen. A segment partially
    /// outside is clipped to the visible rectangle before being
    /// converted to subpixel coordinates.
    ///
    /// Note: clipping happens in cell space against the closed
    /// interval `[0, screen_w] x [0, screen_h]`, so a caller passing
    /// `screen_w`/`screen_h` equal to the canvas's actual cell
    /// width/height can get a clipped endpoint at exactly `screen_w`
    /// (or `screen_h`), which converts to a subpixel coordinate of
    /// `screen_w * subpixels_x` — one past the last valid column
    /// index (`Canvas::grid_width() - 1`). `Canvas::set_pixel`'s own
    /// bounds check makes this a silent no-op (the line just loses its
    /// last subpixel) rather than a panic, so this half-open/closed
    /// boundary mismatch is a known cosmetic quirk, not a bug to fix
    /// here.
    pub fn project_line(
        &self,
        line: Line3,
        params: ProjectLineParams,
    ) -> Option<(u16, u16, u16, u16)> {
        let (sx0, sy0, scale0) = self.project(line.start, params.center_x, params.center_y)?;
        let (sx1, sy1, scale1) = self.project(line.end, params.center_x, params.center_y)?;
        if scale0.max(scale1) < params.min_scale {
            return None;
        }
        let (cx0, cy0, cx1, cy1) =
            clip_to_screen(sx0, sy0, sx1, sy1, params.screen_w, params.screen_h)?;
        Some((
            (cx0 * params.subpixels_x)
                .round()
                .clamp(0.0, u16::MAX as f32) as u16,
            (cy0 * params.subpixels_y)
                .round()
                .clamp(0.0, u16::MAX as f32) as u16,
            (cx1 * params.subpixels_x)
                .round()
                .clamp(0.0, u16::MAX as f32) as u16,
            (cy1 * params.subpixels_y)
                .round()
                .clamp(0.0, u16::MAX as f32) as u16,
        ))
    }

    /// Projects `polygon`'s vertices to `Canvas` subpixel coordinates,
    /// ready for `Canvas::fill_polygon`. Returns `None` if any vertex
    /// is at/behind the near plane, or if every vertex's `scale` is
    /// below `min_scale` — no screen-edge clipping for polygons (see
    /// this Arc's design spec Non-goals).
    pub fn project_polygon(
        &self,
        polygon: &Polygon3,
        center_x: f32,
        center_y: f32,
        subpixels_x: f32,
        subpixels_y: f32,
        min_scale: f32,
    ) -> Option<Vec<(f32, f32)>> {
        let mut points = Vec::with_capacity(polygon.vertices.len());
        let mut max_scale = 0.0f32;
        for &v in &polygon.vertices {
            let (sx, sy, scale) = self.project(v, center_x, center_y)?;
            max_scale = max_scale.max(scale);
            points.push((sx * subpixels_x, sy * subpixels_y));
        }
        if max_scale < min_scale {
            return None;
        }
        Some(points)
    }
}

const OUTCODE_INSIDE: u8 = 0;
const OUTCODE_LEFT: u8 = 1;
const OUTCODE_RIGHT: u8 = 2;
const OUTCODE_TOP: u8 = 4;
const OUTCODE_BOTTOM: u8 = 8;

fn outcode(x: f32, y: f32, xmax: f32, ymax: f32) -> u8 {
    let mut code = OUTCODE_INSIDE;
    if x < 0.0 {
        code |= OUTCODE_LEFT;
    } else if x > xmax {
        code |= OUTCODE_RIGHT;
    }
    if y < 0.0 {
        code |= OUTCODE_TOP;
    } else if y > ymax {
        code |= OUTCODE_BOTTOM;
    }
    code
}

/// Clips a line segment to the visible `[0, xmax] x [0, ymax]`
/// rectangle via Cohen-Sutherland. Returns `None` if the segment lies
/// entirely outside.
fn clip_to_screen(
    mut x0: f32,
    mut y0: f32,
    mut x1: f32,
    mut y1: f32,
    xmax: f32,
    ymax: f32,
) -> Option<(f32, f32, f32, f32)> {
    let mut code0 = outcode(x0, y0, xmax, ymax);
    let mut code1 = outcode(x1, y1, xmax, ymax);
    loop {
        if code0 | code1 == 0 {
            return Some((x0, y0, x1, y1));
        }
        if code0 & code1 != 0 {
            return None;
        }
        let out = if code0 != 0 { code0 } else { code1 };
        let (x, y) = if out & OUTCODE_TOP != 0 {
            (x0 + (x1 - x0) * (0.0 - y0) / (y1 - y0), 0.0)
        } else if out & OUTCODE_BOTTOM != 0 {
            (x0 + (x1 - x0) * (ymax - y0) / (y1 - y0), ymax)
        } else if out & OUTCODE_RIGHT != 0 {
            (xmax, y0 + (y1 - y0) * (xmax - x0) / (x1 - x0))
        } else {
            (0.0, y0 + (y1 - y0) * (0.0 - x0) / (x1 - x0))
        };
        if out == code0 {
            x0 = x;
            y0 = y;
            code0 = outcode(x0, y0, xmax, ymax);
        } else {
            x1 = x;
            y1 = y;
            code1 = outcode(x1, y1, xmax, ymax);
        }
    }
}

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

    fn camera() -> Camera {
        Camera {
            near: 0.5,
            focal_length: 8.0,
        }
    }

    #[test]
    fn point_behind_the_near_plane_returns_none() {
        let cam = camera();
        let p = Point3 {
            x: 4.0,
            y: 0.0,
            z: 0.2,
        };
        assert_eq!(cam.project(p, 10.0, 5.0), None);
    }

    #[test]
    fn point_exactly_at_the_near_plane_returns_none() {
        let cam = camera();
        let p = Point3 {
            x: 4.0,
            y: 0.0,
            z: 0.5,
        };
        assert_eq!(cam.project(p, 10.0, 5.0), None);
    }

    #[test]
    fn nearer_points_project_farther_from_center_and_with_larger_scale() {
        let cam = camera();
        let center_x = 10.0;
        let center_y = 5.0;

        let (x2, y2, s2) = cam
            .project(
                Point3 {
                    x: 4.0,
                    y: 0.0,
                    z: 2.0,
                },
                center_x,
                center_y,
            )
            .unwrap();
        let (x4, y4, s4) = cam
            .project(
                Point3 {
                    x: 4.0,
                    y: 0.0,
                    z: 4.0,
                },
                center_x,
                center_y,
            )
            .unwrap();
        let (x8, y8, s8) = cam
            .project(
                Point3 {
                    x: 4.0,
                    y: 0.0,
                    z: 8.0,
                },
                center_x,
                center_y,
            )
            .unwrap();

        // Hand-verified (all inputs are powers of 2, so every
        // intermediate value is exactly representable in binary
        // floating point — no epsilon needed):
        // z=2: ndc_x=2.0, scale=4.0, screen_x=10+2.0*8*2=42.0
        // z=4: ndc_x=1.0, scale=2.0, screen_x=10+1.0*8*2=26.0
        // z=8: ndc_x=0.5, scale=1.0, screen_x=10+0.5*8*2=18.0
        assert_eq!((x2, s2), (42.0, 4.0));
        assert_eq!((x4, s4), (26.0, 2.0));
        assert_eq!((x8, s8), (18.0, 1.0));
        assert_eq!(y2, 5.0);
        assert_eq!(y4, 5.0);
        assert_eq!(y8, 5.0);

        // Farther points land closer to center_x (convergence toward
        // the vanishing point) and have smaller scale (dimmer/smaller).
        assert!((x8 - center_x).abs() < (x4 - center_x).abs());
        assert!((x4 - center_x).abs() < (x2 - center_x).abs());
        assert!(s8 < s4 && s4 < s2);
    }

    #[test]
    fn positive_world_y_maps_to_a_smaller_screen_y() {
        let cam = camera();
        // z=4.0, y=2.0: ndc_y=0.5, screen_y=5.0-0.5*8.0=1.0 (exact).
        let (x, y, _) = cam
            .project(
                Point3 {
                    x: 0.0,
                    y: 2.0,
                    z: 4.0,
                },
                10.0,
                5.0,
            )
            .unwrap();
        assert_eq!(x, 10.0); // ndc_x = 0 -> no horizontal offset
        assert_eq!(y, 1.0);
    }

    fn assert_close(actual: f32, expected: f32, label: &str) {
        assert!(
            (actual - expected).abs() < 0.001,
            "{label}: expected {expected}, got {actual}"
        );
    }

    #[test]
    fn clip_to_screen_leaves_a_fully_inside_line_unchanged() {
        let result = clip_to_screen(2.0, 2.0, 8.0, 8.0, 10.0, 10.0);
        assert_eq!(result, Some((2.0, 2.0, 8.0, 8.0)));
    }

    #[test]
    fn clip_to_screen_rejects_a_line_fully_outside_on_each_side() {
        assert_eq!(clip_to_screen(-5.0, 3.0, -1.0, 3.0, 10.0, 10.0), None); // left
        assert_eq!(clip_to_screen(15.0, 3.0, 20.0, 3.0, 10.0, 10.0), None); // right
        assert_eq!(clip_to_screen(3.0, -5.0, 3.0, -1.0, 10.0, 10.0), None); // top
        assert_eq!(clip_to_screen(3.0, 15.0, 3.0, 20.0, 10.0, 10.0), None); // bottom
    }

    #[test]
    fn clip_to_screen_clips_a_single_edge_crossing() {
        // (5,5) is inside; (15,5) is outside past the right edge.
        let result = clip_to_screen(5.0, 5.0, 15.0, 5.0, 10.0, 10.0);
        assert_eq!(result, Some((5.0, 5.0, 10.0, 5.0)));
    }

    #[test]
    fn clip_to_screen_resolves_a_two_edge_corner_crossing() {
        // (20,15) is outside past both the right and bottom edges;
        // Cohen-Sutherland must resolve this through two clip
        // iterations (an intermediate point against one edge that's
        // still outside via the other) before landing inside.
        let result = clip_to_screen(20.0, 15.0, 5.0, 5.0, 10.0, 10.0);
        let (cx0, cy0, cx1, cy1) = result.expect("line intersects the box");
        assert_close(cx0, 10.0, "clipped start.x (right edge)");
        assert!(
            (0.0..=10.0).contains(&cy0),
            "clipped start.y should be within the box, got {cy0}"
        );
        assert_eq!(cx1, 5.0);
        assert_eq!(cy1, 5.0);
    }

    #[test]
    fn project_line_returns_none_when_either_endpoint_is_behind_the_near_plane() {
        let cam = camera();
        let line = Line3 {
            start: Point3 {
                x: -1.0,
                y: 0.0,
                z: 4.0,
            },
            end: Point3 {
                x: 1.0,
                y: 0.0,
                z: 0.2,
            },
        };
        assert_eq!(
            cam.project_line(
                line,
                ProjectLineParams {
                    center_x: 5.0,
                    center_y: 5.0,
                    screen_w: 10.0,
                    screen_h: 10.0,
                    subpixels_x: 2.0,
                    subpixels_y: 4.0,
                    min_scale: 0.0,
                }
            ),
            None
        );
    }

    #[test]
    fn project_line_returns_none_when_every_vertexs_scale_is_below_min_scale() {
        let cam = camera();
        // Both points at z=100: scale = 8.0/100.0 = 0.08.
        let line = Line3 {
            start: Point3 {
                x: -1.0,
                y: 0.0,
                z: 100.0,
            },
            end: Point3 {
                x: 1.0,
                y: 0.0,
                z: 100.0,
            },
        };
        assert_eq!(
            cam.project_line(
                line,
                ProjectLineParams {
                    center_x: 5.0,
                    center_y: 5.0,
                    screen_w: 10.0,
                    screen_h: 10.0,
                    subpixels_x: 2.0,
                    subpixels_y: 4.0,
                    min_scale: 0.1,
                }
            ),
            None
        );
    }

    #[test]
    fn project_line_projects_a_fully_visible_line_to_subpixel_coordinates() {
        let cam = camera();
        // Both points at z=4.0: x=-1 -> ndc_x=-0.25 -> screen_x=5+(-0.25*8*2)=1.0
        //                        x=1  -> ndc_x=0.25  -> screen_x=5+(0.25*8*2)=9.0
        //                        y=0  -> ndc_y=0.0   -> screen_y=3.0 (center_y, unchanged by y)
        // Both within [0,10]x[0,6] -> no clipping. screen_w=10/screen_h=6 are
        // asymmetric (catches a screen_w/screen_h swap in clip_to_screen), and
        // center_x=5.0/center_y=3.0 are asymmetric (catches a center_x/center_y
        // swap in project) — both mutants verified live to fail this test
        // before being reverted; see perspective.rs's design spec / fix brief.
        // Subpixel factors (2.0,4.0): (1.0*2, 3.0*4, 9.0*2, 3.0*4) = (2, 12, 18, 12).
        let line = Line3 {
            start: Point3 {
                x: -1.0,
                y: 0.0,
                z: 4.0,
            },
            end: Point3 {
                x: 1.0,
                y: 0.0,
                z: 4.0,
            },
        };
        let result = cam.project_line(
            line,
            ProjectLineParams {
                center_x: 5.0,
                center_y: 3.0,
                screen_w: 10.0,
                screen_h: 6.0,
                subpixels_x: 2.0,
                subpixels_y: 4.0,
                min_scale: 0.0,
            },
        );
        assert_eq!(result, Some((2, 12, 18, 12)));
    }

    #[test]
    fn project_line_clips_instead_of_saturating_an_off_screen_endpoint() {
        let cam = camera();
        // x=20 at z=4.0: ndc_x=5.0, screen_x=5+5.0*8*2=85.0 (far off-screen).
        // x=0 at z=4.0: screen_x=5.0 (on-screen, at y=5.0 both).
        // Real clipping lands the off-screen endpoint at screen_x=10.0
        // (the right edge), not saturated to 0 (the spike's bug).
        let line = Line3 {
            start: Point3 {
                x: 20.0,
                y: 0.0,
                z: 4.0,
            },
            end: Point3 {
                x: 0.0,
                y: 0.0,
                z: 4.0,
            },
        };
        let result = cam
            .project_line(
                line,
                ProjectLineParams {
                    center_x: 5.0,
                    center_y: 5.0,
                    screen_w: 10.0,
                    screen_h: 10.0,
                    subpixels_x: 2.0,
                    subpixels_y: 4.0,
                    min_scale: 0.0,
                },
            )
            .expect("line crosses into the visible screen");
        // Clipped start lands at screen (10.0, 5.0) -> subpixel (20, 20).
        assert_eq!(result, (20, 20, 10, 20));
    }

    #[test]
    fn project_polygon_returns_none_when_any_vertex_is_behind_the_near_plane() {
        let cam = camera();
        let poly = Polygon3 {
            vertices: vec![
                Point3 {
                    x: -1.0,
                    y: -1.0,
                    z: 4.0,
                },
                Point3 {
                    x: -1.0,
                    y: 1.0,
                    z: 4.0,
                },
                Point3 {
                    x: 1.0,
                    y: 0.0,
                    z: 0.2,
                },
            ],
        };
        assert_eq!(cam.project_polygon(&poly, 5.0, 5.0, 2.0, 4.0, 0.0), None);
    }

    #[test]
    fn project_polygon_returns_none_when_every_vertexs_scale_is_below_min_scale() {
        let cam = camera();
        let poly = Polygon3 {
            vertices: vec![
                Point3 {
                    x: -1.0,
                    y: -1.0,
                    z: 100.0,
                },
                Point3 {
                    x: -1.0,
                    y: 1.0,
                    z: 100.0,
                },
                Point3 {
                    x: 1.0,
                    y: 0.0,
                    z: 100.0,
                },
            ],
        };
        assert_eq!(cam.project_polygon(&poly, 5.0, 5.0, 2.0, 4.0, 0.1), None);
    }

    #[test]
    fn project_polygon_projects_every_vertex_when_visible() {
        let cam = camera();
        // z=4.0, x=0.0, y=0.0 -> ndc=(0,0) -> screen=(5.0,5.0) -> subpixel (10.0,20.0).
        let poly = Polygon3 {
            vertices: vec![Point3 {
                x: 0.0,
                y: 0.0,
                z: 4.0,
            }],
        };
        let result = cam
            .project_polygon(&poly, 5.0, 5.0, 2.0, 4.0, 0.0)
            .expect("single visible vertex projects");
        assert_eq!(result, vec![(10.0, 20.0)]);
    }
}