voxel_lighting.fs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #version 120
  2. // Input from vertex shader
  3. varying vec3 fragPosition;
  4. varying vec4 fragColor;
  5. varying vec3 fragNormal;
  6. // Uniforms
  7. uniform vec4 colDiffuse;
  8. uniform vec4 ambient;
  9. uniform vec3 viewPos;
  10. #define MAX_LIGHTS 4
  11. #define LIGHT_DIRECTIONAL 0
  12. #define LIGHT_POINT 1
  13. struct Light {
  14. int enabled;
  15. int type;
  16. vec3 position;
  17. vec3 target;
  18. vec4 color;
  19. };
  20. uniform Light lights[MAX_LIGHTS];
  21. void main()
  22. {
  23. vec3 lightDot = vec3(0.0);
  24. vec3 normal = normalize(fragNormal);
  25. vec3 viewD = normalize(viewPos - fragPosition);
  26. vec3 specular = vec3(0.0);
  27. for (int i = 0; i < MAX_LIGHTS; i++)
  28. {
  29. if (lights[i].enabled == 1)
  30. {
  31. vec3 light = vec3(0.0);
  32. if (lights[i].type == LIGHT_DIRECTIONAL)
  33. light = -normalize(lights[i].target - lights[i].position);
  34. if (lights[i].type == LIGHT_POINT)
  35. light = normalize(lights[i].position - fragPosition);
  36. float NdotL = max(dot(normal, light), 0.0);
  37. lightDot += lights[i].color.rgb*NdotL;
  38. if (NdotL > 0.0)
  39. {
  40. float specCo = pow(max(0.0, dot(viewD, reflect(-light, normal))), 16.0);
  41. specular += specCo;
  42. }
  43. }
  44. }
  45. vec4 finalColor = (fragColor*((colDiffuse + vec4(specular, 1.0))*vec4(lightDot, 1.0)));
  46. finalColor += fragColor*(ambient/10.0)*colDiffuse;
  47. finalColor = pow(finalColor, vec4(1.0/2.2)); // gamma correction
  48. gl_FragColor = finalColor;
  49. }