Skip to main content

sim_logic/platform/desktop/
text.rs

1//! Bounded retained Engine text, separate from canonical ECS state.
2
3use std::{error::Error, fmt};
4
5use sim_engine::{
6    FrameComposer, FramePassOptions, ImageBatchPlacement, ImageSampling, LogicalScreenVector,
7    TextAtlas2d, TextRun2d, WgpuRenderer,
8};
9
10use crate::{
11    ExtractedFrame, ResolvedScreenText,
12    identity::{LogicEntity, WorldGeneration},
13    text::{TextError, TextFont},
14};
15
16#[path = "text/prepared.rs"]
17mod prepared;
18use prepared::DesktopPreparedLine;
19#[path = "text/batches.rs"]
20mod batches;
21pub use batches::DesktopTextUpdates;
22
23/// A managed label failed desktop preparation after a valid CPU frame.
24///
25/// No partial surface frame is presented. Accepted earlier run updates or newly
26/// cached glyphs may remain; this is not rollback of CPU state or GPU uploads.
27#[derive(Debug)]
28pub enum DesktopTextError {
29    /// Font settings or a DPI-specific CPU line could not be prepared.
30    Settings {
31        /// Label requesting the font.
32        source: LogicEntity,
33        /// Concrete CPU text/settings failure.
34        error: TextError,
35    },
36    /// Engine rejected an atlas, glyph raster, run update or device resource.
37    Engine {
38        /// Label whose preparation failed.
39        source: LogicEntity,
40        /// Underlying Engine error, including atlas-full and work-limit cases.
41        error: sim_engine::TextError,
42    },
43    /// Engine rejected retained CPU layout or its atlas/run preparation.
44    Prepared {
45        /// Label whose prepared-line handoff failed.
46        source: LogicEntity,
47        /// Exact font/style provenance or underlying atlas/run failure.
48        error: sim_engine::PreparedTextError,
49    },
50    /// Engine rejected a grouped snapshot of adjacent labels.
51    Batch {
52        /// First label in the group (the underlying error may involve another).
53        source: LogicEntity,
54        /// Exact glyph, allocation or batch-budget failure.
55        error: sim_engine::GlyphError,
56    },
57    /// Group size or derived byte limits cannot be represented.
58    BatchSizeOverflow,
59    /// Bounded cache metadata could not be allocated.
60    Allocation {
61        /// Minimum additional metadata bytes requested.
62        requested_bytes: usize,
63    },
64    /// The published draw plan and prepared cache disagree.
65    InvalidDrawPlan,
66}
67
68impl fmt::Display for DesktopTextError {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        match self {
71            Self::Settings { source, error } => write!(f, "text {source:?} settings: {error}"),
72            Self::Engine { source, error } => write!(f, "text {source:?} preparation: {error}"),
73            Self::Prepared { source, error } => {
74                write!(f, "text {source:?} prepared layout: {error}")
75            }
76            Self::Batch { source, error } => {
77                write!(f, "text group starting at {source:?}: {error}")
78            }
79            Self::BatchSizeOverflow => f.write_str("text group size exceeds addressable limits"),
80            Self::Allocation { requested_bytes } => {
81                write!(f, "text cache could not reserve {requested_bytes} bytes")
82            }
83            Self::InvalidDrawPlan => f.write_str("text snapshot and desktop cache disagree"),
84        }
85    }
86}
87
88impl Error for DesktopTextError {
89    fn source(&self) -> Option<&(dyn Error + 'static)> {
90        match self {
91            Self::Settings { error, .. } => Some(error),
92            Self::Engine { error, .. } => Some(error),
93            Self::Prepared { error, .. } => Some(error),
94            Self::Batch { error, .. } => Some(error),
95            _ => None,
96        }
97    }
98}
99
100struct FontEntry {
101    font: TextFont,
102    atlas: TextAtlas2d,
103}
104
105struct RunEntry {
106    source: LogicEntity,
107    font: TextFont,
108    run: TextRun2d,
109}
110
111/// At most one atlas per used registration and one last-applied run per live
112/// visible entity. Fonts have frozen per-atlas/run bounds; no historic strings
113/// or DPI variants accumulate. Engine retains its own bounded frame bindings.
114#[derive(Default)]
115pub(super) struct DesktopText {
116    cache: RetainedTextCache<FontEntry, RunEntry>,
117    batches: Vec<batches::BatchEntry>,
118    pub(super) updates: DesktopTextUpdates,
119}
120
121/// Resource-free bookkeeping can be tested without fabricating Engine handles.
122struct RetainedTextCache<Font, Run> {
123    fonts: Vec<Font>,
124    runs: Vec<Run>,
125    live: Vec<u64>,
126    generation: Option<WorldGeneration>,
127    scale_bits: Option<u32>,
128}
129
130impl<Font, Run> Default for RetainedTextCache<Font, Run> {
131    fn default() -> Self {
132        Self {
133            fonts: Vec::new(),
134            runs: Vec::new(),
135            live: Vec::new(),
136            generation: None,
137            scale_bits: None,
138        }
139    }
140}
141
142impl<Font, Run> RetainedTextCache<Font, Run> {
143    fn clear(&mut self) {
144        self.runs.clear();
145        self.fonts.clear();
146        self.live.clear();
147        self.generation = None;
148        self.scale_bits = None;
149    }
150
151    fn begin_frame(
152        &mut self,
153        generation: WorldGeneration,
154        scale: f32,
155        clear_frame_bindings: impl FnOnce(),
156    ) {
157        if self.scale_bits != Some(scale.to_bits()) {
158            // Release binding-owned references before retiring old DPI atlases.
159            // Canonical CPU metrics are unchanged; a failed rebuild presents nothing.
160            if self.scale_bits.is_some() {
161                clear_frame_bindings();
162            }
163            self.clear();
164            self.scale_bits = Some(scale.to_bits());
165        }
166        if self.generation != Some(generation) {
167            self.runs.clear();
168            self.generation = Some(generation);
169        }
170    }
171
172    fn retain_visible_runs(
173        &mut self,
174        labels: impl ExactSizeIterator<Item = (LogicEntity, bool)>,
175        source: impl Fn(&Run) -> LogicEntity,
176    ) -> Result<(), DesktopTextError> {
177        self.live.clear();
178        self.live
179            .try_reserve(labels.len())
180            .map_err(|_| DesktopTextError::Allocation {
181                requested_bytes: labels.len().saturating_mul(size_of::<u64>()),
182            })?;
183        self.live.extend(
184            labels.filter_map(|(source, nonempty)| nonempty.then_some(source.stable_bits())),
185        );
186        self.live.sort_unstable();
187        self.runs
188            .retain(|run| self.live.binary_search(&source(run).stable_bits()).is_ok());
189        Ok(())
190    }
191}
192
193impl DesktopText {
194    pub(super) fn has_runs(&self) -> bool {
195        !self.cache.runs.is_empty()
196    }
197
198    pub(super) fn clear(&mut self) {
199        self.batches.clear();
200        self.cache.clear();
201        self.updates = DesktopTextUpdates::default();
202    }
203
204    pub(super) fn prepare(
205        &mut self,
206        renderer: &mut WgpuRenderer,
207        extracted: &ExtractedFrame,
208        batching: bool,
209    ) -> Result<(), DesktopTextError> {
210        let started = std::time::Instant::now();
211        self.updates = DesktopTextUpdates::default();
212        let scale = renderer.scale_factor() as f32;
213        if self.cache.generation != Some(extracted.world_generation())
214            || self.cache.scale_bits != Some(scale.to_bits())
215            || !batching
216        {
217            self.batches.clear();
218        }
219        self.cache
220            .begin_frame(extracted.world_generation(), scale, || {
221                renderer.clear_frame_cache()
222            });
223        self.cache.retain_visible_runs(
224            extracted.resolved_screen_texts().iter().map(|text| {
225                (
226                    text.source(),
227                    !text.text().is_empty()
228                        && text.visual().clip() != crate::screen::ScreenClip::Empty,
229                )
230            }),
231            |run| run.source,
232        )?;
233        for visual in extracted.resolved_screen_texts() {
234            if !visual.text().is_empty()
235                && visual.visual().clip() != crate::screen::ScreenClip::Empty
236            {
237                self.prepare_one(renderer, visual, scale)?;
238            }
239        }
240        self.updates.source_cpu_time = started.elapsed();
241        if batching {
242            // An error may follow accepted uploads, but no partial frame is
243            // presented and no stale comparison key survives into the retry.
244            if let Err(error) = self.prepare_batches(renderer, extracted) {
245                self.batches.clear();
246                return Err(error);
247            }
248        }
249        Ok(())
250    }
251
252    fn prepare_one(
253        &mut self,
254        renderer: &WgpuRenderer,
255        visual: &ResolvedScreenText,
256        scale: f32,
257    ) -> Result<(), DesktopTextError> {
258        let source = visual.source();
259        let font = visual.font();
260        let font_index = match self
261            .cache
262            .fonts
263            .binary_search_by_key(&font.slot(), |entry| entry.font.slot())
264        {
265            Ok(index) => index,
266            Err(index) => {
267                self.cache
268                    .fonts
269                    .try_reserve(1)
270                    .map_err(|_| DesktopTextError::Allocation {
271                        requested_bytes: size_of::<FontEntry>(),
272                    })?;
273                let settings = font.settings();
274                let style = settings
275                    .style(scale)
276                    .map_err(|error| DesktopTextError::Settings { source, error })?;
277                let atlas = TextAtlas2d::new(
278                    renderer,
279                    font.face().clone(),
280                    style,
281                    settings.atlas_budget(),
282                )
283                .map_err(|error| DesktopTextError::Engine { source, error })?;
284                self.cache.fonts.insert(
285                    index,
286                    FontEntry {
287                        font: font.clone(),
288                        atlas,
289                    },
290                );
291                index
292            }
293        };
294        let atlas = &mut self.cache.fonts[font_index].atlas;
295        let existing = self
296            .cache
297            .runs
298            .binary_search_by_key(&source.stable_bits(), |entry| entry.source.stable_bits());
299        if let Ok(index) = existing {
300            let entry = &self.cache.runs[index];
301            if entry.font == *font && entry.run.text() == visual.text() {
302                // Also avoids reconstructing a DPI-specific line for idle frames.
303                return Ok(());
304            }
305        }
306        let prepared = DesktopPreparedLine::new(visual.visual(), scale)
307            .map_err(|error| DesktopTextError::Settings { source, error })?;
308        let shaped = prepared.line();
309        match existing {
310            Ok(index) => {
311                let entry = &mut self.cache.runs[index];
312                if entry.font != *font {
313                    // Font changes replace one run, never mutate another label.
314                    let run = atlas
315                        .prepare_from_shaped(renderer, shaped, font.settings().layout_budget())
316                        .map_err(|error| DesktopTextError::Prepared { source, error })?;
317                    *entry = RunEntry {
318                        source,
319                        font: font.clone(),
320                        run,
321                    };
322                } else if entry.run.text() != visual.text() {
323                    atlas
324                        .update_from_shaped(
325                            renderer,
326                            &mut entry.run,
327                            shaped,
328                            font.settings().layout_budget(),
329                        )
330                        .map_err(|error| DesktopTextError::Prepared { source, error })?;
331                }
332            }
333            Err(index) => {
334                self.cache
335                    .runs
336                    .try_reserve(1)
337                    .map_err(|_| DesktopTextError::Allocation {
338                        requested_bytes: size_of::<RunEntry>(),
339                    })?;
340                let run = atlas
341                    .prepare_from_shaped(renderer, shaped, font.settings().layout_budget())
342                    .map_err(|error| DesktopTextError::Prepared { source, error })?;
343                self.cache.runs.insert(
344                    index,
345                    RunEntry {
346                        source,
347                        font: font.clone(),
348                        run,
349                    },
350                );
351            }
352        }
353        Ok(())
354    }
355
356    pub(super) fn draw<'a>(
357        &'a self,
358        frame: &mut FrameComposer<'a>,
359        visual: &ResolvedScreenText,
360        options: FramePassOptions,
361    ) -> Result<(), super::images::ScreenPresentationError> {
362        let font_index = self
363            .cache
364            .fonts
365            .binary_search_by_key(&visual.font().slot(), |entry| entry.font.slot())
366            .map_err(|_| DesktopTextError::InvalidDrawPlan)?;
367        let run_index = self
368            .cache
369            .runs
370            .binary_search_by_key(&visual.source().stable_bits(), |entry| {
371                entry.source.stable_bits()
372            })
373            .map_err(|_| DesktopTextError::InvalidDrawPlan)?;
374        let run = &self.cache.runs[run_index];
375        if run.source != visual.source()
376            || run.font != *visual.font()
377            || run.run.text() != visual.text()
378        {
379            return Err(DesktopTextError::InvalidDrawPlan.into());
380        }
381        let position = visual.baseline_origin().to_vec2();
382        let placement = ImageBatchPlacement::new(
383            LogicalScreenVector::new(position.x(), position.y()),
384            visual.tint(),
385        )
386        .map_err(|error| DesktopTextError::Engine {
387            source: visual.source(),
388            error: sim_engine::TextError::Glyph(sim_engine::GlyphError::Image(error)),
389        })?;
390        frame.draw_glyph_run_placed(
391            self.cache.fonts[font_index].atlas.atlas(),
392            run.run.glyph_run(),
393            placement,
394            ImageSampling::Linear,
395            options,
396        )?;
397        Ok(())
398    }
399}
400
401#[cfg(test)]
402#[path = "text/batch_tests.rs"]
403mod batch_tests;
404#[cfg(test)]
405#[path = "text/tests.rs"]
406mod tests;