[oden] Let's get started on text

This has already been a journey and it will keep being a journey I think.
This commit is contained in:
John Doty 2023-08-31 08:22:59 -07:00
parent 44130cf22a
commit 71aa3c39f7
6 changed files with 503 additions and 4 deletions

214
src/text.rs Normal file
View file

@ -0,0 +1,214 @@
use fontdue::Font;
use lru::LruCache;
use wgpu;
/*
A note on how Casey Muratori's refterm works in terms of font rendering,
because it's not bad and handles things that we're not going to handle
because I just want to get some dang text on the dang screen right now.
- Step 1: You break the text into runs of characters that need to be
rendered together.
- Step 2: You figure out how many uniform cells this run occupies.
- Step 3: For each cell, you figure out if you already have the necessary
part of the run in the texture atlas. (Right? Each part of the run has a
distinct ID based on the actual run and the cell within the run.) If you
don't have this [run,cell] in the atlas, then:
- Step 3a: Render the run as a bitmap, if you haven't already.
- Step 3b: Get coordinates from the cache for this [run,cell] pair,
evicting something if necessary.
- Step 3c: Copy the part of the bitmap for this [run,cell] into the
texture atlas at the coordinates.
Put the coordinates (either newly generated or pulled from the cache) into
the cell.
- Step 4: Load all the cells onto the GPU and do a shader that renders the
cells.
Specifically what I'm doing right now is going character-by-caracter, and not
doing runs and not handling things that are wider than a cell. I'm also not
doing the efficient big grid render because I want to render characters at
pixel offsets and kern between characters and whatnot, which is different
from what they're doing. Mine is almost certainly less efficient.
*/
#[derive(Eq, PartialEq, Hash)]
enum CellCacheKey {
Garbage(u32), // Exists so that I can prime the LRU, not used generally.
GlyphIndex(u16), // Actual factual cache entries.
}
pub struct FontCache {
font: Font,
size: f32,
atlas_width: u16,
atlas_height: u16,
char_width: u16,
char_height: u16,
texture: wgpu::Texture,
view: wgpu::TextureView,
cells: Vec<GlyphCell>,
cell_cache: LruCache<CellCacheKey, usize>,
}
enum SlotState {
Empty,
Allocated(u16, fontdue::Metrics),
Rendered(u16, fontdue::Metrics),
}
struct GlyphCell {
// The coordinates in the atlas
x: u16,
y: u16,
state: SlotState,
}
impl FontCache {
fn new(device: &wgpu::Device, bytes: &[u8], size: f32) -> Self {
let font = fontdue::Font::from_bytes(bytes, fontdue::FontSettings::default())
.expect("Could not parse font");
// Set up the texture that we'll use to cache the glyphs we're rendering.
let atlas_width = 2048;
let atlas_height = 2048;
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Font Glyph Atlas"),
size: wgpu::Extent3d {
width: atlas_width.into(),
height: atlas_height.into(),
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 4,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
// Measure the font to figure out the size of a cell in the cache.
// NOTE: This metric nonsense is bad, probably.
let mut char_height = 0;
if let Some(line_metrics) = font.horizontal_line_metrics(size) {
char_height = (line_metrics.new_line_size + 0.5) as usize;
}
let metrics = font.metrics('M', size);
let mut char_width = metrics.width;
char_height = metrics.height.max(char_height);
let metrics = font.metrics('g', size);
char_width = metrics.width.max(char_width);
char_height = metrics.height.max(char_height);
// Allocate the individual cells in the texture atlas; this records
// the state of what's in the cell and whatnot.
let mut cells = vec![];
for y in (0..atlas_height).step_by(char_height) {
for x in (0..atlas_width).step_by(char_width) {
cells.push(GlyphCell {
x,
y,
state: SlotState::Empty,
});
}
}
// Allocate the LRU cache for the cells. Fill it with garbage so that
// we can always "allocate" by pulling from the LRU.
let mut cell_cache = LruCache::new(std::num::NonZeroUsize::new(cells.len()).unwrap());
for i in 0..cells.len() {
cell_cache.put(
CellCacheKey::Garbage(i.try_into().expect("Too many cells!")),
i,
);
}
// Set up the binding group and pipeline and whatnot.
FontCache {
font,
size,
atlas_width,
atlas_height,
char_width: char_width as u16,
char_height: char_height as u16,
texture,
view,
cells,
cell_cache,
}
}
fn rasterize_character(&mut self, queue: &wgpu::Queue, index: u16, slot: &GlyphCell) {
let (metrics, bitmap) = self.font.rasterize_indexed(index, self.size);
let mut texture = self.texture.as_image_copy();
texture.origin.x = slot.x.into();
texture.origin.y = slot.y.into();
queue.write_texture(
texture,
&bitmap,
wgpu::ImageDataLayout {
offset: 0,
bytes_per_row: Some(metrics.width as u32),
rows_per_image: None,
},
wgpu::Extent3d {
width: metrics.width as u32,
height: metrics.height as u32,
depth_or_array_layers: 1,
},
);
}
fn get_glyph_slot(&mut self, index: u16) -> &mut GlyphCell {
let key = CellCacheKey::GlyphIndex(index);
if let Some(cell_index) = self.cell_cache.get(&key) {
return &mut self.cells[*cell_index];
}
if let Some((_, cell_index)) = self.cell_cache.pop_lru() {
self.cell_cache.put(key, cell_index);
let cell = &mut self.cells[cell_index];
cell.state = SlotState::Empty;
return cell;
}
panic!("Did not put enough things in the LRU cache, why is it empty here?");
}
}
// pub fn inconsolata() {
// let font = include_bytes!("./Inconsolata-Regular.ttf") as &[u8];
// let font = fontdue::Font::from_bytes(font, fontdue::FontSettings::default()).unwrap();
// let text = "Hello World!";
// // Break to characters.
// let size = 16.0;
// let mut prev = None;
// let mut left = 0.0;
// for c in text.chars() {
// // TODO: Cache this.
// let (metrics, bitmap) = font.rasterize(c, size);
// left += match prev {
// Some(pc) => match font.horizontal_kern(pc, c, size) {
// Some(k) => k,
// None => 0.0,
// },
// None => 0.0,
// };
// left += metrics.advance_width;
// }
// }