initial (bad) voxel renderer

This commit is contained in:
2024-06-04 12:11:28 -04:00
commit 7ae6a01949
31 changed files with 4268 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/target

2300
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

15
Cargo.toml Normal file
View File

@@ -0,0 +1,15 @@
[package]
name = "pixelgame"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
bytemuck = {version="1.14.0", features=["derive"]}
nalgebra = {version="0.32.5", features=["bytemuck"]}
pollster = "0.3"
rand = "0.8.5"
simba = "0.8.1"
wgpu = "0.20"
winit = {version="0.30", features=["serde"]}

491
flamegraph.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 201 KiB

BIN
perf.data Normal file

Binary file not shown.

BIN
perf.data.old Normal file

Binary file not shown.

44
src/client/camera.rs Normal file
View File

@@ -0,0 +1,44 @@
use nalgebra::{Point3, Rotation3, UnitVector3, Vector3};
const DEFAULT_ASPECT_RATIO: f32 = 16. / 9.;
#[derive(Debug, Clone, Copy)]
pub struct Camera {
pub pos: Point3<f32>,
pub orientation: Rotation3<f32>,
pub aspect: f32,
pub scale: f32,
}
impl Default for Camera {
fn default() -> Self {
Self {
pos: Point3::origin(),
orientation: Rotation3::identity(),
aspect: DEFAULT_ASPECT_RATIO,
scale: 1.0,
}
}
}
impl Camera {
pub fn left(&self) -> UnitVector3<f32> {
self.orientation * -Vector3::x_axis()
}
pub fn right(&self) -> UnitVector3<f32> {
self.orientation * Vector3::x_axis()
}
pub fn down(&self) -> UnitVector3<f32> {
self.orientation * -Vector3::y_axis()
}
pub fn up(&self) -> UnitVector3<f32> {
self.orientation * Vector3::y_axis()
}
pub fn backward(&self) -> UnitVector3<f32> {
self.orientation * -Vector3::z_axis()
}
pub fn forward(&self) -> UnitVector3<f32> {
self.orientation * Vector3::z_axis()
}
}

10
src/client/component.rs Normal file
View File

@@ -0,0 +1,10 @@
use bevy_ecs::bundle::Bundle;
use crate::world::{component::{Position, Rotation}, grid::TileGrid};
#[derive(Bundle)]
pub struct ClientGrid {
pub grid: TileGrid,
pub position: Position,
pub rotation: Rotation,
}

View File

@@ -0,0 +1,83 @@
use std::time::Duration;
use nalgebra::{Rotation3, Vector3};
use winit::{keyboard::KeyCode as Key, window::CursorGrabMode};
use super::Client;
impl Client<'_> {
pub fn handle_input(&mut self, dt: &Duration) {
let dt = dt.as_secs_f32();
let Client { input, state, .. } = self;
if input.just_pressed(Key::Escape) {
if let Some(window) = &self.window {
self.grabbed_cursor = !self.grabbed_cursor;
let mode = if self.grabbed_cursor {
window.set_cursor_visible(false);
CursorGrabMode::Locked
} else {
window.set_cursor_visible(true);
CursorGrabMode::None
};
window.set_cursor_grab(mode).expect("wah");
}
return;
}
if self.grabbed_cursor {
let delta = input.mouse_delta;
if delta.x != 0.0 {
state.camera.orientation =
Rotation3::from_axis_angle(&state.camera.up(), delta.x * 0.003)
* state.camera.orientation;
}
if delta.y != 0.0 {
state.camera.orientation =
Rotation3::from_axis_angle(&state.camera.right(), delta.y * 0.003)
* state.camera.orientation;
}
}
let rot_dist = 1.0 * dt;
if input.pressed(Key::KeyQ) {
state.camera.orientation =
Rotation3::from_axis_angle(&state.camera.forward(), rot_dist)
* state.camera.orientation;
}
if input.pressed(Key::KeyE) {
state.camera.orientation =
Rotation3::from_axis_angle(&state.camera.forward(), -rot_dist)
* state.camera.orientation;
}
if input.scroll_delta != 0.0 {
state.camera_scroll += input.scroll_delta;
state.camera.scale = (state.camera_scroll * 0.2).exp();
}
let move_dist = 10.0 * dt;
if input.pressed(Key::KeyW) {
state.camera.pos += *state.camera.forward() * move_dist;
}
if input.pressed(Key::KeyA) {
state.camera.pos += *state.camera.left() * move_dist;
}
if input.pressed(Key::KeyS) {
state.camera.pos += *state.camera.backward() * move_dist;
}
if input.pressed(Key::KeyD) {
state.camera.pos += *state.camera.right() * move_dist;
}
if input.pressed(Key::Space) {
state.camera.pos += *state.camera.up() * move_dist;
}
if input.pressed(Key::ShiftLeft) {
state.camera.pos += *state.camera.down() * move_dist;
}
if input.pressed(Key::KeyZ) {
state.camera_scroll += dt * 10.0;
state.camera.scale = (state.camera_scroll * 0.1).exp();
}
if input.pressed(Key::KeyX) {
state.camera_scroll -= dt * 10.0;
state.camera.scale = (state.camera_scroll * 0.1).exp();
}
}
}

