summaryrefslogtreecommitdiffhomepage
path: root/examples/models/resources/shaders/irradiance.fs
blob: 87113673f404bdda7f43d3a42cc2e9615e2f3b22 (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
/*******************************************************************************************
*
*   rPBR [shader] - Irradiance cubemap fragment shader
*
*   Copyright (c) 2017 Victor Fisac
*
**********************************************************************************************/

#version 330

// Input vertex attributes (from vertex shader)
in vec3 fragPos;

// Input uniform values
uniform samplerCube environmentMap;

// Constant values
const float PI = 3.14159265359f;

// Output fragment color
out vec4 finalColor;

void main()
{
    // The sample direction equals the hemisphere's orientation
    vec3 normal = normalize(fragPos);

    vec3 irradiance = vec3(0.0);  

    vec3 up = vec3(0.0, 1.0, 0.0);
    vec3 right = cross(up, normal);
    up = cross(normal, right);

    float sampleDelta = 0.025f;
    float nrSamples = 0.0f; 

    for (float phi = 0.0; phi < 2.0*PI; phi += sampleDelta)
    {
        for (float theta = 0.0; theta < 0.5*PI; theta += sampleDelta)
        {
            // Spherical to cartesian (in tangent space)
            vec3 tangentSample = vec3(sin(theta)*cos(phi), sin(theta)*sin(phi), cos(theta));
            
            // tangent space to world
            vec3 sampleVec = tangentSample.x*right + tangentSample.y*up + tangentSample.z*normal; 

            // Fetch color from environment cubemap
            irradiance += texture(environmentMap, sampleVec).rgb*cos(theta)*sin(theta);
            nrSamples++;
        }
    }

    // Calculate irradiance average value from samples
    irradiance = PI*irradiance*(1.0/float(nrSamples));

    // Calculate final fragment color
    finalColor = vec4(irradiance, 1.0);
}