fix: rotate normals with model to correct helicopter lighting during rotation

This commit is contained in:
2025-10-02 12:02:58 +02:00
parent e6987e506f
commit 46bdbfb889
2 changed files with 8 additions and 3 deletions

View File

@@ -6,9 +6,10 @@ in layout(location=2) vec3 aNormal;
out vec4 vColor;
out vec3 vNormal;
layout(location = 0) uniform mat4 transform;
uniform mat3 normalMatrix;
void main() {
gl_Position = transform * vec4(position, 1.0f);
vColor = aColor;
vNormal = aNormal;
vNormal = normalize(normalMatrix * aNormal);
}

View File

@@ -130,7 +130,7 @@ unsafe fn create_vao(vertices: &Vec<f32>, normals: &Vec<f32>, colors: &Vec<f32>,
}
// Scene graph drawing function
unsafe fn draw_scene(node: &scene_graph::SceneNode, transform_loc: i32, view_projection: &glm::Mat4, transform_so_far: &glm::Mat4) {
unsafe fn draw_scene(node: &scene_graph::SceneNode, transform_loc: i32, normal_loc: i32, view_projection: &glm::Mat4, transform_so_far: &glm::Mat4) {
// Build model matrix from node transformations
let translation = glm::translation(&node.position);
let rot_x = glm::rotation(node.rotation.x, &glm::vec3(1.0, 0.0, 0.0));
@@ -148,6 +148,9 @@ unsafe fn draw_scene(node: &scene_graph::SceneNode, transform_loc: i32, view_pro
if node.index_count > 0 {
let mvp = view_projection * new_transform;
gl::UniformMatrix4fv(transform_loc, 1, gl::FALSE, mvp.as_ptr());
let nm4 = glm::transpose(&glm::inverse(&new_transform));
let normal_matrix = glm::mat3(&nm4);
gl::UniformMatrix3fv(normal_loc, 1, gl::FALSE, normal_matrix.as_ptr());
gl::BindVertexArray(node.vao_id);
gl::DrawElements(gl::TRIANGLES, node.index_count, gl::UNSIGNED_INT, ptr::null());
}
@@ -349,6 +352,7 @@ fn main() {
};
// get uniform location for the matrix (named `transform` in your vertex shader)
let transform_loc = unsafe { simple_shader.get_uniform_location("transform") };
let normal_loc = unsafe { simple_shader.get_uniform_location("normalMatrix") };
// Used to demonstrate keyboard handling for exercise 2.
let mut _arbitrary_number = 0.0; // feel free to remove
@@ -460,7 +464,7 @@ fn main() {
// Draw scene via scene graph
let view_proj = projection * view;
draw_scene(&*root_node, transform_loc, &view_proj, &glm::identity());
draw_scene(&*root_node, transform_loc, normal_loc, &view_proj, &glm::identity());
}
// Display the new color buffer on the display