Basic Lighting_练习二

尝试实现一个Gouraud着色(而不是冯氏着色)。如果你做对了话,立方体的光照应该会看起来有些奇怪,尝试推理为什么它会看起来这么奇怪

 1 // Vertex shader:
 2 // ================
 3 #version 330 core
 4 layout (location = 0) in vec3 aPos;
 5 layout (location = 1) in vec3 aNormal;
 6 
 7 out vec3 LightingColor; // resulting color from lighting calculations
 8 
 9 uniform vec3 lightPos;
10 uniform vec3 viewPos;
11 uniform vec3 lightColor;
12 
13 uniform mat4 model;
14 uniform mat4 view;
15 uniform mat4 projection;
16 
17 void main()
18 {
19     gl_Position = projection * view * model * vec4(aPos, 1.0);
20     
21     // gouraud shading
22     // ------------------------
23     vec3 Position = vec3(model * vec4(aPos, 1.0));
24     vec3 Normal = mat3(transpose(inverse(model))) * aNormal;
25     
26     // ambient
27     float ambientStrength = 0.1;
28     vec3 ambient = ambientStrength * lightColor;
29       
30     // diffuse 
31     vec3 norm = normalize(Normal);
32     vec3 lightDir = normalize(lightPos - Position);
33     float diff = max(dot(norm, lightDir), 0.0);
34     vec3 diffuse = diff * lightColor;
35     
36     // specular
37     float specularStrength = 1.0; // this is set higher to better show the effect of Gouraud shading 
38     vec3 viewDir = normalize(viewPos - Position);
39     vec3 reflectDir = reflect(-lightDir, norm);  
40     float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32);
41     vec3 specular = specularStrength * spec * lightColor;      
42 
43     LightingColor = ambient + diffuse + specular;
44 }
45 
46 
47 // Fragment shader:
48 // ================
49 #version 330 core
50 out vec4 FragColor;
51 
52 in vec3 LightingColor; 
53 
54 uniform vec3 objectColor;
55 
56 void main()
57 {
58    FragColor = vec4(LightingColor * objectColor, 1.0);
59 }
60 
61 
62 /*
63 So what do we see?
64 You can see (for yourself or in the provided image) the clear distinction of the two triangles at the front of the 
65 cube. This 'stripe' is visible because of fragment interpolation. From the example image we can see that the top-right 
66 vertex of the cube's front face is lit with specular highlights. Since the top-right vertex of the bottom-right triangle is 
67 lit and the other 2 vertices of the triangle are not, the bright values interpolates to the other 2 vertices. The same 
68 happens for the upper-left triangle. Since the intermediate fragment colors are not directly from the light source 
69 but are the result of interpolation, the lighting is incorrect at the intermediate fragments and the top-left and 
70 bottom-right triangle collide in their brightness resulting in a visible stripe between both triangles.
71 
72 This effect will become more apparent when using more complicated shapes.
73 */
View Code

 

解释:顶点着色器中的最终颜色值是仅仅只是那个顶点的颜色值,片段的颜色值是由插值光照颜色所得来的。结果就是这种光照看起来不会非常真实,除非使用了大量顶点。

 

2019//11/30

posted @ 2019-11-30 14:53  ljy3268  阅读(151)  评论(0编辑  收藏  举报