Fix maps not being bound in materials
[opengl.git] / prefilterfrag.glsl
1 #version 330
2
3 in vec3 localPos, normal;
4 out vec4 fragColor;
5
6 uniform samplerCube environmentMap;
7 uniform float roughness;
8
9 const float PI = 3.14159265359;
10
11 //TODO: Put this in a separate shader program
12 float radicalInverse(uint bits) {
13         bits = (bits << 16u) | (bits >> 16u);
14         bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
15     bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
16     bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
17     bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
18     return float(bits) * 2.3283064365386963e-10;
19 }
20
21 vec2 hammersley(uint i, uint N) {
22         return vec2(float(i) / float(N), radicalInverse(i));
23 }
24
25 vec3 importanceSampleGGX(vec2 Xi, vec3 N, float roughness) {
26         float a = roughness * roughness;
27
28         float phi = 2.f * PI * Xi.x;
29         float cosTheta = sqrt((1.f - Xi.y) / (1.f + (a * a - 1.f) * Xi.y));
30         float sinTheta = sqrt(1.f - cosTheta * cosTheta);
31
32         // spherical -> cartesian
33         vec3 H = vec3(cos(phi) * sinTheta, sin(phi) * sinTheta, cosTheta);
34
35         vec3 up = abs(N.z) < 0.999 ? vec3(0, 0, 1) : vec3(1, 0, 0);
36         vec3 tangent = normalize(cross(up, N));
37         vec3 bitangent = cross(N, tangent);
38
39         vec3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z;
40         return normalize(sampleVec);
41 }
42
43 void main() {
44         vec3 N = normalize(localPos);
45
46         // approximate view direction - no grazing specular reflections
47         vec3 R = N;
48         vec3 V = R;
49
50         const uint sampleCount = 1024u;
51         float totalWeight = 0;
52         vec3 prefilteredColor = vec3(0);
53         for (uint i = 0u; i < sampleCount; i++) {
54                 vec2 Xi = hammersley(i, sampleCount);
55                 vec3 H = importanceSampleGGX(Xi, N, roughness);
56                 vec3 L = normalize(2.f * dot(V, H) * H - V);
57
58                 float NdotL = max(dot(N, L), 0.f);
59                 if (NdotL > 0) {
60                         prefilteredColor += texture(environmentMap, L).rgb * NdotL;
61                         totalWeight += NdotL;
62                 }
63         }
64
65         prefilteredColor = prefilteredColor / totalWeight;
66         fragColor = vec4(prefilteredColor, 1.f);
67 }