3 This file is part of libmspgl
4 Copyright © 2009 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
9 #include <msp/strings/formatter.h>
12 #include "meshbuilder.h"
21 static const char blur_vs[]=
22 "varying vec2 texcoord;\n"
25 " gl_Position = vec4(gl_Vertex.xy*2.0-1.0, 0.0, 1.0);\n"
26 " texcoord = gl_Vertex.xy;\n"
29 static const char blur_fs[]=
30 "uniform sampler2D source;\n"
31 "uniform vec2 delta;\n"
32 "uniform float factors[19];\n"
34 "varying vec2 texcoord;\n"
37 " gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);\n"
38 " for(int i=-size; i<=size; ++i)\n"
39 " gl_FragColor += texture2D(source, texcoord+delta*i)*factors[i+size];\n"
42 static const char combine_vs[]=
43 "varying vec2 texcoord;\n"
46 " gl_Position = vec4(gl_Vertex.xy*2.0-1.0, 0.0, 1.0);\n"
47 " texcoord = gl_Vertex.xy;\n"
50 static const char combine_fs[]=
51 "uniform sampler2D source;\n"
52 "uniform sampler2D blurred;\n"
53 "uniform float strength;\n"
54 "varying vec2 texcoord;\n"
57 " gl_FragColor = mix(texture2D(source, texcoord), texture2D(blurred, texcoord), strength);\n"
65 Bloom::Bloom(unsigned w, unsigned h):
66 blur_shader(blur_vs, blur_fs),
67 combine_shader(combine_vs, combine_fs),
70 int loc = blur_shader.get_uniform_location("delta");
71 blur_shdata[0].uniform(loc, 1.0f/w, 0.0f);
72 blur_shdata[1].uniform(loc, 0.0f, 1.0f/h);
74 loc = blur_shader.get_uniform_location("source");
75 for(unsigned i=0; i<2; ++i)
77 blur_shdata[i].uniform(loc, 0);
78 tex[i].set_min_filter(NEAREST);
79 tex[i].storage(RGB16F, w, h, 0);
80 tex[i].image(0, RGB, UNSIGNED_BYTE, 0);
83 combine_shdata.uniform(combine_shader.get_uniform_location("source"), 1);
84 combine_shdata.uniform(combine_shader.get_uniform_location("blurred"), 0);
89 MeshBuilder mbld(quad);
98 void Bloom::set_radius(float r)
101 throw InvalidParameterValue("Radius must be positive");
103 int size = min(static_cast<int>(r*3.0f), 9);
104 int loc = blur_shader.get_uniform_location("size");
105 blur_shdata[0].uniform(loc, size);
106 blur_shdata[1].uniform(loc, size);
108 vector<float> factors(size*2+1);
111 for(int i=-size; i<=size; ++i)
112 sum += (factors[size+i] = exp(-i*i/r));
114 for(int i=0; i<=size*2; ++i)
116 loc = blur_shader.get_uniform_location(format("factors[%d]", i));
117 float f = factors[i]/sum;
118 blur_shdata[0].uniform(loc, f);
119 blur_shdata[1].uniform(loc, f);
123 void Bloom::set_strength(float s)
126 throw InvalidParameterValue("Strength must be in the range [0.0, 1.0]");
127 combine_shdata.uniform(combine_shader.get_uniform_location("strength"), s);
130 void Bloom::render(const Texture2D &src)
132 const Framebuffer *dest = Framebuffer::current();
138 for(unsigned i=0; i<2; ++i)
140 fbo.attach(COLOR_ATTACHMENT0, tex[i], 0);
141 blur_shdata[i].apply();
149 Framebuffer::unbind();
151 combine_shader.bind();
152 combine_shdata.apply();
156 Texture::unbind_from(1);
157 Texture::unbind_from(0);
158 // XXX Should check if the modes were enabled in the first place