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
57pub 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
106pub 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 pub const fn glyph_run(&self) -> &GlyphRun2d {
124 &self.run
125 }
126 pub fn text(&self) -> &str {
128 &self.text
129 }
130 pub const fn advance(&self) -> f32 {
132 self.advance
133 }
134 pub const fn ascent(&self) -> f32 {
136 self.ascent
137 }
138 pub const fn descent(&self) -> f32 {
140 self.descent
141 }
142 pub const fn line_height(&self) -> f32 {
144 self.line_height
145 }
146 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 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 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 pub const fn atlas(&self) -> &GlyphAtlas2d {
202 &self.atlas
203 }
204 pub const fn style(&self) -> &TextStyle {
206 &self.style
207 }
208 pub const fn font(&self) -> &FontFace {
210 &self.font
211 }
212 pub const fn budget(&self) -> TextAtlasBudget {
214 self.budget
215 }
216 pub fn cached_glyph_count(&self) -> usize {
218 self.cached.len()
219 }
220 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 pub fn gpu_allocation_bytes(&self) -> usize {
230 self.atlas.gpu_allocation_bytes()
231 }
232
233 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 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 pub fn restore(&mut self, renderer: &WgpuRenderer) -> Result<(), TextError> {
302 self.atlas = renderer.restore_glyph_atlas(&self.atlas)?;
303 Ok(())
304 }
305
306 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 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 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;