Skip to main content

sim_logic/platform/desktop/text/
batches.rs

1//! Retained snapshots of adjacent labels. Individual runs remain atlas sources.
2
3use std::time::{Duration, Instant};
4
5use sim_engine::{GlyphBatch2d, GlyphBatchBudget, GlyphRunPlacement2d};
6
7use super::*;
8use crate::desktop::draw_plan::{self, DesktopDraw, MAX_TEXT_PLACEMENTS};
9use crate::screen::ScreenClip;
10
11/// Native text preparation outside Engine's surface-frame timings.
12///
13/// Byte counters cover only additional batch snapshots, not source text runs,
14/// font atlases, renderer bindings, temporary placements or driver allocations.
15/// Source runs remain retained independently. This is not a total text-memory
16/// or zero-allocation claim. Counters describe the last successful preparation.
17#[derive(Debug, Default, Clone, Copy)]
18pub struct DesktopTextUpdates {
19    /// Exact-value groups reused without an Engine batch update or upload.
20    pub reused_batches: usize,
21    /// New batches, including replacements on font change or capacity growth.
22    pub created_batches: usize,
23    /// Changed snapshots submitted to the capacity-aware Engine updater.
24    pub updated_batches: usize,
25    /// Current grouped labels, including whitespace-only labels.
26    pub placements: usize,
27    /// Actual raster glyph instances across current groups.
28    pub glyphs: usize,
29    /// Ordered clip spans; different clips cannot merge into one draw call.
30    pub draw_calls: usize,
31    /// Actual batch-instance upload bytes; excludes source-run and atlas uploads.
32    pub uploaded_bytes: usize,
33    /// Batch recovery storage and comparison-record capacities, excluding shared
34    /// prepared strings/font storage and fixed metadata.
35    pub retained_cpu_bytes: usize,
36    /// Live batch instance buffer allocations, separate from source runs.
37    pub retained_gpu_bytes: usize,
38    /// Source atlas/run lookup and preparation time, before grouping.
39    pub source_cpu_time: Duration,
40    /// Group comparison, placement conversion and resource-update CPU wall time.
41    pub batch_cpu_time: Duration,
42}
43
44pub(super) struct BatchEntry {
45    pub(super) records: Vec<ResolvedScreenText>,
46    font: TextFont,
47    resource: GlyphBatch2d,
48}
49
50impl DesktopText {
51    pub(super) fn prepare_batches(
52        &mut self,
53        renderer: &WgpuRenderer,
54        extracted: &ExtractedFrame,
55    ) -> Result<(), DesktopTextError> {
56        let started = Instant::now();
57        let mut count = 0;
58        for draw in draw_plan::draws(extracted, true) {
59            let DesktopDraw::TextBatch(range) =
60                draw.map_err(|_| DesktopTextError::InvalidDrawPlan)?
61            else {
62                continue;
63            };
64            let records = &extracted.resolved_screen_texts()[range];
65            if let Some(entry) = self.batches.get(count)
66                && entry.records == records
67            {
68                self.updates.reused_batches += 1;
69            } else {
70                self.update_batch(renderer, count, records)?;
71            }
72            count += 1;
73        }
74        self.batches.truncate(count);
75        for entry in &self.batches {
76            let resource = &entry.resource;
77            self.updates.placements += resource.placement_count();
78            self.updates.glyphs += resource.glyph_count();
79            self.updates.draw_calls += resource.draw_count();
80            self.updates.retained_cpu_bytes = self.updates.retained_cpu_bytes.saturating_add(
81                resource.recovery_memory_bytes().saturating_add(
82                    entry
83                        .records
84                        .capacity()
85                        .saturating_mul(size_of::<ResolvedScreenText>()),
86                ),
87            );
88            self.updates.retained_gpu_bytes = self
89                .updates
90                .retained_gpu_bytes
91                .saturating_add(resource.gpu_allocation_bytes());
92        }
93        self.updates.batch_cpu_time = started.elapsed();
94        Ok(())
95    }
96
97    fn update_batch(
98        &mut self,
99        renderer: &WgpuRenderer,
100        index: usize,
101        records: &[ResolvedScreenText],
102    ) -> Result<(), DesktopTextError> {
103        let first = records.first().ok_or(DesktopTextError::InvalidDrawPlan)?;
104        let font_index = self
105            .cache
106            .fonts
107            .binary_search_by_key(&first.font().slot(), |entry| entry.font.slot())
108            .map_err(|_| DesktopTextError::InvalidDrawPlan)?;
109        let atlas = &self.cache.fonts[font_index].atlas;
110        let mut placements = Vec::new();
111        reserve(&mut placements, records.len())?;
112        let mut glyphs = 0usize;
113        for visual in records {
114            let run_index = self
115                .cache
116                .runs
117                .binary_search_by_key(&visual.source().stable_bits(), |run| {
118                    run.source.stable_bits()
119                })
120                .map_err(|_| DesktopTextError::InvalidDrawPlan)?;
121            let run = &self.cache.runs[run_index];
122            if run.source != visual.source()
123                || run.font != *first.font()
124                || run.font != *visual.font()
125                || run.run.text() != visual.text()
126            {
127                return Err(DesktopTextError::InvalidDrawPlan);
128            }
129            let position = visual.baseline_origin().to_vec2();
130            let placement = ImageBatchPlacement::new(
131                LogicalScreenVector::new(position.x(), position.y()),
132                visual.tint(),
133            )
134            .map_err(|error| DesktopTextError::Batch {
135                source: first.source(),
136                error: sim_engine::GlyphError::Image(error),
137            })?;
138            let mut placed = GlyphRunPlacement2d::new(run.run.glyph_run(), placement);
139            match visual.visual().clip() {
140                ScreenClip::Rectangle(clip) => placed = placed.with_clip(clip),
141                ScreenClip::Unclipped => (),
142                ScreenClip::Empty => return Err(DesktopTextError::InvalidDrawPlan),
143            }
144            glyphs = glyphs
145                .checked_add(run.run.glyph_run().glyph_count())
146                .ok_or(DesktopTextError::BatchSizeOverflow)?;
147            placements.push(placed);
148        }
149        let error = |error| DesktopTextError::Batch {
150            source: first.source(),
151            error,
152        };
153        if let Some(entry) = self.batches.get_mut(index)
154            && entry.font == *first.font()
155            && glyphs <= entry.resource.budget().max_glyphs()
156        {
157            let additional = records.len().saturating_sub(entry.records.len());
158            reserve(&mut entry.records, additional)?;
159            let report = renderer
160                .update_glyph_batch(atlas.atlas(), &mut entry.resource, &placements)
161                .map_err(error)?;
162            entry.records.clear();
163            entry.records.extend_from_slice(records);
164            self.updates.updated_batches += 1;
165            self.updates.uploaded_bytes = self
166                .updates
167                .uploaded_bytes
168                .saturating_add(report.instances().uploaded_instance_bytes());
169        } else {
170            let mut keys = Vec::new();
171            reserve(&mut keys, records.len())?;
172            keys.extend_from_slice(records);
173            if index == self.batches.len() {
174                reserve(&mut self.batches, 1)?;
175            }
176            let budget = batch_budget(glyphs).map_err(error)?;
177            let resource = renderer
178                .create_glyph_batch(atlas.atlas(), &placements, budget)
179                .map_err(error)?;
180            // Nonempty creation uploads the entire exact-sized instance buffer.
181            // Empty groups allocate a sentinel but upload no instance bytes.
182            self.updates.uploaded_bytes =
183                self.updates.uploaded_bytes.saturating_add(if glyphs == 0 {
184                    0
185                } else {
186                    resource.gpu_allocation_bytes()
187                });
188            let entry = BatchEntry {
189                records: keys,
190                font: first.font().clone(),
191                resource,
192            };
193            if index == self.batches.len() {
194                self.batches.push(entry);
195            } else {
196                self.batches[index] = entry;
197            }
198            self.updates.created_batches += 1;
199        }
200        Ok(())
201    }
202
203    pub(in crate::desktop) fn draw_batch<'a>(
204        &'a self,
205        frame: &mut FrameComposer<'a>,
206        index: usize,
207        options: FramePassOptions,
208    ) -> Result<(), super::super::images::ScreenPresentationError> {
209        let entry = self
210            .batches
211            .get(index)
212            .ok_or(DesktopTextError::InvalidDrawPlan)?;
213        let font_index = self
214            .cache
215            .fonts
216            .binary_search_by_key(&entry.font.slot(), |font| font.font.slot())
217            .map_err(|_| DesktopTextError::InvalidDrawPlan)?;
218        frame.draw_glyph_batch(
219            self.cache.fonts[font_index].atlas.atlas(),
220            &entry.resource,
221            ImageSampling::Linear,
222            options,
223        )?;
224        Ok(())
225    }
226}
227
228fn reserve<T>(items: &mut Vec<T>, additional: usize) -> Result<(), DesktopTextError> {
229    items
230        .try_reserve_exact(additional)
231        .map_err(|_| DesktopTextError::Allocation {
232            requested_bytes: additional.saturating_mul(size_of::<T>()),
233        })
234}
235
236fn batch_budget(glyphs: usize) -> Result<GlyphBatchBudget, sim_engine::GlyphError> {
237    let overflow = || sim_engine::GlyphError::InvalidBudget;
238    let glyphs = glyphs
239        .max(1)
240        .checked_next_power_of_two()
241        .ok_or_else(overflow)?;
242    let bytes = glyphs
243        .checked_mul(GlyphBatchBudget::RETAINED_BYTES_PER_GLYPH)
244        .and_then(|bytes| {
245            bytes.checked_add(MAX_TEXT_PLACEMENTS * GlyphBatchBudget::RETAINED_BYTES_PER_PLACEMENT)
246        })
247        .ok_or_else(overflow)?;
248    GlyphBatchBudget::new(MAX_TEXT_PLACEMENTS, glyphs, bytes)
249}