standard_fragment.glsl 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. precision highp float;
  2. // Inputs from vertex shader
  3. in vec4 Position; // Fragment position in camera coordinates
  4. in vec3 Normal; // Fragment normal in camera coordinates
  5. in vec2 FragTexcoord; // Fragment texture coordinates
  6. #include <lights>
  7. #include <material>
  8. #include <phong_model>
  9. // Final fragment color
  10. out vec4 FragColor;
  11. void main() {
  12. // Compute final texture color
  13. vec4 texMixed = vec4(1);
  14. #if MAT_TEXTURES > 0
  15. bool firstTex = true;
  16. if (MatTexVisible(0)) {
  17. vec4 texColor = texture(MatTexture[0], FragTexcoord * MatTexRepeat(0) + MatTexOffset(0));
  18. if (firstTex) {
  19. texMixed = texColor;
  20. firstTex = false;
  21. } else {
  22. texMixed = Blend(texMixed, texColor);
  23. }
  24. }
  25. #if MAT_TEXTURES > 1
  26. if (MatTexVisible(1)) {
  27. vec4 texColor = texture(MatTexture[1], FragTexcoord * MatTexRepeat(1) + MatTexOffset(1));
  28. if (firstTex) {
  29. texMixed = texColor;
  30. firstTex = false;
  31. } else {
  32. texMixed = Blend(texMixed, texColor);
  33. }
  34. }
  35. #if MAT_TEXTURES > 2
  36. if (MatTexVisible(2)) {
  37. vec4 texColor = texture(MatTexture[2], FragTexcoord * MatTexRepeat(2) + MatTexOffset(2));
  38. if (firstTex) {
  39. texMixed = texColor;
  40. firstTex = false;
  41. } else {
  42. texMixed = Blend(texMixed, texColor);
  43. }
  44. }
  45. #endif
  46. #endif
  47. #endif
  48. // Combine material with texture colors
  49. vec4 matDiffuse = vec4(MatDiffuseColor, MatOpacity) * texMixed;
  50. vec4 matAmbient = vec4(MatAmbientColor, MatOpacity) * texMixed;
  51. // Normalize interpolated normal as it may have shrinked
  52. vec3 fragNormal = normalize(Normal);
  53. // Calculate the direction vector from the fragment to the camera (origin)
  54. vec3 camDir = normalize(-Position.xyz);
  55. // Workaround for gl_FrontFacing
  56. vec3 fdx = dFdx(Position.xyz);
  57. vec3 fdy = dFdy(Position.xyz);
  58. vec3 faceNormal = normalize(cross(fdx,fdy));
  59. if (dot(fragNormal, faceNormal) < 0.0) { // Back-facing
  60. fragNormal = -fragNormal;
  61. }
  62. // Calculates the Ambient+Diffuse and Specular colors for this fragment using the Phong model.
  63. vec3 Ambdiff, Spec;
  64. phongModel(Position, fragNormal, camDir, vec3(matAmbient), vec3(matDiffuse), Ambdiff, Spec);
  65. // Final fragment color
  66. FragColor = min(vec4(Ambdiff + Spec, matDiffuse.a), vec4(1.0));
  67. }