Add specular and normal mapping
[opengl.git] / texturefrag.glsl
index 347cc0121f35e4487e770e922c3f633010bf0486..83cce42cc72a6d42d97fbbda5d1e6761c0f80d57 100644 (file)
@@ -3,37 +3,65 @@
 struct Material {
        vec3 ambient;
        vec3 diffuse;
+       sampler2D diffuseMap;
        vec3 specular;
+       sampler2D specularMap;
        float shininess;
+       
        bool hasTexture;
+       bool hasSpecularMap;
+
+       sampler2D normalMap;
+       bool hasNormalMap;
 };
 
-in vec3 normal;
-in vec3 fragPos;
+in vec3 defNormal;
 in vec2 texCoord;
 
-uniform vec3 lightPos;
-uniform vec3 viewPos;
+// These are all in tangent space
+in vec3 lightPos;
+in vec3 viewPos;
+in vec3 fragPos;
+
 uniform vec4 lightColor;
 
 uniform Material material;
-uniform sampler2D tex;
 
 out vec4 FragColor;
 
 void main() {
-       vec3 lightDir = normalize(fragPos - lightPos);
-       vec3 diffuse = max(0, dot(-normal, lightDir)) * material.diffuse;
 
-       vec3 viewDir = normalize(fragPos - viewPos);
-       vec3 reflectDir = reflect(-lightDir, normal);
-       vec3 specular = pow(max(0, dot(viewDir, reflectDir)), material.shininess) * material.specular;
+       vec3 normal;
+       if (material.hasNormalMap) {
+               normal = texture(material.normalMap, texCoord).rgb;
+               normal = normalize(normal * 2 - 1);
+       } else {
+               normal = defNormal;
+       }
 
-       vec4 lighting = vec4(material.ambient + diffuse + specular, 1) * lightColor;
+       vec3 lightDir = normalize(lightPos - fragPos);
        
+       vec4 diffTex;
        if (material.hasTexture)
-               FragColor = lighting * texture(tex, texCoord);
+               diffTex = texture(material.diffuseMap, texCoord);
        else
+               diffTex = vec4(1);
+       vec4 diffuse = vec4(max(0, dot(lightDir, normal)) * material.diffuse, 1) * diffTex;
+
+       vec3 viewDir = normalize(viewPos - fragPos);
+       vec3 reflectDir = reflect(-lightDir, normal);
+
+
+       vec4 specTex;
+       if (material.hasSpecularMap)
+               specTex = texture(material.specularMap, texCoord);
+       else
+               specTex = vec4(1);
+
+       vec4 specular = vec4(pow(max(0, dot(viewDir, reflectDir)), material.shininess) * material.specular, 1) * specTex;
+
+       vec4 lighting = (vec4(material.ambient, 1) + diffuse + specular) * lightColor;
+
        FragColor = lighting;
 }