Skip to main content

graph_explorer_render/
labels.rs

1use std::collections::HashMap;
2
3use glyphon::{Attrs, Buffer, Cache, Color, Family, FontSystem, Metrics, Resolution, Shaping,
4    SwashCache, TextArea, TextAtlas, TextBounds, TextRenderer, Viewport};
5use crate::Camera;
6
7/// Bundled fallback font (SIL Open Font License, from the `Inter` family).
8///
9/// `cosmic-text`'s `FontSystem::new()` calls `fontdb::Database::load_system_fonts()`,
10/// which is a no-op on `wasm32` (there is no filesystem to scan). Without at least one
11/// face loaded, `Buffer::shape_until_scroll` panics with "no default font found". We embed
12/// a single font and register it as the generic `sans-serif` family so it works
13/// identically on native and in the browser.
14static FALLBACK_FONT: &[u8] = include_bytes!("../assets/Inter-Bold.ttf");
15
16/// One label the caller selected for drawing this frame (LOD survivor).
17/// `key` is the interned `LabelId`; `text` is only read on cache miss.
18pub struct LabelDraw<'a> {
19    pub key: u32,
20    pub text: &'a str,
21    pub pos: [f32; 2],
22    pub radius: f32,
23    pub opacity: f32,
24}
25
26/// A survivor with its shaping already ensured; what `prepare` consumes.
27#[derive(Clone, Copy)]
28struct PlacedLabel { key: u32, pos: [f32; 2], radius: f32, opacity: f32 }
29
30/// Shaped-buffer cache bound: crude clear-on-cap keeps memory bounded across
31/// a session that pans over tens of thousands of distinct labels. After a
32/// clear, the next frames re-shape only the current survivors (≤ the LOD
33/// cap), so the worst case is one shaping burst, not a leak.
34const LABEL_CACHE_CAP: usize = 2048;
35
36pub struct Labels {
37    font_system: FontSystem,
38    swash: SwashCache,
39    atlas: TextAtlas,
40    viewport: Viewport,
41    renderer: TextRenderer,
42    shaped: HashMap<u32, Buffer>,
43    placed: Vec<PlacedLabel>,
44}
45
46impl Labels {
47    pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat) -> Self {
48        let cache = Cache::new(device);
49        let mut atlas = TextAtlas::new(device, queue, &cache, format);
50        let viewport = Viewport::new(device, &cache);
51        let renderer = TextRenderer::new(&mut atlas, device, wgpu::MultisampleState::default(), None);
52        let mut font_system = FontSystem::new();
53        let db = font_system.db_mut();
54        db.load_font_data(FALLBACK_FONT.to_vec());
55        let family = db.faces().next().map(|face| face.families[0].0.clone());
56        if let Some(family) = family {
57            db.set_sans_serif_family(family.clone());
58            db.set_serif_family(family.clone());
59            db.set_monospace_family(family.clone());
60            db.set_cursive_family(family.clone());
61            db.set_fantasy_family(family);
62        }
63        Self {
64            font_system,
65            swash: SwashCache::new(),
66            atlas,
67            viewport,
68            renderer,
69            shaped: HashMap::new(),
70            placed: Vec::new(),
71        }
72    }
73
74    /// Project world position to physical screen pixels (origin top-left).
75    fn project(cam: &Camera, world: [f32; 2]) -> (f32, f32) {
76        let relx = (world[0] - cam.center[0]) * cam.zoom;
77        let rely = (world[1] - cam.center[1]) * cam.zoom;
78        let sx = cam.viewport[0] * 0.5 + relx;
79        let sy = cam.viewport[1] * 0.5 - rely; // flip y
80        (sx, sy)
81    }
82
83    /// Record this frame's survivors, shaping any label not already cached.
84    /// Steady state (same labels visible) shapes nothing.
85    pub fn set_labels(&mut self, labels: &[LabelDraw]) {
86        if self.shaped.len() > LABEL_CACHE_CAP {
87            self.shaped.clear();
88        }
89        self.placed.clear();
90        let Self { shaped, font_system, placed, .. } = self;
91        for l in labels {
92            shaped.entry(l.key).or_insert_with(|| {
93                let mut buf = Buffer::new(font_system, Metrics::new(14.0, 18.0));
94                buf.set_text(font_system, l.text, Attrs::new().family(Family::SansSerif), Shaping::Advanced);
95                buf.shape_until_scroll(font_system, false);
96                buf
97            });
98            placed.push(PlacedLabel { key: l.key, pos: l.pos, radius: l.radius, opacity: l.opacity });
99        }
100    }
101
102    pub fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, cam: &Camera) -> Result<(), String> {
103        self.viewport.update(queue, Resolution { width: cam.viewport[0] as u32, height: cam.viewport[1] as u32 });
104        let areas: Vec<TextArea> = self.placed.iter().filter_map(|p| {
105            // A placed key is always inserted into `shaped` by `set_labels`
106            // before it lands in `placed`; skipping a missing key is pure
107            // defensiveness (drop the label for a frame rather than panic).
108            let buf = self.shaped.get(&p.key)?;
109            let (sx, sy) = Self::project(cam, p.pos);
110            Some(TextArea {
111                buffer: buf,
112                // `p.radius` is a WORLD-unit radius; `sx` is already in
113                // screen px, so it must be scaled by zoom before adding —
114                // otherwise the label anchor drifts off the node at any
115                // zoom other than 1.
116                left: sx + p.radius * cam.zoom + 4.0,
117                top: sy - 9.0,
118                scale: 1.0,
119                bounds: TextBounds { left: 0, top: 0, right: cam.viewport[0] as i32, bottom: cam.viewport[1] as i32 },
120                default_color: Color::rgba(210, 214, 220, (cam.fade * p.opacity * 255.0) as u8),
121                custom_glyphs: &[],
122            })
123        }).collect();
124        self.renderer.prepare(device, queue, &mut self.font_system, &mut self.atlas, &self.viewport, areas, &mut self.swash).map_err(|e| e.to_string())?;
125        Ok(())
126    }
127
128    pub fn draw<'a>(&'a self, rpass: &mut wgpu::RenderPass<'a>) -> Result<(), String> {
129        self.renderer.render(&self.atlas, &self.viewport, rpass).map_err(|e| e.to_string())?;
130        Ok(())
131    }
132}