Fixed camera

This commit is contained in:
STP
2023-11-25 00:04:41 -05:00
parent ccac1f414d
commit ab284e8e98
4 changed files with 50 additions and 65 deletions

View File

@@ -13,13 +13,12 @@ pub fn phong_shade_point(scene: &Scene, intersect: &Intersection) -> Vector3<u8>
material,
..
} = intersect;
let ambient_light = &scene.ambient_light;
let kd = material.kd;
let ks = material.ks;
let shininess = material.shininess;
// Compute the ambient light component and set it as base colour
let mut colour = kd.component_mul(ambient_light);
let mut colour = ZERO_VECTOR;
for light in &scene.lights {
let Light {
@@ -28,42 +27,36 @@ pub fn phong_shade_point(scene: &Scene, intersect: &Intersection) -> Vector3<u8>
falloff: light_falloff,
} = light;
// Compute light incidence vector and its distance
// Point to light
let to_light = light_position - point;
let light_distance = to_light.norm();
let light_incidence = Unit::new_normalize(to_light);
let to_light = Unit::new_normalize(to_light);
// Point to camera
let to_camera = Unit::new_normalize(-incidence.into_inner());
// Diffuse component
let n_dot_l = normal.dot(&to_light).max(0.0);
let diffuse = n_dot_l * kd;
// Specular component
let mut specular = ZERO_VECTOR;
if n_dot_l > 0.0 {
// Halfway vector.
let h = Unit::new_normalize(to_camera.lerp(&to_light, 0.5));
let n_dot_h = normal.dot(&h).max(0.0);
specular = ks * n_dot_h.powf(shininess);
}
// Compute light falloff
let falloff = 1.0
/ (light_falloff[0]
/ (1.0
+ light_falloff[0]
+ light_falloff[1] * light_distance
+ light_falloff[2] * light_distance * light_distance);
+ light_falloff[2] * light_distance.powi(2));
// Compute diffuse
let n_dot_l = normal.dot(&light_incidence);
let diffuse = if n_dot_l > 0.0 {
kd * n_dot_l
} else {
ZERO_VECTOR
};
// Compute specular
let h = (&light_incidence.into_inner() + incidence.into_inner()).normalize();
let n_dot_h = normal.dot(&h);
let specular = if n_dot_h > 0.0 {
ks * n_dot_h.powf(shininess)
} else {
ZERO_VECTOR
};
// Update colour with diffuse and specular components
colour += light_colour.component_mul(&((diffuse + specular) * falloff));
let light_intensity = light_colour.component_mul(&(diffuse + specular)) * falloff;
colour += &light_intensity;
}
// Clamp colour values to [0, 255] and convert to u8
let r = nalgebra::clamp(colour.x * 255.0, 0.0, 255.0) as u8;
let g = nalgebra::clamp(colour.y * 255.0, 0.0, 255.0) as u8;
let b = nalgebra::clamp(colour.z * 255.0, 0.0, 255.0) as u8;
colour *= 255.0;
let (r, g, b) = (colour.x as u8, colour.y as u8, colour.z as u8);
Vector3::new(r, g, b)
}