Add design persistence, world rendering, metrics overlay and logs
Some checks failed
ci / check (macos-latest) (push) Has been cancelled
ci / check (ubuntu-latest) (push) Has been cancelled
ci / check (windows-latest) (push) Has been cancelled

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.
This commit is contained in:
Loki 2026-11-16 23:34:05 +01:00
parent 79928b645b
commit 93075ab1fd
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
107 changed files with 14785 additions and 46 deletions

View file

@ -11,6 +11,9 @@ workspace = true
[dependencies]
fabrilis-core = { path = "../core" }
bytemuck = { version = "1", features = ["derive"] }
fontdue = "0.9"
wgpu = "30"
[build-dependencies]
fabrilis-limits = { path = "../../tools/limits" }

128
crates/render/src/camera.rs Normal file
View file

@ -0,0 +1,128 @@
//! Renderer-local perspective camera.
//!
//! The camera works in the world frame: Z is up and the projection targets the
//! WebGPU depth range `0..=1`. All arithmetic is `f32` because the camera only
//! feeds the renderer and never the authoritative simulation.
use fabrilis_core::math;
type Mat4 = [[f32; 4]; 4];
type Vec3 = [f32; 3];
/// A right-handed perspective camera with an explicit look-at pose.
#[derive(Debug, Clone, Copy)]
pub struct Camera {
eye: Vec3,
target: Vec3,
up: Vec3,
fov_y: f32,
aspect: f32,
near: f32,
far: f32,
}
impl Camera {
/// A camera at `eye` looking at `target`, with sensible projection defaults.
#[must_use]
pub fn look_at(eye: Vec3, target: Vec3, up: Vec3) -> Self {
Self {
eye,
target,
up,
fov_y: 0.9,
aspect: 1.0,
near: 0.1,
far: 500.0,
}
}
/// Replaces the projection parameters, clamping them to usable values.
#[must_use]
pub fn with_projection(mut self, fov_y: f32, aspect: f32, near: f32, far: f32) -> Self {
self.fov_y = fov_y.clamp(0.01, 3.0);
self.aspect = aspect.max(0.0001);
self.near = near.max(0.0001);
self.far = far.max(self.near + 0.0001);
self
}
/// Updates the aspect ratio after a surface resize.
pub fn set_aspect(&mut self, aspect: f32) {
self.aspect = aspect.max(0.0001);
}
/// The eye position in world space.
#[must_use]
pub fn eye(&self) -> Vec3 {
self.eye
}
/// The combined view-projection matrix in column-major order.
#[must_use]
pub fn view_projection(&self) -> Mat4 {
multiply(&self.projection(), &self.view())
}
fn view(&self) -> Mat4 {
let forward = normalize(sub(self.target, self.eye), [0.0, 1.0, 0.0]);
let side = normalize(cross(forward, self.up), [1.0, 0.0, 0.0]);
let up = cross(side, forward);
[
[side[0], up[0], -forward[0], 0.0],
[side[1], up[1], -forward[1], 0.0],
[side[2], up[2], -forward[2], 0.0],
[
-dot(side, self.eye),
-dot(up, self.eye),
dot(forward, self.eye),
1.0,
],
]
}
fn projection(&self) -> Mat4 {
let scale = 1.0 / math::tan(f64::from(self.fov_y) * 0.5) as f32;
let depth = self.far / (self.near - self.far);
[
[scale / self.aspect, 0.0, 0.0, 0.0],
[0.0, scale, 0.0, 0.0],
[0.0, 0.0, depth, -1.0],
[0.0, 0.0, depth * self.near, 0.0],
]
}
}
fn sub(left: Vec3, right: Vec3) -> Vec3 {
[left[0] - right[0], left[1] - right[1], left[2] - right[2]]
}
fn dot(left: Vec3, right: Vec3) -> f32 {
left[0] * right[0] + left[1] * right[1] + left[2] * right[2]
}
fn cross(left: Vec3, right: Vec3) -> Vec3 {
[
left[1] * right[2] - left[2] * right[1],
left[2] * right[0] - left[0] * right[2],
left[0] * right[1] - left[1] * right[0],
]
}
fn normalize(vector: Vec3, fallback: Vec3) -> Vec3 {
let length = dot(vector, vector).sqrt();
if length > 1.0e-6 {
[vector[0] / length, vector[1] / length, vector[2] / length]
} else {
fallback
}
}
fn multiply(left: &Mat4, right: &Mat4) -> Mat4 {
let mut product = [[0.0; 4]; 4];
for (column, output) in product.iter_mut().enumerate() {
for (row, value) in output.iter_mut().enumerate() {
*value = (0..4).map(|k| left[k][row] * right[column][k]).sum();
}
}
product
}

View file

@ -1 +0,0 @@
//! fabrilis-render :: ctx - stub (see docs/ARCHITECTURE.md)

View file

@ -0,0 +1,37 @@
//! Renderer errors.
use core::fmt;
/// Why a renderer resource could not be created or used.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RenderError {
/// No suitable GPU adapter was found.
Adapter(String),
/// The logical device could not be created.
Device(String),
/// A window surface operation failed.
Surface(String),
/// A texture could not be allocated or read back.
Texture(String),
/// A buffer could not be allocated or mapped.
Buffer(String),
/// The requested pixel format is not supported by the readback path.
UnsupportedFormat(String),
}
impl fmt::Display for RenderError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Adapter(detail) => write!(formatter, "GPU adapter unavailable: {detail}"),
Self::Device(detail) => write!(formatter, "GPU device unavailable: {detail}"),
Self::Surface(detail) => write!(formatter, "surface failure: {detail}"),
Self::Texture(detail) => write!(formatter, "texture failure: {detail}"),
Self::Buffer(detail) => write!(formatter, "buffer failure: {detail}"),
Self::UnsupportedFormat(detail) => {
write!(formatter, "unsupported pixel format: {detail}")
}
}
}
}
impl std::error::Error for RenderError {}

View file

