Debian Codegraph @

avogadro/rendering/sphere_ao_bake_fs.glsl

raw
1 //////////////////////////////////////////////////////////////////////
2 //
3 // Ambient occlusion shader for sphere impostors
4 //
5 // This fragment shader is used for baking the ambient occlusion
6 // maps.
7 //
8 //////////////////////////////////////////////////////////////////////
9
10 //
11 // Input
12 //
13 #version 400
14 precision highp float;
15 // the sphere center position: eye coords
16 in vec3 v_pos;
17 // the sphere radius
18 in float v_radius;
19 // stretched corner: [-1.x, 1.x] (see below)
20 in vec2 v_corner;
21
22 //
23 // Uniforms
24 //
25
26 // the model-view matrix
27 uniform mat4 u_modelView;
28 // the orthographic projection matrix
29 uniform mat4 u_projection;
30 // depth texture sampler
31 uniform sampler2D u_depthTex;
32 // intensity = 1 / (number of light directions)
33 uniform float u_intensity;
34
35 out vec4 outColor;
36
37 /**
38 * Inverse gnomonic projection over octahedron unfloded into a square. This
39 * inverse projection goes from texture coordinates to the surface of the unit
40 * sphere. Both the texture and unit sphere coordinates are in the range
41 * [-1, 1].
42 *
43 * In practice, this function returns the normal vector in model coordinate
44 * space. The z is inverted since going from clip coords to NDC inverts the
45 * z axis.
46 *
47 * reference: Tarini et al. page 3, eq. (5)
48 */
49 vec3 textureToSphereSurfaceCoord(in vec2 coord)
50 {
51 vec2 absCoord = abs(coord);
52 float h = 1.0 - absCoord.s - absCoord.t;
53 return (h >= 0.0) ? vec3(coord.st, -h) : vec3(sign(coord.st) * (1.0 - absCoord.ts), -h);
54 }
55
56 void main()
57 {
58 // map texture coords to normal in model coords
59 vec3 N = textureToSphereSurfaceCoord(clamp(v_corner, -1.0, 1.0));
60
61 // model coords -> eye coords
62 N = normalize(vec3(u_modelView * vec4(N, 0.0)));
63
64 // add the normal xy components to the sphere eye coords
65 vec4 pos = vec4(v_pos, 1.0);
66 pos.xy += N.xy * v_radius;
67 // eye coord -> clip coords [-1, 1]
68 pos = u_projection * pos;
69 // clip coords -> [0, 1] for xy and [near, far] for z
70 pos.xy = (pos.xy + vec2(1.0, 1.0)) / 2.0;
71 pos.z = ((gl_DepthRange.diff * pos.z) + gl_DepthRange.near + gl_DepthRange.far) / 2.0;
72
73 // compute angle between sphere surface and light direction
74 float cos_alpha = dot(N, vec3(0, 0, 1));
75
76 // since we are using flat impostors in the depth texture, cos_alpha needs to be positive
77 if (cos_alpha > 0.0 && texture(u_depthTex, pos.xy).r > pos.z) {
78 // the texel is visible from the light source
79 outColor = vec4(vec3(1.0, 1.0, 1.0) * cos_alpha * u_intensity, 1.0);
80 } else {
81 // texel not visible
82 outColor = vec4(0.0, 0.0, 0.0, 0.0);
83 }
84
85 }