123
src/client/input.rs Normal file
View File

@@ -0,0 +1,123 @@
use std::collections::HashSet;
use winit::{
event::{DeviceEvent, ElementState, MouseButton, MouseScrollDelta, WindowEvent},
keyboard::{KeyCode, PhysicalKey},
};
use crate::util::math::{Pos2f, Vec2f};
pub struct Input {
pub mouse_pixel_pos: Pos2f,
pub mouse_delta: Vec2f,
pressed: HashSet<KeyCode>,
just_pressed: HashSet<KeyCode>,
mouse_pressed: HashSet<MouseButton>,
mouse_just_pressed: HashSet<MouseButton>,
mouse_just_released: HashSet<MouseButton>,
pub scroll_delta: f32,
}
impl Input {
pub fn new() -> Self {
Self {
mouse_pixel_pos: Pos2f::origin(),
mouse_delta: Vec2f::zeros(),
pressed: HashSet::new(),
just_pressed: HashSet::new(),
mouse_pressed: HashSet::new(),
mouse_just_pressed: HashSet::new(),
mouse_just_released: HashSet::new(),
scroll_delta: 0.0,
}
}
pub fn update_device(&mut self, event: DeviceEvent) {
match event {
DeviceEvent::MouseWheel { delta } => {
self.scroll_delta = match delta {
MouseScrollDelta::LineDelta(_, v) => v,
MouseScrollDelta::PixelDelta(v) => (v.y / 2.0) as f32,
};
}
DeviceEvent::MouseMotion { delta } => {
self.mouse_delta += Vec2f::new(delta.0 as f32, delta.1 as f32);
}
_ => (),
}
}
pub fn update_window(&mut self, event: WindowEvent) {
match event {
WindowEvent::KeyboardInput { event, .. } => {
let code = if let PhysicalKey::Code(code) = event.physical_key {
code
} else {
return;
};
match event.state {
ElementState::Pressed => {
self.just_pressed.insert(code);
self.pressed.insert(code);
}
ElementState::Released => {
self.pressed.remove(&code);
}
};
}
WindowEvent::CursorLeft { .. } => {
self.pressed.clear();
self.mouse_pressed.clear();
}
WindowEvent::CursorMoved { position, .. } => {
self.mouse_pixel_pos = Pos2f::new(position.x as f32, position.y as f32);
}
WindowEvent::MouseInput { button, state, .. } => match state {
ElementState::Pressed => {
self.mouse_just_pressed.insert(button);
self.mouse_pressed.insert(button);
}
ElementState::Released => {
self.mouse_pressed.remove(&button);
self.mouse_just_released.insert(button);
}
},
_ => (),
}
}
pub fn end(&mut self) {
self.scroll_delta = 0.0;
self.mouse_delta = Vec2f::zeros();
self.just_pressed.clear();
self.mouse_just_pressed.clear();
self.mouse_just_released.clear();
}
#[allow(dead_code)]
pub fn pressed(&self, key: KeyCode) -> bool {
self.pressed.contains(&key)
}
#[allow(dead_code)]
pub fn just_pressed(&self, key: KeyCode) -> bool {
self.just_pressed.contains(&key)
}
#[allow(dead_code)]
pub fn mouse_pressed(&self, button: MouseButton) -> bool {
self.mouse_pressed.contains(&button)
}
#[allow(dead_code)]
pub fn mouse_just_pressed(&self, button: MouseButton) -> bool {
self.mouse_just_pressed.contains(&button)
}
#[allow(dead_code)]
pub fn mouse_just_released(&self, button: MouseButton) -> bool {
self.mouse_just_released.contains(&button)
}
}

68
src/client/mod.rs Normal file
View File

@@ -0,0 +1,68 @@
mod camera;
mod handle_input;
mod input;
mod render;
mod rsc;
mod state;
mod window;
pub use state::*;
use self::{input::Input, render::Renderer, rsc::FRAME_TIME, ClientState};
use std::{
sync::Arc,
time::{Duration, Instant},
};
use winit::window::Window;
pub struct Client<'a> {
window: Option<Arc<Window>>,
renderer: Option<Renderer<'a>>,
frame_time: Duration,
state: ClientState,
exit: bool,
input: Input,
target: Instant,
prev_frame: Instant,
prev_update: Instant,
grabbed_cursor: bool,
}
impl Client<'_> {
pub fn new() -> Self {
Self {
window: None,
renderer: None,
exit: false,
frame_time: FRAME_TIME,
state: ClientState::new(),
input: Input::new(),
prev_frame: Instant::now(),
prev_update: Instant::now(),
target: Instant::now(),
grabbed_cursor: false,
}
}
pub fn start(&mut self) {}
pub fn update(&mut self) -> bool {
let now = Instant::now();
let dt = now - self.prev_update;
self.prev_update = now;
self.handle_input(&dt);
self.input.end();
if now >= self.target {
self.target += self.frame_time;
self.prev_frame = now;
let renderer = self.renderer.as_mut().unwrap();
renderer.update(&self.state);
renderer.draw();
}
self.exit
}
}

