Skip to main content

sim_engine/renderer/
text.rs

1use super::*;
2use crate::{FontError, FontFace, RasterizedGlyph, ShapedLine, TextLayoutBudget, TextStyle};
3
4mod types;
5pub use types::{TextAtlasBudget, TextError, TextUpdateReport};
6
7#[derive(Clone, Copy)]
8struct CachedGlyph {
9    id: u16,
10    width: u32,
11    height: u32,
12    bearing_x: i32,
13    bearing_y: i32,
14}
15
16#[derive(Clone, Copy, Default)]
17struct Shelf {
18    x: u32,
19    y: u32,
20    height: u32,
21}
22
23impl Shelf {
24    fn insert(
25        &mut self,
26        width: u32,
27        height: u32,
28        size: (u32, u32),
29    ) -> Result<ImageTexelRect, TextError> {
30        if width > size.0 || height > size.1 {
31            return Err(TextError::AtlasFull);
32        }
33        let mut next = *self;
34        if next.x.checked_add(width).is_none_or(|right| right > size.0) {
35            next.x = 0;
36            next.y = next
37                .y
38                .checked_add(next.height)
39                .ok_or(TextError::AtlasFull)?;
40            next.height = 0;
41        }
42        if next
43            .y
44            .checked_add(height)
45            .is_none_or(|bottom| bottom > size.1)
46        {
47            return Err(TextError::AtlasFull);
48        }
49        let rectangle = ImageTexelRect::new(next.x, next.y, width, height)?;
50        next.x += width;
51        next.height = next.height.max(height);
52        *self = next;
53        Ok(rectangle)
54    }
55}
56
57/// Antialiased font cache for one font, logical EM size, direction and DPI.
58///
59/// Enable the optional `text` feature. Glyphs never move or disappear: the fixed
60/// atlas returns [`TextError::AtlasFull`] instead of evicting live runs. Create a
61/// new atlas and prepare replacement runs before swapping when size or DPI changes.
62/// The input font must be a trusted application asset, not an untrusted-font sandbox.
63///
64/// Draw [`Self::atlas`] and [`TextRun2d::glyph_run`] with [`ImageSampling::Linear`].
65/// Placements are baseline-relative, in logical pixels. Bitmap coverage is cached
66/// at an integer physical baseline; fractional placement uses bilinear filtering,
67/// not per-subpixel hinting. No fonts are discovered or downloaded automatically.
68///
69/// ```no_run
70/// use sim_engine::{
71///     Color, FontFace, FrameBudget, FramePassOptions, ImageBatchPlacement, ImageSampling,
72///     LogicalPixels, LogicalScreenVector, PhysicalPerLogical, TextAtlas2d,
73///     TextAtlasBudget, TextLayoutBudget, TextStyle, WgpuRenderer,
74/// };
75///
76/// fn draw_label(renderer: &mut WgpuRenderer, font: FontFace)
77///     -> Result<(), Box<dyn std::error::Error>>
78/// {
79///     let style = TextStyle::new(
80///         LogicalPixels::new(24.0)?,
81///         PhysicalPerLogical::new(renderer.scale_factor() as f32)?,
82///     )?;
83///     // Keep these two resources between frames in an application.
84///     let mut atlas = TextAtlas2d::new(renderer, font, style, TextAtlasBudget::default())?;
85///     let label = atlas.prepare(renderer, "Hello, world!", TextLayoutBudget::default())?;
86///     let mut frame = renderer.begin_frame(Color::BLACK, FrameBudget::default())?;
87///     frame.draw_glyph_run_placed(
88///         atlas.atlas(), label.glyph_run(),
89///         ImageBatchPlacement::new(LogicalScreenVector::new(24.0, 80.0), Color::WHITE)?,
90///         ImageSampling::Linear, FramePassOptions::new(0),
91///     )?;
92///     let _report = frame.present()?;
93///     Ok(())
94/// }
95/// ```
96pub struct TextAtlas2d {
97    font: FontFace,
98    style: TextStyle,
99    budget: TextAtlasBudget,
100    atlas: GlyphAtlas2d,
101    identity: Arc<()>,
102    cached: Vec<CachedGlyph>,
103    shelf: Shelf,
104}
105
106/// Retained, shaped single-line text and its baseline metrics.
107///
108/// Drawing an unchanged run needs no shaping, rasterization or geometry upload.
109/// Whitespace contributes to [`Self::advance`] but emits no glyph quad. Drawable
110/// bounds include filtering support and are not typographic advance bounds.
111pub struct TextRun2d {
112    run: GlyphRun2d,
113    atlas_identity: Arc<()>,
114    text: String,
115    advance: f32,
116    ascent: f32,
117    descent: f32,
118    line_height: f32,
119}
120
121impl TextRun2d {
122    /// Returns the retained glyph instances for a composed glyph draw.
123    pub const fn glyph_run(&self) -> &GlyphRun2d {
124        &self.run
125    }
126    /// Returns the original UTF-8 text.
127    pub fn text(&self) -> &str {
128        &self.text
129    }
130    /// Returns horizontal advance, including spaces, in logical pixels.
131    pub const fn advance(&self) -> f32 {
132        self.advance
133    }
134    /// Returns the font ascender above the baseline in logical pixels.
135    pub const fn ascent(&self) -> f32 {
136        self.ascent
137    }
138    /// Returns the signed font descender below the baseline in logical pixels.
139    pub const fn descent(&self) -> f32 {
140        self.descent
141    }
142    /// Returns the font-recommended baseline spacing in logical pixels.
143    pub const fn line_height(&self) -> f32 {
144        self.line_height
145    }
146    /// Returns retained UTF-8 and glyph-layout allocation bytes, excluding allocator overhead.
147    pub fn recovery_memory_bytes(&self) -> usize {
148        self.text
149            .capacity()
150            .saturating_add(self.run.recovery_memory_bytes())
151    }
152}
153
154impl TextAtlas2d {
155    /// Creates a fixed-capacity atlas, checking device dimensions before pixel allocation.
156    pub fn new(
157        renderer: &WgpuRenderer,
158        font: FontFace,
159        style: TextStyle,
160        budget: TextAtlasBudget,
161    ) -> Result<Self, TextError> {
162        let image_budget = budget.image_budget()?;
163        let bytes = image::validate_image_shape(
164            budget.width(),
165            budget.height(),
166            image_budget.max_bytes(),
167            image_budget,
168            renderer.device.limits().max_texture_dimension_2d,
169        )?;
170        let mut pixels = reserve_vec(bytes)?;
171        pixels.resize(bytes, 255);
172        for pixel in pixels.chunks_exact_mut(4) {
173            pixel[3] = 0;
174        }
175        // Reserve the bounded metadata once: inserting a successfully uploaded
176        // glyph must not fail later and leave the packing cursor inconsistent.
177        let cached = reserve_vec(budget.max_cached_glyphs())?;
178        let metadata_bytes = budget
179            .max_cached_glyphs()
180            .checked_mul(std::mem::size_of::<GlyphAtlasEntry>())
181            .ok_or(TextError::InvalidBudget)?;
182        let atlas = renderer.create_glyph_atlas(
183            budget.width(),
184            budget.height(),
185            pixels,
186            Vec::new(),
187            GlyphAtlasBudget::new(image_budget, budget.max_cached_glyphs(), metadata_bytes)?,
188        )?;
189        Ok(Self {
190            font,
191            style,
192            budget,
193            atlas,
194            identity: Arc::new(()),
195            cached,
196            shelf: Shelf::default(),
197        })
198    }
199
200    /// Returns the atlas to use with a retained glyph-run draw. Use linear sampling.
201    pub const fn atlas(&self) -> &GlyphAtlas2d {
202        &self.atlas
203    }
204    /// Returns the immutable font/style/DPI configuration.
205    pub const fn style(&self) -> &TextStyle {
206        &self.style
207    }
208    /// Returns the original font, shared cheaply through [`FontFace::clone`].
209    pub const fn font(&self) -> &FontFace {
210        &self.font
211    }
212    /// Returns immutable atlas and run limits.
213    pub const fn budget(&self) -> TextAtlasBudget {
214        self.budget
215    }
216    /// Returns cached glyph count, including non-drawing spacing glyphs.
217    pub fn cached_glyph_count(&self) -> usize {
218        self.cached.len()
219    }
220    /// Returns retained atlas pixels and metadata bytes, excluding shared font data and allocator overhead.
221    pub fn recovery_memory_bytes(&self) -> usize {
222        self.atlas.recovery_memory_bytes().saturating_add(
223            self.cached
224                .capacity()
225                .saturating_mul(std::mem::size_of::<CachedGlyph>()),
226        )
227    }
228    /// Returns retained GPU image allocation bytes; runs own separate instance buffers.
229    pub fn gpu_allocation_bytes(&self) -> usize {
230        self.atlas.gpu_allocation_bytes()
231    }
232
233    /// Shapes a line and rasterizes only glyphs missing from this immutable-style cache.
234    ///
235    /// Font/input/output limits apply to shaping; raster limits apply to cache misses.
236    /// Run capacity is conservatively preflighted for all shaped glyphs, including
237    /// whitespace, before allocating placements or populating the glyph cache.
238    /// A failure preserves all existing drawable runs, but may warm the bounded
239    /// cache with some new glyphs before a later glyph or run allocation fails.
240    /// There is no implicit atlas growth, eviction, font fallback or wrapping.
241    pub fn prepare(
242        &mut self,
243        renderer: &WgpuRenderer,
244        text: &str,
245        layout_budget: TextLayoutBudget,
246    ) -> Result<TextRun2d, TextError> {
247        renderer.validate_image(&self.atlas.image)?;
248        let shaped = self.font.shape_line(text, &self.style, &layout_budget)?;
249        let owned = owned_text(text)?;
250        let glyphs = self.position_glyphs(renderer, &shaped, &layout_budget)?;
251        let run = renderer.create_glyph_run(&self.atlas, glyphs, self.budget.run_budget())?;
252        Ok(TextRun2d {
253            run,
254            atlas_identity: Arc::clone(&self.identity),
255            text: owned,
256            advance: shaped.advance(),
257            ascent: shaped.ascent(),
258            descent: shaped.descent(),
259            line_height: shaped.line_height(),
260        })
261    }
262
263    /// Replaces a line atomically while reusing its instance-buffer capacity.
264    ///
265    /// Exact unchanged UTF-8 returns immediately after resource-identity validation;
266    /// no shaping/raster work occurs, so `layout_budget` is not consumed or rechecked.
267    /// For changed text, a synchronous error preserves the old run/text/metrics,
268    /// but may warm atlas entries as documented by [`Self::prepare`].
269    pub fn update(
270        &mut self,
271        renderer: &WgpuRenderer,
272        run: &mut TextRun2d,
273        text: &str,
274        layout_budget: TextLayoutBudget,
275    ) -> Result<TextUpdateReport, TextError> {
276        self.validate_run(run)?;
277        renderer.validate_glyph_run(&self.atlas, &run.run)?;
278        if run.text == text {
279            return Ok(TextUpdateReport::default());
280        }
281        let shaped = self.font.shape_line(text, &self.style, &layout_budget)?;
282        let owned = owned_text(text)?;
283        let old_cache_count = self.cached.len();
284        let glyphs = self.position_glyphs(renderer, &shaped, &layout_budget)?;
285        let upload = renderer.update_glyph_run(&self.atlas, &mut run.run, &glyphs)?;
286        run.text = owned;
287        run.advance = shaped.advance();
288        run.ascent = shaped.ascent();
289        run.descent = shaped.descent();
290        run.line_height = shaped.line_height();
291        Ok(TextUpdateReport::new(
292            upload.instances().uploaded_instance_bytes(),
293            self.cached.len() - old_cache_count,
294        ))
295    }
296
297    /// Restores exact atlas pixels on a replacement renderer without rerasterizing.
298    ///
299    /// This replaces the atlas only after successful allocation. Restore each live
300    /// run using [`Self::restore_run`] before drawing on the replacement renderer.
301    pub fn restore(&mut self, renderer: &WgpuRenderer) -> Result<(), TextError> {
302        self.atlas = renderer.restore_glyph_atlas(&self.atlas)?;
303        Ok(())
304    }
305
306    /// Restores one live run against this atlas, preserving text and baseline metrics.
307    pub fn restore_run(
308        &self,
309        renderer: &WgpuRenderer,
310        run: &mut TextRun2d,
311    ) -> Result<(), TextError> {
312        self.validate_run(run)?;
313        run.run = renderer.restore_glyph_run(&self.atlas, &run.run)?;
314        Ok(())
315    }
316
317    fn validate_run(&self, run: &TextRun2d) -> Result<(), TextError> {
318        if !Arc::ptr_eq(&self.identity, &run.atlas_identity) {
319            return Err(TextError::AtlasMismatch);
320        }
321        Ok(())
322    }
323
324    fn position_glyphs(
325        &mut self,
326        renderer: &WgpuRenderer,
327        shaped: &ShapedLine,
328        layout_budget: &TextLayoutBudget,
329    ) -> Result<Vec<PositionedGlyph2d>, TextError> {
330        let run_budget = self.budget.run_budget();
331        glyph::validate_glyph_run_budget(shaped.glyphs().len(), run_budget)?;
332        image::preflight_image_batch_capacity(
333            &renderer.device,
334            shaped.glyphs().len(),
335            ImageBatchBudget::new(run_budget.max_glyphs(), run_budget.max_retained_bytes())?,
336        )?;
337        let mut glyphs = reserve_vec(shaped.glyphs().len())?;
338        for glyph in shaped.glyphs() {
339            let cached = self.cache_glyph(renderer, glyph.glyph_id(), layout_budget)?;
340            if cached.width == 0 || cached.height == 0 {
341                continue;
342            }
343            let destination = destination_from_metrics(
344                cached,
345                glyph.logical_x(),
346                glyph.logical_y(),
347                self.style.scale().get(),
348            )?;
349            glyphs.push(PositionedGlyph2d::new(
350                GlyphId::new(u32::from(cached.id)),
351                destination,
352                Color::WHITE,
353            )?);
354        }
355        Ok(glyphs)
356    }
357
358    fn cache_glyph(
359        &mut self,
360        renderer: &WgpuRenderer,
361        id: u16,
362        layout_budget: &TextLayoutBudget,
363    ) -> Result<CachedGlyph, TextError> {
364        let insertion = match self.cached.binary_search_by_key(&id, |glyph| glyph.id) {
365            Ok(index) => return Ok(self.cached[index]),
366            Err(index) => index,
367        };
368        if self.cached.len() == self.budget.max_cached_glyphs() {
369            return Err(TextError::GlyphCacheFull);
370        }
371        let raster = self.font.rasterize_glyph(id, &self.style, layout_budget)?;
372        let cached = CachedGlyph {
373            id,
374            width: raster.width(),
375            height: raster.height(),
376            bearing_x: raster.bearing_x(),
377            bearing_y: raster.bearing_y(),
378        };
379        if raster.width() > 0 && raster.height() > 0 {
380            let width = raster.width().checked_add(4).ok_or(TextError::AtlasFull)?;
381            let height = raster.height().checked_add(4).ok_or(TextError::AtlasFull)?;
382            let mut shelf = self.shelf;
383            let source = shelf.insert(width, height, self.atlas.size())?;
384            let pixels = padded_rgba(&raster)?;
385            renderer.upload_glyph(
386                &mut self.atlas,
387                GlyphAtlasEntry::new(GlyphId::new(u32::from(id)), source),
388                &pixels,
389            )?;
390            self.shelf = shelf;
391        }
392        self.cached.insert(insertion, cached);
393        Ok(cached)
394    }
395}
396
397fn destination_from_metrics(
398    glyph: CachedGlyph,
399    x: f32,
400    y: f32,
401    scale: f32,
402) -> Result<LogicalViewportRegion, TextError> {
403    // Image quads map texel centers to their boundaries. Two transparent border
404    // texels preserve bitmap scale and keep the bilinear halo inside full MSAA
405    // coverage, even when the baseline falls between physical pixels.
406    LogicalViewportRegion::new(
407        LogicalScreenPosition::new(
408            x + (glyph.bearing_x as f32 - 1.5) / scale,
409            y + (glyph.bearing_y as f32 - 1.5) / scale,
410        ),
411        LogicalViewport::new(
412            (glyph.width as f32 + 3.0) / scale,
413            (glyph.height as f32 + 3.0) / scale,
414        )
415        .map_err(|_| TextError::InvalidPlacement)?,
416    )
417    .map_err(|_| TextError::InvalidPlacement)
418}
419
420#[cfg(test)]
421pub(super) fn glyph_destination(
422    raster: &RasterizedGlyph,
423    x: f32,
424    y: f32,
425    scale: f32,
426) -> Result<LogicalViewportRegion, TextError> {
427    destination_from_metrics(
428        CachedGlyph {
429            id: 0,
430            width: raster.width(),
431            height: raster.height(),
432            bearing_x: raster.bearing_x(),
433            bearing_y: raster.bearing_y(),
434        },
435        x,
436        y,
437        scale,
438    )
439}
440
441pub(super) fn padded_rgba(raster: &RasterizedGlyph) -> Result<Vec<u8>, TextError> {
442    let width = raster.width() as usize + 4;
443    let height = raster.height() as usize + 4;
444    let bytes = width
445        .checked_mul(height)
446        .and_then(|area| area.checked_mul(4))
447        .ok_or(TextError::AtlasFull)?;
448    let mut pixels = reserve_vec(bytes)?;
449    pixels.resize(bytes, 255);
450    // White transparent padding avoids dark fringes under straight-alpha sampling.
451    for pixel in pixels.chunks_exact_mut(4) {
452        pixel[3] = 0;
453    }
454    for y in 0..raster.height() as usize {
455        for x in 0..raster.width() as usize {
456            pixels[((y + 2) * width + x + 2) * 4 + 3] =
457                raster.coverage()[y * raster.width() as usize + x];
458        }
459    }
460    Ok(pixels)
461}
462
463fn reserve_vec<T>(count: usize) -> Result<Vec<T>, TextError> {
464    let mut values = Vec::new();
465    values
466        .try_reserve_exact(count)
467        .map_err(|_| TextError::AllocationFailed)?;
468    Ok(values)
469}
470
471fn owned_text(text: &str) -> Result<String, TextError> {
472    let mut owned = String::new();
473    owned
474        .try_reserve_exact(text.len())
475        .map_err(|_| TextError::AllocationFailed)?;
476    owned.push_str(text);
477    Ok(owned)
478}
479
480#[cfg(test)]
481mod tests;