@ -0,0 +1,100 @@
//! Headless GPU device creation.
//!
//! The window path lives in the application: it owns the surface and passes the
//! device and queue to [`crate::Renderer`].
use std::future::Future;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};
use crate::RenderError;
/// A logical device and its queue, created without a window surface.
#[derive(Debug, Clone)]
pub struct Gpu {
device: wgpu::Device,
queue: wgpu::Queue,
}
impl Gpu {
/// Requests a high-performance adapter, retrying with a fallback adapter.
pub fn headless() -> Result<Self, RenderError> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter = request_adapter(&instance)?;
let (device, queue) = block_on(adapter.request_device(&device_descriptor()))
.map_err(|error| RenderError::Device(error.to_string()))?;
Ok(Self { device, queue })
}
/// The device that owns renderer resources.
#[must_use]
pub fn device(&self) -> &wgpu::Device {
&self.device
}
/// The queue used to upload data and submit commands.
#[must_use]
pub fn queue(&self) -> &wgpu::Queue {
&self.queue
}
}
/// Device limits and features used by both the app and headless tests.
#[must_use]
pub fn device_descriptor() -> wgpu::DeviceDescriptor<'static> {
wgpu::DeviceDescriptor {
label: Some("fabrilis device"),
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::default(),
experimental_features: wgpu::ExperimentalFeatures::default(),
memory_hints: wgpu::MemoryHints::default(),
trace: wgpu::Trace::Off,
}
}
fn request_adapter(instance: &wgpu::Instance) -> Result<wgpu::Adapter, RenderError> {
let options = wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: None,
force_fallback_adapter: false,
..Default::default()
};
match block_on(instance.request_adapter(&options)) {
Ok(adapter) => Ok(adapter),
Err(primary) => {
let fallback = wgpu::RequestAdapterOptions {
force_fallback_adapter: true,
..options
};
block_on(instance.request_adapter(&fallback)).map_err(|secondary| {
RenderError::Adapter(format!("{primary}; fallback adapter: {secondary}"))
})
}
}
}
struct ThreadWake(Thread);
impl Wake for ThreadWake {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
fn wake_by_ref(self: &Arc<Self>) {
self.0.unpark();
}
}
/// Blocks on a future without pulling in an async runtime.
fn block_on<F: Future>(future: F) -> F::Output {
let waker = Waker::from(Arc::new(ThreadWake(thread::current())));
let mut context = Context::from_waker(&waker);
let mut future = std::pin::pin!(future);
loop {
match future.as_mut().poll(&mut context) {
Poll::Ready(value) => return value,
Poll::Pending => thread::park(),
}
}
}

View file

@ -1 +0,0 @@
//! fabrilis-render :: instancing - stub (see docs/ARCHITECTURE.md)

View file

@ -1,5 +1,22 @@
//! Custom wgpu renderer: clipmap terrain, instancing, compute culling, view modes (stress, temperature)
pub mod ctx;
pub mod instancing;
pub mod terrain;
pub mod views;
//! Custom wgpu renderer: depth-tested terrain meshes, instanced boxes, one
//! directional light.
//!
//! The renderer is not part of the authoritative simulation: it may use `f32`
//! and never reads wall-clock time. Headless use builds a [`Gpu`] and renders
//! into an offscreen texture; the app owns its surface and calls
//! [`Renderer::draw_to`].
pub mod camera;
pub mod error;
pub mod gpu;
pub mod overlay;
pub mod renderer;
pub mod scene;
pub use camera::Camera;
pub use error::RenderError;
pub use gpu::Gpu;
pub use overlay::{Overlay, OverlayLine, OverlayRect, OverlayText};
pub use renderer::Renderer;
pub use scene::{Instance, MeshData, Scene};
pub use wgpu;

View file

@ -0,0 +1,193 @@
//! CPU-side glyph packing for the overlay text atlas.
//!
//! The atlas is a single `R8` image: one byte of coverage per texel. Glyphs are
//! packed shelf by shelf and cached by `(char, pixel size)`, so a glyph is
//! rasterized and uploaded once per size.
/// Edge length of the square atlas texture, texels.
pub(super) const SIZE: u32 = 1024;
/// Empty texels kept between glyphs so linear filtering cannot bleed.
const PADDING: u32 = 1;
/// UV of a texel that is always opaque white, shared by solid rectangles and
/// lines so they can use the text pipeline.
pub(super) const WHITE_UV: [f32; 2] = [1.0 / 1024.0, 1.0 / 1024.0];
/// A rectangle of the atlas that has to be uploaded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Region {
pub(super) x: u32,
pub(super) y: u32,
pub(super) w: u32,
pub(super) h: u32,
}
/// A rasterized glyph placed in the atlas.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct Glyph {
pub(super) uv: [f32; 2],
pub(super) uv_size: [f32; 2],
pub(super) xmin: i32,
pub(super) ymin: i32,
pub(super) width: u32,
pub(super) height: u32,
pub(super) advance: f32,
}
/// One rasterized bitmap handed to the atlas.
pub(super) struct Raster<'a> {
pub(super) bitmap: &'a [u8],
pub(super) width: u32,
pub(super) height: u32,
pub(super) xmin: i32,
pub(super) ymin: i32,
pub(super) advance: f32,
}
struct Entry {
ch: char,
size_bits: u32,
glyph: Glyph,
}
/// Packed glyph coverage plus the cache that maps characters onto it.
pub(super) struct GlyphAtlas {
pixels: Vec<u8>,
entries: Vec<Entry>,
cursor_x: u32,
cursor_y: u32,
shelf: u32,
dirty: Vec<Region>,
}
impl GlyphAtlas {
/// An empty atlas with a small white block at the origin.
pub(super) fn new() -> Self {
let mut pixels = vec![0; (SIZE * SIZE) as usize];
// A two by two white block at the origin; sampling its centre stays white
// even when filtering drifts by half a texel.
pixels[0..2].fill(255);
let second_row = SIZE as usize;
pixels[second_row..second_row + 2].fill(255);
Self {
pixels,
entries: Vec::new(),
cursor_x: 2 + PADDING,
cursor_y: 0,
shelf: 2,
dirty: vec![Region {
x: 0,
y: 0,
w: 2,
h: 2,
}],
}
}
/// The raw coverage buffer, `SIZE * SIZE` bytes.
pub(super) fn pixels(&self) -> &[u8] {
&self.pixels
}
/// The number of cached glyphs.
#[allow(dead_code, reason = "read by the overlay atlas test")]
pub(super) fn len(&self) -> usize {
self.entries.len()
}
/// A region that still has to be uploaded to the GPU.
pub(super) fn take_dirty(&mut self) -> Vec<Region> {
std::mem::take(&mut self.dirty)
}
/// The cached glyph for `ch` at a pixel size, if any.
pub(super) fn get(&self, ch: char, size_bits: u32) -> Option<&Glyph> {
self.entries
.iter()
.find(|entry| entry.ch == ch && entry.size_bits == size_bits)
.map(|entry| &entry.glyph)
}
/// Packs a rasterized glyph and returns its placement.
///
/// Returns `None` when the glyph is already cached or the atlas has no room
/// left for it.
pub(super) fn insert(
&mut self,
ch: char,
size_bits: u32,
raster: &Raster<'_>,
) -> Option<Glyph> {
if self.get(ch, size_bits).is_some() {
return None;
}
let (x, y) = self.reserve(raster.width, raster.height)?;
let glyph = Glyph {
uv: [x as f32 / SIZE as f32, y as f32 / SIZE as f32],
uv_size: [
raster.width as f32 / SIZE as f32,
raster.height as f32 / SIZE as f32,
],
xmin: raster.xmin,
ymin: raster.ymin,
width: raster.width,
height: raster.height,
advance: raster.advance,
};
self.write(x, y, raster);
self.entries.push(Entry {
ch,
size_bits,
glyph,
});
Some(glyph)
}
/// Finds a free shelf slot for a `width` by `height` bitmap.
fn reserve(&mut self, width: u32, height: u32) -> Option<(u32, u32)> {
if width == 0 || height == 0 {
// Invisible glyphs (spaces) still need a cache entry, not texels.
return Some((0, 0));
}
if width + 2 * PADDING > SIZE || height + PADDING > SIZE {
return None;
}
if self.cursor_x + width + PADDING > SIZE {
self.cursor_y += self.shelf + PADDING;
self.cursor_x = 0;
self.shelf = 0;
}
if self.cursor_y + height + PADDING > SIZE {
return None;
}
let spot = (self.cursor_x, self.cursor_y);
self.cursor_x += width + PADDING;
self.shelf = self.shelf.max(height);
Some(spot)
}
/// Copies a bitmap into the coverage buffer and marks the region dirty.
fn write(&mut self, x: u32, y: u32, raster: &Raster<'_>) {
if raster.width == 0 || raster.height == 0 {
return;
}
for row in 0..raster.height {
let source = (row * raster.width) as usize;
let target = ((y + row) * SIZE + x) as usize;
let length = raster.width as usize;
if let (Some(from), Some(to)) = (
raster.bitmap.get(source..source + length),
self.pixels.get_mut(target..target + length),
) {
to.copy_from_slice(from);
}
}
self.dirty.push(Region {
x,
y,
w: raster.width,
h: raster.height,
});
}
}

View file

@ -0,0 +1,123 @@
//! Screen-space 2D overlay drawn after the 3D scene.
//!
//! The overlay is a list of rectangles, lines and text in target pixels with the
//! origin at the top-left. One triangle batch draws all of it with depth testing
//! disabled and alpha blending: solid shapes sample a white texel of the glyph
//! atlas, text samples glyph coverage.
mod atlas;
mod pass;
mod text;
#[cfg(test)]
mod tests;
pub(crate) use pass::{OverlayRenderer, Target};
/// A filled rectangle in target pixels.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OverlayRect {
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
pub color: [f32; 4],
}
impl OverlayRect {
/// A rectangle at `(x, y)` with a size and a linear RGBA colour.
#[must_use]
pub fn new(x: f32, y: f32, w: f32, h: f32, color: [f32; 4]) -> Self {
Self { x, y, w, h, color }
}
}
/// A straight line of a given width in target pixels.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OverlayLine {
pub from: [f32; 2],
pub to: [f32; 2],
pub width: f32,
pub color: [f32; 4],
}
impl OverlayLine {
/// A line from `from` to `to` with a width and a linear RGBA colour.
#[must_use]
pub fn new(from: [f32; 2], to: [f32; 2], width: f32, color: [f32; 4]) -> Self {
Self {
from,
to,
width,
color,
}
}
}
/// One line of ASCII text, anchored at its top-left corner.
#[derive(Debug, Clone, PartialEq)]
pub struct OverlayText {
pub x: f32,
pub y: f32,
pub size: f32,
pub color: [f32; 4],
pub text: String,
}
impl OverlayText {
/// Text at `(x, y)` in pixels with a font size and a linear RGBA colour.
#[must_use]
pub fn new(x: f32, y: f32, size: f32, color: [f32; 4], text: impl Into<String>) -> Self {
Self {
x,
y,
size,
color,
text: text.into(),
}
}
}
/// Everything the overlay pass draws in one frame.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Overlay {
pub rects: Vec<OverlayRect>,
pub lines: Vec<OverlayLine>,
pub texts: Vec<OverlayText>,
}
impl Overlay {
/// An empty overlay.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Drops all shapes but keeps the allocated buffers.
pub fn clear(&mut self) {
self.rects.clear();
self.lines.clear();
self.texts.clear();
}
/// Whether the overlay would draw nothing.
#[must_use]
pub fn is_empty(&self) -> bool {
self.rects.is_empty() && self.lines.is_empty() && self.texts.is_empty()
}
/// Queues a filled rectangle.
pub fn push_rect(&mut self, rect: OverlayRect) {
self.rects.push(rect);
}
/// Queues a line.
pub fn push_line(&mut self, line: OverlayLine) {
self.lines.push(line);
}
/// Queues a text line.
pub fn push_text(&mut self, text: OverlayText) {
self.texts.push(text);
}
}

View file

@ -0,0 +1,106 @@
//! Vertex layout and quad assembly for the overlay batch.
use bytemuck::{Pod, Zeroable};
use super::super::OverlayLine;
use super::super::atlas::WHITE_UV;
/// A single overlay vertex: clip-space position, atlas UV and colour.
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
pub(super) struct Vertex {
pub(super) position: [f32; 2],
pub(super) uv: [f32; 2],
pub(super) color: [f32; 4],
}
pub(super) const ATTRIBUTES: [wgpu::VertexAttribute; 3] = [
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x2,
offset: 0,
shader_location: 0,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x2,
offset: 8,
shader_location: 1,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 16,
shader_location: 2,
},
];
/// UV rectangle of the always-white atlas texel.
pub(super) fn solid_uv() -> [f32; 4] {
[WHITE_UV[0], WHITE_UV[1], WHITE_UV[0], WHITE_UV[1]]
}
/// Pixels to normalized device coordinates; the overlay's y axis points down.
fn ndc(x: f32, y: f32, size: (u32, u32)) -> [f32; 2] {
let width = size.0.max(1) as f32;
let height = size.1.max(1) as f32;
[x / width * 2.0 - 1.0, 1.0 - y / height * 2.0]
}
/// Appends an axis-aligned quad as two triangles.
pub(super) fn push_quad(
vertices: &mut Vec<Vertex>,
size: (u32, u32),
rect: [f32; 4],
uv: [f32; 4],
color: [f32; 4],
) {
let [x, y, w, h] = rect;
if w <= 0.0 || h <= 0.0 {
return;
}
let top_left = ndc(x, y, size);
let bottom_right = ndc(x + w, y + h, size);
let corners = [
([top_left[0], top_left[1]], [uv[0], uv[1]]),
([bottom_right[0], top_left[1]], [uv[2], uv[1]]),
([bottom_right[0], bottom_right[1]], [uv[2], uv[3]]),
([top_left[0], bottom_right[1]], [uv[0], uv[3]]),
];
push_corners(vertices, corners, color);
}
/// Appends a line as a quad expanded along its normal.
pub(super) fn push_segment(vertices: &mut Vec<Vertex>, size: (u32, u32), line: &OverlayLine) {
let [x0, y0] = line.from;
let [x1, y1] = line.to;
let dx = x1 - x0;
let dy = y1 - y0;
let length = (dx * dx + dy * dy).sqrt();
if length <= f32::EPSILON || line.width <= 0.0 {
return;
}
let half = line.width * 0.5;
let nx = -dy / length * half;
let ny = dx / length * half;
let uv = WHITE_UV;
let corners = [
(ndc(x0 + nx, y0 + ny, size), uv),
(ndc(x1 + nx, y1 + ny, size), uv),
(ndc(x1 - nx, y1 - ny, size), uv),
(ndc(x0 - nx, y0 - ny, size), uv),
];
push_corners(vertices, corners, line.color);
}
/// Appends two triangles for four pixel-space corners.
fn push_corners(vertices: &mut Vec<Vertex>, corners: [([f32; 2], [f32; 2]); 4], color: [f32; 4]) {
const INDICES: [usize; 6] = [0, 1, 2, 0, 2, 3];
for index in INDICES {
let Some((position, uv)) = corners.get(index) else {
continue;
};
vertices.push(Vertex {
position: *position,
uv: *uv,
color,
});
}
}

View file

@ -0,0 +1,327 @@
//! 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)
}

View file

@ -0,0 +1,29 @@
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) color: vec4<f32>,
};
struct VertexOutput {
@builtin(position) clip_position: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) color: vec4<f32>,
};
@vertex
fn vs_main(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.clip_position = vec4<f32>(input.position, 0.0, 1.0);
output.uv = input.uv;
output.color = input.color;
return output;
}
@group(0) @binding(0) var atlas: texture_2d<f32>;
@group(0) @binding(1) var atlas_sampler: sampler;
@fragment
fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
let coverage = textureSample(atlas, atlas_sampler, input.uv).r;
return vec4<f32>(input.color.rgb, input.color.a * coverage);
}

View file

@ -0,0 +1,156 @@
//! Headless tests for the screen-space overlay.
use super::atlas::{GlyphAtlas, Raster};
use super::text::font_path;
use super::{Overlay, OverlayLine, OverlayRect, OverlayText};
use crate::{Camera, Gpu, MeshData, Renderer, Scene};
use wgpu::TextureFormat;
const SIZE: u32 = 64;
const FORMAT: TextureFormat = TextureFormat::Rgba8UnormSrgb;
fn setup() -> (Gpu, Renderer) {
let gpu = Gpu::headless().expect("headless adapter");
let renderer =
Renderer::new(gpu.device(), gpu.queue(), FORMAT, (SIZE, SIZE)).expect("renderer");
(gpu, renderer)
}
fn empty_scene() -> Scene {
Scene::new(MeshData::default())
}
fn camera() -> Camera {
Camera::look_at([0.0, 0.0, 5.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0])
}
fn pixel_at(pixels: &[u8], x: u32, y: u32) -> [u8; 4] {
let index = ((y * SIZE + x) * 4) as usize;
[
pixels[index],
pixels[index + 1],
pixels[index + 2],
pixels[index + 3],
]
}
#[test]
fn red_rect_changes_pixels() {
let (_gpu, mut renderer) = setup();
let mut overlay = Overlay::new();
overlay.push_rect(OverlayRect::new(
16.0,
16.0,
32.0,
32.0,
[1.0, 0.0, 0.0, 1.0],
));
renderer
.draw_with_overlay(&empty_scene(), &camera(), &overlay)
.expect("draw");
let pixels = renderer.pixels().expect("pixels");
assert_eq!(pixels.len(), (SIZE * SIZE * 4) as usize);
let inside = pixel_at(&pixels, 32, 32);
assert!(
inside[0] > 200 && inside[1] < 40 && inside[2] < 40,
"the rect must be red: {inside:?}"
);
let outside = pixel_at(&pixels, 2, 2);
assert!(
outside[0] < 120,
"the corner must keep the clear colour: {outside:?}"
);
}
#[test]
fn white_line_changes_pixels() {
let (_gpu, mut renderer) = setup();
let mut overlay = Overlay::new();
overlay.push_line(OverlayLine::new(
[4.0, 32.0],
[60.0, 32.0],
3.0,
[1.0, 1.0, 1.0, 1.0],
));
renderer
.draw_with_overlay(&empty_scene(), &camera(), &overlay)
.expect("draw");
let pixels = renderer.pixels().expect("pixels");
let on_line = pixel_at(&pixels, 32, 32);
assert!(
on_line.iter().take(3).all(|channel| *channel > 200),
"the line must be white: {on_line:?}"
);
let off_line = pixel_at(&pixels, 32, 4);
assert!(
off_line[0] < 120,
"away from the line the background stays: {off_line:?}"
);
}
#[test]
fn text_draws_pixels_when_a_font_exists() {
if font_path().is_none() {
return;
}
let (_gpu, mut renderer) = setup();
let mut overlay = Overlay::new();
overlay.push_text(OverlayText::new(
4.0,
4.0,
20.0,
[1.0, 1.0, 1.0, 1.0],
"FPS 60",
));
renderer
.draw_with_overlay(&empty_scene(), &camera(), &overlay)
.expect("draw");
let pixels = renderer.pixels().expect("pixels");
let covered = (4..60)
.flat_map(|x| (4..28).map(move |y| (x, y)))
.filter(|(x, y)| pixel_at(&pixels, *x, *y)[0] > 150)
.count();
assert!(covered > 0, "the text must cover at least one pixel");
}
#[test]
fn atlas_does_not_duplicate_glyphs() {
let mut atlas = GlyphAtlas::new();
let _ = atlas.take_dirty();
let bitmap = [255u8; 16];
let raster = Raster {
bitmap: &bitmap,
width: 4,
height: 4,
xmin: 0,
ymin: 0,
advance: 5.0,
};
let size = 14.0f32.to_bits();
let first = atlas.insert('A', size, &raster).expect("first insert");
assert_eq!(atlas.take_dirty().len(), 1, "one upload per new glyph");
assert!(
atlas.insert('A', size, &raster).is_none(),
"the same glyph is not packed twice"
);
assert!(
atlas.take_dirty().is_empty(),
"no upload for a cached glyph"
);
assert_eq!(atlas.len(), 1);
let cached = atlas.get('A', size).expect("cached glyph");
assert_eq!(cached.uv, first.uv);
}
#[test]
fn zero_size_target_is_skipped() {
let (_gpu, mut renderer) = setup();
renderer.resize((0, 0)).expect("resize to zero");
let mut overlay = Overlay::new();
overlay.push_rect(OverlayRect::new(0.0, 0.0, 8.0, 8.0, [1.0; 4]));
renderer
.draw_with_overlay(&empty_scene(), &camera(), &overlay)
.expect("skipped draw");
assert!(renderer.pixels().expect("pixels").is_empty());
}

View file

@ -0,0 +1,136 @@
//! Font loading and glyph layout for the overlay text.
use std::path::Path;
use fontdue::{Font, FontSettings};
use super::OverlayText;
use super::atlas::{Glyph, GlyphAtlas, Raster, Region};
/// Font files tried in order; the first one that exists is loaded.
const FONT_PATHS: [&str; 5] = [
"/usr/share/fonts/noto/NotoSans-Regular.ttf",
"/usr/share/fonts/TTF/DejaVuSans.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/System/Library/Fonts/Helvetica.ttc",
"C:\\Windows\\Fonts\\segoeui.ttf",
];
/// One textured glyph quad in overlay pixels, origin top-left.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct GlyphQuad {
pub(super) rect: [f32; 4],
pub(super) uv: [f32; 4],
}
/// The first font file that exists on this machine, if any.
pub(super) fn font_path() -> Option<&'static str> {
FONT_PATHS
.iter()
.copied()
.find(|path| Path::new(path).is_file())
}
/// Rasterizes text and caches glyph coverage in the atlas.
pub(super) struct TextRasterizer {
font: Option<Font>,
atlas: GlyphAtlas,
}
impl TextRasterizer {
/// Loads the first available font; without one, text is skipped.
pub(super) fn new() -> Self {
Self {
font: load_font(),
atlas: GlyphAtlas::new(),
}
}
/// Regions of the atlas that were written since the last call.
pub(super) fn take_dirty(&mut self) -> Vec<Region> {
self.atlas.take_dirty()
}
/// The packed coverage that backs the glyph quads.
pub(super) fn atlas(&self) -> &GlyphAtlas {
&self.atlas
}
/// Lays one line of ASCII text out into covered quads.
pub(super) fn layout(&mut self, text: &OverlayText) -> Vec<GlyphQuad> {
let mut quads = Vec::new();
if self.font.is_none() {
return quads;
}
let size = text.size.max(1.0);
let bits = size.to_bits();
let baseline = text.y + self.ascent(size);
let mut pen = text.x;
for ch in text.text.chars() {
if !ch.is_ascii() {
continue;
}
let Some(glyph) = self.glyph(ch, size, bits) else {
continue;
};
if glyph.width > 0 && glyph.height > 0 {
let x = pen + glyph.xmin as f32;
let y = baseline - glyph.ymin as f32 - glyph.height as f32;
quads.push(GlyphQuad {
rect: [x, y, glyph.width as f32, glyph.height as f32],
uv: [
glyph.uv[0],
glyph.uv[1],
glyph.uv[0] + glyph.uv_size[0],
glyph.uv[1] + glyph.uv_size[1],
],
});
}
pen += glyph.advance;
}
quads
}
/// Distance from the top of the text box down to the baseline.
fn ascent(&self, size: f32) -> f32 {
self.font
.as_ref()
.and_then(|font| font.horizontal_line_metrics(size))
.map_or(size * 0.8, |line| line.ascent)
}
/// The cached glyph for `ch`, rasterizing and packing it on first use.
fn glyph(&mut self, ch: char, size: f32, bits: u32) -> Option<Glyph> {
if let Some(cached) = self.atlas.get(ch, bits) {
return Some(*cached);
}
let font = self.font.as_ref()?;
let (metrics, bitmap) = font.rasterize(ch, size);
let raster = Raster {
bitmap: &bitmap,
width: metrics.width as u32,
height: metrics.height as u32,
xmin: metrics.xmin,
ymin: metrics.ymin,
advance: metrics.advance_width,
};
if let Some(packed) = self.atlas.insert(ch, bits, &raster) {
return Some(packed);
}
// The atlas is full: keep the pen moving but draw nothing.
Some(Glyph {
uv: [0.0, 0.0],
uv_size: [0.0, 0.0],
xmin: 0,
ymin: 0,
width: 0,
height: 0,
advance: metrics.advance_width,
})
}
}
fn load_font() -> Option<Font> {
let data = std::fs::read(font_path()?).ok()?;
Font::from_bytes(data, FontSettings::default()).ok()
}

View file