115
src/client/render/buf.rs Normal file
View File

@@ -0,0 +1,115 @@
use std::marker::PhantomData;
use wgpu::{BufferAddress, BufferUsages};
pub struct ArrBuf<T: bytemuck::Pod> {
len: usize,
buffer: wgpu::Buffer,
label: String,
typ: PhantomData<T>,
usage: BufferUsages,
moves: Vec<BufMove>,
}
impl<T: bytemuck::Pod> ArrBuf<T> {
pub fn update(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
belt: &mut wgpu::util::StagingBelt,
size: usize,
updates: &[ArrBufUpdate<T>],
) -> bool {
let mut resized = false;
if size != self.len || !self.moves.is_empty() {
let new = Self::init_buf(device, &self.label, size, self.usage);
let cpy_len = self.len.min(size);
encoder.copy_buffer_to_buffer(
&self.buffer,
0,
&new,
0,
(cpy_len * std::mem::size_of::<T>()) as u64,
);
for m in &self.moves {
encoder.copy_buffer_to_buffer(
&self.buffer,
(m.source * std::mem::size_of::<T>()) as BufferAddress,
&new,
(m.dest * std::mem::size_of::<T>()) as BufferAddress,
(m.size * std::mem::size_of::<T>()) as BufferAddress,
);
}
resized = true;
self.moves.clear();
self.len = size;
self.buffer = new;
}
if self.len == 0 {
return resized;
}
for update in updates {
let mut view = belt.write_buffer(
encoder,
&self.buffer,
(update.offset * std::mem::size_of::<T>()) as BufferAddress,
unsafe {
std::num::NonZeroU64::new_unchecked(
(update.data.len() * std::mem::size_of::<T>()) as u64,
)
},
device,
);
view.copy_from_slice(bytemuck::cast_slice(&update.data));
}
resized
}
pub fn init(device: &wgpu::Device, label: &str, usage: BufferUsages) -> Self {
let label = &(label.to_owned() + " Buffer");
Self {
len: 0,
buffer: Self::init_buf(device, label, 0, usage),
label: label.to_string(),
typ: PhantomData,
usage,
moves: Vec::new(),
}
}
fn init_buf(
device: &wgpu::Device,
label: &str,
mut size: usize,
usage: BufferUsages,
) -> wgpu::Buffer {
if usage.contains(BufferUsages::STORAGE) && size == 0 {
size = 1;
}
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(label),
usage: usage | BufferUsages::COPY_DST | BufferUsages::COPY_SRC,
size: (size * std::mem::size_of::<T>()) as u64,
mapped_at_creation: false,
})
}
pub fn buffer(&self) -> &wgpu::Buffer {
&self.buffer
}
pub fn mov(&mut self, mov: BufMove) {
self.moves.push(mov);
}
}
pub struct ArrBufUpdate<T> {
pub offset: usize,
pub data: Vec<T>,
}
#[derive(Clone, Copy, Debug)]
pub struct BufMove {
pub source: usize,
pub dest: usize,
pub size: usize,
}

View File

@@ -0,0 +1,59 @@
use wgpu::{BufferUsages, VertexAttribute};
use super::buf::{ArrBuf, ArrBufUpdate, BufMove};
pub struct Instances<T: bytemuck::Pod> {
buf: ArrBuf<T>,
location: u32,
attrs: [VertexAttribute; 1],
}
impl<T: bytemuck::Pod> Instances<T> {
pub fn update(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
belt: &mut wgpu::util::StagingBelt,
size: usize,
updates: &[ArrBufUpdate<T>],
) -> bool {
self.buf.update(device, encoder, belt, size, updates)
}
pub fn init(
device: &wgpu::Device,
label: &str,
location: u32,
format: wgpu::VertexFormat,
) -> Self {
Self {
buf: ArrBuf::init(
device,
&(label.to_owned() + " Instance"),
BufferUsages::VERTEX,
),
location,
attrs: [wgpu::VertexAttribute {
format,
offset: 0,
shader_location: location,
}],
}
}
pub fn set_in<'a>(&'a self, render_pass: &mut wgpu::RenderPass<'a>) {
render_pass.set_vertex_buffer(self.location, self.buf.buffer().slice(..));
}
pub fn desc(&self) -> wgpu::VertexBufferLayout {
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<T>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &self.attrs,
}
}
pub fn mov(&mut self, mov: BufMove) {
self.buf.mov(mov);
}
}

