From f64771c2c34c74ebc3bc3990f5704a7f907a3e27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Thu, 15 Jun 2023 18:23:36 +0200 Subject: [PATCH] Grow internal `packer` and re-upload glyphs automatically --- Cargo.toml | 2 +- src/error.rs | 3 +- src/lib.rs | 3 +- src/text_atlas.rs | 91 +++++++++++++++++++++++++++++++++++----------- src/text_render.rs | 17 ++++++--- 5 files changed, 86 insertions(+), 30 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 50f8481..745d6e2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ license = "MIT OR Apache-2.0 OR Zlib" [dependencies] wgpu = "0.16" -etagere = "0.2.6" +etagere = { git = "https://github.com/hecrj/etagere.git", rev = "4ee873d5c412d31237cd51efdcfdc7a0afd1953b" } cosmic-text = "0.8" lru = "0.9" diff --git a/src/error.rs b/src/error.rs index e9d75da..0de51f9 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,4 +1,3 @@ -use crate::ContentType; use std::{ error::Error, fmt::{self, Display, Formatter}, @@ -7,7 +6,7 @@ use std::{ /// An error that occurred while preparing text for rendering. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PrepareError { - AtlasFull(ContentType), + AtlasFull, } impl Display for PrepareError { diff --git a/src/lib.rs b/src/lib.rs index 7c2d736..276dd20 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,9 +10,10 @@ mod text_render; pub use error::{PrepareError, RenderError}; pub use text_atlas::{ColorMode, TextAtlas}; -pub use text_render::ContentType; pub use text_render::TextRenderer; +use text_render::ContentType; + // Re-export all top-level types from `cosmic-text` for convenience. pub use cosmic_text::{ self, fontdb, Action, Affinity, Attrs, AttrsList, AttrsOwned, Buffer, BufferLine, CacheKey, diff --git a/src/text_atlas.rs b/src/text_atlas.rs index 0b1f74a..6e5de01 100644 --- a/src/text_atlas.rs +++ b/src/text_atlas.rs @@ -1,4 +1,7 @@ -use crate::{text_render::ContentType, CacheKey, GlyphDetails, GlyphToRender, Params, Resolution}; +use crate::{ + text_render::ContentType, CacheKey, FontSystem, GlyphDetails, GlyphToRender, GpuCacheStatus, + Params, Resolution, SwashCache, +}; use etagere::{size2, Allocation, BucketedAtlasAllocator}; use lru::LruCache; use std::{borrow::Cow, collections::HashSet, mem::size_of, num::NonZeroU64, sync::Arc}; @@ -6,11 +9,12 @@ use wgpu::{ BindGroup, BindGroupDescriptor, BindGroupEntry, BindGroupLayout, BindGroupLayoutEntry, BindingResource, BindingType, BlendState, Buffer, BufferBindingType, BufferDescriptor, BufferUsages, ColorTargetState, ColorWrites, DepthStencilState, Device, Extent3d, FilterMode, - FragmentState, MultisampleState, PipelineLayout, PipelineLayoutDescriptor, PrimitiveState, - Queue, RenderPipeline, RenderPipelineDescriptor, Sampler, SamplerBindingType, - SamplerDescriptor, ShaderModule, ShaderModuleDescriptor, ShaderSource, ShaderStages, Texture, - TextureDescriptor, TextureDimension, TextureFormat, TextureSampleType, TextureUsages, - TextureView, TextureViewDescriptor, TextureViewDimension, VertexFormat, VertexState, + FragmentState, ImageCopyTexture, ImageDataLayout, MultisampleState, Origin3d, PipelineLayout, + PipelineLayoutDescriptor, PrimitiveState, Queue, RenderPipeline, RenderPipelineDescriptor, + Sampler, SamplerBindingType, SamplerDescriptor, ShaderModule, ShaderModuleDescriptor, + ShaderSource, ShaderStages, Texture, TextureAspect, TextureDescriptor, TextureDimension, + TextureFormat, TextureSampleType, TextureUsages, TextureView, TextureViewDescriptor, + TextureViewDimension, VertexFormat, VertexState, }; #[allow(dead_code)] @@ -78,20 +82,19 @@ impl InnerAtlas { } // Try to free least recently used allocation - let (_, mut value) = self.glyph_cache.peek_lru()?; + let (mut key, mut value) = self.glyph_cache.peek_lru()?; while value.atlas_id.is_none() { let _ = self.glyph_cache.pop_lru(); - (_, value) = self.glyph_cache.peek_lru()?; + (key, value) = self.glyph_cache.peek_lru()?; } - let (key, value) = self.glyph_cache.pop_lru().unwrap(); - if self.glyphs_in_use.contains(&key) { return None; } + let (_, value) = self.glyph_cache.pop_lru().unwrap(); self.packer.deallocate(value.atlas_id.unwrap()); } } @@ -110,7 +113,13 @@ impl InnerAtlas { self.glyphs_in_use.insert(glyph); } - pub(crate) fn grow(&mut self, device: &wgpu::Device) -> bool { + pub(crate) fn grow( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + font_system: &mut FontSystem, + cache: &mut SwashCache, + ) -> bool { if self.size >= self.max_texture_dimension_2d { return false; } @@ -118,7 +127,7 @@ impl InnerAtlas { // TODO: Better resizing logic (?) let new_size = (self.size + Self::INITIAL_SIZE).min(self.max_texture_dimension_2d); - self.packer = BucketedAtlasAllocator::new(size2(new_size as i32, new_size as i32)); + self.packer.grow(size2(new_size as i32, new_size as i32)); // Create a texture to use for our atlas self.texture = device.create_texture(&TextureDescriptor { @@ -136,12 +145,46 @@ impl InnerAtlas { view_formats: &[], }); + // Re-upload glyphs + for (&cache_key, glyph) in &self.glyph_cache { + let (x, y) = match glyph.gpu_cache { + GpuCacheStatus::InAtlas { x, y, .. } => (x, y), + GpuCacheStatus::SkipRasterization => continue, + }; + + let image = cache.get_image_uncached(font_system, cache_key).unwrap(); + + let width = image.placement.width as usize; + let height = image.placement.height as usize; + + queue.write_texture( + ImageCopyTexture { + texture: &self.texture, + mip_level: 0, + origin: Origin3d { + x: x as u32, + y: y as u32, + z: 0, + }, + aspect: TextureAspect::All, + }, + &image.data, + ImageDataLayout { + offset: 0, + bytes_per_row: Some(width as u32 * self.kind.num_channels() as u32), + rows_per_image: None, + }, + Extent3d { + width: width as u32, + height: height as u32, + depth_or_array_layers: 1, + }, + ); + } + self.texture_view = self.texture.create_view(&TextureViewDescriptor::default()); self.size = new_size; - self.glyph_cache.clear(); - self.glyphs_in_use.clear(); - true } @@ -406,18 +449,24 @@ impl TextAtlas { self.color_atlas.trim(); } - pub fn grow(&mut self, device: &wgpu::Device, content_type: ContentType) -> bool { + pub(crate) fn grow( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + font_system: &mut FontSystem, + cache: &mut SwashCache, + content_type: ContentType, + ) -> bool { let did_grow = match content_type { - ContentType::Mask => self.mask_atlas.grow(device), - ContentType::Color => self.color_atlas.grow(device), + ContentType::Mask => self.mask_atlas.grow(device, queue, font_system, cache), + ContentType::Color => self.color_atlas.grow(device, queue, font_system, cache), }; if did_grow { self.rebind(device); - true - } else { - false } + + did_grow } pub(crate) fn glyph(&self, glyph: &CacheKey) -> Option<&GlyphDetails> { diff --git a/src/text_render.rs b/src/text_render.rs index 47f2e0f..dc2ca58 100644 --- a/src/text_render.rs +++ b/src/text_render.rs @@ -118,13 +118,20 @@ impl TextRenderer { let should_rasterize = width > 0 && height > 0; let (gpu_cache, atlas_id, inner) = if should_rasterize { - let inner = atlas.inner_for_content_mut(content_type); + let mut inner = atlas.inner_for_content_mut(content_type); // Find a position in the packer - let allocation = match inner.try_allocate(width, height) { - Some(a) => a, - None => { - return Err(PrepareError::AtlasFull(content_type)); + let allocation = loop { + match inner.try_allocate(width, height) { + Some(a) => break a, + None => { + if !atlas.grow(device, queue, font_system, cache, content_type) + { + return Err(PrepareError::AtlasFull); + } + + inner = atlas.inner_for_content_mut(content_type); + } } }; let atlas_min = allocation.rectangle.min;