aboutsummaryrefslogtreecommitdiff
path: root/shaders/prefiltered_environment_map.frag
blob: 8327950ebeec3023a51fb7e692dc3592493394ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
precision highp float;

#define PI 3.1415926535897932384626433832795
#define NUM_SAMPLES 4096

uniform samplerCube Sky;
uniform float Roughness;

in vec3 Ray;

layout (location = 0) out vec4 Color;

float radical_inverse_VdC(uint bits) {
    bits = (bits << 16u) | (bits >> 16u);
    bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
    bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
    bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
    bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
    return float(bits) * 2.3283064365386963e-10; // / 0x100000000
}

vec2 hammersley(uint i, uint N) {
    return vec2(float(i)/float(N), radical_inverse_VdC(i));
}

vec3 importance_sample_GGX(vec2 sample_box, vec3 N, float roughness) {
  float r2 = roughness * roughness;

  // Spherical coordinates.
  float phi = 2.0 * PI * sample_box.x;
  float cos_theta = sqrt((1.0 - sample_box.y) / (1.0 + (r2*r2 - 1.0) * sample_box.y));
  float sin_theta = sqrt(1.0 - cos_theta * cos_theta);

  // Map spherical coordinates to Cartesian coordinates in tangent space.
  vec3 H = vec3(cos(phi) * sin_theta, sin(phi) * sin_theta, cos_theta);

  // Map from tangent space to world space.
  //
  // Tangent space:
  //
  //        N
  //        |
  //        |
  //        |
  //        |_ _ _ _ _ B
  //       /
  //      /
  //     T
  vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
  vec3 T = normalize(cross(up,N));
  vec3 B = cross(N,T);
  vec3 H_ws = H.x*T + H.y*B + H.z*N;
  return H_ws;
}

void main()
{
  vec3 N = normalize(Ray);
  vec3 R = N;
  vec3 V = R;

  vec3 irradiance = vec3(0.0);
  float total_weight = 0.0;
  for (uint i = 0; i < NUM_SAMPLES; ++i) {
    vec2 sample_box = hammersley(i, NUM_SAMPLES);
    vec3 H = importance_sample_GGX(sample_box, N, Roughness);
    vec3 L = reflect(-V,H);

    float NdotL = max(dot(N,L), 0.0);
    if (NdotL > 0.0) {
      irradiance += texture(Sky, H).rgb * NdotL;
      total_weight += NdotL;
    }
  }
  irradiance /= total_weight;

  Color = vec4(irradiance, 1.0);
}