8
src/client/render/mod.rs Normal file
View File

@@ -0,0 +1,8 @@
mod buf;
mod instance;
mod renderer;
mod storage;
pub mod voxel;
mod uniform;
pub use renderer::*;

View File

@@ -0,0 +1,171 @@
use std::sync::Arc;
use super::voxel::VoxelPipeline;
use crate::client::{rsc::CLEAR_COLOR, ClientState};
use winit::{
dpi::PhysicalSize,
window::{Fullscreen, Window},
};
pub struct Renderer<'a> {
size: PhysicalSize<u32>,
surface: wgpu::Surface<'a>,
device: wgpu::Device,
queue: wgpu::Queue,
config: wgpu::SurfaceConfiguration,
adapter: wgpu::Adapter,
encoder: Option<wgpu::CommandEncoder>,
staging_belt: wgpu::util::StagingBelt,
voxel_pipeline: VoxelPipeline,
}
impl<'a> Renderer<'a> {
pub fn new(window: Arc<Window>, fullscreen: bool) -> Self {
if fullscreen {
window.set_fullscreen(Some(Fullscreen::Borderless(None)));
}
let size = window.inner_size();
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::PRIMARY,
..Default::default()
});
let surface = instance
.create_surface(window)
.expect("Could not create window surface!");
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::default(),
compatible_surface: Some(&surface),
force_fallback_adapter: false,
}))
.expect("Could not get adapter!");
let (device, queue) = pollster::block_on(adapter.request_device(
&wgpu::DeviceDescriptor {
label: None,
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::default(),
},
None, // Trace path
))
.expect("Could not get device!");
// TODO: use a logger
let info = adapter.get_info();
println!("Adapter: {}", info.name);
println!("Backend: {:?}", info.backend);
let surface_caps = surface.get_capabilities(&adapter);
// Set surface format to srbg
let surface_format = surface_caps
.formats
.iter()
.copied()
.find(|f| f.is_srgb())
.unwrap_or(surface_caps.formats[0]);
// create surface config
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface_format,
width: size.width,
height: size.height,
present_mode: surface_caps.present_modes[0],
alpha_mode: surface_caps.alpha_modes[0],
view_formats: vec![],
desired_maximum_frame_latency: 2,
};
surface.configure(&device, &config);
// not exactly sure what this number should be,
// doesn't affect performance much and depends on "normal" zoom
let staging_belt = wgpu::util::StagingBelt::new(4096 * 4);
Self {
size,
voxel_pipeline: VoxelPipeline::new(&device, &config.format),
encoder: None,
staging_belt,
surface,
device,
adapter,
config,
queue,
}
}
fn create_encoder(&mut self) -> wgpu::CommandEncoder {
self.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
})
}
pub fn draw(&mut self) {
let output = self.surface.get_current_texture().unwrap();
let view = output
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = self.encoder.take().unwrap_or(self.create_encoder());
{
let render_pass = &mut encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Render Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(CLEAR_COLOR),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
});
self.voxel_pipeline.draw(render_pass);
}
self.staging_belt.finish();
self.queue.submit(std::iter::once(encoder.finish()));
output.present();
self.staging_belt.recall();
}
pub fn update(&mut self, state: &ClientState) {
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
});
self.voxel_pipeline.update(
&self.device,
&mut encoder,
&mut self.staging_belt,
&mut self.queue,
&RenderUpdateData {
state,
size: &self.size,
},
);
self.encoder = Some(encoder);
}
pub fn resize(&mut self, size: PhysicalSize<u32>) {
self.size = size;
self.config.width = size.width;
self.config.height = size.height;
self.surface.configure(&self.device, &self.config);
}
pub fn size(&self) -> &PhysicalSize<u32> {
&self.size
}
}
pub struct RenderUpdateData<'a> {
pub state: &'a ClientState,
pub size: &'a PhysicalSize<u32>,
}

View File

@@ -0,0 +1,55 @@
use super::buf::{ArrBuf, ArrBufUpdate, BufMove};
use wgpu::BufferUsages;
pub struct Storage<T: bytemuck::Pod + PartialEq> {
binding: u32,
buf: ArrBuf<T>,
}
impl<T: PartialEq + bytemuck::Pod> Storage<T> {
pub fn init(device: &wgpu::Device, label: &str, binding: u32) -> Self {
Self {
buf: ArrBuf::init(
device,
&(label.to_owned() + " Storage"),
BufferUsages::STORAGE,
),
binding,
}
}
}
impl<T: PartialEq + bytemuck::Pod> Storage<T> {
pub fn bind_group_layout_entry(&self) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding: self.binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}
}
pub fn bind_group_entry(&self) -> wgpu::BindGroupEntry {
return wgpu::BindGroupEntry {
binding: self.binding,
resource: self.buf.buffer().as_entire_binding(),
};
}
pub fn update(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
belt: &mut wgpu::util::StagingBelt,
size: usize,
updates: &[ArrBufUpdate<T>],
) -> bool {
self.buf.update(device, encoder, belt, size, updates)
}
pub fn mov(&mut self, mov: BufMove) {
self.buf.mov(mov);
}
}

