Add some UI, major cleanup

This commit is contained in:
Sijmen 2021-05-29 22:49:12 +02:00
parent 4c27d26882
commit 3674f1020f
Signed by: vijfhoek
GPG key ID: 82D05C89B28B0DAE
7 changed files with 701 additions and 475 deletions

View file

@ -36,20 +36,10 @@ impl Chunk {
for (z, z_blocks) in y_blocks.iter().enumerate() {
for (x, block) in z_blocks.iter().enumerate() {
if let Some(block) = block {
let position = Vector3 {
x: x as f32,
y: y as f32,
z: z as f32,
};
let rotation = Quaternion::from_axis_angle(Vector3::unit_z(), Deg(0.0));
let position = Vector3::new(x as f32, y as f32, z as f32);
let instances = map.entry(block.block_type).or_default();
instances.push(Instance {
position,
rotation,
block_type: block.block_type,
position: position.into(),
});
}
}

View file

@ -1,64 +1,20 @@
use crate::chunk::BlockType;
#[derive(Debug)]
pub struct Instance {
pub position: cgmath::Vector3<f32>,
pub rotation: cgmath::Quaternion<f32>,
pub block_type: BlockType,
}
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub struct InstanceRaw {
model: [[f32; 4]; 4],
texture_index: u32,
pub struct Instance {
pub position: [f32; 3],
}
impl Instance {
pub fn to_raw(&self) -> InstanceRaw {
let position = cgmath::Matrix4::from_translation(self.position);
let rotation = cgmath::Matrix4::from(self.rotation);
InstanceRaw {
model: (position * rotation).into(),
texture_index: self.block_type.texture_index(),
}
}
}
impl InstanceRaw {
pub fn desc<'a>() -> wgpu::VertexBufferLayout<'a> {
use std::mem;
wgpu::VertexBufferLayout {
array_stride: mem::size_of::<InstanceRaw>() as wgpu::BufferAddress,
array_stride: mem::size_of::<Self>() as wgpu::BufferAddress,
step_mode: wgpu::InputStepMode::Instance,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 5,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 4]>() as wgpu::BufferAddress,
shader_location: 6,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 8]>() as wgpu::BufferAddress,
shader_location: 7,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 12]>() as wgpu::BufferAddress,
shader_location: 8,
format: wgpu::VertexFormat::Float32x4,
},
wgpu::VertexAttribute {
offset: mem::size_of::<[f32; 16]>() as wgpu::BufferAddress,
shader_location: 9,
format: wgpu::VertexFormat::Uint32,
},
],
attributes: &[wgpu::VertexAttribute {
offset: 0,
shader_location: 5,
format: wgpu::VertexFormat::Float32x3,
}],
}
}
}

View file

