Compare commits

..

No commits in common. "786fff5a6d4ed82785d004adef964adb30de7f65" and "cb64d94c094ac14630091049333778606e8be40e" have entirely different histories.

12 changed files with 354 additions and 415 deletions

View File

@ -1,5 +1,5 @@
use cgmath::{Rotation3, Vector3}; use cgmath::{Rotation3, Vector3};
use solar_engine::{Application, Body, GpuMaterial, InputEvent, Key, Light, MouseButton, RenderInstance, Shape, Simulator, SubInstance}; use solar_engine::{Application, Body, InputEvent, Key, Light, MouseButton, RenderInstance, Shape, Simulator};
use std::sync::{Arc, RwLock}; use std::sync::{Arc, RwLock};
use std::thread; use std::thread;
@ -66,54 +66,26 @@ pub async fn run() {
state.light_manager.add_light(Light::new_point( state.light_manager.add_light(Light::new_point(
sun_pos.cast::<f32>().unwrap(), sun_pos.cast::<f32>().unwrap(),
Vector3::from([1.0, 1.0, 0.8]), Vector3::from([1.0, 1.0, 0.8]),
1.0, 5.0,
1.0 / 1000.0, 1.0 / 1000.0,
)); ));
let sun_material = GpuMaterial::new(
[1.0, 1.0, 0.0, 1.0],
[1.0, 1.0, 0.01],
5.0,
);
let earth_material = GpuMaterial::new(
[0.0, 0.0, 1.0, 1.0],
[0.0, 0.0, 0.0],
1.0
);
let default_material = GpuMaterial::new(
[0.5, 0.5, 0.5, 1.0],
[0.0, 0.0, 0.0],
1.0
);
state.set_materials(vec![
sun_material,
earth_material,
default_material,
]);
let instances = bodies let instances = bodies
.iter() .iter()
.enumerate() .enumerate()
.map(|(i, b)| { .map(|(i, b)| {
let material_id = match i {
0 => 0,
1 => 1,
_ => 2,
};
RenderInstance { RenderInstance {
position: ((b.position / 1.496e11) - sun_pos).cast::<f32>().unwrap(), position: ((b.position / 1.496e11) - sun_pos).cast::<f32>().unwrap(),
rotation: cgmath::Quaternion::from_angle_z(cgmath::Deg(0.0)), rotation: cgmath::Quaternion::from_angle_z(cgmath::Deg(0.0)),
color: match i {
0 => [1.0, 1.0, 0.0], // Sun
1 => [0.0, 0.0, 1.0], // Earth
_ => [0.5, 0.5, 0.5],
},
scale: 0.05, scale: 0.05,
submeshes: vec![ shape: Shape::Sphere,
SubInstance { always_lit: i == 0, // Sun
shape: Shape::Sphere, is_transparent: false,
material_id,
}
],
} }
}) })
.collect(); .collect();

View File

@ -5,10 +5,10 @@ use winit::window::{Window, WindowId};
use crate::input::{InputEvent, InputTracker}; use crate::input::{InputEvent, InputTracker};
pub struct StateApplication<'a> { pub struct StateApplication<'a> {
state: Option<crate::engine_state::EngineState<'a>>, state: Option<crate::state::State<'a>>,
modifiers: Modifiers, modifiers: Modifiers,
update_fn: Option<Box<dyn FnMut(&mut crate::engine_state::EngineState<'a>) + 'a>>, update_fn: Option<Box<dyn FnMut(&mut crate::state::State<'a>) + 'a>>,
input_fn: Option<Box<dyn FnMut(&mut crate::engine_state::EngineState<'a>, &InputEvent) + 'a>>, input_fn: Option<Box<dyn FnMut(&mut crate::state::State<'a>, &InputEvent) + 'a>>,
input_tracker: InputTracker input_tracker: InputTracker
} }
@ -17,12 +17,12 @@ impl<'a> StateApplication<'a> {
Self { state: None, update_fn: None, input_fn: None, modifiers: Modifiers::default(), input_tracker: InputTracker::default() } Self { state: None, update_fn: None, input_fn: None, modifiers: Modifiers::default(), input_tracker: InputTracker::default() }
} }
pub fn on_update<F: FnMut(&mut crate::engine_state::EngineState<'a>) + 'a>(mut self, func: F) -> Self { pub fn on_update<F: FnMut(&mut crate::state::State<'a>) + 'a>(mut self, func: F) -> Self {
self.update_fn = Some(Box::new(func)); self.update_fn = Some(Box::new(func));
self self
} }
pub fn on_input<F: FnMut(&mut crate::engine_state::EngineState<'a>, &InputEvent) + 'a>(mut self, func: F) -> Self { pub fn on_input<F: FnMut(&mut crate::state::State<'a>, &InputEvent) + 'a>(mut self, func: F) -> Self {
self.input_fn = Some(Box::new(func)); self.input_fn = Some(Box::new(func));
self self
} }
@ -38,7 +38,7 @@ impl<'a> ApplicationHandler for StateApplication<'a> {
let window = event_loop let window = event_loop
.create_window(Window::default_attributes().with_title("Solar Engine")) .create_window(Window::default_attributes().with_title("Solar Engine"))
.unwrap(); .unwrap();
self.state = Some(crate::engine_state::EngineState::new(window)); self.state = Some(crate::state::State::new(window));
} }
fn window_event( fn window_event(
@ -58,11 +58,8 @@ impl<'a> ApplicationHandler for StateApplication<'a> {
self.state.as_mut().unwrap().resize(physical_size); self.state.as_mut().unwrap().resize(physical_size);
} }
WindowEvent::RedrawRequested => { WindowEvent::RedrawRequested => {
if let Some(state) = self.state.as_mut() { if let (Some(state), Some(update_fn)) = (self.state.as_mut(), self.update_fn.as_mut()) {
state.update(); update_fn(state);
if let Some(update_fn) = self.update_fn.as_mut() {
update_fn(state);
}
} }
self.state.as_mut().unwrap().render().unwrap(); self.state.as_mut().unwrap().render().unwrap();

View File

@ -1,7 +1,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use wgpu::{Device, Buffer}; use wgpu::{Device, Buffer};
use wgpu::util::DeviceExt; use wgpu::util::DeviceExt;
use crate::render_manager::Vertex; use crate::renderer::Vertex;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Shape { pub enum Shape {
@ -24,19 +24,21 @@ impl GeometryManager {
let mut geometries = HashMap::new(); let mut geometries = HashMap::new();
// Circle // Circle
let (circle_vertices, circle_indices) = generate_circle_mesh(512, 0.5); let (circle_vertices, circle_indices) = create_circle_vertices(512, 0.5, [0.5, 0.5, 0.5]);
geometries.insert( geometries.insert(
Shape::Circle, Shape::Circle,
Self::create_geometry(device, &circle_vertices, &circle_indices), Self::create_geometry(device, &circle_vertices, &circle_indices),
); );
// Sphere // Sphere
let (sphere_vertices, sphere_indices) = generate_sphere_mesh(32, 32, 0.5); let (sphere_vertices, sphere_indices) = create_sphere_vertices(32, 32, 0.5, [0.5, 0.5, 0.5]);
geometries.insert( geometries.insert(
Shape::Sphere, Shape::Sphere,
Self::create_geometry(device, &sphere_vertices, &sphere_indices), Self::create_geometry(device, &sphere_vertices, &sphere_indices),
); );
// Füge hier beliebige weitere Shapes hinzu
Self { geometries } Self { geometries }
} }
@ -69,10 +71,10 @@ impl GeometryManager {
} }
} }
pub fn generate_circle_mesh(segment_count: usize, radius: f32) -> (Vec<Vertex>, Vec<u16>) { pub fn create_circle_vertices(segment_count: usize, radius: f32, color: [f32; 3]) -> (Vec<Vertex>, Vec<u16>) {
let mut vertices = vec![Vertex { let mut vertices = vec![Vertex {
position: [0.0, 0.0, 0.0], position: [0.0, 0.0, 0.0],
color: [1.0, 1.0, 1.0], color,
normal: [0.0, 0.0, 1.0], normal: [0.0, 0.0, 1.0],
}]; }];
let mut indices = vec![]; let mut indices = vec![];
@ -83,7 +85,7 @@ pub fn generate_circle_mesh(segment_count: usize, radius: f32) -> (Vec<Vertex>,
let y = radius * theta.sin(); let y = radius * theta.sin();
vertices.push(Vertex { vertices.push(Vertex {
position: [x, y, 0.0], position: [x, y, 0.0],
color: [1.0, 1.0, 1.0], color,
normal: [0.0, 0.0, 1.0], normal: [0.0, 0.0, 1.0],
}); });
} }
@ -97,7 +99,7 @@ pub fn generate_circle_mesh(segment_count: usize, radius: f32) -> (Vec<Vertex>,
(vertices, indices) (vertices, indices)
} }
pub fn generate_sphere_mesh(stacks: usize, slices: usize, radius: f32) -> (Vec<Vertex>, Vec<u16>) { pub fn create_sphere_vertices(stacks: usize, slices: usize, radius: f32, color: [f32; 3]) -> (Vec<Vertex>, Vec<u16>) {
let mut vertices = Vec::new(); let mut vertices = Vec::new();
let mut indices = Vec::new(); let mut indices = Vec::new();
@ -111,10 +113,12 @@ pub fn generate_sphere_mesh(stacks: usize, slices: usize, radius: f32) -> (Vec<V
let x = r * theta.cos(); let x = r * theta.cos();
let z = r * theta.sin(); let z = r * theta.sin();
let normal = [x, y, z];
vertices.push(Vertex { vertices.push(Vertex {
position: [x * radius, y * radius, z * radius], position: [x * radius, y * radius, z * radius],
color: [1.0, 1.0, 1.0], color,
normal: [x, y, z], normal,
}); });
} }
} }

View File

@ -8,25 +8,25 @@ use wgpu::util::DeviceExt;
pub struct GlobalsUniform { pub struct GlobalsUniform {
pub view_proj: [[f32; 4]; 4], pub view_proj: [[f32; 4]; 4],
pub resolution: [f32; 2], pub resolution: [f32; 2],
_pad: [u32; 2], _padding: [f32; 2],
} }
pub struct GlobalsManager { pub struct GlobalsManager {
pub buffer: Buffer, buffer: Buffer,
pub bind_group: BindGroup, pub(crate) bind_group: BindGroup,
pub layout: BindGroupLayout, layout: BindGroupLayout,
pub resolution: [f32; 2], resolution: [f32; 2],
} }
impl GlobalsManager { impl GlobalsManager {
pub fn new(device: &Device, width: u32, height: u32, camera: &Camera) -> Self { pub fn new(device: &Device, width: u32, height: u32, camera: &Camera) -> Self {
let resolution = [width as f32, height as f32]; let resolution = [width as f32, height as f32];
let view_proj = camera.build_view_projection_matrix(); let view_proj = camera.build_view_projection_matrix();
let data = GlobalsUniform { let data = GlobalsUniform {
view_proj: view_proj.into(), view_proj: view_proj.into(),
resolution, resolution,
_pad: [0; 2], _padding: [0.0; 2],
}; };
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
@ -66,18 +66,29 @@ impl GlobalsManager {
} }
} }
pub fn update(&self, queue: &Queue, camera: &Camera) { pub fn update(&mut self, queue: &Queue, camera: &Camera) {
let view_proj = camera.build_view_projection_matrix(); let view_proj = camera.build_view_projection_matrix();
let data = GlobalsUniform { let data = GlobalsUniform {
view_proj: view_proj.into(), view_proj: view_proj.into(),
resolution: self.resolution, resolution: self.resolution,
_pad: [0; 2], _padding: [0.0; 2],
}; };
queue.write_buffer(&self.buffer, 0, bytemuck::cast_slice(&[data])); queue.write_buffer(&self.buffer, 0, bytemuck::cast_slice(&[data]));
} }
pub fn resize(&mut self, queue: &Queue, width: u32, height: u32, camera: &Camera) { pub fn resize(&mut self, width: u32, height: u32) {
self.resolution = [width as f32, height as f32]; self.resolution = [width as f32, height as f32];
self.update(queue, camera); }
pub fn layout(&self) -> &BindGroupLayout {
&self.layout
}
pub fn bind_group(&self) -> &BindGroup {
&self.bind_group
}
pub fn resolution(&self) -> [f32; 2] {
self.resolution
} }
} }

View File

@ -1,63 +1,12 @@
use std::collections::HashMap;
use std::mem::size_of;
use wgpu::{Buffer, Device, Queue}; use wgpu::{Buffer, Device, Queue};
use wgpu::util::DeviceExt; use wgpu::util::DeviceExt;
use std::mem::size_of;
use crate::geometry_manager::Shape; use crate::geometry_manager::Shape;
use crate::renderer::{InstanceRaw, RenderInstance};
pub struct SubInstance {
pub shape: Shape,
pub material_id: u32,
}
pub struct RenderInstance {
pub position: cgmath::Vector3<f32>,
pub rotation: cgmath::Quaternion<f32>,
pub scale: f32,
pub submeshes: Vec<SubInstance>,
}
impl RenderInstance {
pub fn to_raws(&self) -> Vec<InstanceRaw> {
let model = cgmath::Matrix4::from_translation(self.position)
* cgmath::Matrix4::from(self.rotation)
* cgmath::Matrix4::from_scale(self.scale);
self.submeshes
.iter()
.map(|sub| InstanceRaw {
model: model.into(),
material_id: sub.material_id,
})
.collect()
}
}
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub struct InstanceRaw {
pub model: [[f32; 4]; 4],
pub material_id: u32,
}
impl InstanceRaw {
pub fn desc<'a>() -> wgpu::VertexBufferLayout<'a> {
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &[
wgpu::VertexAttribute { offset: 0, shader_location: 5, format: wgpu::VertexFormat::Float32x4 },
wgpu::VertexAttribute { offset: 16, shader_location: 6, format: wgpu::VertexFormat::Float32x4 },
wgpu::VertexAttribute { offset: 32, shader_location: 7, format: wgpu::VertexFormat::Float32x4 },
wgpu::VertexAttribute { offset: 48, shader_location: 8, format: wgpu::VertexFormat::Float32x4 },
wgpu::VertexAttribute { offset: 64, shader_location: 9, format: wgpu::VertexFormat::Uint32 },
],
}
}
}
pub struct InstanceManager { pub struct InstanceManager {
instances: Vec<RenderInstance>, instances: Vec<RenderInstance>,
raw_by_shape: HashMap<Shape, Vec<InstanceRaw>>, raw: Vec<InstanceRaw>,
buffer: Buffer, buffer: Buffer,
} }
@ -72,50 +21,35 @@ impl InstanceManager {
Self { Self {
instances: Vec::new(), instances: Vec::new(),
raw_by_shape: HashMap::new(), raw: Vec::new(),
buffer, buffer,
} }
} }
pub fn set_instances(&mut self, device: &Device, queue: &Queue, instances: Vec<RenderInstance>) { pub fn set_instances(&mut self, device: &Device, queue: &Queue, instances: Vec<RenderInstance>) {
let mut raw_by_shape: HashMap<Shape, Vec<InstanceRaw>> = HashMap::new(); self.raw = instances.iter().map(RenderInstance::to_raw).collect();
let byte_len = (self.raw.len() * size_of::<InstanceRaw>()) as wgpu::BufferAddress;
for instance in &instances {
let model = cgmath::Matrix4::from_translation(instance.position)
* cgmath::Matrix4::from(instance.rotation)
* cgmath::Matrix4::from_scale(instance.scale);
for sub in &instance.submeshes {
raw_by_shape
.entry(sub.shape)
.or_default()
.push(InstanceRaw {
model: model.into(),
material_id: sub.material_id,
});
}
}
let all_raws: Vec<InstanceRaw> =
raw_by_shape.values().flat_map(|v| v.iter().copied()).collect();
let byte_len = (all_raws.len() * size_of::<InstanceRaw>()) as wgpu::BufferAddress;
if byte_len > self.buffer.size() { if byte_len > self.buffer.size() {
self.buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { self.buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Instance Buffer (resized)"), label: Some("Instance Buffer (resized)"),
contents: bytemuck::cast_slice(&all_raws), contents: bytemuck::cast_slice(&self.raw),
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
}); });
} else { } else {
queue.write_buffer(&self.buffer, 0, bytemuck::cast_slice(&all_raws)); queue.write_buffer(&self.buffer, 0, bytemuck::cast_slice(&self.raw));
} }
self.instances = instances; self.instances = instances;
self.raw_by_shape = raw_by_shape;
} }
pub fn raw_instances_for_shape(&self, shape: Shape) -> &[InstanceRaw] { pub fn raw_instances_for_shape(&self, shape: Shape) -> Vec<&InstanceRaw> {
self.raw_by_shape.get(&shape).map_or(&[], |v| v.as_slice()) self.instances
.iter()
.zip(self.raw.iter())
.filter(|(inst, _)| inst.shape == shape)
.map(|(_, raw)| raw)
.collect()
} }
pub fn buffer(&self) -> &Buffer { pub fn buffer(&self) -> &Buffer {

View File

@ -1,15 +1,15 @@
mod body; mod body;
mod simulator; mod simulator;
mod engine_state; mod state;
mod application; mod application;
mod input; mod input;
mod camera; mod camera;
mod light_manager; mod light;
mod render_manager; mod renderer;
mod instance_manager; mod instance_manager;
mod globals_manager; mod globals;
mod geometry_manager; mod geometry_manager;
mod material_manager; mod material;
pub use body::Body; pub use body::Body;
@ -18,15 +18,12 @@ pub use simulator::distance_squared;
pub use application::StateApplication as Application; pub use application::StateApplication as Application;
pub use engine_state::EngineState; pub use state::State;
pub use instance_manager::RenderInstance; pub use renderer::RenderInstance;
pub use instance_manager::SubInstance;
pub use material_manager::GpuMaterial; pub use light::Light;
pub use light::LightType;
pub use light_manager::Light;
pub use light_manager::LightType;
pub use geometry_manager::Shape; pub use geometry_manager::Shape;

View File

@ -73,8 +73,8 @@ impl Light {
pub struct LightManager { pub struct LightManager {
pub lights: Vec<Light>, pub lights: Vec<Light>,
pub buffer: wgpu::Buffer, pub buffer: wgpu::Buffer,
pub count_buffer: wgpu::Buffer,
pub bind_group: wgpu::BindGroup, pub bind_group: wgpu::BindGroup,
pub count_buffer: wgpu::Buffer,
pub layout: wgpu::BindGroupLayout, pub layout: wgpu::BindGroupLayout,
pub cluster_buffers: Option<ClusterBuffers>, pub cluster_buffers: Option<ClusterBuffers>,
} }
@ -183,10 +183,12 @@ impl LightManager {
queue.write_buffer(&self.count_buffer, 0, bytemuck::bytes_of(&count)); queue.write_buffer(&self.count_buffer, 0, bytemuck::bytes_of(&count));
} }
pub fn ensure_cluster_buffers(&mut self, device: &wgpu::Device, assignment: &ClusterAssignment) { pub fn bind_group(&self) -> &wgpu::BindGroup {
if self.cluster_buffers.is_none() { &self.bind_group
self.cluster_buffers = Some(self.create_cluster_buffers(device, assignment)); }
}
pub fn layout(&self) -> &wgpu::BindGroupLayout {
&self.layout
} }
pub fn create_cluster_buffers( pub fn create_cluster_buffers(
@ -355,18 +357,4 @@ impl LightManager {
cluster_offsets, cluster_offsets,
} }
} }
pub fn update_all(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
view_matrix: Matrix4<f32>,
projection_matrix: Matrix4<f32>,
screen_width: f32,
screen_height: f32,
) {
self.update_gpu(queue);
let assignment = self.compute_cluster_assignments(view_matrix, projection_matrix, screen_width, screen_height);
self.update_cluster_buffers(device, queue, &assignment);
}
} }