View File

@@ -0,0 +1,72 @@
use wgpu::util::DeviceExt;
use super::RenderUpdateData;
pub trait UniformData {
fn update(&mut self, data: &RenderUpdateData) -> bool;
}
pub struct Uniform<T: bytemuck::Pod + PartialEq + UniformData> {
data: T,
buffer: wgpu::Buffer,
binding: u32,
}
impl<T: Default + PartialEq + bytemuck::Pod + UniformData> Uniform<T> {
pub fn init(device: &wgpu::Device, name: &str, binding: u32) -> Self {
let data = T::default();
Self {
data,
buffer: device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(&(name.to_owned() + " Uniform Buf")),
contents: bytemuck::cast_slice(&[data]),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
}),
binding,
}
}
}
impl<T: PartialEq + bytemuck::Pod + UniformData> Uniform<T> {
pub fn bind_group_layout_entry(&self) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding: self.binding,
visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}
}
pub fn bind_group_entry(&self) -> wgpu::BindGroupEntry {
return wgpu::BindGroupEntry {
binding: self.binding,
resource: self.buffer.as_entire_binding(),
};
}
pub fn update(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
belt: &mut wgpu::util::StagingBelt,
update_data: &RenderUpdateData,
) {
if self.data.update(update_data) {
let slice = &[self.data];
let mut view = belt.write_buffer(
encoder,
&self.buffer,
0,
unsafe {
std::num::NonZeroU64::new_unchecked(
(slice.len() * std::mem::size_of::<T>()) as u64,
)
},
device,
);
view.copy_from_slice(bytemuck::cast_slice(slice));
}
}
}

View File

@@ -0,0 +1,35 @@
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, bytemuck::Zeroable, bytemuck::Pod)]
pub struct VoxelColor {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
}
impl VoxelColor {
pub fn none() -> Self {
Self {
r: 0,
g: 0,
b: 0,
a: 0,
}
}
pub fn black() -> Self {
Self {
r: 0,
g: 0,
b: 0,
a: 255,
}
}
pub fn white() -> Self {
Self {
r: 255,
g: 255,
b: 255,
a: 255,
}
}
}

View File

@@ -0,0 +1,24 @@
use nalgebra::Matrix4x3;
// this has cost me more than a couple of hours trying to figure out alignment :skull:
// putting transform at the beginning so I don't have to deal with its alignment
// I should probably look into encase (crate)
#[repr(C, align(16))]
#[derive(Clone, Copy, PartialEq, bytemuck::Zeroable)]
pub struct GridInfo {
pub transform: Matrix4x3<f32>,
pub width: u32,
pub height: u32,
}
unsafe impl bytemuck::Pod for GridInfo {}
impl Default for GridInfo {
fn default() -> Self {
Self {
transform: Matrix4x3::identity(),
width: 0,
height: 0,
}
}
}

View File

@@ -0,0 +1,6 @@
mod grid;
mod view;
mod pipeline;
mod color;
pub use pipeline::*;

View File

