1 #define GL_GLEXT_PROTOTYPES 1
14 #include "effect_chain.h"
15 #include "gamma_expansion_effect.h"
16 #include "gamma_compression_effect.h"
17 #include "lift_gamma_gain_effect.h"
18 #include "colorspace_conversion_effect.h"
19 #include "sandbox_effect.h"
20 #include "saturation_effect.h"
21 #include "mirror_effect.h"
22 #include "vignette_effect.h"
23 #include "blur_effect.h"
24 #include "diffusion_effect.h"
27 EffectChain::EffectChain(unsigned width, unsigned height)
32 Input *EffectChain::add_input(const ImageFormat &format)
34 Input *input = new Input(format, width, height);
35 effects.push_back(input);
36 output_color_space.insert(std::make_pair(input, format.color_space));
37 output_gamma_curve.insert(std::make_pair(input, format.gamma_curve));
38 effect_ids.insert(std::make_pair(input, "src_image"));
39 incoming_links.insert(std::make_pair(input, std::vector<Effect *>()));
43 void EffectChain::add_output(const ImageFormat &format)
45 output_format = format;
48 void EffectChain::add_effect_raw(Effect *effect, const std::vector<Effect *> &inputs)
51 sprintf(effect_id, "eff%u", (unsigned)effects.size());
53 effects.push_back(effect);
54 effect_ids.insert(std::make_pair(effect, effect_id));
55 assert(inputs.size() == effect->num_inputs());
56 for (unsigned i = 0; i < inputs.size(); ++i) {
57 assert(std::find(effects.begin(), effects.end(), inputs[i]) != effects.end());
58 outgoing_links[inputs[i]].push_back(effect);
60 incoming_links.insert(std::make_pair(effect, inputs));
61 output_gamma_curve[effect] = output_gamma_curve[last_added_effect()];
62 output_color_space[effect] = output_color_space[last_added_effect()];
65 Effect *instantiate_effect(EffectId effect)
68 case EFFECT_GAMMA_EXPANSION:
69 return new GammaExpansionEffect();
70 case EFFECT_GAMMA_COMPRESSION:
71 return new GammaCompressionEffect();
72 case EFFECT_COLOR_SPACE_CONVERSION:
73 return new ColorSpaceConversionEffect();
75 return new SandboxEffect();
76 case EFFECT_LIFT_GAMMA_GAIN:
77 return new LiftGammaGainEffect();
78 case EFFECT_SATURATION:
79 return new SaturationEffect();
81 return new MirrorEffect();
83 return new VignetteEffect();
85 return new BlurEffect();
86 case EFFECT_DIFFUSION:
87 return new DiffusionEffect();
92 Effect *EffectChain::normalize_to_linear_gamma(Effect *input)
94 assert(output_gamma_curve.count(input) != 0);
95 if (output_gamma_curve[input] == GAMMA_sRGB) {
96 // TODO: check if the extension exists
97 effects[0]->set_int("use_srgb_texture_format", 1);
98 output_gamma_curve[input] = GAMMA_LINEAR;
101 GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
102 gamma_conversion->set_int("source_curve", output_gamma_curve[input]);
103 std::vector<Effect *> inputs;
104 inputs.push_back(input);
105 gamma_conversion->add_self_to_effect_chain(this, inputs);
106 output_gamma_curve[gamma_conversion] = GAMMA_LINEAR;
107 return gamma_conversion;
111 Effect *EffectChain::normalize_to_srgb(Effect *input)
113 assert(output_gamma_curve.count(input) != 0);
114 assert(output_color_space.count(input) != 0);
115 assert(output_gamma_curve[input] == GAMMA_LINEAR);
116 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
117 colorspace_conversion->set_int("source_space", output_color_space[input]);
118 colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
119 std::vector<Effect *> inputs;
120 inputs.push_back(input);
121 colorspace_conversion->add_self_to_effect_chain(this, inputs);
122 output_color_space[colorspace_conversion] = COLORSPACE_sRGB;
123 return colorspace_conversion;
126 Effect *EffectChain::add_effect(EffectId effect_id, const std::vector<Effect *> &inputs)
128 Effect *effect = instantiate_effect(effect_id);
130 assert(inputs.size() == effect->num_inputs());
132 std::vector<Effect *> normalized_inputs = inputs;
133 for (unsigned i = 0; i < normalized_inputs.size(); ++i) {
134 assert(output_gamma_curve.count(normalized_inputs[i]) != 0);
135 if (effect->needs_linear_light() && output_gamma_curve[normalized_inputs[i]] != GAMMA_LINEAR) {
136 normalized_inputs[i] = normalize_to_linear_gamma(normalized_inputs[i]);
138 assert(output_color_space.count(normalized_inputs[i]) != 0);
139 if (effect->needs_srgb_primaries() && output_color_space[normalized_inputs[i]] != COLORSPACE_sRGB) {
140 normalized_inputs[i] = normalize_to_srgb(normalized_inputs[i]);
144 effect->add_self_to_effect_chain(this, normalized_inputs);
148 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
149 std::string replace_prefix(const std::string &text, const std::string &prefix)
154 while (start < text.size()) {
155 size_t pos = text.find("PREFIX(", start);
156 if (pos == std::string::npos) {
157 output.append(text.substr(start, std::string::npos));
161 output.append(text.substr(start, pos - start));
162 output.append(prefix);
165 pos += strlen("PREFIX(");
167 // Output stuff until we find the matching ), which we then eat.
169 size_t end_arg_pos = pos;
170 while (end_arg_pos < text.size()) {
171 if (text[end_arg_pos] == '(') {
173 } else if (text[end_arg_pos] == ')') {
181 output.append(text.substr(pos, end_arg_pos - pos));
189 EffectChain::Phase EffectChain::compile_glsl_program(const std::vector<Effect *> &inputs, const std::vector<Effect *> &effects)
191 assert(!inputs.empty());
192 assert(!effects.empty());
194 // Figure out the true set of inputs to this phase. These are the ones
195 // that we need somehow but don't calculate ourselves.
196 std::set<Effect *> effect_set(effects.begin(), effects.end());
197 std::set<Effect *> input_set(inputs.begin(), inputs.end());
198 std::vector<Effect *> true_inputs;
199 std::set_difference(input_set.begin(), input_set.end(),
200 effect_set.begin(), effect_set.end(),
201 std::back_inserter(true_inputs));
203 bool input_needs_mipmaps = false;
204 std::string frag_shader = read_file("header.frag");
206 // Create functions for all the texture inputs that we need.
207 for (unsigned i = 0; i < true_inputs.size(); ++i) {
208 Effect *effect = true_inputs[i];
209 assert(effect_ids.count(effect) != 0);
210 std::string effect_id = effect_ids[effect];
212 frag_shader += std::string("uniform sampler2D tex_") + effect_id + ";\n";
213 frag_shader += std::string("vec4 ") + effect_id + "(vec2 tc) {\n";
214 if (effect->num_inputs() == 0) {
215 // OpenGL's origin is bottom-left, but most graphics software assumes
216 // a top-left origin. Thus, for inputs that come from the user,
217 // we flip the y coordinate. However, for FBOs, the origin
218 // is all correct, so don't do anything.
219 frag_shader += "\ttc.y = 1.0f - tc.y;\n";
221 frag_shader += "\treturn texture2D(tex_" + effect_id + ", tc);\n";
222 frag_shader += "}\n";
226 std::string last_effect_id;
227 for (unsigned i = 0; i < effects.size(); ++i) {
228 Effect *effect = effects[i];
229 assert(effect != NULL);
230 assert(effect_ids.count(effect) != 0);
231 std::string effect_id = effect_ids[effect];
232 last_effect_id = effect_id;
234 if (incoming_links[effect].size() == 1) {
235 frag_shader += std::string("#define INPUT ") + effect_ids[incoming_links[effect][0]] + "\n";
237 for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
239 sprintf(buf, "#define INPUT%d %s\n", j + 1, effect_ids[incoming_links[effect][j]].c_str());
245 frag_shader += std::string("#define FUNCNAME ") + effect_id + "\n";
246 frag_shader += replace_prefix(effect->output_convenience_uniforms(), effect_id);
247 frag_shader += replace_prefix(effect->output_fragment_shader(), effect_id);
248 frag_shader += "#undef PREFIX\n";
249 frag_shader += "#undef FUNCNAME\n";
250 if (incoming_links[effect].size() == 1) {
251 frag_shader += "#undef INPUT\n";
253 for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
255 sprintf(buf, "#undef INPUT%d\n", j + 1);
261 input_needs_mipmaps |= effect->needs_mipmaps();
263 for (unsigned i = 0; i < effects.size(); ++i) {
264 Effect *effect = effects[i];
265 if (effect->num_inputs() == 0) {
266 effect->set_int("needs_mipmaps", input_needs_mipmaps);
269 assert(!last_effect_id.empty());
270 frag_shader += std::string("#define INPUT ") + last_effect_id + "\n";
271 frag_shader.append(read_file("footer.frag"));
272 printf("%s\n", frag_shader.c_str());
274 GLuint glsl_program_num = glCreateProgram();
275 GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
276 GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
277 glAttachShader(glsl_program_num, vs_obj);
279 glAttachShader(glsl_program_num, fs_obj);
281 glLinkProgram(glsl_program_num);
285 phase.glsl_program_num = glsl_program_num;
286 phase.input_needs_mipmaps = input_needs_mipmaps;
287 phase.inputs = true_inputs;
288 phase.effects = effects;
293 // Construct GLSL programs, starting at the given effect and following
294 // the chain from there. We end a program every time we come to an effect
295 // marked as "needs texture bounce", one that is used by multiple other
296 // effects, and of course at the end.
297 void EffectChain::construct_glsl_programs(Effect *start, std::set<Effect *> *completed_effects)
299 assert(start != NULL);
300 if (completed_effects->count(start) != 0) {
301 // This has already been done for us.
305 std::vector<Effect *> this_phase_inputs; // Also includes all intermediates; these will be filtered away later.
306 std::vector<Effect *> this_phase_effects;
307 Effect *node = start;
308 for ( ;; ) { // Termination condition within loop.
309 assert(node != NULL);
311 // Check that we have all the inputs we need for this effect.
312 // If not, we end the phase here right away; the other side
313 // of the input chain will eventually come and pick the effect up.
314 assert(incoming_links.count(node) == 1);
315 std::vector<Effect *> deps = incoming_links[node];
316 assert(node->num_inputs() == deps.size());
318 bool have_all_deps = true;
319 for (unsigned i = 0; i < deps.size(); ++i) {
320 if (completed_effects->count(deps[i]) == 0) {
321 have_all_deps = false;
326 if (!have_all_deps) {
327 if (!this_phase_effects.empty()) {
328 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
332 this_phase_inputs.insert(this_phase_inputs.end(), deps.begin(), deps.end());
334 this_phase_effects.push_back(node);
335 completed_effects->insert(node);
337 // Find all the effects that use this one as a direct input.
338 if (outgoing_links.count(node) == 0) {
339 // End of the line; output.
340 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
344 std::vector<Effect *> next = outgoing_links[node];
345 assert(!next.empty());
346 if (next.size() > 1) {
347 if (node->num_inputs() != 0) {
348 // More than one effect uses this as the input, and it is not a texture itself.
349 // The easiest thing to do (and probably also the safest
350 // performance-wise in most cases) is to bounce it to a texture
351 // and then let the next passes read from that.
352 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
355 // Start phases for all the effects that need us (in arbitrary order).
356 for (unsigned i = 0; i < next.size(); ++i) {
357 construct_glsl_programs(next[i], completed_effects);
362 // OK, only one effect uses this as the input. Keep iterating,
363 // but first see if it requires a texture bounce; if so, give it
364 // one by starting a new phase.
366 if (node->needs_texture_bounce()) {
367 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
368 this_phase_inputs.clear();
369 this_phase_effects.clear();
374 void EffectChain::finalize()
376 // Add normalizers to get the output format right.
377 assert(output_gamma_curve.count(last_added_effect()) != 0);
378 assert(output_color_space.count(last_added_effect()) != 0);
379 ColorSpace current_color_space = output_color_space[last_added_effect()]; // FIXME
380 if (current_color_space != output_format.color_space) {
381 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
382 colorspace_conversion->set_int("source_space", current_color_space);
383 colorspace_conversion->set_int("destination_space", output_format.color_space);
384 std::vector<Effect *> inputs;
385 inputs.push_back(last_added_effect());
386 colorspace_conversion->add_self_to_effect_chain(this, inputs);
387 output_color_space[colorspace_conversion] = output_format.color_space;
389 GammaCurve current_gamma_curve = output_gamma_curve[last_added_effect()]; // FIXME
390 if (current_gamma_curve != output_format.gamma_curve) {
391 if (current_gamma_curve != GAMMA_LINEAR) {
392 normalize_to_linear_gamma(last_added_effect()); // FIXME
394 assert(current_gamma_curve == GAMMA_LINEAR);
395 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
396 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
397 std::vector<Effect *> inputs;
398 inputs.push_back(last_added_effect());
399 gamma_conversion->add_self_to_effect_chain(this, inputs);
400 output_gamma_curve[gamma_conversion] = output_format.gamma_curve;
403 // Construct all needed GLSL programs, starting at the input.
404 std::set<Effect *> completed_effects;
405 construct_glsl_programs(effects[0], &completed_effects);
407 // If we have more than one phase, we need intermediate render-to-texture.
408 // Construct an FBO, and then as many textures as we need.
409 // We choose the simplest option of having one texture per output,
410 // since otherwise this turns into an (albeit simple)
411 // register allocation problem.
412 if (phases.size() > 1) {
413 glGenFramebuffers(1, &fbo);
415 for (unsigned i = 0; i < phases.size() - 1; ++i) {
416 Effect *output_effect = phases[i].effects.back();
418 glGenTextures(1, &temp_texture);
420 glBindTexture(GL_TEXTURE_2D, temp_texture);
422 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
424 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
426 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
428 effect_output_textures.insert(std::make_pair(output_effect, temp_texture));
432 (static_cast<Input *>(effects[0]))->finalize();
437 void EffectChain::render_to_screen()
444 glDisable(GL_DEPTH_TEST);
446 glDepthMask(GL_FALSE);
449 glMatrixMode(GL_PROJECTION);
451 glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
453 glMatrixMode(GL_MODELVIEW);
456 if (phases.size() > 1) {
457 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
461 std::set<Effect *> generated_mipmaps;
462 generated_mipmaps.insert(effects[0]); // Already done further up.
464 for (unsigned phase = 0; phase < phases.size(); ++phase) {
465 glUseProgram(phases[phase].glsl_program_num);
468 // Set up RTT inputs for this phase.
469 for (unsigned sampler = 0; sampler < phases[phase].inputs.size(); ++sampler) {
470 glActiveTexture(GL_TEXTURE0 + sampler);
471 Effect *input = phases[phase].inputs[sampler];
472 assert(effect_output_textures.count(input) != 0);
473 glBindTexture(GL_TEXTURE_2D, effect_output_textures[input]);
475 if (phases[phase].input_needs_mipmaps) {
476 if (generated_mipmaps.count(input) == 0) {
477 glGenerateMipmap(GL_TEXTURE_2D);
479 generated_mipmaps.insert(input);
481 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
484 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
488 assert(effect_ids.count(input));
489 std::string texture_name = std::string("tex_") + effect_ids[input];
490 glUniform1i(glGetUniformLocation(phases[phase].glsl_program_num, texture_name.c_str()), sampler);
494 // And now the output.
495 if (phase == phases.size() - 1) {
496 // Last phase goes directly to the screen.
497 glBindFramebuffer(GL_FRAMEBUFFER, 0);
500 Effect *last_effect = phases[phase].effects.back();
501 assert(effect_output_textures.count(last_effect) != 0);
502 glFramebufferTexture2D(
504 GL_COLOR_ATTACHMENT0,
506 effect_output_textures[last_effect],
511 // Give the required parameters to all the effects.
512 unsigned sampler_num = phases[phase].inputs.size();
513 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
514 Effect *effect = phases[phase].effects[i];
515 effect->set_gl_state(phases[phase].glsl_program_num, effect_ids[effect], &sampler_num);
521 glTexCoord2f(0.0f, 0.0f);
522 glVertex2f(0.0f, 0.0f);
524 glTexCoord2f(1.0f, 0.0f);
525 glVertex2f(1.0f, 0.0f);
527 glTexCoord2f(1.0f, 1.0f);
528 glVertex2f(1.0f, 1.0f);
530 glTexCoord2f(0.0f, 1.0f);
531 glVertex2f(0.0f, 1.0f);
536 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
537 Effect *effect = phases[phase].effects[i];
538 effect->clear_gl_state();