@ -8,6 +8,7 @@ mod state;
mod texture;
mod uniforms;
mod vertex;
mod world_state;
use std::time::Instant;
use winit::{
@ -95,7 +96,7 @@ fn main() {
match state.render() {
Ok(_) => {}
// Recreate the swap_chain if lost
Err(wgpu::SwapChainError::Lost) => state.resize(state.size),
Err(wgpu::SwapChainError::Lost) => state.resize(state.window_size),
// The system is out of memory, we should probably quit
Err(wgpu::SwapChainError::OutOfMemory) => *control_flow = ControlFlow::Exit,
// All other errors (Outdated, Timeout) should be resolved by the next frame

26
src/shaders/ui.wgsl Normal file
View file

@ -0,0 +1,26 @@
struct VertexInput {
[[location(0)]] position: vec3<f32>;
[[location(1)]] texture_coordinates: vec2<f32>;
[[location(2)]] normal: vec3<f32>;
};
struct VertexOutput {
[[builtin(position)]] clip_position: vec4<f32>;
[[location(0)]] texture_coordinates: vec2<f32>;
};
[[stage(vertex)]]
fn main(model: VertexInput) -> VertexOutput {
var out: VertexOutput;
out.texture_coordinates = model.texture_coordinates;
out.clip_position = vec4<f32>(model.position, 1.0);
return out;
}
[[group(0), binding(0)]] var sampler: sampler;
[[group(0), binding(1)]] var texture: texture_2d<f32>;
[[stage(fragment)]]
fn main(in: VertexOutput) -> [[location(0)]] vec4<f32> {
return textureSample(texture, sampler, in.texture_coordinates);
}

View file

@ -30,32 +30,17 @@ struct VertexOutput {
};
struct InstanceInput {
[[location(5)]] model_matrix_0: vec4<f32>;
[[location(6)]] model_matrix_1: vec4<f32>;
[[location(7)]] model_matrix_2: vec4<f32>;
[[location(8)]] model_matrix_3: vec4<f32>;
[[location(9)]] texture_index: u32;
[[location(5)]] position: vec3<f32>;
};
[[stage(vertex)]]
fn main(model: VertexInput, instance: InstanceInput) -> VertexOutput {
let model_matrix = mat4x4<f32>(
instance.model_matrix_0,
instance.model_matrix_1,
instance.model_matrix_2,
instance.model_matrix_3,
);
var out: VertexOutput;
out.texture_coordinates = model.texture_coordinates;
out.world_normal = model.normal;
var world_position: vec4<f32> = model_matrix * vec4<f32>(model.position, 1.0);
out.world_position = world_position.xyz;
out.clip_position = uniforms.view_projection * model_matrix * vec4<f32>(model.position, 1.0);
out.world_position = model.position + instance.position;
out.clip_position = uniforms.view_projection * vec4<f32>(out.world_position, 1.0);
return out;
}

View file

@ -1,92 +1,189 @@
use std::{
collections::HashMap,
time::{Duration, Instant},
};
use std::time::Duration;
use cgmath::{EuclideanSpace, InnerSpace, Rad};
use cgmath::{InnerSpace, Rad};
use wgpu::util::{BufferInitDescriptor, DeviceExt};
use winit::{
event::{DeviceEvent, ElementState, KeyboardInput, VirtualKeyCode},
window::Window,
};
use crate::{
camera::{Camera, Projection},
chunk::{Block, BlockType, Chunk},
cube,
instance::{Instance, InstanceRaw},
light::Light,
texture::Texture,
uniforms::Uniforms,
vertex::Vertex,
};
use crate::{cube, texture::Texture, vertex::Vertex, world_state::WorldState};
const UI_SCALE_X: f32 = 0.0045;
const UI_SCALE_Y: f32 = 0.008;
pub const CROSSHAIR_VERTICES: &[Vertex] = &[
// Crosshair
Vertex {
position: [-UI_SCALE_X * 8.0, UI_SCALE_Y * 8.0, 0.0],
texture_coordinates: [240.0 / 256.0, 0.0 / 256.0],
normal: [0.0, 0.0, 0.0],
},
Vertex {
position: [UI_SCALE_X * 8.0, UI_SCALE_Y * 8.0, 0.0],
texture_coordinates: [256.0 / 256.0, 0.0 / 256.0],
normal: [0.0, 0.0, 0.0],
},
Vertex {
position: [UI_SCALE_X * 8.0, -UI_SCALE_Y * 8.0, 0.0],
texture_coordinates: [256.0 / 256.0, 16.0 / 256.0],
normal: [0.0, 0.0, 0.0],
},
Vertex {
position: [-UI_SCALE_X * 8.0, -UI_SCALE_Y * 8.0, 0.0],
texture_coordinates: [240.0 / 256.0, 16.0 / 256.0],
normal: [0.0, 0.0, 0.0],
},
// Hotbar
Vertex {
position: [-UI_SCALE_X * 91.0, -1.0 + UI_SCALE_Y * 22.0, 0.0],
texture_coordinates: [0.0 / 256.0, 0.0 / 256.0],
normal: [0.0, 0.0, 0.0],
},
Vertex {
position: [UI_SCALE_X * 91.0, -1.0 + UI_SCALE_Y * 22.0, 0.0],
texture_coordinates: [182.0 / 256.0, 0.0 / 256.0],
normal: [0.0, 0.0, 0.0],
},
Vertex {
position: [UI_SCALE_X * 91.0, -1.0, 0.0],
texture_coordinates: [182.0 / 256.0, 22.0 / 256.0],
normal: [0.0, 0.0, 0.0],
},
Vertex {
position: [-UI_SCALE_X * 91.0, -1.0, 0.0],
texture_coordinates: [0.0 / 256.0, 22.0 / 256.0],
normal: [0.0, 0.0, 0.0],
},
];
#[rustfmt::skip]
pub const CROSSHAIR_INDICES: &[u16] = &[
1, 0, 3,
1, 3, 2,
5, 4, 7,
5, 7, 6,
];
pub struct State {
pub window_size: winit::dpi::PhysicalSize<u32>,
render_surface: wgpu::Surface,
render_device: wgpu::Device,
queue: wgpu::Queue,
render_queue: wgpu::Queue,
swap_chain_descriptor: wgpu::SwapChainDescriptor,
swap_chain: wgpu::SwapChain,
pub size: winit::dpi::PhysicalSize<u32>,
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
index_buffer: wgpu::Buffer,
texture_bind_groups: HashMap<BlockType, wgpu::BindGroup>,
uniform_bind_group: wgpu::BindGroup,
instance_lists: Vec<(BlockType, Vec<Instance>)>,
instance_buffers: Vec<(BlockType, wgpu::Buffer)>,
depth_texture: Texture,
_light: Light,
_light_buffer: wgpu::Buffer,
light_bind_group: wgpu::BindGroup,
world_state: WorldState,
ui_texture_bind_group_layout: wgpu::BindGroupLayout,
ui_texture_bind_group: wgpu::BindGroup,
ui_render_pipeline: wgpu::RenderPipeline,
ui_crosshair_vertex_buffer: wgpu::Buffer,
ui_crosshair_index_buffer: wgpu::Buffer,
right_speed: f32,
forward_speed: f32,
up_speed: f32,
camera: Camera,
uniforms: Uniforms,
projection: Projection,
uniform_buffer: wgpu::Buffer,
pub mouse_grabbed: bool,
}
impl State {
fn create_render_pipeline(
fn create_ui_textures(
render_device: &wgpu::Device,
render_queue: &wgpu::Queue,
) -> (wgpu::BindGroupLayout, wgpu::BindGroup) {
let texture = Texture::from_bytes(
render_device,
render_queue,
include_bytes!("../assets/gui/widgets.png"),
"Texture GUI widgets",
)
.unwrap();
let sampler = render_device.create_sampler(&wgpu::SamplerDescriptor {
mag_filter: wgpu::FilterMode::Nearest,
min_filter: wgpu::FilterMode::Linear,
..wgpu::SamplerDescriptor::default()
});
let bind_group_layout =
render_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("GUI texture bind group layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Sampler {
comparison: false,
filtering: true,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
],
});
let bind_group = render_device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("GUI texture bind group"),
layout: &bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Sampler(&sampler),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&texture.view),
},
],
});
(bind_group_layout, bind_group)
}
fn create_ui_render_pipeline(
render_device: &wgpu::Device,
swap_chain_descriptor: &wgpu::SwapChainDescriptor,
bind_group_layouts: &[&wgpu::BindGroupLayout],
) -> wgpu::RenderPipeline {
let shader = render_device.create_shader_module(
&(wgpu::ShaderModuleDescriptor {
label: Some("shader"),
flags: wgpu::ShaderFlags::all(),
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
}),
);
let module = &render_device.create_shader_module(&wgpu::ShaderModuleDescriptor {
label: Some("UI shader"),
flags: wgpu::ShaderFlags::all(),
source: wgpu::ShaderSource::Wgsl(include_str!("shaders/ui.wgsl").into()),
});
let render_pipeline_layout =
let pipeline_layout =
render_device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("render_pipeline_layout"),
label: Some("UI render pipeline layout"),
bind_group_layouts,
push_constant_ranges: &[],
});
render_device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: Some(&render_pipeline_layout),
label: Some("UI render pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
module,
entry_point: "main",
buffers: &[Vertex::desc(), InstanceRaw::desc()],
buffers: &[Vertex::desc()],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
module,
entry_point: "main",
targets: &[wgpu::ColorTargetState {
format: swap_chain_descriptor.format,
blend: Some(wgpu::BlendState {
alpha: wgpu::BlendComponent::REPLACE,
color: wgpu::BlendComponent::REPLACE,
}),
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrite::ALL,
}],
}),
@ -94,18 +191,12 @@ impl State {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: Some(wgpu::Face::Back),
cull_mode: None,
polygon_mode: wgpu::PolygonMode::Fill,
clamp_depth: false,
conservative: false,
},
depth_stencil: Some(wgpu::DepthStencilState {
format: Texture::DEPTH_FORMAT,
depth_write_enabled: true,
depth_compare: wgpu::CompareFunction::Less,
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
depth_stencil: None,
multisample: wgpu::MultisampleState {
count: 1,
mask: !0,
@ -161,350 +252,75 @@ impl State {
.unwrap(),
width: size.width,
height: size.height,
present_mode: wgpu::PresentMode::Fifo,
present_mode: wgpu::PresentMode::Immediate,
};
let swap_chain = render_device.create_swap_chain(&render_surface, &swap_chain_descriptor);
(swap_chain_descriptor, swap_chain)
}
fn create_textures(
render_device: &wgpu::Device,
queue: &wgpu::Queue,
) -> (wgpu::BindGroupLayout, HashMap<BlockType, wgpu::BindGroup>) {
let dirt_texture = Texture::from_bytes(
render_device,
queue,
include_bytes!("../assets/block/dirt.png"),
"dirt",
)
.unwrap();
let cobblestone_texture = Texture::from_bytes(
render_device,
queue,
include_bytes!("../assets/block/cobblestone.png"),
"cobblestone",
)
.unwrap();
let sampler = render_device.create_sampler(&wgpu::SamplerDescriptor::default());
let bind_group_layout =
render_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("texture_bind_group_layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Sampler {
comparison: false,
filtering: true,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
],
});
let bind_groups: HashMap<BlockType, wgpu::BindGroup> = [
(BlockType::Dirt, dirt_texture),
(BlockType::Cobblestone, cobblestone_texture),
]
.iter()
.map(|(block_type, texture)| {
(
*block_type,
render_device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("texture_bind_group"),
layout: &bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Sampler(&sampler),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&texture.view),
},
],
}),
)
})
.collect();
(bind_group_layout, bind_groups)
}
fn create_camera(swap_chain_descriptor: &wgpu::SwapChainDescriptor) -> (Camera, Projection) {
let camera = Camera::new(
(0.0, 5.0, 10.0).into(),
cgmath::Deg(0.0).into(),
cgmath::Deg(-20.0).into(),
);
let projection = Projection::new(
swap_chain_descriptor.width,
swap_chain_descriptor.height,
cgmath::Deg(45.0),
0.1,
100.0,
);
(camera, projection)
}
fn create_uniforms(
camera: &Camera,
projection: &Projection,
render_device: &wgpu::Device,
) -> (
Uniforms,
wgpu::Buffer,
wgpu::BindGroupLayout,
wgpu::BindGroup,
) {
let mut uniforms = Uniforms::new();
uniforms.update_view_projection(camera, projection);
let uniform_buffer = render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("uniform_buffer"),
contents: bytemuck::cast_slice(&[uniforms]),
usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
});
let uniform_bind_group_layout =
render_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
label: Some("uniform_bind_group_layout"),
});
let uniform_bind_group = render_device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &uniform_bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: uniform_buffer.as_entire_binding(),
}],
label: Some("uniform_bind_group"),
});
(
uniforms,
uniform_buffer,
uniform_bind_group_layout,
uniform_bind_group,
)
}
fn create_light(
render_device: &wgpu::Device,
) -> (Light, wgpu::Buffer, wgpu::BindGroupLayout, wgpu::BindGroup) {
let light = Light {
position: [5.0, 5.0, 5.0],
_padding: 0,
color: [1.0, 1.0, 1.0],
};
let light_buffer = render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("light_buffer"),
contents: bytemuck::cast_slice(&[light]),
usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
});
let light_bind_group_layout =
render_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
label: None,
});
let light_bind_group = render_device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &light_bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: light_buffer.as_entire_binding(),
}],
label: None,
});
(
light,
light_buffer,
light_bind_group_layout,
light_bind_group,
)
}
fn create_instances(
render_device: &wgpu::Device,
chunk: &Chunk,
) -> (
Vec<(BlockType, Vec<Instance>)>,
Vec<(BlockType, wgpu::Buffer)>,
) {
let instance_lists = chunk.to_instances();
let instance_buffers = instance_lists
.iter()
.map(|(block_type, instance_list)| {
let instance_data: Vec<InstanceRaw> =
instance_list.iter().map(Instance::to_raw).collect();
(
*block_type,
render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("instance_buffer"),
contents: bytemuck::cast_slice(&instance_data),
usage: wgpu::BufferUsage::VERTEX,
}),
)
})
.collect();
(instance_lists, instance_buffers)
}
pub async fn new(window: &Window) -> Self {
let size = window.inner_size();
let window_size = window.inner_size();
let mut chunk = Chunk {
blocks: [
[[Some(Block {
block_type: BlockType::Cobblestone,
}); 16]; 16],
[[Some(Block {
block_type: BlockType::Dirt,
}); 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
],
};
let (render_surface, adapter, render_device, queue) =
let (render_surface, render_adapter, render_device, render_queue) =
Self::create_render_device(window).await;
let (swap_chain_descriptor, swap_chain) =
Self::create_swap_chain(window, &adapter, &render_device, &render_surface);
Self::create_swap_chain(window, &render_adapter, &render_device, &render_surface);
let (texture_layout, texture_bind_groups) = Self::create_textures(&render_device, &queue);
let world_state = WorldState::new(&render_device, &render_queue, &swap_chain_descriptor);
let (camera, projection) = Self::create_camera(&swap_chain_descriptor);
let (ui_texture_bind_group_layout, ui_texture_bind_group) =
Self::create_ui_textures(&render_device, &render_queue);
let ui_render_pipeline = Self::create_ui_render_pipeline(
&render_device,
&swap_chain_descriptor,
&[&ui_texture_bind_group_layout],
);
let pointy_at = chunk
.dda(camera.position.to_vec(), camera.direction())
.unwrap();
chunk.blocks[pointy_at.y][pointy_at.z][pointy_at.x] = Some(Block {
block_type: BlockType::Cobblestone,
});
let (uniforms, uniform_buffer, uniform_layout, uniform_bind_group) =
Self::create_uniforms(&camera, &projection, &render_device);
let (light, light_buffer, light_layout, light_bind_group) =
Self::create_light(&render_device);
let layouts = [&texture_layout, &uniform_layout, &light_layout];
let render_pipeline =
Self::create_render_pipeline(&render_device, &swap_chain_descriptor, &layouts);
let vertex_buffer = render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("vertex_buffer"),
contents: bytemuck::cast_slice(cube::VERTICES),
let ui_crosshair_vertex_buffer = render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("GUI crosshair vertex buffer"),
contents: bytemuck::cast_slice(CROSSHAIR_VERTICES),
usage: wgpu::BufferUsage::VERTEX,
});
let index_buffer = render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("index_buffer"),
contents: bytemuck::cast_slice(cube::INDICES),
let ui_crosshair_index_buffer = render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("GUI crosshair index buffer"),
contents: bytemuck::cast_slice(CROSSHAIR_INDICES),
usage: wgpu::BufferUsage::INDEX,
});
let (instance_lists, instance_buffers) = Self::create_instances(&render_device, &chunk);
let depth_texture =
Texture::create_depth_texture(&render_device, &swap_chain_descriptor, "depth_texture");
Self {
window_size,
render_surface,
render_device,
queue,
render_queue,
swap_chain_descriptor,
swap_chain,
size,
render_pipeline,
vertex_buffer,
index_buffer,
uniforms,
uniform_buffer,
uniform_bind_group,
texture_bind_groups,
camera,
projection,
instance_lists,
instance_buffers,
depth_texture,
_light: light,
_light_buffer: light_buffer,
light_bind_group,
mouse_grabbed: false,
world_state,
ui_render_pipeline,
ui_texture_bind_group,
ui_texture_bind_group_layout,
ui_crosshair_vertex_buffer,
ui_crosshair_index_buffer,
right_speed: 0.0,
forward_speed: 0.0,
up_speed: 0.0,
mouse_grabbed: false,
}
}
pub fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
println!("resizing to {:?}", new_size);
self.size = new_size;
self.window_size = new_size;
self.swap_chain_descriptor.width = new_size.width;
self.swap_chain_descriptor.height = new_size.height;
self.projection.resize(new_size.width, new_size.height);
self.depth_texture = Texture::create_depth_texture(
&self.render_device,
&self.swap_chain_descriptor,
"depth_texture",
);
self.world_state
.resize(&self.render_device, &self.swap_chain_descriptor, new_size);
self.swap_chain = self
.render_device
@ -530,13 +346,13 @@ impl State {
}
fn update_camera(&mut self, dx: f64, dy: f64) {
self.camera.yaw += Rad(dx as f32 * 0.005);
self.camera.pitch -= Rad(dy as f32 * 0.005);
self.world_state.camera.yaw += Rad(dx as f32 * 0.003);
self.world_state.camera.pitch -= Rad(dy as f32 * 0.003);
if self.camera.pitch < Rad::from(cgmath::Deg(-80.0)) {
self.camera.pitch = Rad::from(cgmath::Deg(-80.0));
} else if self.camera.pitch > Rad::from(cgmath::Deg(89.0)) {
self.camera.pitch = Rad::from(cgmath::Deg(89.0));
if self.world_state.camera.pitch < Rad::from(cgmath::Deg(-80.0)) {
self.world_state.camera.pitch = Rad::from(cgmath::Deg(-80.0));
} else if self.world_state.camera.pitch > Rad::from(cgmath::Deg(89.9)) {
self.world_state.camera.pitch = Rad::from(cgmath::Deg(89.9));
}
}
@ -565,23 +381,24 @@ impl State {
let dt_secs = dt.as_secs_f32();
// Move forward/backward and left/right
let (yaw_sin, yaw_cos) = self.camera.yaw.0.sin_cos();
let (yaw_sin, yaw_cos) = self.world_state.camera.yaw.0.sin_cos();
let forward = cgmath::Vector3::new(yaw_cos, 0.0, yaw_sin).normalize();
self.camera.position += forward * self.forward_speed * 6.0 * dt_secs;
self.world_state.camera.position += forward * self.forward_speed * 6.0 * dt_secs;
let right = cgmath::Vector3::new(-yaw_sin, 0.0, yaw_cos).normalize();
self.camera.position += right * self.right_speed * 6.0 * dt_secs;
self.world_state.camera.position += right * self.right_speed * 6.0 * dt_secs;
let up = cgmath::Vector3::new(0.0, 1.0, 0.0).normalize();
self.camera.position += up * self.up_speed * 6.0 * dt_secs;
self.world_state.camera.position += up * self.up_speed * 6.0 * dt_secs;
self.uniforms
.update_view_projection(&self.camera, &self.projection);
self.queue.write_buffer(
&self.uniform_buffer,
self.world_state
.uniforms
.update_view_projection(&self.world_state.camera, &self.world_state.projection);
self.render_queue.write_buffer(
&self.world_state.uniform_buffer,
0,
bytemuck::cast_slice(&[self.uniforms]),
bytemuck::cast_slice(&[self.world_state.uniforms]),
);
}
@ -606,7 +423,7 @@ impl State {
},
}],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth_texture.view,
view: &self.world_state.depth_texture.view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: true,
@ -615,18 +432,23 @@ impl State {
}),
});
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_pipeline(&self.world_state.render_pipeline);
render_pass.set_bind_group(1, &self.uniform_bind_group, &[]);
render_pass.set_bind_group(2, &self.light_bind_group, &[]);
render_pass.set_bind_group(1, &self.world_state.uniform_bind_group, &[]);
render_pass.set_bind_group(2, &self.world_state.light_bind_group, &[]);
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
render_pass.set_vertex_buffer(0, self.world_state.vertex_buffer.slice(..));
render_pass.set_index_buffer(
self.world_state.index_buffer.slice(..),
wgpu::IndexFormat::Uint16,
);
for (i, (block_type, instance_list)) in self.instance_lists.iter().enumerate() {
let (_, instance_buffer) = &self.instance_buffers[i];
for (i, (block_type, instance_list)) in
self.world_state.instance_lists.iter().enumerate()
{
let (_, instance_buffer) = &self.world_state.instance_buffers[i];
let texture_bind_group = &self.texture_bind_groups[block_type];
let texture_bind_group = &self.world_state.texture_bind_groups[block_type];
render_pass.set_bind_group(0, texture_bind_group, &[]);
render_pass.set_vertex_buffer(1, instance_buffer.slice(..));
@ -638,7 +460,33 @@ impl State {
}
}
self.queue.submit(std::iter::once(render_encoder.finish()));
{
let mut render_pass = render_encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("render_pass"),
color_attachments: &[wgpu::RenderPassColorAttachment {
view: &frame.view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: true,
},
}],
depth_stencil_attachment: None,
});
render_pass.set_pipeline(&self.ui_render_pipeline);
render_pass.set_vertex_buffer(0, self.ui_crosshair_vertex_buffer.slice(..));
render_pass.set_index_buffer(
self.ui_crosshair_index_buffer.slice(..),
wgpu::IndexFormat::Uint16,
);
render_pass.set_bind_group(0, &self.ui_texture_bind_group, &[]);
render_pass.draw_indexed(0..CROSSHAIR_INDICES.len() as u32, 0, 0..1);
}
self.render_queue
.submit(std::iter::once(render_encoder.finish()));
Ok(())
}

