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"
25 #include "glow_effect.h"
26 #include "mix_effect.h"
29 EffectChain::EffectChain(unsigned width, unsigned height)
34 Input *EffectChain::add_input(const ImageFormat &format)
36 Input *input = new Input(format, width, height);
37 effects.push_back(input);
38 inputs.push_back(input);
39 output_color_space.insert(std::make_pair(input, format.color_space));
40 output_gamma_curve.insert(std::make_pair(input, format.gamma_curve));
41 effect_ids.insert(std::make_pair(input, "src_image"));
42 incoming_links.insert(std::make_pair(input, std::vector<Effect *>()));
46 void EffectChain::add_output(const ImageFormat &format)
48 output_format = format;
51 void EffectChain::add_effect_raw(Effect *effect, const std::vector<Effect *> &inputs)
54 sprintf(effect_id, "eff%u", (unsigned)effects.size());
56 effects.push_back(effect);
57 effect_ids.insert(std::make_pair(effect, effect_id));
58 assert(inputs.size() == effect->num_inputs());
59 for (unsigned i = 0; i < inputs.size(); ++i) {
60 assert(std::find(effects.begin(), effects.end(), inputs[i]) != effects.end());
61 outgoing_links[inputs[i]].push_back(effect);
63 incoming_links.insert(std::make_pair(effect, inputs));
64 output_gamma_curve[effect] = output_gamma_curve[last_added_effect()];
65 output_color_space[effect] = output_color_space[last_added_effect()];
68 Effect *instantiate_effect(EffectId effect)
71 case EFFECT_GAMMA_EXPANSION:
72 return new GammaExpansionEffect();
73 case EFFECT_GAMMA_COMPRESSION:
74 return new GammaCompressionEffect();
75 case EFFECT_COLOR_SPACE_CONVERSION:
76 return new ColorSpaceConversionEffect();
78 return new SandboxEffect();
79 case EFFECT_LIFT_GAMMA_GAIN:
80 return new LiftGammaGainEffect();
81 case EFFECT_SATURATION:
82 return new SaturationEffect();
84 return new MirrorEffect();
86 return new VignetteEffect();
88 return new BlurEffect();
89 case EFFECT_DIFFUSION:
90 return new DiffusionEffect();
92 return new GlowEffect();
94 return new MixEffect();
99 // Set the "use_srgb_texture_format" option on all inputs that feed into this node,
100 // and update the output_gamma_curve[] map as we go.
102 // NOTE: We assume that the only way we could actually get GAMMA_sRGB from an
103 // effect (except from GammaCompressionCurve, which should never be inserted
104 // into a chain when this is called) is by pass-through from a texture.
105 // Thus, we can simply feed the flag up towards all inputs.
106 void EffectChain::set_use_srgb_texture_format(Effect *effect)
108 assert(output_gamma_curve.count(effect) != 0);
109 assert(output_gamma_curve[effect] == GAMMA_sRGB);
110 if (effect->num_inputs() == 0) {
111 effect->set_int("use_srgb_texture_format", 1);
113 assert(incoming_links.count(effect) == 1);
114 std::vector<Effect *> deps = incoming_links[effect];
115 assert(effect->num_inputs() == deps.size());
116 for (unsigned i = 0; i < deps.size(); ++i) {
117 set_use_srgb_texture_format(deps[i]);
118 assert(output_gamma_curve[deps[i]] == GAMMA_LINEAR);
121 output_gamma_curve[effect] = GAMMA_LINEAR;
124 Effect *EffectChain::normalize_to_linear_gamma(Effect *input)
126 assert(output_gamma_curve.count(input) != 0);
127 if (output_gamma_curve[input] == GAMMA_sRGB) {
128 // TODO: check if the extension exists
129 set_use_srgb_texture_format(input);
130 output_gamma_curve[input] = GAMMA_LINEAR;
133 GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
134 gamma_conversion->set_int("source_curve", output_gamma_curve[input]);
135 std::vector<Effect *> inputs;
136 inputs.push_back(input);
137 gamma_conversion->add_self_to_effect_chain(this, inputs);
138 output_gamma_curve[gamma_conversion] = GAMMA_LINEAR;
139 return gamma_conversion;
143 Effect *EffectChain::normalize_to_srgb(Effect *input)
145 assert(output_gamma_curve.count(input) != 0);
146 assert(output_color_space.count(input) != 0);
147 assert(output_gamma_curve[input] == GAMMA_LINEAR);
148 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
149 colorspace_conversion->set_int("source_space", output_color_space[input]);
150 colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
151 std::vector<Effect *> inputs;
152 inputs.push_back(input);
153 colorspace_conversion->add_self_to_effect_chain(this, inputs);
154 output_color_space[colorspace_conversion] = COLORSPACE_sRGB;
155 return colorspace_conversion;
158 Effect *EffectChain::add_effect(EffectId effect_id, const std::vector<Effect *> &inputs)
160 Effect *effect = instantiate_effect(effect_id);
162 assert(inputs.size() == effect->num_inputs());
164 std::vector<Effect *> normalized_inputs = inputs;
165 for (unsigned i = 0; i < normalized_inputs.size(); ++i) {
166 assert(output_gamma_curve.count(normalized_inputs[i]) != 0);
167 if (effect->needs_linear_light() && output_gamma_curve[normalized_inputs[i]] != GAMMA_LINEAR) {
168 normalized_inputs[i] = normalize_to_linear_gamma(normalized_inputs[i]);
170 assert(output_color_space.count(normalized_inputs[i]) != 0);
171 if (effect->needs_srgb_primaries() && output_color_space[normalized_inputs[i]] != COLORSPACE_sRGB) {
172 normalized_inputs[i] = normalize_to_srgb(normalized_inputs[i]);
176 effect->add_self_to_effect_chain(this, normalized_inputs);
180 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
181 std::string replace_prefix(const std::string &text, const std::string &prefix)
186 while (start < text.size()) {
187 size_t pos = text.find("PREFIX(", start);
188 if (pos == std::string::npos) {
189 output.append(text.substr(start, std::string::npos));
193 output.append(text.substr(start, pos - start));
194 output.append(prefix);
197 pos += strlen("PREFIX(");
199 // Output stuff until we find the matching ), which we then eat.
201 size_t end_arg_pos = pos;
202 while (end_arg_pos < text.size()) {
203 if (text[end_arg_pos] == '(') {
205 } else if (text[end_arg_pos] == ')') {
213 output.append(text.substr(pos, end_arg_pos - pos));
221 EffectChain::Phase EffectChain::compile_glsl_program(const std::vector<Effect *> &inputs, const std::vector<Effect *> &effects)
223 assert(!inputs.empty());
224 assert(!effects.empty());
226 // Figure out the true set of inputs to this phase. These are the ones
227 // that we need somehow but don't calculate ourselves.
228 std::set<Effect *> effect_set(effects.begin(), effects.end());
229 std::set<Effect *> input_set(inputs.begin(), inputs.end());
230 std::vector<Effect *> true_inputs;
231 std::set_difference(input_set.begin(), input_set.end(),
232 effect_set.begin(), effect_set.end(),
233 std::back_inserter(true_inputs));
235 bool input_needs_mipmaps = false;
236 std::string frag_shader = read_file("header.frag");
238 // Create functions for all the texture inputs that we need.
239 for (unsigned i = 0; i < true_inputs.size(); ++i) {
240 Effect *effect = true_inputs[i];
241 assert(effect_ids.count(effect) != 0);
242 std::string effect_id = effect_ids[effect];
244 frag_shader += std::string("uniform sampler2D tex_") + effect_id + ";\n";
245 frag_shader += std::string("vec4 ") + effect_id + "(vec2 tc) {\n";
246 if (effect->num_inputs() == 0) {
247 // OpenGL's origin is bottom-left, but most graphics software assumes
248 // a top-left origin. Thus, for inputs that come from the user,
249 // we flip the y coordinate. However, for FBOs, the origin
250 // is all correct, so don't do anything.
251 frag_shader += "\ttc.y = 1.0f - tc.y;\n";
253 frag_shader += "\treturn texture2D(tex_" + effect_id + ", tc);\n";
254 frag_shader += "}\n";
258 std::string last_effect_id;
259 for (unsigned i = 0; i < effects.size(); ++i) {
260 Effect *effect = effects[i];
261 assert(effect != NULL);
262 assert(effect_ids.count(effect) != 0);
263 std::string effect_id = effect_ids[effect];
264 last_effect_id = effect_id;
266 if (incoming_links[effect].size() == 1) {
267 frag_shader += std::string("#define INPUT ") + effect_ids[incoming_links[effect][0]] + "\n";
269 for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
271 sprintf(buf, "#define INPUT%d %s\n", j + 1, effect_ids[incoming_links[effect][j]].c_str());
277 frag_shader += std::string("#define FUNCNAME ") + effect_id + "\n";
278 frag_shader += replace_prefix(effect->output_convenience_uniforms(), effect_id);
279 frag_shader += replace_prefix(effect->output_fragment_shader(), effect_id);
280 frag_shader += "#undef PREFIX\n";
281 frag_shader += "#undef FUNCNAME\n";
282 if (incoming_links[effect].size() == 1) {
283 frag_shader += "#undef INPUT\n";
285 for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
287 sprintf(buf, "#undef INPUT%d\n", j + 1);
293 input_needs_mipmaps |= effect->needs_mipmaps();
295 for (unsigned i = 0; i < effects.size(); ++i) {
296 Effect *effect = effects[i];
297 if (effect->num_inputs() == 0) {
298 effect->set_int("needs_mipmaps", input_needs_mipmaps);
301 assert(!last_effect_id.empty());
302 frag_shader += std::string("#define INPUT ") + last_effect_id + "\n";
303 frag_shader.append(read_file("footer.frag"));
304 printf("%s\n", frag_shader.c_str());
306 GLuint glsl_program_num = glCreateProgram();
307 GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
308 GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
309 glAttachShader(glsl_program_num, vs_obj);
311 glAttachShader(glsl_program_num, fs_obj);
313 glLinkProgram(glsl_program_num);
317 phase.glsl_program_num = glsl_program_num;
318 phase.input_needs_mipmaps = input_needs_mipmaps;
319 phase.inputs = true_inputs;
320 phase.effects = effects;
325 // Construct GLSL programs, starting at the given effect and following
326 // the chain from there. We end a program every time we come to an effect
327 // marked as "needs texture bounce", one that is used by multiple other
328 // effects, and of course at the end.
329 void EffectChain::construct_glsl_programs(Effect *start, std::set<Effect *> *completed_effects)
331 assert(start != NULL);
332 if (completed_effects->count(start) != 0) {
333 // This has already been done for us.
337 std::vector<Effect *> this_phase_inputs; // Also includes all intermediates; these will be filtered away later.
338 std::vector<Effect *> this_phase_effects;
339 Effect *node = start;
340 for ( ;; ) { // Termination condition within loop.
341 assert(node != NULL);
343 // Check that we have all the inputs we need for this effect.
344 // If not, we end the phase here right away; the other side
345 // of the input chain will eventually come and pick the effect up.
346 assert(incoming_links.count(node) == 1);
347 std::vector<Effect *> deps = incoming_links[node];
348 assert(node->num_inputs() == deps.size());
350 bool have_all_deps = true;
351 for (unsigned i = 0; i < deps.size(); ++i) {
352 if (completed_effects->count(deps[i]) == 0) {
353 have_all_deps = false;
358 if (!have_all_deps) {
359 if (!this_phase_effects.empty()) {
360 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
364 this_phase_inputs.insert(this_phase_inputs.end(), deps.begin(), deps.end());
366 this_phase_effects.push_back(node);
367 completed_effects->insert(node);
369 // Find all the effects that use this one as a direct input.
370 if (outgoing_links.count(node) == 0) {
371 // End of the line; output.
372 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
376 std::vector<Effect *> next = outgoing_links[node];
377 assert(!next.empty());
378 if (next.size() > 1) {
379 if (node->num_inputs() != 0) {
380 // More than one effect uses this as the input, and it is not a texture itself.
381 // The easiest thing to do (and probably also the safest
382 // performance-wise in most cases) is to bounce it to a texture
383 // and then let the next passes read from that.
384 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
387 // Start phases for all the effects that need us (in arbitrary order).
388 for (unsigned i = 0; i < next.size(); ++i) {
389 construct_glsl_programs(next[i], completed_effects);
394 // OK, only one effect uses this as the input. Keep iterating,
395 // but first see if it requires a texture bounce; if so, give it
396 // one by starting a new phase.
398 if (node->needs_texture_bounce()) {
399 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
400 this_phase_inputs.clear();
401 this_phase_effects.clear();
406 void EffectChain::finalize()
408 // Add normalizers to get the output format right.
409 assert(output_gamma_curve.count(last_added_effect()) != 0);
410 assert(output_color_space.count(last_added_effect()) != 0);
411 ColorSpace current_color_space = output_color_space[last_added_effect()]; // FIXME
412 if (current_color_space != output_format.color_space) {
413 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
414 colorspace_conversion->set_int("source_space", current_color_space);
415 colorspace_conversion->set_int("destination_space", output_format.color_space);
416 std::vector<Effect *> inputs;
417 inputs.push_back(last_added_effect());
418 colorspace_conversion->add_self_to_effect_chain(this, inputs);
419 output_color_space[colorspace_conversion] = output_format.color_space;
421 GammaCurve current_gamma_curve = output_gamma_curve[last_added_effect()]; // FIXME
422 if (current_gamma_curve != output_format.gamma_curve) {
423 if (current_gamma_curve != GAMMA_LINEAR) {
424 normalize_to_linear_gamma(last_added_effect()); // FIXME
426 assert(current_gamma_curve == GAMMA_LINEAR);
427 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
428 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
429 std::vector<Effect *> inputs;
430 inputs.push_back(last_added_effect());
431 gamma_conversion->add_self_to_effect_chain(this, inputs);
432 output_gamma_curve[gamma_conversion] = output_format.gamma_curve;
435 // Construct all needed GLSL programs, starting at the inputs.
436 std::set<Effect *> completed_effects;
437 for (unsigned i = 0; i < inputs.size(); ++i) {
438 construct_glsl_programs(inputs[i], &completed_effects);
441 // If we have more than one phase, we need intermediate render-to-texture.
442 // Construct an FBO, and then as many textures as we need.
443 // We choose the simplest option of having one texture per output,
444 // since otherwise this turns into an (albeit simple)
445 // register allocation problem.
446 if (phases.size() > 1) {
447 glGenFramebuffers(1, &fbo);
449 for (unsigned i = 0; i < phases.size() - 1; ++i) {
450 Effect *output_effect = phases[i].effects.back();
452 glGenTextures(1, &temp_texture);
454 glBindTexture(GL_TEXTURE_2D, temp_texture);
456 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
458 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
460 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
462 effect_output_textures.insert(std::make_pair(output_effect, temp_texture));
466 for (unsigned i = 0; i < inputs.size(); ++i) {
467 inputs[i]->finalize();
473 void EffectChain::render_to_screen()
480 glDisable(GL_DEPTH_TEST);
482 glDepthMask(GL_FALSE);
485 glMatrixMode(GL_PROJECTION);
487 glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
489 glMatrixMode(GL_MODELVIEW);
492 if (phases.size() > 1) {
493 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
497 std::set<Effect *> generated_mipmaps;
498 for (unsigned i = 0; i < inputs.size(); ++i) {
499 // Inputs generate their own mipmaps if they need to
501 generated_mipmaps.insert(inputs[i]);
504 for (unsigned phase = 0; phase < phases.size(); ++phase) {
505 glUseProgram(phases[phase].glsl_program_num);
508 // Set up RTT inputs for this phase.
509 for (unsigned sampler = 0; sampler < phases[phase].inputs.size(); ++sampler) {
510 glActiveTexture(GL_TEXTURE0 + sampler);
511 Effect *input = phases[phase].inputs[sampler];
512 assert(effect_output_textures.count(input) != 0);
513 glBindTexture(GL_TEXTURE_2D, effect_output_textures[input]);
515 if (phases[phase].input_needs_mipmaps) {
516 if (generated_mipmaps.count(input) == 0) {
517 glGenerateMipmap(GL_TEXTURE_2D);
519 generated_mipmaps.insert(input);
521 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
524 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
528 assert(effect_ids.count(input));
529 std::string texture_name = std::string("tex_") + effect_ids[input];
530 glUniform1i(glGetUniformLocation(phases[phase].glsl_program_num, texture_name.c_str()), sampler);
534 // And now the output.
535 if (phase == phases.size() - 1) {
536 // Last phase goes directly to the screen.
537 glBindFramebuffer(GL_FRAMEBUFFER, 0);
540 Effect *last_effect = phases[phase].effects.back();
541 assert(effect_output_textures.count(last_effect) != 0);
542 glFramebufferTexture2D(
544 GL_COLOR_ATTACHMENT0,
546 effect_output_textures[last_effect],
551 // Give the required parameters to all the effects.
552 unsigned sampler_num = phases[phase].inputs.size();
553 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
554 Effect *effect = phases[phase].effects[i];
555 effect->set_gl_state(phases[phase].glsl_program_num, effect_ids[effect], &sampler_num);
561 glTexCoord2f(0.0f, 0.0f);
562 glVertex2f(0.0f, 0.0f);
564 glTexCoord2f(1.0f, 0.0f);
565 glVertex2f(1.0f, 0.0f);
567 glTexCoord2f(1.0f, 1.0f);
568 glVertex2f(1.0f, 1.0f);
570 glTexCoord2f(0.0f, 1.0f);
571 glVertex2f(0.0f, 1.0f);
576 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
577 Effect *effect = phases[phase].effects[i];
578 effect->clear_gl_state();