Skip to content

Instantly share code, notes, and snippets.

@adrian-afl
Created June 4, 2015 10:36
Show Gist options
  • Save adrian-afl/cfee5534b38eda7c66eb to your computer and use it in GitHub Desktop.
Save adrian-afl/cfee5534b38eda7c66eb to your computer and use it in GitHub Desktop.
vec2 projdir(vec3 start, vec3 end)
{
vec4 clipspace = (ProjectionMatrix * ViewMatrix) * vec4((start), 1.0);
vec2 sspace1 = ((clipspace.xyz / clipspace.w).xy + 1.0) / 2.0;
clipspace = (ProjectionMatrix * ViewMatrix) * vec4((end), 1.0);
vec2 sspace2 = ((clipspace.xyz / clipspace.w).xy + 1.0) / 2.0;
return (sspace2 - sspace1);
}
bool testVisibility3d(vec2 cuv, vec3 w1, vec3 w2)
{
float d3d1 = length(w1);
float d3d2 = length(w2);
vec2 sdir = projdir(FromCameraSpace(w1), FromCameraSpace(w2));
for(float i=0;i<1.0;i+= 0.1)
{
vec2 ruv = mix(cuv, cuv + sdir, i);
vec3 wd = texture(worldPosTex, ruv).rgb;
float rd3d = length(wd) + 0.01;
if(rd3d < mix(d3d1, d3d2, i) && mix(d3d1, d3d2, i) - rd3d < 1.01)
{
return false;
}
}
return true;
}
float rand(vec2 co){
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
vec3 VDAO()
{
vec3 posCenter = texture(worldPosTex, UV).rgb;
vec3 normalCenter = normalize(texture(normalsTex, UV).rgb);
vec3 ambient = vec3(0);
const int samples = 65;
// choose between noisy and slower, but better looking variant
//float randomizer = 138.345341 * rand(UV);
// or faster, non noisy variant, which is also cool looking
const float randomizer = 138.345341;
uint counter = 0;
for(int i=0;i<samples;i++)
{
float rd = randomizer * float(i);
vec3 displace = vec3(
fract(rd) * 2 - 1,
fract(rd*12.2562),
fract(rd*7.121214) * 2 - 1
) * clamp(length(posCenter), 0.1, 2.0);
float dotdiffuse = 1.0 - max(0, dot(normalize(displace), (normalCenter.xyz)));
for(int div = 0;div < 2; div++)
{
if(testVisibility3d(UV, posCenter, posCenter + displace))
{
ambient += vec3(1,1,1) * dotdiffuse;
}
displace = displace * 0.5;
counter++;
}
}
vec3 rs = counter == 0 ? vec3(0) : (ambient / (counter));
return rs;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment