Separate atlas pages from textures, and draw both through one instance list

Rework of the review on #11. Pages and standalone images were one
`Textures` manager separated by a `TextureKind` tag, and images were a
second instance list beside `Primitives::instances`. The tag forced
`image_index()`/`layer()` to panic on the wrong kind of handle, and the
second list forced an `is_image` branch through `free`, `region_mut`,
`apply_free` and `PrimitiveChange`.

Pages are now their own thing. `GlyphAtlas` owns its page images
outright and hands the renderer dirty rectangles; `GpuPages` owns the
array texture they upload to. `Textures` is standalone images only, so
`TextureHandle` has one kind, `slot()` cannot be wrong, and nothing
needs a free list that skips pages. `GlyphAtlas::insert` no longer takes
a `Textures`, which drops that parameter from `TextData::render` and
`SizeCtx` too.

Images go back through the one instance list. A texture instance is an
ordinary `PrimitiveInstance` whose `idx` names a texture rather than a
group-1 entry, which `PrimitiveHandle::data_idx: Option` records.
`RenderLayer::plan_draws` batches the layer's instances into runs
sharing a bind group, so a ui with no images still plans a single draw,
and an image draws in instance order rather than on top of its layer.

Group 2 is now one `texture_2d_array` and a sampler, bound per run: the
atlas for rects and glyphs, or one image viewed as an array of one. That
removes the second texture binding and the 1x1 null view that had to
fill it. Masks move to group 3, so resizing that buffer no longer stales
every texture bind group, and `GpuTextures` no longer reports whether
the caller must rebuild one.

`GlyphPrimitive` drops its manual pad: the WGSL struct now declares the
uvs as scalars, which matches the Rust layout exactly. `#[repr(C,
align(8))]` would have left real padding bytes, which `bytemuck::Pod`
forbids.

Verified with a headless run of the `tabs` example and of a scratch
example mixing images, rects, glyphs and a mask in one layer; 52 glyphs
at size 300 grew the atlas array from 1 to 4 layers with every earlier
page still sampling correctly.
This commit is contained in:
iris committed 2026-09-13 12:47:41 -04:00
1 parent bafaa1db6d
commit 0106257be0
15 files changed
+544 -932

No files matched your search