@@ -0,0 +1,208 @@
use super::{color::VoxelColor, view::View};
use crate::client::render::{
buf::ArrBufUpdate, storage::Storage, uniform::Uniform, RenderUpdateData,
};
pub struct VoxelPipeline {
pipeline: wgpu::RenderPipeline,
view: Uniform<View>,
bind_group_layout: wgpu::BindGroupLayout,
bind_group: wgpu::BindGroup,
texture: wgpu::Texture,
voxels: Storage<VoxelColor>,
arst: bool,
}
const WIDTH: u32 = 300;
const HEIGHT: u32 = 300;
impl VoxelPipeline {
pub fn new(device: &wgpu::Device, format: &wgpu::TextureFormat) -> Self {
// shaders
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Tile Shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
});
let view = Uniform::<View>::init(device, "View", 0);
let texture_size = wgpu::Extent3d {
width: WIDTH,
height: HEIGHT,
depth_or_array_layers: 1,
};
let texture = device.create_texture(&wgpu::TextureDescriptor {
size: texture_size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8UnormSrgb,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
label: Some("diffuse_texture"),
view_formats: &[],
});
let voxels = Storage::init(device, "voxels", 3);
let diffuse_texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let diffuse_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
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::Nearest,
mipmap_filter: wgpu::FilterMode::Nearest,
..Default::default()
});
// bind groups
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[
view.bind_group_layout_entry(),
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
multisampled: false,
view_dimension: wgpu::TextureViewDimension::D2,
sample_type: wgpu::TextureSampleType::Float { filterable: true },
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
voxels.bind_group_layout_entry(),
],
label: Some("tile_bind_group_layout"),
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &bind_group_layout,
entries: &[
view.bind_group_entry(),
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&diffuse_texture_view),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&diffuse_sampler),
},
voxels.bind_group_entry(),
],
label: Some("tile_bind_group"),
});
// pipeline
let render_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Tile Pipeline Layout"),
bind_group_layouts: &[&bind_group_layout],
push_constant_ranges: &[],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Voxel Pipeline"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "vs_main",
buffers: &[],
compilation_options: wgpu::PipelineCompilationOptions::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "fs_main",
targets: &[Some(wgpu::ColorTargetState {
format: *format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
compilation_options: wgpu::PipelineCompilationOptions::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleStrip,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: None,
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
},
depth_stencil: None,
multisample: wgpu::MultisampleState {
count: 1,
mask: !0,
alpha_to_coverage_enabled: true,
},
multiview: None,
});
Self {
pipeline: render_pipeline,
view,
bind_group,
bind_group_layout,
texture,
voxels,
arst: false,
}
}
pub fn update(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
belt: &mut wgpu::util::StagingBelt,
queue: &mut wgpu::Queue,
update_data: &RenderUpdateData,
) {
let texture_size = wgpu::Extent3d {
width: WIDTH,
height: HEIGHT,
depth_or_array_layers: 1,
};
if !self.arst {
queue.write_texture(
// Tells wgpu where to copy the pixel data
wgpu::ImageCopyTexture {
texture: &self.texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
// The actual pixel data
&[0xff, 0x00, 0xff, 0xff].repeat((WIDTH * HEIGHT) as usize),
// The layout of the texture
wgpu::ImageDataLayout {
offset: 0,
bytes_per_row: Some(4 * WIDTH),
rows_per_image: Some(HEIGHT),
},
texture_size,
);
let l = 10;
let size = l * l * l;
let mut data: Vec<_> = vec![VoxelColor::none(); size];
data[0] = VoxelColor::white();
data[size - 1] = VoxelColor::white();
self.voxels.update(
device,
encoder,
belt,
data.len(),
&[ArrBufUpdate { offset: 0, data }],
);
self.arst = true;
}
self.view.update(device, encoder, belt, update_data);
}
pub fn draw<'a>(&'a self, render_pass: &mut wgpu::RenderPass<'a>) {
render_pass.set_pipeline(&self.pipeline);
render_pass.set_bind_group(0, &self.bind_group, &[]);
render_pass.draw(0..4, 0..1);
}
}

View File

@@ -0,0 +1,81 @@
// Vertex shader
struct VertexOutput {
@builtin(position) clip_position: vec4<f32>,
@location(0) tex_coords: vec2<f32>,
};
struct View {
width: u32,
height: u32,
zoom: f32,
padding: u32,
transform: mat4x4<f32>,
};
@group(0) @binding(0)
var<uniform> view: View;
@group(0) @binding(1)
var t_diffuse: texture_2d<f32>;
@group(0) @binding(2)
var s_diffuse: sampler;
@group(0) @binding(3)
var<storage, read> voxels: array<u32>;
@vertex
fn vs_main(
@builtin(vertex_index) vi: u32,
@builtin(instance_index) ii: u32,
) -> VertexOutput {
var out: VertexOutput;
var pos = vec2<f32>(
f32(vi % 2u) * 2.0 - 1.0,
f32(vi / 2u) * 2.0 - 1.0,
);
out.clip_position = vec4<f32>(pos.x, pos.y, 0.0, 1.0);
out.tex_coords = pos;
return out;
}
// Fragment shader
@fragment
fn fs_main(
in: VertexOutput,
) -> @location(0) vec4<f32> {
let aspect = f32(view.height) / f32(view.width);
var pixel_pos = vec3<f32>(in.clip_position.x / f32(view.width), 1.0 - in.clip_position.y / f32(view.height), 1.0);
pixel_pos.x -= 0.5;
pixel_pos.y -= 0.5;
pixel_pos.x *= 2.0;
pixel_pos.y *= 2.0;
pixel_pos.y *= aspect;
pixel_pos = (view.transform * vec4<f32>(pixel_pos, 1.0)).xyz;
let origin = (view.transform * vec4<f32>(0.0, 0.0, 0.0, 1.0)).xyz;
let dir = normalize(pixel_pos - origin);
let voxel_pos = vec3<f32>(-5.0, -5.0, 30.0);
var t = 0;
for(t = 0; t < 1000; t += 1) {
let pos = pixel_pos + f32(t) * 0.1 * dir - voxel_pos;
let rel_coords = vec3<i32>(pos.xyz);
if rel_coords.x < 0 || rel_coords.y < 0 || rel_coords.z < 0 || rel_coords.x > 10 || rel_coords.y > 10 || rel_coords.z > 10 {
continue;
} else {
let i = rel_coords.x + rel_coords.y * 10 + rel_coords.z * 100;
let color = unpack4x8unorm(voxels[i]);
if voxels[i] != 0 {
return vec4<f32>(1.0);
} else {
let pos = vec3<f32>(rel_coords);
return vec4<f32>(pos.x / 10.0, pos.y / 10.0, pos.z / 10.0, 1.0);
}
}
}
return vec4<f32>(0.0, 0.0, 0.0, 1.0);
}

