standard_fragment.glsl 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. #extension GL_OES_standard_derivatives : enable
  57. vec3 fdx = dFdx(Position.xyz);
  58. vec3 fdy = dFdy(Position.xyz);
  59. vec3 faceNormal = normalize(cross(fdx,fdy));
  60. if (dot(fragNormal, faceNormal) < 0.0) { // Back-facing
  61. fragNormal = -fragNormal;
  62. }
  63. // Calculates the Ambient+Diffuse and Specular colors for this fragment using the Phong model.
  64. vec3 Ambdiff, Spec;
  65. phongModel(Position, fragNormal, camDir, vec3(matAmbient), vec3(matDiffuse), Ambdiff, Spec);
  66. // Final fragment color
  67. FragColor = min(vec4(Ambdiff + Spec, matDiffuse.a), vec4(1.0));
  68. }