2 #include "ambientocclusion.h"
14 AmbientOcclusion::AmbientOcclusion(unsigned w, unsigned h, float):
15 occlude_target(w, h, (RENDER_COLOR,RGB)),
16 occlude_shader("ambientocclusion_occlude.glsl"),
17 combine_shader("ambientocclusion_combine.glsl"),
18 quad(get_fullscreen_quad())
20 occlude_target.set_texture_filter(LINEAR);
21 texturing.attach(2, occlude_target.get_target_texture(RENDER_COLOR));
24 rotate_lookup.storage(RGBA, 4, 4);
25 rotate_lookup.set_filter(NEAREST);
26 unsigned char data[64];
27 for(unsigned i=0; i<16; ++i)
29 Geometry::Angle<float> a = Geometry::Angle<float>::from_turns(random(seed));
30 unsigned char c = (cos(a)*0.5f+0.5f)*255;
31 unsigned char s = (sin(a)*0.5f+0.5f)*255;
35 data[i*3+4] = ((i+i/4)%2)*255;
37 rotate_lookup.image(0, RGBA, UNSIGNED_BYTE, data);
39 texturing.attach(3, rotate_lookup);
41 shdata.uniform("source", 0);
42 shdata.uniform("depth", 1);
43 shdata.uniform("occlusion", 2);
44 shdata.uniform("rotate", 3);
45 shdata.uniform("inverse_projection", Matrix());
48 set_occlusion_radius(0.5f);
52 float AmbientOcclusion::random(unsigned &seed)
54 static const unsigned modulus = (1U<<31)-1;
55 seed = (static_cast<UInt64>(seed)*48271)%modulus; // minstd
56 return static_cast<float>(seed)/(modulus-1);
59 void AmbientOcclusion::set_n_samples(unsigned n)
62 throw out_of_range("AmbientOcclusion::set_n_samples");
65 float radius_divisor = (n-1)*(n-1);
66 Vector3 sample_points[32];
67 for(unsigned i=0; i<n; ++i)
69 Vector3 v(random(seed)-0.5f, random(seed)-0.5f, random(seed)-0.5f);
70 sample_points[i] = normalize(v)*(0.1f+0.9f*i*i/radius_divisor);
72 shdata.uniform3_array("sample_points", n, &sample_points[0].x);
73 shdata.uniform("n_samples", static_cast<int>(n));
76 void AmbientOcclusion::set_occlusion_radius(float r)
78 shdata.uniform("occlusion_radius", r);
81 void AmbientOcclusion::set_depth_ratio(float)
85 void AmbientOcclusion::set_darkness(float darkness)
87 shdata.uniform("darkness", darkness);
90 void AmbientOcclusion::render(Renderer &renderer, const Texture2D &color, const Texture2D &depth)
92 texturing.attach(0, color);
93 texturing.attach(1, depth);
95 if(renderer.get_camera())
96 shdata.uniform("inverse_projection", invert(renderer.get_camera()->get_projection_matrix()));
98 Renderer::Push push(renderer);
99 renderer.set_texturing(&texturing);
100 renderer.set_shader_program(&occlude_shader, &shdata);
103 BindRestore bind_fbo(occlude_target.get_framebuffer());
107 renderer.set_shader_program(&combine_shader);