terrain-gen/shaders/shading.frag

91 lines
2.8 KiB
GLSL

#version 400 core
out vec4 out_color;
uniform sampler2D colorTexture;
uniform sampler2D positionTexture;
uniform sampler2D normalTexture;
uniform sampler2D meshPropertyTexture;
uniform sampler2D depthTexture;
uniform sampler2D shadowMapTexture;
uniform float u_dayNightFactor;
uniform mat4 u_depthVP;
uniform mat4 u_view;
uniform mat4 u_projection;
uniform vec4 u_lightPos;
uniform ivec2 u_screenSize;
uniform vec3 u_cameraPosition;
in vec2 textureCoord;
#include "commonlighting.glsl"
float linearDepth(float depth) {
return (u_projection[3][2] / (u_projection[2][2] + depth));
}
float logDepth(float depth) {
return log(linearDepth(depth));
}
float edgeDetection() {
float meshType = texture2D(meshPropertyTexture, textureCoord).x;
vec2 texelSize = vec2(0.3, 0.3) / u_screenSize;
vec2 coord[4] = vec2[](
vec2(0, 1),
vec2(1, 1),
vec2(1, 0),
vec2(1, -1)
);
for (int i = 0; i < 5; i++) {
vec3 currentNormal = texture2D(normalTexture, textureCoord + coord[i] * texelSize).xyz;
float currentBiome = log(texture2D(meshPropertyTexture, textureCoord + coord[i] * texelSize).y);
float currentDepth = logDepth(texture2D(depthTexture, textureCoord + coord[i] * texelSize).r);
vec4 currentValue = vec4(currentNormal, currentDepth);
vec3 oppositeNormal = texture2D(normalTexture, textureCoord - coord[i] * texelSize).xyz;
float oppositeBiome = log(texture2D(meshPropertyTexture, textureCoord - coord[i] * texelSize).y);
float oppositeDepth = logDepth(texture2D(depthTexture, textureCoord - coord[i] * texelSize).r);
vec4 oppositeValue = vec4(oppositeNormal, oppositeDepth);
if (distance(currentValue, oppositeValue) > 0.1 || distance(currentBiome, oppositeBiome) > 0.2) {
return min(linearDepth(texture2D(depthTexture, textureCoord).r) / 100, 1);
}
}
return 1.0;
}
void main() {
vec3 color = texture2D(colorTexture, textureCoord).rgb;
vec3 worldSpacePosition = texture2D(positionTexture, textureCoord).xyz;
vec3 cameraSpaceNormal = texture2D(normalTexture, textureCoord).xyz;
float depth = texture2D(depthTexture, textureCoord).r;
if (depth == 1) {
discard;
}
float ambiantFactor = 0.2;
float diffuseFactor = 0.7;
float specularFactor = 0;
// Shadow
float shadow = shadow(vec4(worldSpacePosition, 1), cameraSpaceNormal);
float visibility = visibility(shadow);
// Diffuse
float diffuseLight = 0;
if (shadow < 0.9) {
diffuseLight = diffuse(cameraSpaceNormal);
diffuseLight = (ceil(diffuseLight * 3) / 3) * mix(0.2, 1.0, u_dayNightFactor);
}
out_color = vec4(color * (ambiantFactor + diffuseFactor * min(diffuseLight, visibility)) * edgeDetection(), 1);
}