Skip to main content

strata_render/
overlay3d.rs

1//! 2D overlay pass drawn over depth-tested 3D geometry.
2//!
3//! The Earth reference draws graticules, contours, trajectories, waypoints,
4//! reticles, and labels as 2D primitives after the 3D pass. They share the 3D
5//! camera projection, so a projected anchor lands on the same pixel as the mesh
6//! vertex it annotates, and everything is clipped to the viewport.
7//!
8//! The pass is split in two on purpose:
9//!
10//! 1. Projection: scene-space anchors are projected with the f64 frame and
11//!    reduced to screen-space commands. This step is deterministic and pure, so
12//!    tests can assert anchor accuracy without reading pixels.
13//! 2. Rasterization: the commands are drawn into a [`FrameBuffer`].
14
15use crate::camera64::{DVec3, RenderFrame64};
16use crate::font::get_glyph_or_fallback;
17use crate::rasterizer::FrameBuffer;
18use strata_layout::Rect;
19use strata_style::types::Color;
20
21/// A marker glyph drawn at a projected anchor.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum MarkerKind {
24    /// Filled square, the default waypoint glyph.
25    Square,
26    /// Filled circle.
27    Circle,
28    /// Diamond.
29    Diamond,
30    /// Hollow square: selected or focused entity.
31    Ring,
32}
33
34/// Placement of a label relative to its projected anchor.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum LabelAnchor {
37    /// Box centred on the anchor.
38    Centre,
39    /// Box starts at the anchor.
40    Left,
41    /// Box ends at the anchor.
42    Right,
43    /// Box sits above the anchor with a short gap.
44    Above,
45}
46
47/// Text styling for an overlay label.
48#[derive(Debug, Clone, Copy, PartialEq)]
49pub struct OverlayTextStyle {
50    pub color: Color,
51    /// Integer scale of the 8x16 glyph cell.
52    pub scale: u32,
53}
54
55impl Default for OverlayTextStyle {
56    fn default() -> Self {
57        Self {
58            color: Color::rgba(241, 245, 249, 255),
59            scale: 1,
60        }
61    }
62}
63
64/// A scene-space overlay primitive.
65#[derive(Debug, Clone, PartialEq)]
66pub enum OverlayPrimitive {
67    /// Connected line segments through scene points.
68    Polyline {
69        points: Vec<DVec3>,
70        color: Color,
71        width: f32,
72    },
73    /// Circle of constant world radius around a scene-space centre.
74    Circle {
75        centre: DVec3,
76        radius: f64,
77        color: Color,
78        width: f32,
79    },
80    /// Filled marker at a scene anchor.
81    Marker {
82        anchor: DVec3,
83        kind: MarkerKind,
84        color: Color,
85        size: f32,
86    },
87    /// Text label at a scene anchor, optionally with a leader line back to the
88    /// anchor.
89    Label {
90        anchor: DVec3,
91        text: String,
92        style: OverlayTextStyle,
93        placement: LabelAnchor,
94        leader: bool,
95    },
96    /// Screen-space line, for reticles and crosshairs.
97    Line {
98        a: [f32; 2],
99        b: [f32; 2],
100        color: Color,
101        width: f32,
102    },
103}
104
105/// A projected, screen-space overlay command.
106#[derive(Debug, Clone, PartialEq)]
107pub enum OverlayCommand {
108    Polyline {
109        points: Vec<[f32; 2]>,
110        color: Color,
111        width: f32,
112    },
113    Circle {
114        centre: [f32; 2],
115        radius: f32,
116        color: Color,
117        width: f32,
118    },
119    Marker {
120        centre: [f32; 2],
121        kind: MarkerKind,
122        color: Color,
123        size: f32,
124    },
125    Label {
126        text: String,
127        /// Top-left of the text box in screen space.
128        origin: [f32; 2],
129        style: OverlayTextStyle,
130        /// Leader from the label box edge to the anchor, when requested.
131        leader: Option<([f32; 2], [f32; 2])>,
132    },
133    Line {
134        a: [f32; 2],
135        b: [f32; 2],
136        color: Color,
137        width: f32,
138    },
139}
140
141/// Overlay primitives plus an optional screen-space clip rectangle.
142#[derive(Debug, Clone, Default, PartialEq)]
143pub struct Overlay3D {
144    pub primitives: Vec<OverlayPrimitive>,
145    /// Clip in screen space. `None` clips to the draw viewport.
146    pub clip: Option<Rect>,
147}
148
149impl Overlay3D {
150    pub fn new() -> Self {
151        Self::default()
152    }
153
154    pub fn push(&mut self, primitive: OverlayPrimitive) -> &mut Self {
155        self.primitives.push(primitive);
156        self
157    }
158
159    pub fn is_empty(&self) -> bool {
160        self.primitives.is_empty()
161    }
162
163    /// Projects every primitive into screen space with the shared 3D frame.
164    ///
165    /// Pieces behind the near plane are dropped, matching the geometry pass.
166    pub fn project(&self, frame: &RenderFrame64) -> Vec<OverlayCommand> {
167        let mut out = Vec::with_capacity(self.primitives.len());
168        for primitive in &self.primitives {
169            match primitive {
170                OverlayPrimitive::Polyline {
171                    points,
172                    color,
173                    width,
174                } => {
175                    let mut projected = Vec::with_capacity(points.len());
176                    let mut visible = true;
177                    for point in points {
178                        let p = frame.project(*point);
179                        if p.clipped {
180                            visible = false;
181                            break;
182                        }
183                        projected.push([p.x as f32, p.y as f32]);
184                    }
185                    if visible && projected.len() >= 2 {
186                        out.push(OverlayCommand::Polyline {
187                            points: projected,
188                            color: *color,
189                            width: *width,
190                        });
191                    }
192                }
193                OverlayPrimitive::Circle {
194                    centre,
195                    radius,
196                    color,
197                    width,
198                } => {
199                    let p = frame.project(*centre);
200                    if p.clipped {
201                        continue;
202                    }
203                    // Radius is projected through a second point one radius
204                    // away along a screen-parallel axis so the circle shrinks
205                    // with distance exactly like the geometry does.
206                    let edge = frame.project(centre.add(DVec3::new(*radius, 0.0, 0.0)));
207                    let screen_radius = if edge.clipped {
208                        0.0
209                    } else {
210                        ((edge.x - p.x).hypot(edge.y - p.y)) as f32
211                    };
212                    out.push(OverlayCommand::Circle {
213                        centre: [p.x as f32, p.y as f32],
214                        radius: screen_radius,
215                        color: *color,
216                        width: *width,
217                    });
218                }
219                OverlayPrimitive::Marker {
220                    anchor,
221                    kind,
222                    color,
223                    size,
224                } => {
225                    let p = frame.project(*anchor);
226                    if p.clipped {
227                        continue;
228                    }
229                    out.push(OverlayCommand::Marker {
230                        centre: [p.x as f32, p.y as f32],
231                        kind: *kind,
232                        color: *color,
233                        size: *size,
234                    });
235                }
236                OverlayPrimitive::Label {
237                    anchor,
238                    text,
239                    style,
240                    placement,
241                    leader,
242                } => {
243                    let p = frame.project(*anchor);
244                    if p.clipped {
245                        continue;
246                    }
247                    let (w, h) = text_size(text, style.scale);
248                    let ax = p.x as f32;
249                    let ay = p.y as f32;
250                    let (ox, oy) = match placement {
251                        LabelAnchor::Centre => (ax - w * 0.5, ay - h * 0.5),
252                        LabelAnchor::Left => (ax, ay - h * 0.5),
253                        LabelAnchor::Right => (ax - w, ay - h * 0.5),
254                        LabelAnchor::Above => (ax - w * 0.5, ay - h - 6.0),
255                    };
256                    let leader_info = if *leader {
257                        Some(([ax, ay], [ax, oy + h]))
258                    } else {
259                        None
260                    };
261                    out.push(OverlayCommand::Label {
262                        text: text.clone(),
263                        origin: [ox, oy],
264                        style: *style,
265                        leader: leader_info,
266                    });
267                }
268                OverlayPrimitive::Line { a, b, color, width } => out.push(OverlayCommand::Line {
269                    a: *a,
270                    b: *b,
271                    color: *color,
272                    width: *width,
273                }),
274            }
275        }
276        out
277    }
278
279    /// Projects and rasterizes this overlay over already-rendered geometry,
280    /// including text labels.
281    pub fn render(&self, frame_buffer: &mut FrameBuffer, viewport: Rect, frame: &RenderFrame64) {
282        self.render_with(frame_buffer, viewport, frame, draw_text);
283    }
284
285    /// Projects and rasterizes with an explicit text rasterizer.
286    pub fn render_with(
287        &self,
288        frame_buffer: &mut FrameBuffer,
289        viewport: Rect,
290        frame: &RenderFrame64,
291        text: TextRasterizer,
292    ) {
293        let commands = self.project(frame);
294        rasterize_overlay_with_text(frame_buffer, viewport, self.clip, &commands, text);
295    }
296
297    /// Projects and rasterizes everything except text, for callers that have no
298    /// text backend installed.
299    pub fn render_geometry_only(
300        &self,
301        frame_buffer: &mut FrameBuffer,
302        viewport: Rect,
303        frame: &RenderFrame64,
304    ) {
305        let commands = self.project(frame);
306        rasterize_overlay(frame_buffer, viewport, self.clip, &commands);
307    }
308}
309
310/// Screen size of a text run in the 8x16 glyph cell.
311pub fn text_size(text: &str, scale: u32) -> (f32, f32) {
312    let scale = scale.max(1) as f32;
313    let chars = text.chars().count() as f32;
314    (chars * 8.0 * scale, 16.0 * scale)
315}
316
317/// Signature of a text rasterizer installed by the platform layer.
318pub type TextRasterizer = fn(&mut FrameBuffer, Rect, [f32; 2], &str, OverlayTextStyle);
319
320/// Rasterizes projected overlay commands into `frame_buffer`, clipped to
321/// `clip` when present and to `viewport` always. Labels are drawn with the
322/// built-in glyph rasterizer.
323pub fn rasterize_overlay(
324    frame_buffer: &mut FrameBuffer,
325    viewport: Rect,
326    clip: Option<Rect>,
327    commands: &[OverlayCommand],
328) {
329    rasterize_overlay_with_text(frame_buffer, viewport, clip, commands, draw_text);
330}
331
332/// Rasterizes projected overlay commands with an explicit text rasterizer.
333pub fn rasterize_overlay_with_text(
334    frame_buffer: &mut FrameBuffer,
335    viewport: Rect,
336    clip: Option<Rect>,
337    commands: &[OverlayCommand],
338    text: TextRasterizer,
339) {
340    let Some(region) = viewport.intersect(clip.unwrap_or(viewport)) else {
341        return;
342    };
343    if region.width <= 0.0 || region.height <= 0.0 {
344        return;
345    }
346
347    for command in commands {
348        match command {
349            OverlayCommand::Polyline {
350                points,
351                color,
352                width,
353            } => {
354                for pair in points.windows(2) {
355                    draw_line(frame_buffer, region, pair[0], pair[1], *color, *width);
356                }
357            }
358            OverlayCommand::Circle {
359                centre,
360                radius,
361                color,
362                width,
363            } => draw_circle(frame_buffer, region, *centre, *radius, *color, *width),
364            OverlayCommand::Marker {
365                centre,
366                kind,
367                color,
368                size,
369            } => draw_marker(frame_buffer, region, *centre, *kind, *color, *size),
370            OverlayCommand::Label {
371                text: text_run,
372                origin,
373                style,
374                leader,
375            } => {
376                if let Some((from, to)) = leader {
377                    draw_line(frame_buffer, region, *from, *to, style.color, 1.0);
378                }
379                text(frame_buffer, region, *origin, text_run, *style);
380            }
381            OverlayCommand::Line { a, b, color, width } => {
382                draw_line(frame_buffer, region, *a, *b, *color, *width)
383            }
384        }
385    }
386}
387
388#[inline]
389fn plot(frame_buffer: &mut FrameBuffer, region: Rect, x: i32, y: i32, color: Color) {
390    let fx = x as f32 + 0.5;
391    let fy = y as f32 + 0.5;
392    if fx < region.x || fy < region.y || fx >= region.max_x() || fy >= region.max_y() {
393        return;
394    }
395    if x < 0 || y < 0 {
396        return;
397    }
398    frame_buffer.set_pixel(x as usize, y as usize, color);
399}
400
401/// Clips a segment to a rectangle with Liang-Barsky.
402///
403/// Projected globe-scale polylines can have endpoints millions of pixels
404/// outside the frame. Clipping first keeps the Bresenham loop proportional to
405/// the visible part instead of the full off-screen span.
406fn clip_segment_to_rect(a: [f32; 2], b: [f32; 2], region: Rect) -> Option<([f32; 2], [f32; 2])> {
407    let dx = b[0] - a[0];
408    let dy = b[1] - a[1];
409    let p = [-dx, dx, -dy, dy];
410    let q = [
411        a[0] - region.x,
412        region.max_x() - a[0],
413        a[1] - region.y,
414        region.max_y() - a[1],
415    ];
416    let mut t0 = 0.0f32;
417    let mut t1 = 1.0f32;
418    for index in 0..4 {
419        if p[index].abs() < 1e-9 {
420            if q[index] < 0.0 {
421                return None;
422            }
423            continue;
424        }
425        let t = q[index] / p[index];
426        if p[index] < 0.0 {
427            t0 = t0.max(t);
428        } else {
429            t1 = t1.min(t);
430        }
431        if t0 > t1 {
432            return None;
433        }
434    }
435    Some((
436        [a[0] + dx * t0, a[1] + dy * t0],
437        [a[0] + dx * t1, a[1] + dy * t1],
438    ))
439}
440
441/// Bresenham line with a square brush so widths above one pixel are visible.
442fn draw_line(
443    frame_buffer: &mut FrameBuffer,
444    region: Rect,
445    a: [f32; 2],
446    b: [f32; 2],
447    color: Color,
448    width: f32,
449) {
450    let Some((a, b)) = clip_segment_to_rect(a, b, region) else {
451        return;
452    };
453    let half = ((width.max(1.0) / 2.0).round() as i32).max(0);
454    let (mut x0, mut y0) = (a[0].round() as i32, a[1].round() as i32);
455    let (x1, y1) = (b[0].round() as i32, b[1].round() as i32);
456    let dx = (x1 - x0).abs();
457    let sx = if x0 < x1 { 1 } else { -1 };
458    let dy = -(y1 - y0).abs();
459    let sy = if y0 < y1 { 1 } else { -1 };
460    let mut err = dx + dy;
461
462    loop {
463        for oy in -half..=half {
464            for ox in -half..=half {
465                plot(frame_buffer, region, x0 + ox, y0 + oy, color);
466            }
467        }
468        if x0 == x1 && y0 == y1 {
469            break;
470        }
471        let e2 = 2 * err;
472        if e2 >= dy {
473            err += dy;
474            x0 += sx;
475        }
476        if e2 <= dx {
477            err += dx;
478            y0 += sy;
479        }
480    }
481}
482
483fn draw_circle(
484    frame_buffer: &mut FrameBuffer,
485    region: Rect,
486    centre: [f32; 2],
487    radius: f32,
488    color: Color,
489    width: f32,
490) {
491    if radius <= 0.5 {
492        return;
493    }
494    let steps = ((radius * 6.0).ceil() as i32).max(16);
495    let mut prev = [centre[0] + radius, centre[1]];
496    for step in 1..=steps {
497        let angle = step as f32 / steps as f32 * std::f32::consts::TAU;
498        let next = [
499            centre[0] + radius * angle.cos(),
500            centre[1] + radius * angle.sin(),
501        ];
502        draw_line(frame_buffer, region, prev, next, color, width);
503        prev = next;
504    }
505}
506
507fn draw_marker(
508    frame_buffer: &mut FrameBuffer,
509    region: Rect,
510    centre: [f32; 2],
511    kind: MarkerKind,
512    color: Color,
513    size: f32,
514) {
515    let half = (size * 0.5).max(1.0);
516    let cx = centre[0].round() as i32;
517    let cy = centre[1].round() as i32;
518    let h = half.round() as i32;
519    match kind {
520        MarkerKind::Square => {
521            for y in -h..=h {
522                for x in -h..=h {
523                    plot(frame_buffer, region, cx + x, cy + y, color);
524                }
525            }
526        }
527        MarkerKind::Ring => {
528            for y in -h..=h {
529                for x in -h..=h {
530                    let edge = x.abs() == h || y.abs() == h;
531                    if edge {
532                        plot(frame_buffer, region, cx + x, cy + y, color);
533                    }
534                }
535            }
536        }
537        MarkerKind::Circle => {
538            for y in -h..=h {
539                for x in -h..=h {
540                    if x * x + y * y <= h * h {
541                        plot(frame_buffer, region, cx + x, cy + y, color);
542                    }
543                }
544            }
545        }
546        MarkerKind::Diamond => {
547            for y in -h..=h {
548                for x in -h..=h {
549                    if x.abs() + y.abs() <= h {
550                        plot(frame_buffer, region, cx + x, cy + y, color);
551                    }
552                }
553            }
554        }
555    }
556}
557
558/// Draws text with the built-in 8x16 cell font, scaled by integer steps.
559pub fn draw_text(
560    frame_buffer: &mut FrameBuffer,
561    region: Rect,
562    origin: [f32; 2],
563    text: &str,
564    style: OverlayTextStyle,
565) {
566    let scale = style.scale.max(1) as i32;
567    let mut cursor_x = origin[0].round() as i32;
568    let cursor_y = origin[1].round() as i32;
569    for ch in text.chars() {
570        let glyph = get_glyph_or_fallback(ch);
571        for (row, bits) in glyph.iter().enumerate() {
572            for col in 0..8 {
573                if bits & (0x80 >> col) == 0 {
574                    continue;
575                }
576                for sy in 0..scale {
577                    for sx in 0..scale {
578                        plot(
579                            frame_buffer,
580                            region,
581                            cursor_x + col * scale + sx,
582                            cursor_y + row as i32 * scale + sy,
583                            style.color,
584                        );
585                    }
586                }
587            }
588        }
589        cursor_x += 8 * scale;
590    }
591}