Skip to content
0.2.0-dev Download ZIP
50 lines ·2.1 KB Raw
1// S4AO (Stupid Simple Screen Space Ambient Occlusion) - Jonathan Dummer (O1S)
2// The mega version uses N concentric rings of samples.
3
4#if defined(USE_SSAO_MEGA)
5const int rings = 4; // Start with the outer ring.
6const int samps[] = int[](24, 18, 12, 6); // ( 9, 6, 3 ) is a minimum, but I want better.
7#else
8const int rings = 3; // Start with the outer ring.
9const int samps[] = int[](15, 10, 5, 1); // ( 9, 6, 3 ) is a minimum, but I want better.
10#endif
11const float average_samples = 1.0 / float(samps[0] + samps[1] * int(rings > 1) + samps[2] * int(rings > 2) + samps[3] * int(rings > 3));
12const float ssao_falloff_frac = 0.25;
13// Perform the SSAO.
14float s4ao(vec2 UV) {
15#ifdef USE_MULTIVIEW
16 float depth = texture(depth_buffer_array, vec3(UV, view)).r;
17#else
18 float depth = texture(depth_buffer, UV).r;
19#endif
20 float inv_falloff = 1.0f / max(1e-4f, depth * ssao_falloff_frac);
21 // Random 2D rotation per pixel (0..1 -> parabola approximating a 180 deg arc)
22 float r01 = fract(dot(UV, ssao_prn_UV));
23 vec2 rcos = vec2(r01 - 0.5f, 2.0f * (r01 - r01 * r01)) * (2.0f * depth * ssao_radius_frac); // 180 degrees.
24 vec2 rsin = rcos.yx * vec2(-1, 1); // Perpendicular to the random cosine vector.
25 // Grab the samples and determine the occlusion.
26 float occlusion = 0.0f;
27 float ring_shrink = 0.75f; // Shrink every ring.
28 for (int r = 0; r < rings; ++r) {
29 float dt = (6.283185307f) / float(samps[r]);
30 float t = float(r & 1) * 0.5f * dt;
31 for (int s = 0; s < samps[r]; ++s) {
32 vec2 duv = cos(t) * rcos + sin(t) * rsin;
33#ifdef USE_MULTIVIEW
34 float dz = texture(depth_buffer_array, vec3(UV + duv, view)).r - depth;
35#else
36 float dz = texture(depth_buffer, UV + duv).r - depth;
37#endif
38 // How 'directly overhead' is it? Factor in the falloff depth.
39 occlusion += normalize(vec3(duv, dz)).z * smoothstep(1.0f, 0.0f, dz * inv_falloff);
40 t += dt;
41 }
42 // The next ring will be smaller.
43 rcos *= ring_shrink;
44 rsin *= ring_shrink;
45 }
46 // Adjust the occlusion for intensity, and # samples.
47 occlusion *= ssao_intensity * average_samples;
48 occlusion = 1.0f - clamp(occlusion, 0.0f, 1.0f);
49 return occlusion * occlusion;
50}