View File

@ -0,0 +1,58 @@
use wgpu::{Buffer, Device, Queue};
use wgpu::util::DeviceExt;
use bytemuck::{Pod, Zeroable};
#[repr(C)]
#[derive(Copy, Clone, Pod, Zeroable)]
pub struct GpuMaterial {
pub albedo: [f32; 3],
pub emissive: [f32; 3],
pub metallic: f32,
pub roughness: f32,
}
pub struct MaterialManager {
materials: Vec<GpuMaterial>,
buffer: Buffer,
pub layout: wgpu::BindGroupLayout,
pub bind_group: wgpu::BindGroup,
}
impl MaterialManager {
pub fn new(device: &Device, materials: Vec<GpuMaterial>) -> Self {
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Material Buffer"),
contents: bytemuck::cast_slice(&materials),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
});
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Material BindGroupLayout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
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,
}],
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Material BindGroup"),
layout: &layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: buffer.as_entire_binding(),
}],
});
Self { materials, buffer, layout, bind_group }
}
pub fn update(&mut self, queue: &Queue) {
queue.write_buffer(&self.buffer, 0, bytemuck::cast_slice(&self.materials));
}
}

View File

@ -1,110 +0,0 @@
use wgpu::{Buffer, Device, Queue};
use wgpu::util::DeviceExt;
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct GpuMaterial {
pub base_color: [f32; 4],
pub emission: [f32; 3],
pub emissive_strength: f32,
}
impl GpuMaterial {
pub fn new(base_color: [f32; 4], emission: [f32; 3], emissive_strength: f32) -> Self {
Self {
base_color,
emission,
emissive_strength,
}
}
}
pub struct MaterialManager {
materials: Vec<GpuMaterial>,
buffer: Buffer,
pub layout: wgpu::BindGroupLayout,
pub bind_group: wgpu::BindGroup,
}
impl MaterialManager {
pub fn new(device: &Device) -> Self {
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Material BindGroup Layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
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,
},
],
});
let default_materials = vec![
GpuMaterial {
base_color: [1.0, 1.0, 1.0, 1.0],
emission: [0.0, 0.0, 0.0],
emissive_strength: 0.0,
},
];
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Material Buffer"),
contents: bytemuck::cast_slice(&default_materials),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: buffer.as_entire_binding(),
}],
label: Some("Material BindGroup"),
});
Self {
materials: default_materials,
buffer,
bind_group,
layout,
}
}
pub fn update(&self, queue: &Queue) {
queue.write_buffer(&self.buffer, 0, bytemuck::cast_slice(&self.materials));
}
pub fn add_material(&mut self, material: GpuMaterial) -> u32 {
self.materials.push(material);
(self.materials.len() - 1) as u32
}
pub fn set_materials(&mut self, device: &Device, materials: Vec<GpuMaterial>) {
self.materials = materials;
self.buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Material Buffer"),
contents: bytemuck::cast_slice(&self.materials),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
});
self.bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &self.layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: self.buffer.as_entire_binding(),
}],
label: Some("Material BindGroup"),
});
}
pub fn get_materials(&self) -> &[GpuMaterial] {
&self.materials
}
}

