Skip to content

Commit

Permalink
Grow internal packer and re-upload glyphs automatically
Browse files Browse the repository at this point in the history
  • Loading branch information
hecrj authored and grovesNL committed Jul 4, 2023
1 parent a74ce29 commit f64771c
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 30 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
3 changes: 1 addition & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use crate::ContentType;
use std::{
error::Error,
fmt::{self, Display, Formatter},
Expand All @@ -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 {
Expand Down
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
91 changes: 70 additions & 21 deletions src/text_atlas.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
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};
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)]
Expand Down Expand Up @@ -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());
}
}
Expand All @@ -110,15 +113,21 @@ 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;
}

// 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 {
Expand All @@ -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
}

Expand Down Expand Up @@ -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> {
Expand Down
17 changes: 12 additions & 5 deletions src/text_render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit f64771c

Please sign in to comment.