normalmap.fs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #version 120
  2. //input textures
  3. uniform sampler2D colourMap;
  4. uniform sampler2D normalMap;
  5. uniform sampler2D reflectMap;
  6. uniform sampler2D specularMap;
  7. //light properties
  8. uniform vec3 lightPosition = vec3(0.0);
  9. uniform vec3 lightColour = vec3(0.6, 0.6, 0.6);
  10. uniform float lightPower = 0.6;
  11. uniform vec4 lightSpecColour = vec4(0.6, 0.6, 0.6, 1.0);
  12. uniform float lightSpecPower = 0.08; //smaller is more glossy
  13. uniform vec2 reflectOffset; //offset the reflection map by sprite coords
  14. //so that the reflection appears static when the sprite moves
  15. uniform vec2 resolution = vec2(60.0, 102.0); //set this to size of the sprite to which this shader is applied
  16. uniform bool invertBumpY = true; //some normal maps require inverted Y channel
  17. void main()
  18. {
  19. //sample our diffuse and normal maps
  20. vec2 coord = gl_TexCoord[0].xy;
  21. vec4 diffuseColour = texture2D(colourMap, coord);
  22. vec3 normalColour = texture2D(normalMap, coord).rgb;
  23. //get normal value from sample
  24. normalColour.g = invertBumpY ? 1.0 - normalColour.g : normalColour.g;
  25. vec3 normal = normalize(normalColour * 2.0 - 1.0);
  26. //mix reflection map with colour using normal map alpha
  27. float blendVal = texture2D(normalMap, coord).a;
  28. coord = mod(reflectOffset, resolution) / resolution; //add offset to coord
  29. coord.y = 1.0 - coord.y;
  30. vec3 reflectColour = texture2D(reflectMap, coord + (normal.rg * 2.0)).rgb; //adding normal distorts reflection
  31. diffuseColour.rgb = mix(diffuseColour.rgb, reflectColour, blendVal);
  32. //calculate the light vector
  33. vec3 lightDir = vec3((lightPosition.xy - gl_FragCoord.xy) / resolution, lightPosition.z);
  34. //calculate the colour intensity based on normal and add specular to pixels facing light
  35. float colourIntensity = max(dot(normal, normalize(lightDir)), 0.0);
  36. vec4 specular = vec4(0.0);
  37. vec4 diffuse = vec4(0.0);
  38. if(colourIntensity > 0.0)
  39. {
  40. //vector half way between light and view direction
  41. vec3 halfVec = normalize(lightDir + vec3(0.5, 0.5, 0.5)); //fixed 2D view, so view is centred
  42. //get specular value from map
  43. vec4 specColour = vec4(texture2D(specularMap, gl_TexCoord[0].xy).rgb, 1.0);
  44. float specModifier = max(dot(normal, halfVec), 0.0);
  45. specular = pow(specModifier, lightSpecPower) * specColour * lightSpecColour;
  46. specular.a *= diffuseColour.a;
  47. diffuse = lightSpecColour * diffuseColour * colourIntensity;
  48. }
  49. //add light colour
  50. diffuseColour.rgb += ((lightColour * lightPower) * colourIntensity);
  51. diffuseColour.rgb *= diffuseColour.rgb;
  52. //output sum
  53. gl_FragColor = clamp(specular + diffuse + diffuseColour, 0.0, 1.0);
  54. }