From 73d162337c473a013773509ef313863ff3fbb38b Mon Sep 17 00:00:00 2001 From: Eryn Wells Date: Wed, 21 Nov 2018 08:19:41 -0700 Subject: [PATCH] Attempt to do Phong shading in the fragment shader --- Terrain2/Shaders/Shaders.metal | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/Terrain2/Shaders/Shaders.metal b/Terrain2/Shaders/Shaders.metal index 171280a..5348d42 100644 --- a/Terrain2/Shaders/Shaders.metal +++ b/Terrain2/Shaders/Shaders.metal @@ -43,7 +43,7 @@ vertex ColorInOut vertexShader(Vertex in [[stage_in]], out.position = uniforms.projectionMatrix * eyeCoords; out.eyeCoords = eyeCoords; - out.normal = in.normal; + out.normal = normalize(in.normal); out.texCoord = in.texCoord; return out; @@ -53,10 +53,24 @@ fragment float4 fragmentShader(ColorInOut in [[stage_in]], constant Uniforms &uniforms [[buffer(BufferIndexUniforms)]]) { float3 normal = normalize(uniforms.normalMatrix * in.normal); - float3 lightDirection = -in.eyeCoords.xyz; + float3 lightDirection = normalize(float3(-8, 8, 1) - in.eyeCoords.xyz); + float3 viewDirection = normalize(-in.eyeCoords.xyz); + float3 reflection = -reflect(lightDirection, normal); + + float4 out; float lightDotNormal = dot(normal, lightDirection); - float4 color(abs(lightDotNormal) * float3(0.2), 1.0); - return color; + if (lightDotNormal <= 0.0) { + // No color contribution to this pixel. + out = float4(); + } else { + float3 color = 0.8 * lightDotNormal * float3(0.6); + float reflectDotViewDirection = dot(reflection, viewDirection); + if (reflectDotViewDirection > 0.0) { + color += 0.4 * pow(reflectDotViewDirection, 10) * float3(0, 0, 1); + } + out = float4(color, 1); + } + return out; } #pragma mark - Normal Shaders