Made the Sun a directional light source and fixed some lighting bugs, which affect the sun to have a shadow

This commit is contained in:
Verox001 2025-05-06 18:13:42 +02:00
parent 5a444c3e07
commit 966aabc649
3 changed files with 23 additions and 6 deletions

View File

@ -85,6 +85,8 @@ pub async fn run() {
},
scale: 0.05,
shape: solar_engine::Shape::Sphere,
always_lit: i == 0, // Sun
is_transparent: false
}
})
.collect();

View File

@ -22,6 +22,8 @@ pub struct RenderInstance {
pub color: [f32; 3],
pub scale: f32,
pub shape: Shape,
pub always_lit: bool,
pub is_transparent: bool
}
impl RenderInstance {
@ -32,6 +34,7 @@ impl RenderInstance {
InstanceRaw {
model: model.into(),
color: self.color,
flags: (self.always_lit as u32) | ((self.is_transparent as u32) << 1)
}
}
}
@ -41,6 +44,7 @@ impl RenderInstance {
pub struct InstanceRaw {
model: [[f32; 4]; 4],
color: [f32; 3],
flags: u32,
}
impl InstanceRaw {
@ -54,6 +58,7 @@ impl InstanceRaw {
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 },
],
}
}

View File

@ -10,6 +10,7 @@ struct InstanceInput {
@location(7) model_row2: vec4<f32>,
@location(8) model_row3: vec4<f32>,
@location(9) color: vec3<f32>,
@location(10) flags: u32,
};
struct VSOutput {
@ -17,6 +18,7 @@ struct VSOutput {
@location(0) frag_color: vec3<f32>,
@location(1) world_pos: vec3<f32>,
@location(2) normal: vec3<f32>,
@location(3) flags: u32,
};
struct Globals {
@ -57,19 +59,27 @@ fn vs_main(vertex: VertexInput, instance: InstanceInput) -> VSOutput {
out.frag_color = instance.color * vertex.color;
out.world_pos = world_position;
out.normal = normalize(normal_matrix * vertex.normal);
out.flags = instance.flags;
return out;
}
@fragment
fn fs_main(input: VSOutput) -> @location(0) vec4<f32> {
var lighting: vec3<f32> = vec3<f32>(0.0);
var lighting: vec3<f32>;
for (var i = 0u; i < 10u; i = i + 1u) {
let light = lights[i];
let light_dir = normalize(light.position - input.world_pos);
let diff = max(dot(input.normal, light_dir), 0.0);
lighting += light.color * light.intensity * diff;
let always_lit = (input.flags & 0x1u) != 0u;
if (always_lit) {
return vec4<f32>(input.frag_color * 2.0, 1.0);
} else {
lighting = vec3<f32>(0.0);
for (var i = 0u; i < 10u; i = i + 1u) {
let light = lights[i];
let light_dir = normalize(light.position - input.world_pos);
let diff = max(dot(input.normal, light_dir), 0.0);
lighting += light.color * light.intensity * diff;
}
}
let final_color = input.frag_color * lighting;