M3: STL/OBJ import with mesh validation, mass/COM/inertia, material database, RON scene with content-addressed blobs and v0->v1 migration. M4: deterministic heightmap terrain, trimesh colliders, wgpu renderer with instancing and depth, winit app with 1 kHz physics, fly camera, on-screen metrics overlay and per-frame CSV/dev logs. Docs: UI, logging, network and headless CLI plans.
327 lines
8.9 KiB
Rust
327 lines
8.9 KiB
Rust
//! The overlay render pass: one triangle batch with alpha blending, no depth.
|
|
|
|
mod geometry;
|
|
|
|
use std::sync::Mutex;
|
|
|
|
use wgpu::util::DeviceExt;
|
|
|
|
use self::geometry::{ATTRIBUTES, Vertex, push_quad, push_segment, solid_uv};
|
|
use super::Overlay;
|
|
use super::atlas::{GlyphAtlas, Region, SIZE};
|
|
use super::text::TextRasterizer;
|
|
|
|
/// GPU state of the overlay pass.
|
|
///
|
|
/// The glyph atlas grows while drawing, so it sits behind a mutex: that keeps
|
|
/// [`crate::Renderer::draw_overlay`] callable through a shared reference.
|
|
pub(crate) struct OverlayRenderer {
|
|
state: Mutex<State>,
|
|
}
|
|
|
|
struct State {
|
|
pipeline: wgpu::RenderPipeline,
|
|
bind_group: wgpu::BindGroup,
|
|
texture: wgpu::Texture,
|
|
rasterizer: TextRasterizer,
|
|
}
|
|
|
|
/// The colour view and pixel size the overlay draws into.
|
|
#[derive(Clone, Copy)]
|
|
pub(crate) struct Target<'a> {
|
|
pub(crate) view: &'a wgpu::TextureView,
|
|
pub(crate) size: (u32, u32),
|
|
}
|
|
|
|
/// A recorded vertex batch: pipeline, atlas binding and geometry.
|
|
struct Batch<'a> {
|
|
pipeline: &'a wgpu::RenderPipeline,
|
|
bind_group: &'a wgpu::BindGroup,
|
|
vertices: &'a [Vertex],
|
|
}
|
|
|
|
impl OverlayRenderer {
|
|
/// Creates the atlas texture, sampler, bind group and pipeline.
|
|
pub(crate) fn new(
|
|
device: &wgpu::Device,
|
|
queue: &wgpu::Queue,
|
|
format: wgpu::TextureFormat,
|
|
) -> Self {
|
|
let texture = create_atlas_texture(device);
|
|
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
|
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
|
label: Some("fabrilis atlas sampler"),
|
|
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
|
address_mode_v: wgpu::AddressMode::ClampToEdge,
|
|
address_mode_w: wgpu::AddressMode::ClampToEdge,
|
|
mag_filter: wgpu::FilterMode::Linear,
|
|
min_filter: wgpu::FilterMode::Linear,
|
|
..Default::default()
|
|
});
|
|
let layout = create_layout(device);
|
|
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
|
label: Some("fabrilis atlas"),
|
|
layout: &layout,
|
|
entries: &[
|
|
wgpu::BindGroupEntry {
|
|
binding: 0,
|
|
resource: wgpu::BindingResource::TextureView(&view),
|
|
},
|
|
wgpu::BindGroupEntry {
|
|
binding: 1,
|
|
resource: wgpu::BindingResource::Sampler(&sampler),
|
|
},
|
|
],
|
|
});
|
|
let pipeline = create_pipeline(device, format, &layout);
|
|
let mut rasterizer = TextRasterizer::new();
|
|
upload_atlas(queue, &texture, &mut rasterizer);
|
|
Self {
|
|
state: Mutex::new(State {
|
|
pipeline,
|
|
bind_group,
|
|
texture,
|
|
rasterizer,
|
|
}),
|
|
}
|
|
}
|
|
|
|
/// Draws the overlay over whatever is already in the target.
|
|
pub(crate) fn draw(
|
|
&self,
|
|
device: &wgpu::Device,
|
|
queue: &wgpu::Queue,
|
|
target: Target<'_>,
|
|
overlay: &Overlay,
|
|
) {
|
|
if target.size.0 == 0 || target.size.1 == 0 || overlay.is_empty() {
|
|
return;
|
|
}
|
|
let Ok(mut guard) = self.state.lock() else {
|
|
return;
|
|
};
|
|
let State {
|
|
pipeline,
|
|
bind_group,
|
|
texture,
|
|
rasterizer,
|
|
} = &mut *guard;
|
|
let mut vertices = Vec::with_capacity(
|
|
overlay.rects.len() * 6 + overlay.lines.len() * 6 + overlay.texts.len() * 24,
|
|
);
|
|
for rect in &overlay.rects {
|
|
push_quad(
|
|
&mut vertices,
|
|
target.size,
|
|
[rect.x, rect.y, rect.w, rect.h],
|
|
solid_uv(),
|
|
rect.color,
|
|
);
|
|
}
|
|
for line in &overlay.lines {
|
|
push_segment(&mut vertices, target.size, line);
|
|
}
|
|
for item in &overlay.texts {
|
|
for quad in rasterizer.layout(item) {
|
|
push_quad(&mut vertices, target.size, quad.rect, quad.uv, item.color);
|
|
}
|
|
}
|
|
// Layout may have rasterized new glyphs, so upload after it.
|
|
upload_atlas(queue, texture, rasterizer);
|
|
submit(
|
|
device,
|
|
queue,
|
|
target,
|
|
Batch {
|
|
pipeline,
|
|
bind_group,
|
|
vertices: &vertices,
|
|
},
|
|
);
|
|
}
|
|
}
|
|
|
|
/// Uploads the vertex batch and records the overlay pass.
|
|
fn submit(device: &wgpu::Device, queue: &wgpu::Queue, target: Target<'_>, batch: Batch<'_>) {
|
|
let vertices = batch.vertices;
|
|
if vertices.is_empty() {
|
|
return;
|
|
}
|
|
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
|
label: Some("fabrilis overlay vertices"),
|
|
contents: bytemuck::cast_slice(vertices),
|
|
usage: wgpu::BufferUsages::VERTEX,
|
|
});
|
|
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
|
label: Some("fabrilis overlay frame"),
|
|
});
|
|
{
|
|
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
|
view: target.view,
|
|
depth_slice: None,
|
|
resolve_target: None,
|
|
ops: wgpu::Operations {
|
|
load: wgpu::LoadOp::Load,
|
|
store: wgpu::StoreOp::Store,
|
|
},
|
|
})];
|
|
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
|
label: Some("fabrilis overlay pass"),
|
|
color_attachments: &attachments,
|
|
depth_stencil_attachment: None,
|
|
timestamp_writes: None,
|
|
occlusion_query_set: None,
|
|
multiview_mask: None,
|
|
});
|
|
pass.set_pipeline(batch.pipeline);
|
|
pass.set_bind_group(0, batch.bind_group, &[]);
|
|
pass.set_vertex_buffer(0, buffer.slice(..));
|
|
pass.draw(0..vertices.len() as u32, 0..1);
|
|
}
|
|
queue.submit([encoder.finish()]);
|
|
}
|
|
|
|
fn create_atlas_texture(device: &wgpu::Device) -> wgpu::Texture {
|
|
device.create_texture(&wgpu::TextureDescriptor {
|
|
label: Some("fabrilis glyph atlas"),
|
|
size: wgpu::Extent3d {
|
|
width: SIZE,
|
|
height: SIZE,
|
|
depth_or_array_layers: 1,
|
|
},
|
|
mip_level_count: 1,
|
|
sample_count: 1,
|
|
dimension: wgpu::TextureDimension::D2,
|
|
format: wgpu::TextureFormat::R8Unorm,
|
|
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
|
view_formats: &[],
|
|
})
|
|
}
|
|
|
|
fn create_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
|
|
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
|
label: Some("fabrilis overlay layout"),
|
|
entries: &[
|
|
wgpu::BindGroupLayoutEntry {
|
|
binding: 0,
|
|
visibility: wgpu::ShaderStages::FRAGMENT,
|
|
ty: wgpu::BindingType::Texture {
|
|
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
|
view_dimension: wgpu::TextureViewDimension::D2,
|
|
multisampled: false,
|
|
},
|
|
count: None,
|
|
},
|
|
wgpu::BindGroupLayoutEntry {
|
|
binding: 1,
|
|
visibility: wgpu::ShaderStages::FRAGMENT,
|
|
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
|
count: None,
|
|
},
|
|
],
|
|
})
|
|
}
|
|
|
|
fn create_pipeline(
|
|
device: &wgpu::Device,
|
|
format: wgpu::TextureFormat,
|
|
layout: &wgpu::BindGroupLayout,
|
|
) -> wgpu::RenderPipeline {
|
|
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
|
label: Some("fabrilis overlay shader"),
|
|
source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!("overlay.wgsl"))),
|
|
});
|
|
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
|
label: Some("fabrilis overlay pipeline layout"),
|
|
bind_group_layouts: &[Some(layout)],
|
|
immediate_size: 0,
|
|
});
|
|
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
|
label: Some("fabrilis overlay pipeline"),
|
|
layout: Some(&pipeline_layout),
|
|
vertex: wgpu::VertexState {
|
|
module: &shader,
|
|
entry_point: Some("vs_main"),
|
|
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
|
buffers: &[Some(wgpu::VertexBufferLayout {
|
|
array_stride: 32,
|
|
step_mode: wgpu::VertexStepMode::Vertex,
|
|
attributes: &ATTRIBUTES,
|
|
})],
|
|
},
|
|
primitive: wgpu::PrimitiveState {
|
|
topology: wgpu::PrimitiveTopology::TriangleList,
|
|
cull_mode: None,
|
|
..Default::default()
|
|
},
|
|
depth_stencil: None,
|
|
multisample: wgpu::MultisampleState::default(),
|
|
fragment: Some(wgpu::FragmentState {
|
|
module: &shader,
|
|
entry_point: Some("fs_main"),
|
|
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
|
targets: &[Some(wgpu::ColorTargetState {
|
|
format,
|
|
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
|
|
write_mask: wgpu::ColorWrites::ALL,
|
|
})],
|
|
}),
|
|
multiview_mask: None,
|
|
cache: None,
|
|
})
|
|
}
|
|
|
|
/// Uploads every atlas region written since the previous frame.
|
|
fn upload_atlas(queue: &wgpu::Queue, texture: &wgpu::Texture, rasterizer: &mut TextRasterizer) {
|
|
let regions = rasterizer.take_dirty();
|
|
if regions.is_empty() {
|
|
return;
|
|
}
|
|
let atlas = rasterizer.atlas();
|
|
for region in regions {
|
|
let (data, row) = padded_region(atlas, region);
|
|
queue.write_texture(
|
|
wgpu::TexelCopyTextureInfo {
|
|
texture,
|
|
mip_level: 0,
|
|
origin: wgpu::Origin3d {
|
|
x: region.x,
|
|
y: region.y,
|
|
z: 0,
|
|
},
|
|
aspect: wgpu::TextureAspect::All,
|
|
},
|
|
&data,
|
|
wgpu::TexelCopyBufferLayout {
|
|
offset: 0,
|
|
bytes_per_row: Some(row),
|
|
rows_per_image: Some(region.h),
|
|
},
|
|
wgpu::Extent3d {
|
|
width: region.w,
|
|
height: region.h,
|
|
depth_or_array_layers: 1,
|
|
},
|
|
);
|
|
}
|
|
}
|
|
|
|
/// Copies one atlas region into a row-padded staging buffer.
|
|
fn padded_region(atlas: &GlyphAtlas, region: Region) -> (Vec<u8>, u32) {
|
|
let row =
|
|
region.w.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
|
|
let mut data = vec![0; (row * region.h) as usize];
|
|
let pixels = atlas.pixels();
|
|
let length = region.w as usize;
|
|
for line in 0..region.h {
|
|
let source = ((region.y + line) * SIZE + region.x) as usize;
|
|
let target = (line * row) as usize;
|
|
if let (Some(from), Some(to)) = (
|
|
pixels.get(source..source + length),
|
|
data.get_mut(target..target + length),
|
|
) {
|
|
to.copy_from_slice(from);
|
|
}
|
|
}
|
|
(data, row)
|
|
}
|