From b8cc592235b47657910127df97d9d815bce9c109 Mon Sep 17 00:00:00 2001 From: Verox001 Date: Thu, 16 Jan 2025 13:18:43 +0100 Subject: [PATCH] Finished Ray Tracing lighting --- src/lib.rs | 9 ++++++--- src/shader.wgsl | 11 +++++++++-- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index d39814b..f3c9d18 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -56,19 +56,23 @@ impl Camera { } #[repr(C)] -#[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] +#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] struct CameraUniform { + view_position: [f32; 4], view_proj: [[f32; 4]; 4], } impl CameraUniform { fn new() -> Self { Self { + view_position: [0.0; 4], view_proj: cgmath::Matrix4::identity().into(), } } fn update_view_proj(&mut self, camera: &Camera) { + // We're using Vector4 because of the uniforms 16 byte spacing requirement + self.view_position = camera.eye.to_homogeneous().into(); self.view_proj = (OPENGL_TO_WGPU_MATRIX * camera.build_view_projection_matrix()).into(); } } @@ -467,7 +471,7 @@ impl<'a> State<'a> { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { entries: &[wgpu::BindGroupLayoutEntry { binding: 0, - visibility: wgpu::ShaderStages::VERTEX, + visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, @@ -634,7 +638,6 @@ impl<'a> State<'a> { self.camera_controller.update_camera(&mut self.camera); log::info!("{:?}", self.camera); self.camera_uniform.update_view_proj(&self.camera); - log::info!("{:?}", self.camera_uniform); self.queue.write_buffer( &self.camera_buffer, 0, diff --git a/src/shader.wgsl b/src/shader.wgsl index 5c33ddb..39ba767 100644 --- a/src/shader.wgsl +++ b/src/shader.wgsl @@ -8,6 +8,7 @@ struct Light { var light: Light; struct Camera { + view_pos: vec4, view_proj: mat4x4, } @group(1) @binding(0) @@ -74,14 +75,20 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4 { let light_dir = normalize(light.position - in.world_position); + let view_dir = normalize(camera.view_pos.xyz - in.world_position); + let half_dir = normalize(view_dir + light_dir); + + let specular_strength = pow(max(dot(in.world_normal, half_dir), 0.0), 32.0); + let specular_color = specular_strength * light.color; + let diffuse_strength = max(dot(in.world_normal, light_dir), 0.0); let diffuse_color = light.color * diffuse_strength; // We don't need (or want) much ambient light, so 0.1 is fine - let ambient_strength = 0.1; + let ambient_strength = 0.03; let ambient_color = light.color * ambient_strength; - let result = (ambient_color + diffuse_color) * object_color.xyz; + let result = (ambient_color + diffuse_color + specular_color) * object_color.xyz; return vec4(result, object_color.a); } \ No newline at end of file