vengine  0.0.1
3D graphics engine
Loading...
Searching...
No Matches
fragment_shader.frag
Go to the documentation of this file.
1#version 450
2
3layout(location = 0) in vec3 fragColor;
4layout(location = 1) in vec3 fragPosWorld;
5layout(location = 2) in vec3 fragNormalWorld;
6layout(location = 3) in vec2 fragUv;
7
8layout(location = 0) out vec4 outColor;
9
10struct PointLight {
11 vec4 position; // ignore w
12 vec4 color; // w is intensity
13 float shininess;
14};
15
16layout(set = 0, binding = 0) uniform GlobalUbo {
17 mat4 projection;
18 mat4 view;
19 mat4 invView;
20 vec4 ambientLightColor; // w is intensity
21 PointLight pointLights[10];
22 int numLights;
23} ubo;
24
25layout(set = 1, binding = 1) uniform sampler2D diffuseMap;
26
27layout(push_constant) uniform Push {
28 mat4 modelMatrix;
29 mat4 normalMatrix;
30} push;
31
32void main() {
33 vec3 specularLight = vec3(0.0);
34 vec3 surfaceNormal = normalize(gl_FrontFacing ? fragNormalWorld : -fragNormalWorld);
35 vec3 diffuseLight = ubo.ambientLightColor.rgb * ubo.ambientLightColor.a;
36
37 vec3 cameraPosWorld = ubo.invView[3].xyz;
38 vec3 viewDirection = normalize(cameraPosWorld - fragPosWorld);
39
40 for (int i = 0; i < ubo.numLights; i++) {
41 PointLight light = ubo.pointLights[i];
42 vec3 directionToLight = light.position.xyz - fragPosWorld;
43 float distanceSquared = dot(directionToLight, directionToLight);
44 float attenuation = distanceSquared > 0.001 ? (light.position.w + 1.0) / distanceSquared : 0.0;
45 directionToLight = normalize(directionToLight);
46
47 float cosAngIncidence = max(dot(surfaceNormal, directionToLight), 0);
48 vec3 intensity = light.color.rgb * light.color.a * attenuation;
49
50 if (cosAngIncidence > 0) {
51 vec3 halfVector = normalize(directionToLight + viewDirection);
52 float cosAngHalf = max(dot(surfaceNormal, halfVector), 0);
53
54 float specular = pow(cosAngHalf, light.shininess);
55
56 diffuseLight += intensity * cosAngIncidence;
57 specularLight += intensity * specular;
58 }
59 }
60
61 vec3 color = texture(diffuseMap, fragUv).xyz;
62 outColor = vec4(diffuseLight * color + specularLight, 1.0);
63}