View File

@@ -0,0 +1,50 @@
use nalgebra::{Transform3, Translation3};
use crate::client::render::uniform::UniformData;
#[repr(C, align(16))]
#[derive(Clone, Copy, PartialEq, bytemuck::Zeroable)]
pub struct View {
pub width: u32,
pub height: u32,
pub zoom: f32,
pub padding: u32,
pub transform: Transform3<f32>,
}
unsafe impl bytemuck::Pod for View {}
impl Default for View {
fn default() -> Self {
Self {
width: 1,
height: 1,
zoom: 1.0,
padding: 0,
transform: Transform3::identity(),
}
}
}
impl UniformData for View {
fn update(&mut self, data: &crate::client::render::RenderUpdateData) -> bool {
let camera = data.state.camera;
let new = Transform3::identity() * Translation3::from(camera.pos) * camera.orientation;
if new == self.transform
&& data.size.width == self.width
&& data.size.height == self.height
&& camera.scale == self.zoom
{
false
} else {
*self = Self {
width: data.size.width,
height: data.size.height,
zoom: camera.scale,
padding: 0,
transform: new,
};
true
}
}
}

12
src/client/rsc.rs Normal file
View File

@@ -0,0 +1,12 @@
use std::time::Duration;
pub const FPS: u32 = 30;
pub const FRAME_TIME: Duration = Duration::from_millis(1000 / FPS as u64);
pub const CLEAR_COLOR: wgpu::Color = wgpu::Color {
r: 0.1,
g: 0.1,
b: 0.1,
a: 1.0,
};

15
src/client/state.rs Normal file
View File

@@ -0,0 +1,15 @@
use super::camera::Camera;
pub struct ClientState {
pub camera: Camera,
pub camera_scroll: f32,
}
impl ClientState {
pub fn new() -> Self {
Self {
camera: Camera::default(),
camera_scroll: 0.0,
}
}
}

55
src/client/window.rs Normal file
View File

@@ -0,0 +1,55 @@
use std::sync::Arc;
use winit::{
application::ApplicationHandler, event::WindowEvent, event_loop::ControlFlow,
window::WindowAttributes,
};
use super::{render::Renderer, Client};
impl ApplicationHandler for Client<'_> {
fn resumed(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) {
if self.window.is_none() {
let window = Arc::new(
event_loop
.create_window(WindowAttributes::default())
.expect("Failed to create window"),
);
self.renderer = Some(Renderer::new(window.clone(), false));
self.window = Some(window);
self.start();
}
event_loop.set_control_flow(ControlFlow::Poll);
}
fn window_event(
&mut self,
_event_loop: &winit::event_loop::ActiveEventLoop,
_window_id: winit::window::WindowId,
event: WindowEvent,
) {
let renderer = self.renderer.as_mut().unwrap();
match event {
WindowEvent::CloseRequested => self.exit = true,
WindowEvent::Resized(size) => renderer.resize(size),
WindowEvent::RedrawRequested => renderer.draw(),
_ => self.input.update_window(event),
}
}
fn device_event(
&mut self,
_event_loop: &winit::event_loop::ActiveEventLoop,
_device_id: winit::event::DeviceId,
event: winit::event::DeviceEvent,
) {
self.input.update_device(event);
}
fn about_to_wait(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) {
if self.update() {
event_loop.exit();
}
}
}

12
src/main.rs Normal file
View File

@@ -0,0 +1,12 @@
use client::Client;
use winit::event_loop::EventLoop;
mod client;
mod util;
fn main() {
let event_loop = EventLoop::new().expect("Failed to create event loop");
event_loop
.run_app(&mut Client::new())
.expect("Failed to run event loop");
}

29
src/util/math.rs Normal file
View File