@ -0,0 +1,306 @@
//! Depth-tested scene renderer with an optional offscreen colour target.
mod pipeline;
mod target;
#[cfg(test)]
mod tests;
use pipeline::Pipelines;
use crate::overlay::{Overlay, OverlayRenderer, Target};
use crate::{Camera, RenderError, Scene};
/// A renderer that owns its pipelines, depth buffer and optional colour target.
pub struct Renderer {
device: wgpu::Device,
queue: wgpu::Queue,
format: wgpu::TextureFormat,
size: (u32, u32),
offscreen: bool,
pipelines: Pipelines,
overlay: OverlayRenderer,
depth: Option<(wgpu::Texture, wgpu::TextureView)>,
color: Option<(wgpu::Texture, wgpu::TextureView)>,
}
impl Renderer {
/// Builds a renderer with an offscreen colour target for pixel readback.
pub fn new(
device: &wgpu::Device,
queue: &wgpu::Queue,
format: wgpu::TextureFormat,
size: (u32, u32),
) -> Result<Self, RenderError> {
Self::create(device, queue, format, size, true)
}
/// Builds a renderer that draws directly into a caller-provided view.
pub fn for_surface(
device: &wgpu::Device,
queue: &wgpu::Queue,
format: wgpu::TextureFormat,
size: (u32, u32),
) -> Result<Self, RenderError> {
Self::create(device, queue, format, size, false)
}
fn create(
device: &wgpu::Device,
queue: &wgpu::Queue,
format: wgpu::TextureFormat,
size: (u32, u32),
offscreen: bool,
) -> Result<Self, RenderError> {
let pipelines = pipeline::build(device, format);
let overlay = OverlayRenderer::new(device, queue, format);
let mut renderer = Self {
device: device.clone(),
queue: queue.clone(),
format,
size,
offscreen,
pipelines,
overlay,
depth: None,
color: None,
};
renderer.allocate_targets()?;
Ok(renderer)
}
/// Replaces the depth and colour targets after a resize.
pub fn resize(&mut self, size: (u32, u32)) -> Result<(), RenderError> {
if size == self.size {
return Ok(());
}
self.size = size;
self.depth = None;
self.color = None;
self.allocate_targets()
}
/// The current target size in pixels.
#[must_use]
pub fn size(&self) -> (u32, u32) {
self.size
}
/// Draws the scene into the offscreen colour target.
pub fn draw(&mut self, scene: &Scene, camera: &Camera) -> Result<(), RenderError> {
if self.size.0 == 0 || self.size.1 == 0 {
return Ok(());
}
let (_, view) = self.color.as_ref().ok_or_else(|| {
RenderError::Texture("renderer has no offscreen colour target".to_string())
})?;
self.render(view, scene, camera);
Ok(())
}
/// Draws the scene into a surface texture view owned by the caller.
pub fn draw_to(
&self,
view: &wgpu::TextureView,
scene: &Scene,
camera: &Camera,
) -> Result<(), RenderError> {
if self.size.0 == 0 || self.size.1 == 0 {
return Ok(());
}
self.render(view, scene, camera);
Ok(())
}
/// Draws the 2D overlay into a target view, on top of what is already there.
pub fn draw_overlay(
&self,
view: &wgpu::TextureView,
overlay: &Overlay,
) -> Result<(), RenderError> {
if self.size.0 == 0 || self.size.1 == 0 {
return Ok(());
}
self.overlay.draw(
&self.device,
&self.queue,
Target {
view,
size: self.size,
},
overlay,
);
Ok(())
}
/// Draws the scene and then the overlay into the offscreen colour target.
pub fn draw_with_overlay(
&mut self,
scene: &Scene,
camera: &Camera,
overlay: &Overlay,
) -> Result<(), RenderError> {
if self.size.0 == 0 || self.size.1 == 0 {
return Ok(());
}
self.draw(scene, camera)?;
let (_, view) = self.color.as_ref().ok_or_else(|| {
RenderError::Texture("renderer has no offscreen colour target".to_string())
})?;
self.draw_overlay(view, overlay)
}
/// Reads the offscreen target back as tightly packed RGBA8 pixels.
pub fn pixels(&self) -> Result<Vec<u8>, RenderError> {
if self.size.0 == 0 || self.size.1 == 0 {
return Ok(Vec::new());
}
let (texture, _) = self.color.as_ref().ok_or_else(|| {
RenderError::Texture("renderer has no offscreen colour target".to_string())
})?;
self.read_texture(texture)
}
fn render(&self, view: &wgpu::TextureView, scene: &Scene, camera: &Camera) {
let Some((_, depth)) = &self.depth else {
return;
};
self.write_globals(camera);
let geometry = self.prepare_geometry(scene);
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("fabrilis frame"),
});
{
let attachments = [Some(wgpu::RenderPassColorAttachment {
view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(pipeline::CLEAR_COLOR),
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("fabrilis scene pass"),
color_attachments: &attachments,
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(&self.pipelines.pipeline);
pass.set_bind_group(0, &self.pipelines.bind_group, &[]);
geometry.draw_mesh(&mut pass, &self.pipelines);
geometry.draw_boxes(&mut pass, &self.pipelines);
}
self.queue.submit([encoder.finish()]);
}
fn write_globals(&self, camera: &Camera) {
let globals = pipeline::Globals::new(camera.view_projection(), camera.eye());
self.queue
.write_buffer(&self.pipelines.globals, 0, bytemuck::bytes_of(&globals));
}
fn prepare_geometry(&self, scene: &Scene) -> Geometry {
let terrain = pipeline::RawInstance {
model: crate::Instance::IDENTITY,
color: scene.mesh_color,
};
self.queue.write_buffer(
&self.pipelines.terrain_instance,
0,
bytemuck::bytes_of(&terrain),
);
Geometry {
mesh_vertices: upload_vertices(&self.device, scene),
mesh_indices: upload_indices(&self.device, scene),
mesh_index_count: scene.mesh.indices.len() as u32,
boxes: upload_instances(&self.device, scene),
instance_count: scene.instances.len() as u32,
}
}
}
struct Geometry {
mesh_vertices: Option<wgpu::Buffer>,
mesh_indices: Option<wgpu::Buffer>,
mesh_index_count: u32,
boxes: Option<wgpu::Buffer>,
instance_count: u32,
}
impl Geometry {
fn draw_mesh(&self, pass: &mut wgpu::RenderPass<'_>, pipelines: &Pipelines) {
let (Some(vertices), Some(indices)) = (&self.mesh_vertices, &self.mesh_indices) else {
return;
};
pass.set_vertex_buffer(0, vertices.slice(..));
pass.set_vertex_buffer(1, pipelines.terrain_instance.slice(..));
pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
pass.draw_indexed(0..self.mesh_index_count, 0, 0..1);
}
fn draw_boxes(&self, pass: &mut wgpu::RenderPass<'_>, pipelines: &Pipelines) {
let Some(instances) = &self.boxes else {
return;
};
pass.set_vertex_buffer(0, pipelines.cube_vertices.slice(..));
pass.set_vertex_buffer(1, instances.slice(..));
pass.set_index_buffer(pipelines.cube_indices.slice(..), wgpu::IndexFormat::Uint32);
pass.draw_indexed(0..pipelines.cube_index_count, 0, 0..self.instance_count);
}
}
fn upload_vertices(device: &wgpu::Device, scene: &Scene) -> Option<wgpu::Buffer> {
if scene.mesh.vertices.is_empty() {
return None;
}
Some(pipeline::upload(
device,
"fabrilis mesh vertices",
bytemuck::cast_slice(&scene.mesh.vertices),
wgpu::BufferUsages::VERTEX,
))
}
fn upload_indices(device: &wgpu::Device, scene: &Scene) -> Option<wgpu::Buffer> {
if scene.mesh.indices.is_empty() {
return None;
}
Some(pipeline::upload(
device,
"fabrilis mesh indices",
bytemuck::cast_slice(&scene.mesh.indices),
wgpu::BufferUsages::INDEX,
))
}
fn upload_instances(device: &wgpu::Device, scene: &Scene) -> Option<wgpu::Buffer> {
if scene.instances.is_empty() {
return None;
}
let instances: Vec<pipeline::RawInstance> = scene
.instances
.iter()
.map(|instance| pipeline::RawInstance {
model: instance.model,
color: instance.color,
})
.collect();
Some(pipeline::upload(
device,
"fabrilis box instances",
bytemuck::cast_slice(&instances),
wgpu::BufferUsages::VERTEX,
))
}

View file

@ -0,0 +1,274 @@
//! Pipeline, bind group, uniform block and static geometry shared by all frames.
use bytemuck::{Pod, Zeroable};
use wgpu::util::DeviceExt;
/// Depth format used by the depth buffer.
pub(crate) const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
/// Background colour cleared before every pass.
pub(crate) const CLEAR_COLOR: wgpu::Color = wgpu::Color {
r: 0.05,
g: 0.06,
b: 0.08,
a: 1.0,
};
/// Per-frame uniform block; must match `Globals` in the WGSL shader.
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
pub(crate) struct Globals {
pub view_proj: [[f32; 4]; 4],
pub light_dir: [f32; 4],
pub camera_pos: [f32; 4],
}
impl Globals {
pub(crate) fn new(view_proj: [[f32; 4]; 4], camera_pos: [f32; 3]) -> Self {
Self {
view_proj,
light_dir: [0.35, -0.55, 0.75, 0.0],
camera_pos: [camera_pos[0], camera_pos[1], camera_pos[2], 1.0],
}
}
}
/// One GPU instance: a column-major model matrix and a colour.
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
pub(crate) struct RawInstance {
pub model: [[f32; 4]; 4],
pub color: [f32; 4],
}
const MESH_ATTRIBUTES: [wgpu::VertexAttribute; 1] = [wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x3,
offset: 0,
shader_location: 0,
}];
const INSTANCE_ATTRIBUTES: [wgpu::VertexAttribute; 5] = [
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 0,
shader_location: 1,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 16,
shader_location: 2,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 32,
shader_location: 3,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 48,
shader_location: 4,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 64,
shader_location: 5,
},
];
/// Resource set built once per surface format.
pub(crate) struct Pipelines {
pub pipeline: wgpu::RenderPipeline,
pub bind_group: wgpu::BindGroup,
pub globals: wgpu::Buffer,
pub cube_vertices: wgpu::Buffer,
pub cube_indices: wgpu::Buffer,
pub cube_index_count: u32,
pub terrain_instance: wgpu::Buffer,
}
/// Builds the render pipeline, uniform binding and the unit-cube geometry.
pub(crate) fn build(device: &wgpu::Device, format: wgpu::TextureFormat) -> Pipelines {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("fabrilis mesh shader"),
source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!("shader.wgsl"))),
});
let layout = create_bind_group_layout(device);
let (globals, bind_group) = create_globals(device, &layout);
let pipeline = create_pipeline(device, format, &shader, &layout);
let (cube_vertices, cube_indices, cube_index_count) = cube_geometry(device);
let terrain_instance = upload(
device,
"fabrilis terrain instance",
bytemuck::bytes_of(&identity_instance()),
wgpu::BufferUsages::VERTEX,
);
Pipelines {
pipeline,
bind_group,
globals,
cube_vertices,
cube_indices,
cube_index_count,
terrain_instance,
}
}
/// Uploads data into a fresh buffer with `usage | COPY_DST`.
pub(crate) fn upload(
device: &wgpu::Device,
label: &str,
data: &[u8],
usage: wgpu::BufferUsages,
) -> wgpu::Buffer {
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(label),
contents: data,
usage: usage | wgpu::BufferUsages::COPY_DST,
})
}
fn identity_instance() -> RawInstance {
RawInstance {
model: [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
],
color: [1.0; 4],
}
}
const CUBE_FACES: [([f32; 3], [f32; 3], [f32; 3]); 6] = [
([-0.5, -0.5, 0.5], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
([-0.5, -0.5, -0.5], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]),
([0.5, -0.5, -0.5], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]),
([-0.5, -0.5, -0.5], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]),
([-0.5, 0.5, -0.5], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
([-0.5, -0.5, -0.5], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]),
];
fn cube_geometry(device: &wgpu::Device) -> (wgpu::Buffer, wgpu::Buffer, u32) {
let mut vertices = Vec::with_capacity(24);
let mut indices = Vec::with_capacity(36);
for (origin, axis_u, axis_v) in CUBE_FACES {
let base = vertices.len() as u32;
for (u, v) in [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)] {
vertices.push([
origin[0] + axis_u[0] * u + axis_v[0] * v,
origin[1] + axis_u[1] * u + axis_v[1] * v,
origin[2] + axis_u[2] * u + axis_v[2] * v,
]);
}
indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
}
let vertex_buffer = upload(
device,
"fabrilis cube vertices",
bytemuck::cast_slice(&vertices),
wgpu::BufferUsages::VERTEX,
);
let index_buffer = upload(
device,
"fabrilis cube indices",
bytemuck::cast_slice(&indices),
wgpu::BufferUsages::INDEX,
);
(vertex_buffer, index_buffer, indices.len() as u32)
}
fn create_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("fabrilis globals layout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
})
}
fn create_globals(
device: &wgpu::Device,
layout: &wgpu::BindGroupLayout,
) -> (wgpu::Buffer, wgpu::BindGroup) {
let globals = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("fabrilis globals"),
size: std::mem::size_of::<Globals>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("fabrilis globals"),
layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: globals.as_entire_binding(),
}],
});
(globals, bind_group)
}
fn create_pipeline(
device: &wgpu::Device,
format: wgpu::TextureFormat,
shader: &wgpu::ShaderModule,
layout: &wgpu::BindGroupLayout,
) -> wgpu::RenderPipeline {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("fabrilis pipeline layout"),
bind_group_layouts: &[Some(layout)],
immediate_size: 0,
});
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("fabrilis scene 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: 12,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &MESH_ATTRIBUTES,
}),
Some(wgpu::VertexBufferLayout {
array_stride: 80,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &INSTANCE_ATTRIBUTES,
}),
],
},
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
cull_mode: None,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: DEPTH_FORMAT,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::Less),
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
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::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
}