View File

@ -1,93 +1,149 @@
use wgpu::{Device, Queue, SurfaceConfiguration, SurfaceTexture, TextureView};
use crate::camera::Camera; use crate::camera::Camera;
use crate::geometry_manager::GeometryManager; use crate::geometry_manager::{GeometryManager, Shape};
use crate::globals_manager::GlobalsManager; use crate::globals::GlobalsManager;
use crate::instance_manager::{InstanceManager, InstanceRaw}; use crate::instance_manager::InstanceManager;
use crate::light_manager::LightManager; use crate::light::LightManager;
use crate::material_manager::MaterialManager; use wgpu::{Device, Queue, SurfaceTexture, TextureView};
use crate::material::MaterialManager;
pub struct RenderInstance {
pub position: cgmath::Vector3<f32>,
pub rotation: cgmath::Quaternion<f32>,
pub color: [f32; 3],
pub scale: f32,
pub shape: Shape,
pub always_lit: bool,
pub is_transparent: bool
}
impl RenderInstance {
pub fn to_raw(&self) -> InstanceRaw {
let model = cgmath::Matrix4::from_translation(self.position)
* cgmath::Matrix4::from(self.rotation)
* cgmath::Matrix4::from_scale(self.scale);
InstanceRaw {
model: model.into(),
color: self.color,
flags: (self.always_lit as u32) | ((self.is_transparent as u32) << 1)
}
}
}
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub struct InstanceRaw {
model: [[f32; 4]; 4],
color: [f32; 3],
flags: u32,
}
impl InstanceRaw {
pub(crate) fn desc() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout {
array_stride: size_of::<InstanceRaw>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &[
wgpu::VertexAttribute { offset: 0, shader_location: 5, format: wgpu::VertexFormat::Float32x4 },
wgpu::VertexAttribute { offset: 16, shader_location: 6, format: wgpu::VertexFormat::Float32x4 },
wgpu::VertexAttribute { offset: 32, shader_location: 7, format: wgpu::VertexFormat::Float32x4 },
wgpu::VertexAttribute { offset: 48, shader_location: 8, format: wgpu::VertexFormat::Float32x4 },
wgpu::VertexAttribute { offset: 64, shader_location: 9, format: wgpu::VertexFormat::Float32x3 },
wgpu::VertexAttribute { offset: 76, shader_location: 10, format: wgpu::VertexFormat::Uint32 },
],
}
}
}
#[repr(C)] #[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] #[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Vertex { pub struct Vertex {
pub position: [f32; 3], pub(crate) position: [f32; 3],
pub color: [f32; 3], pub(crate) color: [f32; 3],
pub normal: [f32; 3], pub(crate) normal: [f32; 3],
} }
impl Vertex { impl Vertex {
const ATTRIBS: [wgpu::VertexAttribute; 3] = const ATTRIBS: [wgpu::VertexAttribute; 3] =
wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x3]; wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x3];
pub fn desc<'a>() -> wgpu::VertexBufferLayout<'a> { pub(crate) fn desc() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout { wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress, array_stride: size_of::<Self>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex, step_mode: wgpu::VertexStepMode::Vertex,
attributes: &Self::ATTRIBS, attributes: &Self::ATTRIBS,
} }
} }
} }
pub struct RenderManager { pub struct Renderer {
pipeline: wgpu::RenderPipeline, pipeline: wgpu::RenderPipeline,
depth_texture: wgpu::TextureView, depth_texture: TextureView,
sample_count: u32, sample_count: u32
} }
impl RenderManager { impl Renderer {
pub fn new( pub fn new(
device: &Device, device: &Device,
config: &SurfaceConfiguration, config: &wgpu::SurfaceConfiguration,
globals: &GlobalsManager, global_layout: &wgpu::BindGroupLayout,
lights: &LightManager, light_manager: &mut LightManager,
materials: &MaterialManager, material_manager: &MaterialManager,
camera: &Camera, camera: &Camera,
sample_count: u32, sample_count: u32,
) -> Self { ) -> Self {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Main Shader"), label: Some("Shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("shaders/shader.wgsl").into()), source: wgpu::ShaderSource::Wgsl(include_str!("shaders/shader.wgsl").into()),
}); });
let cluster_assignment = lights.compute_cluster_assignments( let cluster_assignment = light_manager.compute_cluster_assignments(
camera.build_view_matrix(), camera.build_view_matrix(),
camera.build_view_projection_matrix(), camera.build_view_projection_matrix(),
config.width as f32, config.width as f32,
config.height as f32, config.height as f32,
); );
let cluster_buffers = lights.create_cluster_buffers(device, &cluster_assignment); let cluster_buffers = light_manager.create_cluster_buffers(device, &cluster_assignment);
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Main Pipeline Layout"), label: Some("Render Pipeline Layout"),
bind_group_layouts: &[ bind_group_layouts: &[
&globals.layout, global_layout,
&lights.layout, &light_manager.layout,
&cluster_buffers.layout, &cluster_buffers.layout,
&materials.layout, &material_manager.layout,
], ],
push_constant_ranges: &[], push_constant_ranges: &[],
}); });
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Main Render Pipeline"), label: Some("Render Pipeline"),
layout: Some(&pipeline_layout), layout: Some(&pipeline_layout),
vertex: wgpu::VertexState { vertex: wgpu::VertexState {
module: &shader, module: &shader,
entry_point: Some("vs_main"), entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &[Vertex::desc(), InstanceRaw::desc()], buffers: &[Vertex::desc(), InstanceRaw::desc()],
compilation_options: Default::default(),
}, },
fragment: Some(wgpu::FragmentState { fragment: Some(wgpu::FragmentState {
module: &shader, module: &shader,
entry_point: Some("fs_main"), entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState { targets: &[Some(wgpu::ColorTargetState {
format: config.format, format: config.format,
blend: Some(wgpu::BlendState::REPLACE), blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL, write_mask: wgpu::ColorWrites::ALL,
})], })],
compilation_options: Default::default(),
}), }),
primitive: wgpu::PrimitiveState::default(), 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,
unclipped_depth: false,
conservative: false,
},
depth_stencil: Some(wgpu::DepthStencilState { depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float, format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: true, depth_write_enabled: true,
@ -104,7 +160,8 @@ impl RenderManager {
cache: None, cache: None,
}); });
let depth_texture = Self::create_depth_texture(device, config.width, config.height, sample_count); let depth_texture =
Self::create_depth_texture(device, config.width, config.height, sample_count);
Self { Self {
pipeline, pipeline,
@ -113,12 +170,25 @@ impl RenderManager {
} }
} }
fn create_depth_texture(device: &Device, width: u32, height: u32, samples: u32) -> wgpu::TextureView { pub fn resize(&mut self, device: &Device, width: u32, height: u32) {
self.depth_texture = Self::create_depth_texture(device, width, height, self.sample_count);
}
fn create_depth_texture(
device: &Device,
width: u32,
height: u32,
sample_count: u32,
) -> TextureView {
let texture = device.create_texture(&wgpu::TextureDescriptor { let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Depth Texture"), label: Some("Depth Texture"),
size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 }, size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1, mip_level_count: 1,
sample_count: samples, sample_count,
dimension: wgpu::TextureDimension::D2, dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Depth32Float, format: wgpu::TextureFormat::Depth32Float,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT, usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
@ -127,10 +197,6 @@ impl RenderManager {
texture.create_view(&Default::default()) texture.create_view(&Default::default())
} }
pub fn resize(&mut self, device: &Device, width: u32, height: u32) {
self.depth_texture = Self::create_depth_texture(device, width, height, self.sample_count);
}
pub fn render_frame( pub fn render_frame(
&mut self, &mut self,
device: &Device, device: &Device,
@ -138,35 +204,34 @@ impl RenderManager {
output: SurfaceTexture, output: SurfaceTexture,
view: &TextureView, view: &TextureView,
surface_format: wgpu::TextureFormat, surface_format: wgpu::TextureFormat,
globals: &GlobalsManager, globals: &mut GlobalsManager,
camera: &Camera, camera: &Camera,
lights: &mut LightManager, light_manager: &mut LightManager,
geometry: &GeometryManager, geometry: &GeometryManager,
instances: &InstanceManager, instances: &InstanceManager,
materials: &mut MaterialManager, material_manager: &mut MaterialManager,
) -> Result<(), wgpu::SurfaceError> { ) -> Result<(), wgpu::SurfaceError> {
// Update globals // Update uniform buffer
globals.update(queue, camera); globals.update(queue, camera);
// Update light cluster // Update cluster buffers
let assignment = lights.compute_cluster_assignments( let assignment = light_manager.compute_cluster_assignments(
camera.build_view_matrix(), camera.build_view_matrix(),
camera.build_view_projection_matrix(), camera.build_view_projection_matrix(),
globals.resolution[0], globals.resolution()[0],
globals.resolution[1], globals.resolution()[1],
); );
lights.update_cluster_buffers(device, queue, &assignment); light_manager.update_cluster_buffers(device, queue, &assignment);
lights.update_gpu(queue); light_manager.update_gpu(queue);
// Update materials // Update material buffer
materials.update(queue); material_manager.update(queue);
// Create MSAA target
let multisampled_texture = device.create_texture(&wgpu::TextureDescriptor { let multisampled_texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Multisample Target"), label: Some("Multisample Target"),
size: wgpu::Extent3d { size: wgpu::Extent3d {
width: globals.resolution[0] as u32, width: globals.resolution()[0] as u32,
height: globals.resolution[1] as u32, height: globals.resolution()[1] as u32,
depth_or_array_layers: 1, depth_or_array_layers: 1,
}, },
mip_level_count: 1, mip_level_count: 1,
@ -176,10 +241,8 @@ impl RenderManager {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT, usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[], view_formats: &[],
}); });
let multisampled_view = multisampled_texture.create_view(&Default::default()); let multisampled_view = multisampled_texture.create_view(&Default::default());
// Begin render
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"), label: Some("Render Encoder"),
}); });
@ -191,7 +254,12 @@ impl RenderManager {
view: &multisampled_view, view: &multisampled_view,
resolve_target: Some(view), resolve_target: Some(view),
ops: wgpu::Operations { ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.05, g: 0.05, b: 0.1, a: 1.0 }), load: wgpu::LoadOp::Clear(wgpu::Color {
r: 0.1,
g: 0.1,
b: 0.2,
a: 1.0,
}),
store: wgpu::StoreOp::Store, store: wgpu::StoreOp::Store,
}, },
})], })],
@ -208,23 +276,24 @@ impl RenderManager {
pass.set_pipeline(&self.pipeline); pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &globals.bind_group, &[]); pass.set_bind_group(0, &globals.bind_group, &[]);
pass.set_bind_group(1, &lights.bind_group, &[]); pass.set_bind_group(1, &light_manager.bind_group, &[]);
if let Some(cluster) = &lights.cluster_buffers {
pass.set_bind_group(2, &cluster.bind_group, &[]); if let Some(clusters) = &light_manager.cluster_buffers {
pass.set_bind_group(2, &clusters.bind_group, &[]);
} }
pass.set_bind_group(3, &materials.bind_group, &[]); pass.set_bind_group(3, &material_manager.bind_group, &[]);
for shape in geometry.shapes() { for shape in geometry.shapes() {
if let Some(mesh) = geometry.get(&shape) { if let Some(mesh) = geometry.get(&shape) {
let instances_for_shape = instances.raw_instances_for_shape(shape); let relevant = instances.raw_instances_for_shape(shape);
if instances_for_shape.is_empty() { if relevant.is_empty() {
continue; continue;
} }
pass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..)); pass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
pass.set_vertex_buffer(1, instances.buffer().slice(..)); pass.set_vertex_buffer(1, instances.buffer().slice(..));
pass.set_index_buffer(mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint16); pass.set_index_buffer(mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
pass.draw_indexed(0..mesh.index_count, 0, 0..instances_for_shape.len() as u32); pass.draw_indexed(0..mesh.index_count, 0, 0..relevant.len() as u32);
} }
} }
} }