@@ -0,0 +1,29 @@
use nalgebra::{Matrix4x3, Point2, Projective2, Transform2, Vector2, Vector3};
pub type Vec2f = Vector2<f32>;
pub type Vec3f = Vector3<f32>;
pub type Pos2f = Point2<f32>;
pub type Vec2us = Vector2<usize>;
// hahaha.. HAHAHAAAAAAAAAAA... it's over now, surely I'll remember this lesson
pub trait Bruh<T> {
fn gpu_mat3(&self) -> Matrix4x3<T>;
}
impl Bruh<f32> for Transform2<f32> {
fn gpu_mat3(&self) -> Matrix4x3<f32> {
let mut a = Matrix4x3::identity();
// I LOVE GPU DATA STRUCTURE ALIGNMENT (it makes sense tho)
a.view_mut((0,0), (3,3)).copy_from(self.matrix());
a
}
}
impl Bruh<f32> for Projective2<f32> {
fn gpu_mat3(&self) -> Matrix4x3<f32> {
let mut a = Matrix4x3::identity();
// I LOVE GPU DATA STRUCTURE ALIGNMENT (it makes sense tho)
a.view_mut((0,0), (3,3)).copy_from(self.matrix());
a
}
}

2
src/util/mod.rs Normal file
View File

@@ -0,0 +1,2 @@
pub mod swap_buf;
pub mod math;

43
src/util/swap_buf.rs Normal file
View File

@@ -0,0 +1,43 @@
use std::ops::{Deref, DerefMut, Add};
pub struct SwapBuffer<T> {
read: Vec<T>,
write: Vec<T>,
modify: Vec<T>,
}
impl<T: Default + Copy + Clone + Add<Output = T>> SwapBuffer<T> {
pub fn new(size: usize) -> Self {
Self {
read: vec![T::default(); size],
write: vec![T::default(); size],
modify: vec![T::default(); size],
}
}
pub fn swap(&mut self) {
std::mem::swap(&mut self.read, &mut self.write);
for (m, r) in self.modify.iter_mut().zip(&mut self.read) {
*r = *r + *m;
*m = T::default();
}
}
pub fn rwm(&mut self) -> (&mut Vec<T>, &mut Vec<T>, &mut Vec<T>) {
(&mut self.read, &mut self.write, &mut self.modify)
}
}
impl<T> Deref for SwapBuffer<T> {
type Target = Vec<T>;
fn deref(&self) -> &Self::Target {
&self.read
}
}
impl<T> DerefMut for SwapBuffer<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.read
}
}

81
src/util/tracked_grid.rs Normal file
View File

@@ -0,0 +1,81 @@
use crate::util::math::Vec2us;
use bevy_ecs::component::Component;
use nalgebra::{DMatrix, DimRange, Dyn};
use std::ops::{Deref, Range};
pub type GridRegion = (Range<usize>, Range<usize>);
pub type GridView<'a, T> = nalgebra::Matrix<
T,
Dyn,
Dyn,
nalgebra::ViewStorageMut<'a, T, Dyn, Dyn, nalgebra::Const<1>, Dyn>,
>;
#[derive(Clone, Component)]
pub struct TrackedGrid<T> {
data: DMatrix<T>,
changes: Vec<GridRegion>,
}
impl<T> TrackedGrid<T> {
pub fn new(data: DMatrix<T>) -> Self {
Self {
data,
changes: Vec::new(),
}
}
pub fn width(&self) -> usize {
self.data.ncols()
}
pub fn height(&self) -> usize {
self.data.nrows()
}
pub fn view_range_mut<RowRange: DimRange<Dyn>, ColRange: DimRange<Dyn>>(
&mut self,
x_range: ColRange,
y_range: RowRange,
) -> GridView<'_, T> {
let shape = self.data.shape();
let r = Dyn(shape.0);
let rows = y_range.begin(r)..y_range.end(r);
let c = Dyn(shape.1);
let cols = x_range.begin(c)..x_range.end(c);
self.changes.push((rows.clone(), cols.clone()));
self.data.view_range_mut(rows, cols)
}
pub fn take_changes(&mut self) -> Vec<GridRegion> {
std::mem::replace(&mut self.changes, Vec::new())
}
pub fn change(&mut self, index: Vec2us) -> Option<&mut T> {
if let Some(d) = self.data.get_mut((index.y, index.x)) {
self.changes
.push((index.y..index.y + 1, index.x..index.x + 1));
Some(d)
} else {
None
}
}
}
impl<T> Deref for TrackedGrid<T> {
type Target = DMatrix<T>;
fn deref(&self) -> &Self::Target {
&self.data
}
}
// pub fn tile_pos(&self, pos: Pos2f) -> Option<Vec2us> {
// let mut pos = self.orientation.inverse() * pos;
// pos += Vec2f::new(
// (self.size.x / 2) as f32 + 0.5,
// (self.size.y / 2) as f32 + 0.5,
// );
// if pos.x < 0.0 || pos.y < 0.0 {
// return None;
// }
// let truncated = Vec2us::new(pos.x as usize, pos.y as usize);
// if truncated.x > self.size.x - 1 || truncated.y > self.size.y - 1 {
// return None;
// }
// Some(truncated)
// }