View file

@ -0,0 +1,48 @@
struct Globals {
view_proj: mat4x4<f32>,
light_dir: vec4<f32>,
camera_pos: vec4<f32>,
};
@group(0) @binding(0) var<uniform> globals: Globals;
struct VertexInput {
@location(0) position: vec3<f32>,
@location(1) model_0: vec4<f32>,
@location(2) model_1: vec4<f32>,
@location(3) model_2: vec4<f32>,
@location(4) model_3: vec4<f32>,
@location(5) color: vec4<f32>,
};
struct VertexOutput {
@builtin(position) clip_position: vec4<f32>,
@location(0) world_position: vec3<f32>,
@location(1) color: vec4<f32>,
};
@vertex
fn vs_main(input: VertexInput) -> VertexOutput {
let model = mat4x4<f32>(
input.model_0,
input.model_1,
input.model_2,
input.model_3,
);
let world = model * vec4<f32>(input.position, 1.0);
var output: VertexOutput;
output.clip_position = globals.view_proj * world;
output.world_position = world.xyz;
output.color = input.color;
return output;
}
@fragment
fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
// Flat face normal from screen-space derivatives; this keeps the mesh data
// to positions only, and two-sided shading tolerates either triangle winding.
let normal = normalize(cross(dpdx(input.world_position), dpdy(input.world_position)));
let light = normalize(globals.light_dir.xyz);
let diffuse = 0.25 + 0.75 * abs(dot(normal, light));
return vec4<f32>(input.color.rgb * diffuse, input.color.a);
}

View file

@ -0,0 +1,149 @@
//! Offscreen targets and pixel readback.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use super::Renderer;
use super::pipeline;
use crate::RenderError;
impl Renderer {
pub(super) fn allocate_targets(&mut self) -> Result<(), RenderError> {
if self.size.0 == 0 || self.size.1 == 0 {
return Ok(());
}
let depth = create_texture(
&self.device,
"fabrilis depth",
pipeline::DEPTH_FORMAT,
self.size,
wgpu::TextureUsages::RENDER_ATTACHMENT,
);
self.depth = Some(depth);
if self.offscreen {
let color = create_texture(
&self.device,
"fabrilis colour",
self.format,
self.size,
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
);
self.color = Some(color);
}
Ok(())
}
pub(super) fn read_texture(&self, texture: &wgpu::Texture) -> Result<Vec<u8>, RenderError> {
let bgra = match self.format {
wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Rgba8UnormSrgb => false,
wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb => true,
other => {
return Err(RenderError::UnsupportedFormat(format!("{other:?}")));
}
};
let (width, height) = self.size;
let row_bytes = width * 4;
let padded_row = row_bytes.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
* wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let output = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("fabrilis readback"),
size: u64::from(padded_row) * u64::from(height),
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("fabrilis readback"),
});
encoder.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo {
texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyBufferInfo {
buffer: &output,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(padded_row),
rows_per_image: Some(height),
},
},
wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
);
self.queue.submit([encoder.finish()]);
let mut pixels = map_and_copy(&self.device, &output, padded_row, row_bytes, height)?;
if bgra {
for pixel in pixels.as_chunks_mut::<4>().0 {
pixel.swap(0, 2);
}
}
Ok(pixels)
}
}
fn create_texture(
device: &wgpu::Device,
label: &str,
format: wgpu::TextureFormat,
size: (u32, u32),
usage: wgpu::TextureUsages,
) -> (wgpu::Texture, wgpu::TextureView) {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: size.0,
height: size.1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
});
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
(texture, view)
}
fn map_and_copy(
device: &wgpu::Device,
buffer: &wgpu::Buffer,
padded_row: u32,
row_bytes: u32,
height: u32,
) -> Result<Vec<u8>, RenderError> {
let failed = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&failed);
buffer
.slice(..)
.map_async(wgpu::MapMode::Read, move |result| {
if result.is_err() {
flag.store(true, Ordering::SeqCst);
}
});
device
.poll(wgpu::PollType::wait_indefinitely())
.map_err(|error| RenderError::Buffer(error.to_string()))?;
if failed.load(Ordering::SeqCst) {
return Err(RenderError::Buffer("readback mapping failed".to_string()));
}
let view = buffer
.slice(..)
.get_mapped_range()
.map_err(|error| RenderError::Buffer(error.to_string()))?;
let mut pixels = Vec::with_capacity((row_bytes * height) as usize);
for row in view.chunks(padded_row as usize) {
pixels.extend(row.iter().take(row_bytes as usize).copied());
}
drop(view);
buffer.unmap();
Ok(pixels)
}