420
src/world_state.rs Normal file
View file

@ -0,0 +1,420 @@
use std::collections::HashMap;
use cgmath::EuclideanSpace;
use wgpu::util::{BufferInitDescriptor, DeviceExt};
use winit::dpi::PhysicalSize;
use crate::{
camera::{Camera, Projection},
chunk::{Block, BlockType, Chunk},
cube,
instance::Instance,
light::Light,
texture::Texture,
uniforms::Uniforms,
vertex::Vertex,
};
pub struct WorldState {
pub render_pipeline: wgpu::RenderPipeline,
pub uniforms: Uniforms,
pub uniform_buffer: wgpu::Buffer,
pub uniform_bind_group: wgpu::BindGroup,
pub texture_bind_groups: HashMap<BlockType, wgpu::BindGroup>,
pub camera: Camera,
pub projection: Projection,
pub instance_lists: Vec<(BlockType, Vec<Instance>)>,
pub vertex_buffer: wgpu::Buffer,
pub index_buffer: wgpu::Buffer,
pub instance_buffers: Vec<(BlockType, wgpu::Buffer)>,
pub depth_texture: Texture,
pub light_bind_group: wgpu::BindGroup,
}
impl WorldState {
fn create_textures(
render_device: &wgpu::Device,
render_queue: &wgpu::Queue,
) -> (wgpu::BindGroupLayout, HashMap<BlockType, wgpu::BindGroup>) {
let dirt_texture = Texture::from_bytes(
render_device,
render_queue,
include_bytes!("../assets/block/dirt.png"),
"dirt",
)
.unwrap();
let cobblestone_texture = Texture::from_bytes(
render_device,
render_queue,
include_bytes!("../assets/block/cobblestone.png"),
"cobblestone",
)
.unwrap();
let sampler = render_device.create_sampler(&wgpu::SamplerDescriptor::default());
let bind_group_layout =
render_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("texture_bind_group_layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Sampler {
comparison: false,
filtering: true,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
],
});
let bind_groups: HashMap<BlockType, wgpu::BindGroup> = [
(BlockType::Dirt, dirt_texture),
(BlockType::Cobblestone, cobblestone_texture),
]
.iter()
.map(|(block_type, texture)| {
(
*block_type,
render_device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("texture_bind_group"),
layout: &bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Sampler(&sampler),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&texture.view),
},
],
}),
)
})
.collect();
(bind_group_layout, bind_groups)
}
fn create_camera(swap_chain_descriptor: &wgpu::SwapChainDescriptor) -> (Camera, Projection) {
let camera = Camera::new(
(0.0, 5.0, 10.0).into(),
cgmath::Deg(0.0).into(),
cgmath::Deg(-20.0).into(),
);
let projection = Projection::new(
swap_chain_descriptor.width,
swap_chain_descriptor.height,
cgmath::Deg(45.0),
0.1,
100.0,
);
(camera, projection)
}
fn create_uniforms(
camera: &Camera,
projection: &Projection,
render_device: &wgpu::Device,
) -> (
Uniforms,
wgpu::Buffer,
wgpu::BindGroupLayout,
wgpu::BindGroup,
) {
let mut uniforms = Uniforms::new();
uniforms.update_view_projection(camera, projection);
let uniform_buffer = render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("uniform_buffer"),
contents: bytemuck::cast_slice(&[uniforms]),
usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
});
let uniform_bind_group_layout =
render_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
label: Some("uniform_bind_group_layout"),
});
let uniform_bind_group = render_device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &uniform_bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: uniform_buffer.as_entire_binding(),
}],
label: Some("uniform_bind_group"),
});
(
uniforms,
uniform_buffer,
uniform_bind_group_layout,
uniform_bind_group,
)
}
fn create_light(
render_device: &wgpu::Device,
) -> (Light, wgpu::Buffer, wgpu::BindGroupLayout, wgpu::BindGroup) {
let light = Light {
position: [5.0, 5.0, 5.0],
_padding: 0,
color: [1.0, 1.0, 1.0],
};
let light_buffer = render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("light_buffer"),
contents: bytemuck::cast_slice(&[light]),
usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
});
let light_bind_group_layout =
render_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
label: None,
});
let light_bind_group = render_device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &light_bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: light_buffer.as_entire_binding(),
}],
label: None,
});
(
light,
light_buffer,
light_bind_group_layout,
light_bind_group,
)
}
fn create_render_pipeline(
render_device: &wgpu::Device,
swap_chain_descriptor: &wgpu::SwapChainDescriptor,
bind_group_layouts: &[&wgpu::BindGroupLayout],
) -> wgpu::RenderPipeline {
let shader = render_device.create_shader_module(
&(wgpu::ShaderModuleDescriptor {
label: Some("shader"),
flags: wgpu::ShaderFlags::all(),
source: wgpu::ShaderSource::Wgsl(include_str!("shaders/world.wgsl").into()),
}),
);
let render_pipeline_layout =
render_device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("render_pipeline_layout"),
bind_group_layouts,
push_constant_ranges: &[],
});
render_device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "main",
buffers: &[Vertex::desc(), Instance::desc()],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "main",
targets: &[wgpu::ColorTargetState {
format: swap_chain_descriptor.format,
blend: Some(wgpu::BlendState {
alpha: wgpu::BlendComponent::REPLACE,
color: wgpu::BlendComponent::REPLACE,
}),
write_mask: wgpu::ColorWrite::ALL,
}],
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: Some(wgpu::Face::Back),
polygon_mode: wgpu::PolygonMode::Fill,
clamp_depth: false,
conservative: false,
},
depth_stencil: Some(wgpu::DepthStencilState {
format: Texture::DEPTH_FORMAT,
depth_write_enabled: true,
depth_compare: wgpu::CompareFunction::Less,
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
multisample: wgpu::MultisampleState {
count: 1,
mask: !0,
alpha_to_coverage_enabled: false,
},
})
}
fn create_instances(
render_device: &wgpu::Device,
chunk: &Chunk,
) -> (
Vec<(BlockType, Vec<Instance>)>,
Vec<(BlockType, wgpu::Buffer)>,
) {
let instance_lists = chunk.to_instances();
let instance_buffers = instance_lists
.iter()
.map(|(block_type, instance_list)| {
(
*block_type,
render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("instance_buffer"),
contents: bytemuck::cast_slice(&instance_list),
usage: wgpu::BufferUsage::VERTEX,
}),
)
})
.collect();
(instance_lists, instance_buffers)
}
pub fn new(
render_device: &wgpu::Device,
queue: &wgpu::Queue,
swap_chain_descriptor: &wgpu::SwapChainDescriptor,
) -> WorldState {
let mut chunk = Chunk {
blocks: [
[[Some(Block {
block_type: BlockType::Cobblestone,
}); 16]; 16],
[[Some(Block {
block_type: BlockType::Dirt,
}); 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
[[None; 16]; 16],
],
};
let (world_texture_layout, texture_bind_groups) =
Self::create_textures(&render_device, &queue);
let (camera, projection) = Self::create_camera(&swap_chain_descriptor);
let pointy_at = chunk
.dda(camera.position.to_vec(), camera.direction())
.unwrap();
chunk.blocks[pointy_at.y][pointy_at.z][pointy_at.x] = Some(Block {
block_type: BlockType::Cobblestone,
});
let (uniforms, uniform_buffer, world_uniform_layout, uniform_bind_group) =
Self::create_uniforms(&camera, &projection, &render_device);
let (_, _, world_light_layout, light_bind_group) = Self::create_light(&render_device);
let render_pipeline = Self::create_render_pipeline(
&render_device,
&swap_chain_descriptor,
&[
&world_texture_layout,
&world_uniform_layout,
&world_light_layout,
],
);
let vertex_buffer = render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("vertex_buffer"),
contents: bytemuck::cast_slice(cube::VERTICES),
usage: wgpu::BufferUsage::VERTEX,
});
let index_buffer = render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("index_buffer"),
contents: bytemuck::cast_slice(cube::INDICES),
usage: wgpu::BufferUsage::INDEX,
});
let (instance_lists, instance_buffers) = Self::create_instances(&render_device, &chunk);
let depth_texture =
Texture::create_depth_texture(&render_device, &swap_chain_descriptor, "depth_texture");
WorldState {
render_pipeline,
uniforms,
uniform_buffer,
uniform_bind_group,
texture_bind_groups,
camera,
projection,
light_bind_group,
vertex_buffer,
index_buffer,
instance_lists,
instance_buffers,
depth_texture,
}
}
pub fn resize(
&mut self,
render_device: &wgpu::Device,
swap_chain_descriptor: &wgpu::SwapChainDescriptor,
new_size: PhysicalSize<u32>,
) {
self.projection.resize(new_size.width, new_size.height);
self.depth_texture =
Texture::create_depth_texture(render_device, swap_chain_descriptor, "depth_texture");
}
}