+3 -3
View File
@@ -133,15 +133,15 @@ impl PrimitiveLayers {
self[h.layer].free(h)
}
pub fn write_image(
pub fn write_texture(
&mut self,
layer: LayerId,
id: WidgetId,
texture_idx: u32,
texture: u32,
region: UiRegion,
mask_idx: MaskIdx,
) -> PrimitiveHandle {
self[layer].write_image(layer, id, texture_idx, region, mask_idx)
self[layer].write_texture(layer, id, texture, region, mask_idx)
}
}
+13 -22
View File
@@ -1,6 +1,5 @@
use crate::{
Align, GlyphAtlas, GlyphEntry, GlyphKey, PlacedGlyph, RegionAlign, Textures, UiColor,
util::Vec2,
Align, GlyphAtlas, GlyphEntry, GlyphKey, PlacedGlyph, RegionAlign, UiColor, util::Vec2,
};
use parley::{
Alignment, AlignmentOptions, FontContext, FontFamily, FontFamilyName, GenericFamily, Layout,
@@ -159,7 +158,7 @@ impl TextBuffer {
}
impl TextData {
pub fn place(&mut self, buffer: &TextBuffer, textures: &mut Textures) -> Vec<PlacedGlyph> {
pub fn place(&mut self, buffer: &TextBuffer) -> Vec<PlacedGlyph> {
let mut placed = Vec::new();
for line in buffer.layout.lines() {
for item in line.items() {
@@ -185,17 +184,14 @@ impl TextData {
subpixel,
coords: coords_hash,
};
let Some(entry) = self.glyph_entry(
GlyphRaster {
key,
font: font_ref,
font_size,
coords,
subpixel,
glyph_id: glyph.id,
},
textures,
) else {
let Some(entry) = self.glyph_entry(GlyphRaster {
key,
font: font_ref,
font_size,
coords,
subpixel,
glyph_id: glyph.id,
}) else {
continue;
};
placed.push(PlacedGlyph {
@@ -211,11 +207,7 @@ impl TextData {
placed
}
fn glyph_entry(
&mut self,
glyph: GlyphRaster<'_>,
textures: &mut Textures,
) -> Option<GlyphEntry> {
fn glyph_entry(&mut self, glyph: GlyphRaster<'_>) -> Option<GlyphEntry> {
if let Some(entry) = self.atlas.get(&glyph.key) {
return entry;
}
@@ -237,7 +229,7 @@ impl TextData {
.render(&mut scaler, glyph.glyph_id as u16);
if let Some(image) = image {
self.atlas.insert(glyph.key, &image, textures)
self.atlas.insert(glyph.key, &image)
} else {
self.atlas.insert_empty(glyph.key);
None
@@ -278,10 +270,9 @@ impl TextData {
buffer: &mut TextBuffer,
attrs: &TextAttrs,
width: Option<f32>,
textures: &mut Textures,
) -> RenderedText {
buffer.shape(self, attrs, width);
let glyphs = self.place(buffer, textures);
let glyphs = self.place(buffer);
RenderedText {
glyphs,
size: buffer.size(),
+26 -94
View File
@@ -5,28 +5,12 @@ use std::{
sync::mpsc::{Receiver, Sender, channel},
};
/// Which of the two things a texture slot holds. The two are drawn very
/// differently: a page is a layer of one shared array texture and never gets
/// its own bind group; a standalone image is the opposite, one texture and
/// one bind group, never a layer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextureKind {
Image,
/// The array-texture layer this page was assigned. Chosen synchronously
/// by `Textures::add_page` rather than by the renderer, because glyph
/// insertion needs it in the same call, before any GPU sync happens.
Page {
layer: u32,
},
}
#[derive(Debug, Clone)]
pub struct TextureHandle {
slot: u32,
kind: TextureKind,
size: Vec2,
counter: RefCounter,
send: Sender<(TextureKind, u32)>,
send: Sender<u32>,
}
/// a texture manager for a ui
@@ -34,24 +18,19 @@ pub struct TextureHandle {
pub struct Textures {
free: Vec<u32>,
images: Vec<Option<DynamicImage>>,
/// Next layer to hand out to an atlas page. Pages are never freed (no
/// atlas eviction), so this only grows and `free` never holds one.
next_page_layer: u32,
updates: Vec<Update>,
send: Sender<(TextureKind, u32)>,
recv: Receiver<(TextureKind, u32)>,
send: Sender<u32>,
recv: Receiver<u32>,
}
pub enum TextureUpdate<'a> {
Push(TextureKind, &'a DynamicImage),
Set(TextureKind, u32, &'a DynamicImage),
/// Overwrite a rectangle of an existing texture, rather than replacing it.
/// The glyph atlas grows a glyph at a time, and re-uploading a whole atlas
/// per glyph is megabytes of copy for a few hundred bytes of change.
/// Only ever issued against a page -- a standalone image is never patched.
Push(&'a DynamicImage),
Set(u32, &'a DynamicImage),
Patch(u32, PatchRect, &'a DynamicImage),
Free(u32),
PushFree(TextureKind),
/// Added and freed before the renderer drained either update. It still has
/// to push a slot to stay lined up with `images`; `Free` then empties it.
PushFree,
SetFree,
}
@@ -64,8 +43,8 @@ pub struct PatchRect {
}
enum Update {
Push(TextureKind, u32),
Set(TextureKind, u32),
Push(u32),
Set(u32),
Patch(u32, PatchRect),
Free(u32),
}
@@ -76,54 +55,31 @@ impl Textures {
Self {
free: Vec::new(),
images: Vec::new(),
next_page_layer: 0,
updates: Vec::new(),
send,
recv,
}
}
pub fn add(&mut self, image: impl Into<DynamicImage>) -> TextureHandle {
let image = image.into();
let size = image.dimensions().into();
let kind = TextureKind::Image;
let slot = self.push(kind, image);
TextureHandle {
slot,
kind,
slot: self.push(image),
size,
counter: RefCounter::new(),
send: self.send.clone(),
}
}
/// Adds a page of the shared glyph atlas array. Only `atlas.rs` should
/// call this -- everything else wants `add`.
pub fn add_page(&mut self, image: impl Into<DynamicImage>) -> TextureHandle {
let image = image.into();
let size = image.dimensions().into();
let layer = self.next_page_layer;
self.next_page_layer += 1;
let kind = TextureKind::Page { layer };
let slot = self.push(kind, image);
TextureHandle {
slot,
kind,
size,
counter: RefCounter::new(),
send: self.send.clone(),
}
}
fn push(&mut self, kind: TextureKind, image: DynamicImage) -> u32 {
fn push(&mut self, image: DynamicImage) -> u32 {
if let Some(i) = self.free.pop() {
self.images[i as usize] = Some(image);
self.updates.push(Update::Set(kind, i));
self.updates.push(Update::Set(i));
i
} else {
let i = self.images.len() as u32;
self.images.push(Some(image));
self.updates.push(Update::Push(kind, i));
self.updates.push(Update::Push(i));
i
}
}
@@ -140,29 +96,22 @@ impl Textures {
}
pub fn free(&mut self) {
for (kind, idx) in self.recv.try_iter() {
for idx in self.recv.try_iter() {
self.images[idx as usize] = None;
self.updates.push(Update::Free(idx));
// A page's slot is never reclaimed: `GlyphAtlas` never drops the
// handles it holds, and there is no eviction path for a hole in
// the middle of the array's layers. So `free` holds ordinary
// image slots only, and a page's layer would need a free list of
// its own were that to change.
if kind == TextureKind::Image {
self.free.push(idx);
}
self.free.push(idx);
}
}
pub fn updates(&mut self) -> impl Iterator<Item = TextureUpdate<'_>> {
self.updates.drain(..).map(|u| match u {
Update::Push(kind, i) => self.images[i as usize]
Update::Push(i) => self.images[i as usize]
.as_ref()
.map(|img| TextureUpdate::Push(kind, img))
.unwrap_or(TextureUpdate::PushFree(kind)),
Update::Set(kind, i) => self.images[i as usize]
.map(TextureUpdate::Push)
.unwrap_or(TextureUpdate::PushFree),
Update::Set(i) => self.images[i as usize]
.as_ref()
.map(|img| TextureUpdate::Set(kind, i, img))
.map(|img| TextureUpdate::Set(i, img))
.unwrap_or(TextureUpdate::SetFree),
Update::Patch(i, rect) => self.images[i as usize]
.as_ref()
@@ -174,36 +123,19 @@ impl Textures {
}
impl TextureHandle {
/// Index into `Textures`, and into the renderer's parallel slots.
pub fn slot(&self) -> u32 {
self.slot
}
pub fn size(&self) -> Vec2 {
self.size
}
/// The bind-group index this handle draws with. Only valid for a
/// standalone image; an atlas page has no bind group of its own -- it
/// samples the shared array via `layer()` instead. Getting this wrong is
/// a caller bug (the wrong kind of handle reached the wrong draw path),
/// not a recoverable condition, so it panics rather than drawing garbage.
pub fn image_index(&self) -> u32 {
match self.kind {
TextureKind::Image => self.slot,
TextureKind::Page { .. } => panic!("image_index() called on an atlas page handle"),
}
}
/// The layer this page occupies in the shared atlas array texture.
/// Only valid for a page handle; see `image_index`'s note.
pub fn layer(&self) -> u32 {
match self.kind {
TextureKind::Page { layer } => layer,
TextureKind::Image => panic!("layer() called on a standalone image handle"),
}
}
}
impl Drop for TextureHandle {
fn drop(&mut self) {
if self.counter.drop() {
let _ = self.send.send((self.kind, self.slot));
let _ = self.send.send(self.slot);
}
}
}