View file

@ -0,0 +1,135 @@
//! Headless rendering tests.
use super::*;
use crate::{Camera, Gpu, Instance, MeshData, Scene};
const SIZE: u32 = 256;
const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb;
fn setup(size: (u32, u32)) -> (Gpu, Renderer) {
let gpu = Gpu::headless().expect("headless adapter");
let renderer = Renderer::new(gpu.device(), gpu.queue(), FORMAT, size).expect("renderer");
(gpu, renderer)
}
fn sloped_terrain() -> Scene {
let mesh = MeshData {
vertices: vec![
[-2.0, -2.0, -0.6],
[2.0, -2.0, 0.6],
[2.0, 2.0, 0.6],
[-2.0, 2.0, -0.6],
],
indices: vec![0, 1, 2, 0, 2, 3],
};
let mut scene = Scene::new(mesh);
scene.instances.push(Instance::box_at(
[0.0, 0.0, 1.2],
[1.0, 1.0, 1.0],
[0.9, 0.4, 0.2, 1.0],
));
scene
}
fn orbit_camera() -> Camera {
Camera::look_at([4.0, -6.0, 5.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0])
.with_projection(0.9, 1.0, 0.1, 100.0)
}
fn pixel_at(pixels: &[u8], size: (u32, u32), x: u32, y: u32) -> [u8; 4] {
let index = (y * size.0 + x) as usize * 4;
[
pixels[index],
pixels[index + 1],
pixels[index + 2],
pixels[index + 3],
]
}
#[test]
fn renders_terrain_and_box() {
let (_gpu, mut renderer) = setup((SIZE, SIZE));
let scene = sloped_terrain();
renderer.draw(&scene, &orbit_camera()).expect("draw");
let pixels = renderer.pixels().expect("pixels");
assert_eq!(pixels.len(), (SIZE * SIZE * 4) as usize);
let corner = pixel_at(&pixels, (SIZE, SIZE), 2, 2);
let centre = pixel_at(&pixels, (SIZE, SIZE), SIZE / 2, SIZE / 2);
assert_ne!(
corner, centre,
"the scene must cover the centre of the frame"
);
let covered = pixels
.as_chunks::<4>()
.0
.iter()
.filter(|pixel| {
pixel
.iter()
.zip(corner.iter())
.any(|(channel, reference)| channel.abs_diff(*reference) > 8)
})
.count();
assert!(
covered > (SIZE * SIZE / 10) as usize,
"only {covered} pixels differ from the corner"
);
}
#[test]
fn resize_reallocates_the_pixel_buffer() {
let (_gpu, mut renderer) = setup((SIZE, SIZE));
let scene = sloped_terrain();
renderer.draw(&scene, &orbit_camera()).expect("first draw");
renderer.resize((64, 96)).expect("resize");
assert_eq!(renderer.size(), (64, 96));
renderer.draw(&scene, &orbit_camera()).expect("second draw");
let pixels = renderer.pixels().expect("pixels");
assert_eq!(pixels.len(), (64 * 96 * 4) as usize);
}
#[test]
fn zero_size_target_is_skipped() {
let (_gpu, mut renderer) = setup((SIZE, SIZE));
let scene = sloped_terrain();
renderer.resize((0, 0)).expect("resize to zero");
renderer
.draw(&scene, &orbit_camera())
.expect("skipped draw");
assert!(renderer.pixels().expect("pixels").is_empty());
renderer.resize((32, 32)).expect("resize back");
renderer
.draw(&scene, &orbit_camera())
.expect("draw after resize");
assert_eq!(
renderer.pixels().expect("pixels").len(),
(32 * 32 * 4) as usize
);
}
#[test]
fn near_box_covers_far_box() {
let (_gpu, mut renderer) = setup((SIZE, SIZE));
let mut scene = Scene::new(MeshData::default());
scene.instances.push(Instance::box_at(
[0.0, 0.0, 0.0],
[2.0, 2.0, 2.0],
[1.0, 0.0, 0.0, 1.0],
));
scene.instances.push(Instance::box_at(
[0.0, 4.0, 0.0],
[2.0, 2.0, 2.0],
[0.0, 0.0, 1.0, 1.0],
));
let camera = Camera::look_at([0.0, -8.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0])
.with_projection(0.9, 1.0, 0.1, 100.0);
renderer.draw(&scene, &camera).expect("draw");
let pixels = renderer.pixels().expect("pixels");
let centre = pixel_at(&pixels, (SIZE, SIZE), SIZE / 2, SIZE / 2);
assert!(
centre[0] > centre[2],
"near red box should cover the far blue one: {centre:?}"
);
}

View file

@ -0,0 +1,80 @@
//! Scene data handed to the renderer: one triangle mesh plus instanced boxes.
type Mat4 = [[f32; 4]; 4];
/// A triangle mesh with positions in metres and `u32` triangle indices.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct MeshData {
/// Vertex positions in world space.
pub vertices: Vec<[f32; 3]>,
/// Triples of vertex indices.
pub indices: Vec<u32>,
}
impl MeshData {
/// The number of complete triangles in the mesh.
#[must_use]
pub fn triangle_count(&self) -> usize {
self.indices.len() / 3
}
}
/// One drawable box: a model matrix and a flat colour.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Instance {
/// Column-major model matrix.
pub model: Mat4,
/// Linear RGBA colour.
pub color: [f32; 4],
}
impl Instance {
/// The identity model matrix.
pub const IDENTITY: Mat4 = [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
/// Builds an instance from a model matrix and a colour.
#[must_use]
pub fn new(model: Mat4, color: [f32; 4]) -> Self {
Self { model, color }
}
/// A box centred at `center` with the given size along each axis.
#[must_use]
pub fn box_at(center: [f32; 3], size: [f32; 3], color: [f32; 4]) -> Self {
let model = [
[size[0], 0.0, 0.0, 0.0],
[0.0, size[1], 0.0, 0.0],
[0.0, 0.0, size[2], 0.0],
[center[0], center[1], center[2], 1.0],
];
Self::new(model, color)
}
}
/// Everything the renderer draws in one frame.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Scene {
/// The terrain surface.
pub mesh: MeshData,
/// Colour multiplied into the terrain vertices.
pub mesh_color: [f32; 4],
/// Boxes drawn with instancing.
pub instances: Vec<Instance>,
}
impl Scene {
/// A scene with one terrain mesh and the default terrain colour.
#[must_use]
pub fn new(mesh: MeshData) -> Self {
Self {
mesh,
mesh_color: [0.34, 0.46, 0.29, 1.0],
instances: Vec::new(),
}
}
}

View file

@ -1 +0,0 @@
//! fabrilis-render :: terrain - stub (see docs/ARCHITECTURE.md)

View file

@ -1 +0,0 @@
//! fabrilis-render :: views - stub (see docs/ARCHITECTURE.md)