View File

@ -16,16 +16,25 @@ struct InstanceInput {
@location(6) model_row1: vec4<f32>, @location(6) model_row1: vec4<f32>,
@location(7) model_row2: vec4<f32>, @location(7) model_row2: vec4<f32>,
@location(8) model_row3: vec4<f32>, @location(8) model_row3: vec4<f32>,
@location(9) material_id: u32, @location(9) color: vec3<f32>,
@location(10) flags: u32,
}; };
struct VSOutput { struct VSOutput {
@builtin(position) position: vec4<f32>, @builtin(position) position: vec4<f32>,
@location(0) world_pos: vec3<f32>, @location(0) frag_color: vec3<f32>,
@location(1) normal: vec3<f32>, @location(1) world_pos: vec3<f32>,
@location(2) material_id: u32, @location(2) normal: vec3<f32>,
@location(3) flags: u32,
}; };
struct LightCount {
count: u32,
};
@group(1) @binding(1)
var<uniform> light_count: LightCount;
struct Globals { struct Globals {
view_proj: mat4x4<f32>, view_proj: mat4x4<f32>,
resolution: vec2<f32>, resolution: vec2<f32>,
@ -48,19 +57,17 @@ struct GpuLight {
@group(1) @binding(0) @group(1) @binding(0)
var<storage, read> all_lights: array<GpuLight>; var<storage, read> all_lights: array<GpuLight>;
@group(1) @binding(1)
var<uniform> light_count: u32;
@group(2) @binding(0) @group(2) @binding(0)
var<storage, read> cluster_light_indices: array<u32>; var<storage, read> cluster_light_indices: array<u32>;
@group(2) @binding(1) @group(2) @binding(1)
var<storage, read> cluster_offsets: array<vec2<u32>>; var<storage, read> cluster_offsets: array<vec2<u32>>;
struct GpuMaterial { struct GpuMaterial {
base_color: vec4<f32>, albedo: vec3<f32>,
emission: vec3<f32>, emissive: vec3<f32>,
emissive_strength: f32, metallic: f32,
roughness: f32,
_pad: vec2<f32>,
}; };
@group(3) @binding(0) @group(3) @binding(0)
@ -77,17 +84,18 @@ fn vs_main(vertex: VertexInput, instance: InstanceInput) -> VSOutput {
instance.model_row3 instance.model_row3
); );
let world_pos = (model * vec4<f32>(vertex.position, 1.0)).xyz; let world_position = (model * vec4<f32>(vertex.position, 1.0)).xyz;
let normal_matrix = mat3x3<f32>( let normal_matrix = mat3x3<f32>(
instance.model_row0.xyz, instance.model_row0.xyz,
instance.model_row1.xyz, instance.model_row1.xyz,
instance.model_row2.xyz instance.model_row2.xyz
); );
out.position = globals.view_proj * vec4<f32>(world_pos, 1.0); out.position = globals.view_proj * vec4<f32>(world_position, 1.0);
out.world_pos = world_pos; out.frag_color = instance.color * vertex.color;
out.world_pos = world_position;
out.normal = normalize(normal_matrix * vertex.normal); out.normal = normalize(normal_matrix * vertex.normal);
out.material_id = instance.material_id; out.flags = instance.flags;
return out; return out;
} }
@ -99,7 +107,8 @@ fn compute_cluster_id(frag_coord: vec4<f32>, view_pos_z: f32, screen_size: vec2<
let x = clamp(u32(x_frac * f32(CLUSTER_COUNT_X)), 0u, CLUSTER_COUNT_X - 1u); let x = clamp(u32(x_frac * f32(CLUSTER_COUNT_X)), 0u, CLUSTER_COUNT_X - 1u);
let y = clamp(u32(y_frac * f32(CLUSTER_COUNT_Y)), 0u, CLUSTER_COUNT_Y - 1u); let y = clamp(u32(y_frac * f32(CLUSTER_COUNT_Y)), 0u, CLUSTER_COUNT_Y - 1u);
let depth = -view_pos_z; // Z: logarithmic depth
let depth = -view_pos_z; // view-space z is negative
let depth_clamped = clamp(depth, NEAR_PLANE, FAR_PLANE); let depth_clamped = clamp(depth, NEAR_PLANE, FAR_PLANE);
let log_depth = log2(depth_clamped); let log_depth = log2(depth_clamped);
let z = clamp(u32((log_depth / log2(FAR_PLANE / NEAR_PLANE)) * f32(CLUSTER_COUNT_Z)), 0u, CLUSTER_COUNT_Z - 1u); let z = clamp(u32((log_depth / log2(FAR_PLANE / NEAR_PLANE)) * f32(CLUSTER_COUNT_Z)), 0u, CLUSTER_COUNT_Z - 1u);
@ -107,15 +116,18 @@ fn compute_cluster_id(frag_coord: vec4<f32>, view_pos_z: f32, screen_size: vec2<
return x + y * CLUSTER_COUNT_X + z * CLUSTER_COUNT_X * CLUSTER_COUNT_Y; return x + y * CLUSTER_COUNT_X + z * CLUSTER_COUNT_X * CLUSTER_COUNT_Y;
} }
// Thanks Reinhard fn is_nan_f32(x: f32) -> bool {
fn tone_map(color: vec3<f32>) -> vec3<f32> { return x != x;
return color / (color + vec3<f32>(1.0)); }
fn is_nan_vec3(v: vec3<f32>) -> bool {
return any(vec3<bool>(v != v));
} }
@fragment @fragment
fn fs_main(input: VSOutput) -> @location(0) vec4<f32> { fn fs_main(input: VSOutput) -> @location(0) vec4<f32> {
let material = materials[input.material_id]; var lighting: vec3<f32> = vec3<f32>(0.0);
var lighting = vec3<f32>(0.0); let always_lit = (input.flags & 0x1u) != 0u;
let cluster_id = compute_cluster_id(input.position, input.world_pos.z, globals.resolution); let cluster_id = compute_cluster_id(input.position, input.world_pos.z, globals.resolution);
let offset_info = cluster_offsets[cluster_id]; let offset_info = cluster_offsets[cluster_id];
@ -125,39 +137,43 @@ fn fs_main(input: VSOutput) -> @location(0) vec4<f32> {
for (var i = 0u; i < count; i = i + 1u) { for (var i = 0u; i < count; i = i + 1u) {
let light_index = cluster_light_indices[offset + i]; let light_index = cluster_light_indices[offset + i];
let light = all_lights[light_index]; let light = all_lights[light_index];
var light_contrib: vec3<f32> = vec3<f32>(0.0);
let light_dir = normalize(light.position - input.world_pos); let light_dir = normalize(light.position - input.world_pos);
let diff = max(dot(input.normal, light_dir), 0.0); let diff = max(dot(input.normal, light_dir), 0.0);
var light_contrib = vec3<f32>(0.0);
switch (light.light_type) { switch (light.light_type) {
case 0u: { case 0u: { // Directional
light_contrib = light.color * light.intensity * diff; light_contrib = light.color * light.intensity * diff;
} }
case 1u: { case 1u: { // Point
let dist = distance(light.position, input.world_pos); let dist = distance(light.position, input.world_pos);
if (dist < light.range) { if (dist < light.range) {
let attenuation = 1.0 / (dist * dist); let attenuation = 1.0 / (dist * dist);
light_contrib = light.color * light.intensity * diff * attenuation; light_contrib = light.color * light.intensity * diff * attenuation;
} }
} }
case 2u: { case 2u: { // Spot
let spot_dir = normalize(-light.direction); let spot_dir = normalize(-light.direction);
let angle = dot(spot_dir, light_dir); let angle = dot(spot_dir, light_dir);
if (angle > light.outer_cutoff) { if (angle > light.outer_cutoff) {
let falloff = clamp((angle - light.outer_cutoff) / (light.inner_cutoff - light.outer_cutoff), 0.0, 1.0); let intensity = clamp((angle - light.outer_cutoff) / (light.inner_cutoff - light.outer_cutoff), 0.0, 1.0);
let dist = distance(light.position, input.world_pos); let dist = distance(light.position, input.world_pos);
let attenuation = 1.0 / (dist * dist); let attenuation = 1.0 / (dist * dist);
light_contrib = light.color * light.intensity * diff * attenuation * falloff; light_contrib = light.color * light.intensity * diff * attenuation * intensity;
} }
} }
default: {} default: {}
} }
lighting += light_contrib; if (!always_lit) {
lighting += light_contrib;
}
} }
let emissive_rgb = material.emission * material.emissive_strength; if (always_lit) {
let final_rgb = tone_map(material.base_color.rgb * lighting + emissive_rgb); lighting = vec3<f32>(1.0, 1.0, 1.0) * 2.0;
return vec4<f32>(final_rgb, material.base_color.a); }
return vec4<f32>(input.frag_color * lighting, 1.0);
} }

View File

@ -6,14 +6,13 @@ use winit::dpi::PhysicalSize;
use winit::window::{Window}; use winit::window::{Window};
use crate::camera::Camera; use crate::camera::Camera;
use crate::geometry_manager::GeometryManager; use crate::geometry_manager::GeometryManager;
use crate::globals_manager::GlobalsManager; use crate::globals::GlobalsManager;
use crate::instance_manager::{InstanceManager, RenderInstance}; use crate::instance_manager::InstanceManager;
use crate::light_manager::{LightManager}; use crate::light::{LightManager};
use crate::material_manager::{GpuMaterial, MaterialManager}; use crate::material::{GpuMaterial, MaterialManager};
use crate::render_manager::{RenderManager}; use crate::renderer::{RenderInstance, Renderer};
pub struct SampleCount(pub u32); pub struct SampleCount(pub u32);
type RenderResult = Result<(), SurfaceError>;
impl SampleCount { impl SampleCount {
pub fn get(&self) -> u32 { pub fn get(&self) -> u32 {
@ -21,7 +20,7 @@ impl SampleCount {
} }
} }
pub struct EngineState<'a> { pub struct State<'a> {
surface: Surface<'a>, surface: Surface<'a>,
device: Device, device: Device,
queue: Queue, queue: Queue,
@ -32,15 +31,15 @@ pub struct EngineState<'a> {
window: Arc<Window>, window: Arc<Window>,
pub camera: Camera, pub camera: Camera,
pub globals_manager: GlobalsManager, pub globals: GlobalsManager,
pub geometry_manager: GeometryManager, pub geometry_manager: GeometryManager,
pub instance_manager: InstanceManager, pub instance_manager: InstanceManager,
pub light_manager: LightManager, pub light_manager: LightManager,
pub material_manager: MaterialManager, pub material_manager: MaterialManager,
pub render_manager: RenderManager, pub renderer: Renderer,
} }
impl<'a> EngineState<'a> { impl<'a> State<'a> {
pub(crate) fn new(window: Window) -> Self { pub(crate) fn new(window: Window) -> Self {
let window = Arc::new(window); let window = Arc::new(window);
let size = window.inner_size(); let size = window.inner_size();
@ -62,17 +61,27 @@ impl<'a> EngineState<'a> {
let camera = Camera::new(config.width as f32 / config.height as f32); let camera = Camera::new(config.width as f32 / config.height as f32);
let globals_manager = GlobalsManager::new(&device, config.width, config.height, &camera); let globals = GlobalsManager::new(&device, config.width, config.height, &camera);
let geometry_manager = GeometryManager::new(&device); let geometry_manager = GeometryManager::new(&device);
let instance_manager = InstanceManager::new(&device); let instance_manager = InstanceManager::new(&device);
let mut light_manager = LightManager::new(&device, 100); let mut light_manager = LightManager::new(&device, 100);
let mut material_manager = MaterialManager::new(&device); let initial_materials = vec![
GpuMaterial {
albedo: [1.0, 1.0, 1.0],
emissive: [0.0, 0.0, 0.0],
metallic: 0.0,
roughness: 0.5,
};
8
];
let render_manager = RenderManager::new( let mut material_manager = MaterialManager::new(&device, initial_materials);
let renderer = Renderer::new(
&device, &device,
&config, &config,
&globals_manager, globals.layout(),
&mut light_manager, &mut light_manager,
&material_manager, &material_manager,
&camera, &camera,
@ -88,12 +97,12 @@ impl<'a> EngineState<'a> {
size, size,
window, window,
camera, camera,
globals_manager, globals,
geometry_manager, geometry_manager,
instance_manager, instance_manager,
light_manager, light_manager,
material_manager, material_manager,
render_manager, renderer,
} }
} }
@ -180,24 +189,22 @@ impl<'a> EngineState<'a> {
self.surface.configure(&self.device, &self.config); self.surface.configure(&self.device, &self.config);
self.camera.set_aspect(new_size.width as f32 / new_size.height as f32); self.camera.set_aspect(new_size.width as f32 / new_size.height as f32);
self.globals_manager.resize(&self.queue, new_size.width, new_size.height, &self.camera); self.globals.resize(new_size.width, new_size.height);
self.render_manager.resize(&self.device, new_size.width, new_size.height); self.renderer.resize(&self.device, new_size.width, new_size.height);
} }
} }
pub fn update(&mut self) {} pub fn render(&mut self) -> Result<(), SurfaceError> {
pub fn render(&mut self) -> RenderResult {
let output = self.surface.get_current_texture()?; let output = self.surface.get_current_texture()?;
let view = output.texture.create_view(&Default::default()); let view = output.texture.create_view(&Default::default());
self.render_manager.render_frame( self.renderer.render_frame(
&self.device, &self.device,
&self.queue, &self.queue,
output, output,
&view, &view,
self.config.format, self.config.format,
&mut self.globals_manager, &mut self.globals,
&self.camera, &self.camera,
&mut self.light_manager, &mut self.light_manager,
&self.geometry_manager, &self.geometry_manager,
@ -206,10 +213,6 @@ impl<'a> EngineState<'a> {
) )
} }
pub fn set_materials(&mut self, materials: Vec<GpuMaterial>) {
self.material_manager.set_materials(&self.device, materials);
}
pub fn set_instances(&mut self, instances: Vec<RenderInstance>) { pub fn set_instances(&mut self, instances: Vec<RenderInstance>) {
self.instance_manager.set_instances(&self.device, &self.queue, instances); self.instance_manager.set_instances(&self.device, &self.queue, instances);
} }