Major renderer refactor

Replace old per-mesh bind group model with a better batching schema
built around wgpu's TEXTURE_BINDING_ARRAY support. Each batch now
holds multiple textures. Vertex and index buffers are now only set once
per frame. Massively improves rendering performance.
This commit is contained in:
meehl committed 2026-08-16 01:25:22 +02:00
1 parent 3fc87339ca
commit 4d6c258932
8 files changed
+376 -351

No files matched your search

+10 -13
View File
@@ -1,13 +1,14 @@
use crate::{
args::Game,
batcher::build_render_job,
dpi::{ConvertToLogical, PhysicalPoint, PhysicalSize},
fonts::{FontData, FontDefinitions, Fonts},
gfx::{GraphicsContext, RenderJob},
gfx::GraphicsContext,
input::InputState,
installer::InstallMode,
mode::{AppEvent, AppMode, ModeTransition},
pob::PoBMode,
renderer::{tessellator::Tessellator, textures::WrappedTextureManager},
renderer::{RenderJob, textures::WrappedTextureManager},
window::WindowState,
};
use anyhow::Result;
@@ -19,7 +20,7 @@ use winit::{
};
struct FrameOutput {
pub render_job: RenderJob,
pub render_job: Option<RenderJob>,
pub should_continue: bool,
}
@@ -43,7 +44,6 @@ pub struct App {
gfx_context: Option<GraphicsContext>,
state: AppState,
game: Game,
tessellator: Tessellator,
needs_reconfigure: bool,
force_render: bool,
current_mode: AppMode,
@@ -76,7 +76,6 @@ impl App {
gfx_context: None,
state,
game,
tessellator: Tessellator::default(),
needs_reconfigure: true,
force_render: true,
current_mode,
@@ -112,16 +111,14 @@ impl App {
let render_job = if mode_output.can_elide && textures_delta.is_empty() && !self.force_render
{
RenderJob::Skip
None
} else {
let meshes = self
.tessellator
.convert_draw_commands(mode_output.draw_commands);
RenderJob::Render {
meshes,
Some(build_render_job(
&mode_output.draw_commands,
textures_delta,
}
// TODO: find better way to determine this and how to pass it in
32,
))
};
Ok(FrameOutput {
+163
View File
@@ -0,0 +1,163 @@
use ahash::HashMap;
use crate::{
dpi::LogicalRect,
draw_commands::DrawCommand,
renderer::{
Batch, RenderJob, Vertex,
textures::{TextureId, TexturesDelta},
},
};
struct BatchBuilder {
textures: Vec<TextureId>,
// maps TextureId to index into textures array
texture_mapping: HashMap<TextureId, u32>,
clip_rect: LogicalRect<f32>,
// index into batch's indecies array
start_index: u32,
}
impl BatchBuilder {
fn new(clip_rect: LogicalRect<f32>, start_index: u32) -> Self {
// seed slot 0 with font atlas.
// the font atlas texture is used for solid color and text
// rendering so it needs to be present in almost every batch.
let textures = vec![TextureId::default()];
let texture_mapping = HashMap::from_iter([(TextureId::default(), 0)]);
Self {
textures,
texture_mapping,
clip_rect,
start_index,
}
}
/// Tries to assign a texture to the batch.
///
/// Returns slot_index into textures array if texture can be assigned.
/// Returns `None` if maximum amount of texture slots is reached.
fn try_assign(&mut self, id: TextureId, max_slots: u32) -> Option<u32> {
if let Some(&slot) = self.texture_mapping.get(&id) {
return Some(slot);
}
if self.textures.len() as u32 > max_slots {
return None;
}
let slot = self.textures.len() as u32;
self.textures.push(id);
self.texture_mapping.insert(id, slot);
Some(slot)
}
fn finish(self, end_index: u32) -> Option<Batch> {
if self.start_index < end_index {
Some(Batch {
clip_rect: self.clip_rect,
textures: self.textures,
index_range: self.start_index..end_index,
})
} else {
None
}
}
}
pub fn build_render_job(
commands: &[DrawCommand],
textures_delta: TexturesDelta,
max_slots: u32,
) -> RenderJob {
profiling::scope!("build_render_job");
let mut vertices = Vec::with_capacity(commands.len() * 4);
let mut indices = Vec::with_capacity(commands.len() * 6);
let mut batches = Vec::new();
let Some(first_cmd) = commands.first() else {
// no draw commands, only texture updates
return RenderJob {
vertices,
indices,
batches,
textures_delta,
};
};
let mut builder = BatchBuilder::new(first_cmd.clip_rect, 0);
for cmd in commands {
// start new batch if clip_rects don't match
if cmd.clip_rect != builder.clip_rect {
let next_builder = BatchBuilder::new(cmd.clip_rect, indices.len() as u32);
if let Some(batch) =
std::mem::replace(&mut builder, next_builder).finish(indices.len() as u32)
{
batches.push(batch);
}
}
let slot = builder
.try_assign(cmd.texture_id, max_slots)
.unwrap_or_else(|| {
let next_builder = BatchBuilder::new(cmd.clip_rect, indices.len() as u32);
if let Some(batch) =
std::mem::replace(&mut builder, next_builder).finish(indices.len() as u32)
{
batches.push(batch);
}
builder
.try_assign(cmd.texture_id, max_slots)
.expect("new batch always has enough space")
});
let i = vertices.len() as u32;
indices.extend_from_slice(&[i, i + 1, i + 3, i + 1, i + 2, i + 3]);
vertices.extend_from_slice(&[
Vertex {
pos: cmd.positions.p0,
uv: cmd.uvs.p0,
color: cmd.color,
texture_slot: slot,
layer_idx: cmd.texture_layer_idx,
},
Vertex {
pos: cmd.positions.p1,
uv: cmd.uvs.p1,
color: cmd.color,
texture_slot: slot,
layer_idx: cmd.texture_layer_idx,
},
Vertex {
pos: cmd.positions.p2,
uv: cmd.uvs.p2,
color: cmd.color,
texture_slot: slot,
layer_idx: cmd.texture_layer_idx,
},
Vertex {
pos: cmd.positions.p3,
uv: cmd.uvs.p3,
color: cmd.color,
texture_slot: slot,
layer_idx: cmd.texture_layer_idx,
},
]);
}
if let Some(batch) = builder.finish(indices.len() as u32) {
batches.push(batch);
}
return RenderJob {
vertices,
indices,
batches,
textures_delta,
};
}
+22 -22
View File
@@ -1,18 +1,13 @@
use crate::{
dpi::PhysicalSize,
renderer::{Renderer, mesh::ClippedMesh, textures::TexturesDelta},
renderer::{RenderJob, Renderer},
};
use std::sync::Arc;
use wgpu::{Texture, TextureFormat, TextureView};
use winit::window::Window;
pub enum RenderJob {
Render {
meshes: Vec<ClippedMesh>,
textures_delta: TexturesDelta,
},
Skip,
}
const REQUIRED_TEXTURE_LAYERS: u32 = 1024;
const REQUIRED_TEXTURE_ARRAY_SLOTS: u32 = 64;
pub struct GraphicsContext {
surface: wgpu::Surface<'static>,
@@ -50,9 +45,13 @@ impl GraphicsContext {
})
.await?;
let required_features = wgpu::Features::TEXTURE_COMPRESSION_BC;
let required_features = wgpu::Features::TEXTURE_COMPRESSION_BC
| wgpu::Features::TEXTURE_BINDING_ARRAY
| wgpu::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING;
let required_limits = wgpu::Limits {
max_texture_array_layers: 1024,
max_texture_array_layers: REQUIRED_TEXTURE_LAYERS,
max_binding_array_elements_per_shader_stage: REQUIRED_TEXTURE_ARRAY_SLOTS,
max_binding_array_sampler_elements_per_shader_stage: REQUIRED_TEXTURE_ARRAY_SLOTS,
..Default::default()
};
@@ -148,7 +147,11 @@ impl GraphicsContext {
}
}
pub fn render(&mut self, render_job: RenderJob, scale_factor: f32) -> anyhow::Result<()> {
pub fn render(
&mut self,
render_job: Option<RenderJob>,
scale_factor: f32,
) -> anyhow::Result<()> {
profiling::scope!("render");
if !self.is_surface_configured {
@@ -180,24 +183,20 @@ impl GraphicsContext {
label: Some("Render Encoder"),
});
// If render_job is [`RenderJob::Skip`], skip rendering and just
// blit the texture of the previous frame onto the surface texture.
if let RenderJob::Render {
meshes,
textures_delta,
} = render_job
{
// If render_job is `None`, skip rendering and just blit the texture
// of the previous frame onto the surface texture.
if let Some(render_job) = render_job {
let screen_size = PhysicalSize::new(self.config.width, self.config.height);
// upload new textures
self.renderer
.update_textures(&self.device, &self.queue, &textures_delta);
.update_textures(&self.device, &self.queue, &render_job.textures_delta);
// upload vertex, index, and uniform buffers
self.renderer.update_buffers(
&self.device,
&self.queue,
&meshes,
&render_job,
screen_size,
scale_factor,
);
@@ -225,13 +224,14 @@ impl GraphicsContext {
});
self.renderer.render(
&self.device,
&mut rpass.forget_lifetime(),
&meshes,
&render_job,
screen_size,
scale_factor,
);
self.renderer.free_textures(&textures_delta);
self.renderer.free_textures(&render_job.textures_delta);
}
{
+1
View File
@@ -6,6 +6,7 @@ use winit::event_loop::EventLoop;
mod api;
mod app;
mod args;
mod batcher;
mod clipboard;
mod color;
mod dpi;
+169 -122
View File
@@ -1,26 +1,64 @@
use crate::{
dpi::{ConvertToLogical, ConvertToPhysical, LogicalSize, PhysicalRect, PhysicalSize},
color::Srgba,
dpi::{
ConvertToLogical, ConvertToPhysical, LogicalPoint, LogicalRect, LogicalSize,
NormalizedPoint, PhysicalRect, PhysicalSize,
},
math::Point,
renderer::{
image::ImageData,
mesh::{ClippedMesh, Vertex},
textures::{TextureId, TextureOptions, TexturesDelta},
},
util::calculate_hash,
};
use ahash::HashMap;
use std::{borrow::Cow, num::NonZeroU64, ops::Range};
use std::{
borrow::Cow,
num::{NonZeroU32, NonZeroU64},
ops::Range,
};
use wgpu::util::DeviceExt;
pub mod image;
pub mod mesh;
mod mipmap;
pub mod tessellator;
pub mod textures;
// TODO:
const MAX_SLOTS: u32 = 32;
// TODO: use font atlas as dummy texture for now
const DUMMY_TEXTURE_ID: TextureId = 0;
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Vertex {
pub pos: LogicalPoint<f32>,
pub uv: NormalizedPoint,
pub color: Srgba,
/// Index into batch's texture array
pub texture_slot: u32,
/// Index into texture array
pub layer_idx: u32,
}
pub struct Batch {
pub clip_rect: LogicalRect<f32>,
pub textures: Vec<TextureId>,
/// Points into combined index buffer of `RenderJob`
pub index_range: Range<u32>,
}
pub struct RenderJob {
pub vertices: Vec<Vertex>,
pub indices: Vec<u32>,
pub batches: Vec<Batch>,
pub textures_delta: TexturesDelta,
}
#[derive(Debug)]
struct Texture {
struct TextureEntry {
texture: wgpu::Texture,
bind_group: wgpu::BindGroup,
view: wgpu::TextureView,
options: TextureOptions,
}
#[repr(C)]
@@ -32,16 +70,17 @@ struct Globals {
pub struct Renderer {
pipeline: wgpu::RenderPipeline,
index_buffer: SlicedBuffer,
vertex_buffer: SlicedBuffer,
index_buffer: Buffer,
vertex_buffer: Buffer,
globals_buffer: wgpu::Buffer,
previous_globals: Globals,
globals_bind_group: wgpu::BindGroup,
texture_bind_group_layout: wgpu::BindGroupLayout,
textures_bind_group_layout: wgpu::BindGroupLayout,
textures: HashMap<TextureId, Texture>,
textures: HashMap<TextureId, TextureEntry>,
samplers: HashMap<TextureOptions, wgpu::Sampler>,
batch_bind_group_cache: HashMap<u64, wgpu::BindGroup>,
}
impl Renderer {
@@ -91,7 +130,7 @@ impl Renderer {
}],
});
let texture_bind_group_layout =
let textures_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("texture_bind_group_layout"),
entries: &[
@@ -103,13 +142,13 @@ impl Renderer {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2Array,
},
count: None,
count: Some(NonZeroU32::new(MAX_SLOTS).unwrap()),
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
count: Some(NonZeroU32::new(MAX_SLOTS).unwrap()),
},
],
});
@@ -118,7 +157,7 @@ impl Renderer {
label: Some("pipeline_layout"),
bind_group_layouts: &[
Some(&globals_bind_group_layout),
Some(&texture_bind_group_layout),
Some(&textures_bind_group_layout),
],
immediate_size: 0,
});
@@ -138,14 +177,15 @@ impl Renderer {
entry_point: Some("vs_main"),
module: &shader_module,
buffers: &[Some(wgpu::VertexBufferLayout {
// 4x f32, 2x u32 -> 6 * 4 bytes
array_stride: 6 * 4,
// 4x f32, 3x u32 -> 7 * 4 bytes
array_stride: 7 * 4,
step_mode: wgpu::VertexStepMode::Vertex,
// 0: vec2 position
// 1: vec2 texture coordinates
// 2: uint color
// 3: uint layer_idx
attributes: &wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x2, 2 => Uint32, 3 => Uint32],
// 3: uint texture_idx
// 4: uint layer_idx
attributes: &wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x2, 2 => Uint32, 3 => Uint32, 4 => Uint32],
})],
compilation_options: wgpu::PipelineCompilationOptions::default()
},
@@ -178,14 +218,14 @@ impl Renderer {
cache: None,
});
let vertex_buffer = SlicedBuffer::new(
let vertex_buffer = Buffer::new(
device,
wgpu::BufferUsages::VERTEX,
NonZeroU64::new(2048).expect("2048 is non-zero"),
NonZeroU64::new(std::mem::size_of::<Vertex>() as u64)
.expect("size of vertex is non-zero"),
);
let index_buffer = SlicedBuffer::new(
let index_buffer = Buffer::new(
device,
wgpu::BufferUsages::INDEX,
NonZeroU64::new(2048 * 3).expect("2048 * 3 is non-zero"),
@@ -201,25 +241,24 @@ impl Renderer {
screen_size: LogicalSize::zero(),
},
globals_bind_group,
texture_bind_group_layout,
textures_bind_group_layout,
textures: HashMap::default(),
samplers: HashMap::default(),
batch_bind_group_cache: Default::default(),
}
}
pub fn render(
&self,
&mut self,
device: &wgpu::Device,
render_pass: &mut wgpu::RenderPass<'static>,
paint_jobs: &[ClippedMesh],
render_job: &RenderJob,
screen_size: PhysicalSize<u32>,
pixels_per_point: f32,
) {
profiling::scope!("render");
let screen_rect = PhysicalRect::from_origin_and_size(Point::zero(), screen_size);
let mut index_buffer_slices = self.index_buffer.slices.iter();
let mut vertex_buffer_slices = self.vertex_buffer.slices.iter();
render_pass.set_viewport(
0.0,
0.0,
@@ -230,18 +269,30 @@ impl Renderer {
);
render_pass.set_pipeline(&self.pipeline);
render_pass.set_bind_group(0, &self.globals_bind_group, &[]);
render_pass.set_index_buffer(
self.index_buffer.buffer.slice(..),
wgpu::IndexFormat::Uint32,
);
render_pass.set_vertex_buffer(0, self.vertex_buffer.buffer.slice(..));
for ClippedMesh { clip_rect, mesh } in paint_jobs {
let phys_clip_rect = clip_rect.to_physical::<f32, _>(pixels_per_point).round();
for batch in &render_job.batches {
// set textures array bind group
let bind_group = self.get_or_build_batch_bind_group(device, batch);
render_pass.set_bind_group(1, bind_group, &[]);
// scissor
let phys_clip_rect = batch
.clip_rect
.to_physical::<f32, _>(pixels_per_point)
.round();
let scissor = phys_clip_rect
// NOTE: can't cast to u32 directly because negative values cause a panic
.cast::<i32>()
.intersection(&screen_rect.to_i32())
.map(|s| s.to_u32());
// skip batch if scissor doesn't intersect screen
let Some(scissor) = scissor else {
index_buffer_slices.next().unwrap();
vertex_buffer_slices.next().unwrap();
continue;
};
@@ -252,27 +303,8 @@ impl Renderer {
scissor.height(),
);
let index_buffer_slice = index_buffer_slices.next().unwrap();
let vertex_buffer_slice = vertex_buffer_slices.next().unwrap();
if let Some(Texture { bind_group, .. }) = self.textures.get(&mesh.texture_id) {
render_pass.set_bind_group(1, bind_group, &[]);
render_pass.set_index_buffer(
self.index_buffer
.buffer
.slice(index_buffer_slice.start as u64..index_buffer_slice.end as u64),
wgpu::IndexFormat::Uint32,
);
render_pass.set_vertex_buffer(
0,
self.vertex_buffer
.buffer
.slice(vertex_buffer_slice.start as u64..vertex_buffer_slice.end as u64),
);
render_pass.draw_indexed(0..mesh.indices.len() as u32, 0, 0..1);
} else {
log::warn!("Missing texture: {:?}", mesh.texture_id);
}
// draw batch
render_pass.draw_indexed(batch.index_range.clone(), 0, 0..1);
}
render_pass.set_scissor_rect(0, 0, screen_size.width, screen_size.height);
@@ -288,6 +320,10 @@ impl Renderer {
) {
profiling::scope!("update_textures");
if !textures_delta.update.is_empty() {
self.batch_bind_group_cache.clear();
}
for (id, image_delta) in &textures_delta.update {
let ImageData {
format,
@@ -341,36 +377,21 @@ impl Renderer {
mipmap::generate_mipmap_chain(queue, &texture, bytes);
}
let texture_view = texture.create_view(&wgpu::TextureViewDescriptor {
let view = texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
let sampler = self
.samplers
self.samplers
.entry(image_delta.options)
.or_insert_with(|| create_sampler(image_delta.options, device));
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label,
layout: &self.texture_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&texture_view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(sampler),
},
],
});
self.textures.insert(
*id,
Texture {
TextureEntry {
texture,
bind_group,
view,
options: image_delta.options,
},
);
}
@@ -379,6 +400,10 @@ impl Renderer {
pub fn free_textures(&mut self, textures_delta: &TexturesDelta) {
profiling::scope!("free_textures");
if !textures_delta.free.is_empty() {
self.batch_bind_group_cache.clear();
}
for id in &textures_delta.free {
if let Some(texture) = self.textures.remove(id) {
texture.texture.destroy();
@@ -392,7 +417,7 @@ impl Renderer {
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
paint_jobs: &[ClippedMesh],
render_job: &RenderJob,
screen_size: PhysicalSize<u32>,
pixels_per_point: f32,
) {
@@ -412,67 +437,90 @@ impl Renderer {
self.previous_globals = uniform_buffer_content;
}
// count how many vertices & indices need to be rendered
let (vertex_count, index_count) = {
paint_jobs.iter().fold((0, 0), |acc, clipped_mesh| {
(
acc.0 + clipped_mesh.mesh.vertices.len(),
acc.1 + clipped_mesh.mesh.indices.len(),
)
})
};
let vertex_count = render_job.vertices.len();
let index_count = render_job.indices.len();
if !(index_count > 0 && vertex_count > 0) {
return;
}
// update index and vertex buffers
if index_count > 0 && vertex_count > 0 {
self.index_buffer.slices.clear();
self.vertex_buffer.slices.clear();
let mut staging_index_buffer = self.index_buffer.create_staging_buffer(
device,
queue,
NonZeroU64::new(index_count as u64).expect("index_count > 0"),
);
let mut staging_vertex_buffer = self.vertex_buffer.create_staging_buffer(
device,
queue,
NonZeroU64::new(vertex_count as u64).expect("vertex_count > 0"),
);
let mut staging_index_buffer = self.index_buffer.create_staging_buffer(
device,
queue,
NonZeroU64::new(index_count as u64).expect("index_count > 0"),
);
let mut staging_vertex_buffer = self.vertex_buffer.create_staging_buffer(
device,
queue,
NonZeroU64::new(vertex_count as u64).expect("vertex_count > 0"),
);
staging_index_buffer
.slice(..)
.copy_from_slice(bytemuck::cast_slice(&render_job.indices));
let mut index_offset = 0;
let mut vertex_offset = 0;
for ClippedMesh { mesh, .. } in paint_jobs {
{
let size = mesh.indices.len() * std::mem::size_of::<u32>();
let slice = index_offset..(index_offset + size);
staging_index_buffer
.slice(slice.clone())
.copy_from_slice(bytemuck::cast_slice(&mesh.indices));
self.index_buffer.slices.push(slice);
index_offset += size;
}
{
let size = mesh.vertices.len() * std::mem::size_of::<Vertex>();
let slice = vertex_offset..(vertex_offset + size);
staging_vertex_buffer
.slice(slice.clone())
.copy_from_slice(bytemuck::cast_slice(&mesh.vertices));
self.vertex_buffer.slices.push(slice);
vertex_offset += size;
}
}
}
staging_vertex_buffer
.slice(..)
.copy_from_slice(bytemuck::cast_slice(&render_job.vertices));
}
fn get_or_build_batch_bind_group(
&mut self,
device: &wgpu::Device,
batch: &Batch,
) -> &wgpu::BindGroup {
let key = calculate_hash(&batch.textures);
self.batch_bind_group_cache.entry(key).or_insert_with(|| {
let mut views: Vec<_> = batch
.textures
.iter()
.map(|id| &self.textures[id].view)
.collect();
let mut samplers: Vec<_> = batch
.textures
.iter()
.map(|id| {
self.samplers
.get(&self.textures[id].options)
.expect("sampler is present from update_textures")
})
.collect();
// Metal doesn't support the PARTIALLY_BOUND_BINDING_ARRAY feature
// so we pad to up MAX_SLOTS with a dummy view/sampler
let dummy = &self.textures[&DUMMY_TEXTURE_ID];
let dummy_sampler = self.samplers.get(&dummy.options).unwrap();
views.resize(MAX_SLOTS as usize, &dummy.view);
samplers.resize(MAX_SLOTS as usize, dummy_sampler);
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("batch_textures_bind_group"),
layout: &self.textures_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureViewArray(&views),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::SamplerArray(&samplers),
},
],
})
})
}
}
struct SlicedBuffer {
struct Buffer {
buffer: wgpu::Buffer,
slices: Vec<Range<usize>>,
size: wgpu::BufferSize,
usage: wgpu::BufferUsages,
stride: NonZeroU64,
}
impl SlicedBuffer {
impl Buffer {
fn new(
device: &wgpu::Device,
usage: wgpu::BufferUsages,
@@ -490,7 +538,6 @@ impl SlicedBuffer {
Self {
buffer,
slices: Vec::with_capacity(64),
size,
usage,
stride,
+11 -5
View File
@@ -1,8 +1,11 @@
enable wgpu_binding_array;
// Vertex shader bindings
struct VertexOutput {
@location(0) tex_coord: vec2<f32>,
@location(1) color: vec4<f32>, // linear
@location(2) @interpolate(flat) layer_idx: u32,
@location(2) @interpolate(flat) texture_idx: u32,
@location(3) @interpolate(flat) layer_idx: u32,
@builtin(position) position: vec4<f32>,
};
@@ -36,18 +39,21 @@ fn vs_main(
@location(0) a_pos: vec2<f32>,
@location(1) a_tex_coord: vec2<f32>,
@location(2) a_color: u32, // non-linear
@location(3) a_layer_idx: u32,
@location(3) a_texture_idx: u32,
@location(4) a_layer_idx: u32,
) -> VertexOutput {
var out: VertexOutput;
out.tex_coord = a_tex_coord;
out.texture_idx = a_texture_idx;
out.layer_idx = a_layer_idx;
out.color = unpack_color(a_color);
out.position = position_from_screen(a_pos);
return out;
}
@group(1) @binding(0) var r_tex_color: texture_2d_array<f32>;
@group(1) @binding(1) var r_tex_sampler: sampler;
// TODO: substitute array size based on device limits
@group(1) @binding(0) var textures: binding_array<texture_2d_array<f32>, 32>;
@group(1) @binding(1) var samplers: binding_array<sampler, 32>;
@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
@@ -56,7 +62,7 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
// Vertex colors, texture samples, and the output color are all in sRGB.
// Texture formats and output surface formats are selected such that no automatic
// conversion between linear <-> sRGB is performed.
let tex_color = textureSample(r_tex_color, r_tex_sampler, in.tex_coord, in.layer_idx);
let tex_color = textureSample(textures[in.texture_idx], samplers[in.texture_idx], in.tex_coord, in.layer_idx);
var out_color = in.color * tex_color;
return out_color;
}
-118
View File
@@ -1,118 +0,0 @@
use crate::{
color::Srgba,
dpi::{
LogicalPoint, LogicalQuad, LogicalRect, NormalizedPoint, NormalizedQuad, NormalizedRect,
},
math::Corners,
renderer::textures::TextureId,
};
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Vertex {
pub pos: LogicalPoint<f32>,
pub uv: NormalizedPoint,
pub color: Srgba,
/// Index into texture array
pub layer_idx: u32,
}
#[derive(Clone, Debug, Default)]
pub struct Mesh {
pub vertices: Vec<Vertex>,
pub indices: Vec<u32>,
pub texture_id: TextureId,
}
impl Mesh {
#[allow(dead_code)]
#[inline]
pub fn add_rect(
&mut self,
rect: LogicalRect<f32>,
uv: NormalizedRect,
color: Srgba,
layer_idx: u32,
) {
let i = self.vertices.len() as u32;
self.indices
.extend_from_slice(&[i, i + 1, i + 3, i + 1, i + 2, i + 3]);
self.vertices.extend_from_slice(&[
Vertex {
pos: rect.top_left(),
uv: uv.top_left(),
color,
layer_idx,
},
Vertex {
pos: rect.top_right(),
uv: uv.top_right(),
color,
layer_idx,
},
Vertex {
pos: rect.bottom_right(),
uv: uv.bottom_right(),
color,
layer_idx,
},
Vertex {
pos: rect.bottom_left(),
uv: uv.bottom_left(),
color,
layer_idx,
},
]);
}
#[inline]
pub fn add_quad(
&mut self,
quad: LogicalQuad<f32>,
uv: NormalizedQuad,
color: Srgba,
layer_idx: u32,
) {
let i = self.vertices.len() as u32;
self.indices
.extend_from_slice(&[i, i + 1, i + 3, i + 1, i + 2, i + 3]);
self.vertices.extend_from_slice(&[
Vertex {
pos: quad.p0,
uv: uv.p0,
color,
layer_idx,
},
Vertex {
pos: quad.p1,
uv: uv.p1,
color,
layer_idx,
},
Vertex {
pos: quad.p2,
uv: uv.p2,
color,
layer_idx,
},
Vertex {
pos: quad.p3,
uv: uv.p3,
color,
layer_idx,
},
]);
}
pub fn is_empty(&self) -> bool {
self.vertices.is_empty() && self.indices.is_empty()
}
}
pub struct ClippedMesh {
// Only parts of the mesh that intersect with this will be rendered
pub clip_rect: LogicalRect<f32>,
pub mesh: Mesh,
}
-71
View File
@@ -1,71 +0,0 @@
use crate::{
draw_commands::DrawCommand,
renderer::mesh::{ClippedMesh, Mesh},
};
/// Converts [`DrawPrimitive`]s into [`Mesh`]es.
#[derive(Default)]
pub struct Tessellator {
last_clipped_meshes_size: usize,
}
impl Tessellator {
pub fn convert_draw_commands(&mut self, draw_commands: Vec<DrawCommand>) -> Vec<ClippedMesh> {
profiling::scope!("convert_primitives");
let mut clipped_meshes = Vec::with_capacity(self.last_clipped_meshes_size);
for cmd in draw_commands {
self.convert_draw_command(cmd, &mut clipped_meshes);
}
self.last_clipped_meshes_size = clipped_meshes.len();
clipped_meshes
}
pub fn convert_draw_command(
&mut self,
cmd: DrawCommand,
out_clipped_meshes: &mut Vec<ClippedMesh>,
) {
let DrawCommand {
positions,
uvs,
color,
texture_id,
texture_layer_idx,
clip_rect,
} = cmd;
if clip_rect.is_empty() {
return;
}
let start_new_mesh = out_clipped_meshes.last().is_none_or(|last_clipped_mesh| {
// append to previous mesh if clip_rect and texture_id match.
// otherwise, start a new mesh.
!(last_clipped_mesh.clip_rect == clip_rect
&& last_clipped_mesh.mesh.texture_id == texture_id)
});
if start_new_mesh {
out_clipped_meshes.push(ClippedMesh {
clip_rect,
mesh: Mesh::default(),
});
}
let last_clipped_mesh = out_clipped_meshes.last_mut().unwrap();
last_clipped_mesh
.mesh
.add_quad(positions, uvs, color, texture_layer_idx);
last_clipped_mesh.mesh.texture_id = texture_id;
// This can be empty if a new mesh was started but the conversion from a text primitive
// didn't add any vertices. Our renderer doesn't support empty meshes so remove it
if last_clipped_mesh.mesh.is_empty() {
out_clipped_meshes.pop();
}
}
}