Skip to main content

sim_engine/renderer/text/
mod.rs

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