1 #define GL_GLEXT_PROTOTYPES 1
16 #include "effect_chain.h"
17 #include "gamma_expansion_effect.h"
18 #include "gamma_compression_effect.h"
19 #include "colorspace_conversion_effect.h"
22 EffectChain::EffectChain(unsigned width, unsigned height)
27 Input *EffectChain::add_input(Input *input)
30 sprintf(eff_id, "src_image%u", (unsigned)inputs.size());
32 effects.push_back(input);
33 inputs.push_back(input);
34 output_color_space.insert(std::make_pair(input, input->get_color_space()));
35 output_gamma_curve.insert(std::make_pair(input, input->get_gamma_curve()));
36 effect_ids.insert(std::make_pair(input, eff_id));
37 incoming_links.insert(std::make_pair(input, std::vector<Effect *>()));
41 void EffectChain::add_output(const ImageFormat &format)
43 output_format = format;
46 void EffectChain::add_effect_raw(Effect *effect, const std::vector<Effect *> &inputs)
49 sprintf(effect_id, "eff%u", (unsigned)effects.size());
51 effects.push_back(effect);
52 effect_ids.insert(std::make_pair(effect, effect_id));
53 assert(inputs.size() == effect->num_inputs());
54 for (unsigned i = 0; i < inputs.size(); ++i) {
55 assert(std::find(effects.begin(), effects.end(), inputs[i]) != effects.end());
56 outgoing_links[inputs[i]].push_back(effect);
58 incoming_links.insert(std::make_pair(effect, inputs));
59 output_gamma_curve[effect] = output_gamma_curve[last_added_effect()];
60 output_color_space[effect] = output_color_space[last_added_effect()];
63 void EffectChain::find_all_nonlinear_inputs(Effect *effect,
64 std::vector<Input *> *nonlinear_inputs,
65 std::vector<Effect *> *intermediates)
67 assert(output_gamma_curve.count(effect) != 0);
68 if (output_gamma_curve[effect] == GAMMA_LINEAR) {
71 if (effect->num_inputs() == 0) {
72 nonlinear_inputs->push_back(static_cast<Input *>(effect));
74 intermediates->push_back(effect);
76 assert(incoming_links.count(effect) == 1);
77 std::vector<Effect *> deps = incoming_links[effect];
78 assert(effect->num_inputs() == deps.size());
79 for (unsigned i = 0; i < deps.size(); ++i) {
80 find_all_nonlinear_inputs(deps[i], nonlinear_inputs, intermediates);
85 Effect *EffectChain::normalize_to_linear_gamma(Effect *input)
87 // Find out if all the inputs can be set to deliver sRGB inputs.
88 // If so, we can just ask them to do that instead of inserting a
89 // (possibly expensive) conversion operation.
91 // NOTE: We assume that effects generally don't mess with the gamma
92 // curve (except GammaCompressionEffect, which should never be
93 // inserted into a chain when this is called), so that we can just
94 // update the output gamma as we go.
96 // TODO: Setting this flag for one source might confuse a different
97 // part of the pipeline using the same source.
98 std::vector<Input *> nonlinear_inputs;
99 std::vector<Effect *> intermediates;
100 find_all_nonlinear_inputs(input, &nonlinear_inputs, &intermediates);
103 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
104 all_ok &= nonlinear_inputs[i]->can_output_linear_gamma();
108 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
109 bool ok = nonlinear_inputs[i]->set_int("output_linear_gamma", 1);
111 output_gamma_curve[nonlinear_inputs[i]] = GAMMA_LINEAR;
113 for (unsigned i = 0; i < intermediates.size(); ++i) {
114 output_gamma_curve[intermediates[i]] = GAMMA_LINEAR;
119 // OK, that didn't work. Insert a conversion effect.
120 GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
121 gamma_conversion->set_int("source_curve", output_gamma_curve[input]);
122 std::vector<Effect *> inputs;
123 inputs.push_back(input);
124 gamma_conversion->add_self_to_effect_chain(this, inputs);
125 output_gamma_curve[gamma_conversion] = GAMMA_LINEAR;
126 return gamma_conversion;
129 Effect *EffectChain::normalize_to_srgb(Effect *input)
131 assert(output_gamma_curve.count(input) != 0);
132 assert(output_color_space.count(input) != 0);
133 assert(output_gamma_curve[input] == GAMMA_LINEAR);
134 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
135 colorspace_conversion->set_int("source_space", output_color_space[input]);
136 colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
137 std::vector<Effect *> inputs;
138 inputs.push_back(input);
139 colorspace_conversion->add_self_to_effect_chain(this, inputs);
140 output_color_space[colorspace_conversion] = COLORSPACE_sRGB;
141 return colorspace_conversion;
144 Effect *EffectChain::add_effect(Effect *effect, const std::vector<Effect *> &inputs)
146 assert(inputs.size() == effect->num_inputs());
148 std::vector<Effect *> normalized_inputs = inputs;
149 for (unsigned i = 0; i < normalized_inputs.size(); ++i) {
150 assert(output_gamma_curve.count(normalized_inputs[i]) != 0);
151 if (effect->needs_linear_light() && output_gamma_curve[normalized_inputs[i]] != GAMMA_LINEAR) {
152 normalized_inputs[i] = normalize_to_linear_gamma(normalized_inputs[i]);
154 assert(output_color_space.count(normalized_inputs[i]) != 0);
155 if (effect->needs_srgb_primaries() && output_color_space[normalized_inputs[i]] != COLORSPACE_sRGB) {
156 normalized_inputs[i] = normalize_to_srgb(normalized_inputs[i]);
160 effect->add_self_to_effect_chain(this, normalized_inputs);
164 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
165 std::string replace_prefix(const std::string &text, const std::string &prefix)
170 while (start < text.size()) {
171 size_t pos = text.find("PREFIX(", start);
172 if (pos == std::string::npos) {
173 output.append(text.substr(start, std::string::npos));
177 output.append(text.substr(start, pos - start));
178 output.append(prefix);
181 pos += strlen("PREFIX(");
183 // Output stuff until we find the matching ), which we then eat.
185 size_t end_arg_pos = pos;
186 while (end_arg_pos < text.size()) {
187 if (text[end_arg_pos] == '(') {
189 } else if (text[end_arg_pos] == ')') {
197 output.append(text.substr(pos, end_arg_pos - pos));
205 EffectChain::Phase EffectChain::compile_glsl_program(const std::vector<Effect *> &inputs, const std::vector<Effect *> &effects)
207 assert(!effects.empty());
209 // Deduplicate the inputs.
210 std::vector<Effect *> true_inputs = inputs;
211 std::sort(true_inputs.begin(), true_inputs.end());
212 true_inputs.erase(std::unique(true_inputs.begin(), true_inputs.end()), true_inputs.end());
214 bool input_needs_mipmaps = false;
215 std::string frag_shader = read_file("header.frag");
217 // Create functions for all the texture inputs that we need.
218 for (unsigned i = 0; i < true_inputs.size(); ++i) {
219 Effect *effect = true_inputs[i];
220 assert(effect_ids.count(effect) != 0);
221 std::string effect_id = effect_ids[effect];
223 frag_shader += std::string("uniform sampler2D tex_") + effect_id + ";\n";
224 frag_shader += std::string("vec4 ") + effect_id + "(vec2 tc) {\n";
225 if (effect->num_inputs() == 0) {
226 // OpenGL's origin is bottom-left, but most graphics software assumes
227 // a top-left origin. Thus, for inputs that come from the user,
228 // we flip the y coordinate. However, for FBOs, the origin
229 // is all correct, so don't do anything.
230 frag_shader += "\ttc.y = 1.0f - tc.y;\n";
232 frag_shader += "\treturn texture2D(tex_" + effect_id + ", tc);\n";
233 frag_shader += "}\n";
237 std::string last_effect_id;
238 for (unsigned i = 0; i < effects.size(); ++i) {
239 Effect *effect = effects[i];
240 assert(effect != NULL);
241 assert(effect_ids.count(effect) != 0);
242 std::string effect_id = effect_ids[effect];
243 last_effect_id = effect_id;
245 if (incoming_links[effect].size() == 1) {
246 frag_shader += std::string("#define INPUT ") + effect_ids[incoming_links[effect][0]] + "\n";
248 for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
250 sprintf(buf, "#define INPUT%d %s\n", j + 1, effect_ids[incoming_links[effect][j]].c_str());
256 frag_shader += std::string("#define FUNCNAME ") + effect_id + "\n";
257 frag_shader += replace_prefix(effect->output_convenience_uniforms(), effect_id);
258 frag_shader += replace_prefix(effect->output_fragment_shader(), effect_id);
259 frag_shader += "#undef PREFIX\n";
260 frag_shader += "#undef FUNCNAME\n";
261 if (incoming_links[effect].size() == 1) {
262 frag_shader += "#undef INPUT\n";
264 for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
266 sprintf(buf, "#undef INPUT%d\n", j + 1);
272 input_needs_mipmaps |= effect->needs_mipmaps();
274 for (unsigned i = 0; i < effects.size(); ++i) {
275 Effect *effect = effects[i];
276 if (effect->num_inputs() == 0) {
277 effect->set_int("needs_mipmaps", input_needs_mipmaps);
280 assert(!last_effect_id.empty());
281 frag_shader += std::string("#define INPUT ") + last_effect_id + "\n";
282 frag_shader.append(read_file("footer.frag"));
283 printf("%s\n", frag_shader.c_str());
285 GLuint glsl_program_num = glCreateProgram();
286 GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
287 GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
288 glAttachShader(glsl_program_num, vs_obj);
290 glAttachShader(glsl_program_num, fs_obj);
292 glLinkProgram(glsl_program_num);
296 phase.glsl_program_num = glsl_program_num;
297 phase.input_needs_mipmaps = input_needs_mipmaps;
298 phase.inputs = true_inputs;
299 phase.effects = effects;
304 // Construct GLSL programs, starting at the given effect and following
305 // the chain from there. We end a program every time we come to an effect
306 // marked as "needs texture bounce", one that is used by multiple other
307 // effects, and of course at the end.
309 // We follow a quite simple depth-first search from the output, although
310 // without any explicit recursion.
311 void EffectChain::construct_glsl_programs(Effect *output)
313 // Which effects have already been completed in this phase?
314 // We need to keep track of it, as an effect with multiple outputs
315 // could otherwise be calculate multiple times.
316 std::set<Effect *> completed_effects;
318 // Effects in the current phase, as well as inputs (outputs from other phases
319 // that we depend on). Note that since we start iterating from the end,
320 // the effect list will be in the reverse order.
321 std::vector<Effect *> this_phase_inputs;
322 std::vector<Effect *> this_phase_effects;
324 // Effects that we have yet to calculate, but that we know should
325 // be in the current phase.
326 std::stack<Effect *> effects_todo_this_phase;
328 // Effects that we have yet to calculate, but that come from other phases.
329 // We delay these until we have this phase done in its entirety,
330 // at which point we pick any of them and start a new phase from that.
331 std::stack<Effect *> effects_todo_other_phases;
333 effects_todo_this_phase.push(output);
335 for ( ;; ) { // Termination condition within loop.
336 if (!effects_todo_this_phase.empty()) {
337 // OK, we have more to do this phase.
338 Effect *effect = effects_todo_this_phase.top();
339 effects_todo_this_phase.pop();
341 // This should currently only happen for effects that are phase outputs,
342 // and we throw those out separately below.
343 assert(completed_effects.count(effect) == 0);
345 this_phase_effects.push_back(effect);
346 completed_effects.insert(effect);
348 // Find all the dependencies of this effect, and add them to the stack.
349 assert(incoming_links.count(effect) == 1);
350 std::vector<Effect *> deps = incoming_links[effect];
351 assert(effect->num_inputs() == deps.size());
352 for (unsigned i = 0; i < deps.size(); ++i) {
353 bool start_new_phase = false;
355 if (effect->needs_texture_bounce()) {
356 start_new_phase = true;
359 assert(outgoing_links.count(deps[i]) == 1);
360 if (outgoing_links[deps[i]].size() > 1 && deps[i]->num_inputs() > 0) {
361 // More than one effect uses this as the input,
362 // and it is not a texture itself.
363 // The easiest thing to do (and probably also the safest
364 // performance-wise in most cases) is to bounce it to a texture
365 // and then let the next passes read from that.
366 start_new_phase = true;
369 if (start_new_phase) {
370 effects_todo_other_phases.push(deps[i]);
371 this_phase_inputs.push_back(deps[i]);
373 effects_todo_this_phase.push(deps[i]);
379 // No more effects to do this phase. Take all the ones we have,
380 // and create a GLSL program for it.
381 if (!this_phase_effects.empty()) {
382 reverse(this_phase_effects.begin(), this_phase_effects.end());
383 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
384 this_phase_inputs.clear();
385 this_phase_effects.clear();
387 assert(this_phase_inputs.empty());
388 assert(this_phase_effects.empty());
390 // If we have no effects left, exit.
391 if (effects_todo_other_phases.empty()) {
395 Effect *effect = effects_todo_other_phases.top();
396 effects_todo_other_phases.pop();
398 if (completed_effects.count(effect) == 0) {
399 // Start a new phase, calculating from this effect.
400 effects_todo_this_phase.push(effect);
404 // Finally, since the phases are found from the output but must be executed
405 // from the input(s), reverse them, too.
406 std::reverse(phases.begin(), phases.end());
409 void EffectChain::finalize()
411 // Find the output effect. This is, simply, one that has no outgoing links.
412 // If there are multiple ones, the graph is malformed (we do not support
413 // multiple outputs right now).
414 std::vector<Effect *> output_effects;
415 for (unsigned i = 0; i < effects.size(); ++i) {
416 Effect *effect = effects[i];
417 if (outgoing_links.count(effect) == 0 || outgoing_links[effect].size() == 0) {
418 output_effects.push_back(effect);
421 assert(output_effects.size() == 1);
422 Effect *output_effect = output_effects[0];
424 // Add normalizers to get the output format right.
425 assert(output_gamma_curve.count(output_effect) != 0);
426 assert(output_color_space.count(output_effect) != 0);
427 ColorSpace current_color_space = output_color_space[output_effect];
428 if (current_color_space != output_format.color_space) {
429 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
430 colorspace_conversion->set_int("source_space", current_color_space);
431 colorspace_conversion->set_int("destination_space", output_format.color_space);
432 std::vector<Effect *> inputs;
433 inputs.push_back(output_effect);
434 colorspace_conversion->add_self_to_effect_chain(this, inputs);
435 output_color_space[colorspace_conversion] = output_format.color_space;
436 output_effect = colorspace_conversion;
438 GammaCurve current_gamma_curve = output_gamma_curve[output_effect];
439 if (current_gamma_curve != output_format.gamma_curve) {
440 if (current_gamma_curve != GAMMA_LINEAR) {
441 output_effect = normalize_to_linear_gamma(output_effect);
442 current_gamma_curve = GAMMA_LINEAR;
444 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
445 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
446 std::vector<Effect *> inputs;
447 inputs.push_back(output_effect);
448 gamma_conversion->add_self_to_effect_chain(this, inputs);
449 output_gamma_curve[gamma_conversion] = output_format.gamma_curve;
450 output_effect = gamma_conversion;
453 // Construct all needed GLSL programs, starting at the output.
454 construct_glsl_programs(output_effect);
456 // If we have more than one phase, we need intermediate render-to-texture.
457 // Construct an FBO, and then as many textures as we need.
458 // We choose the simplest option of having one texture per output,
459 // since otherwise this turns into an (albeit simple)
460 // register allocation problem.
461 if (phases.size() > 1) {
462 glGenFramebuffers(1, &fbo);
464 for (unsigned i = 0; i < phases.size() - 1; ++i) {
465 Effect *output_effect = phases[i].effects.back();
467 glGenTextures(1, &temp_texture);
469 glBindTexture(GL_TEXTURE_2D, temp_texture);
471 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
473 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
475 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
477 effect_output_textures.insert(std::make_pair(output_effect, temp_texture));
481 for (unsigned i = 0; i < inputs.size(); ++i) {
482 inputs[i]->finalize();
488 void EffectChain::render_to_screen()
495 glDisable(GL_DEPTH_TEST);
497 glDepthMask(GL_FALSE);
500 glMatrixMode(GL_PROJECTION);
502 glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
504 glMatrixMode(GL_MODELVIEW);
507 if (phases.size() > 1) {
508 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
512 std::set<Effect *> generated_mipmaps;
513 for (unsigned i = 0; i < inputs.size(); ++i) {
514 // Inputs generate their own mipmaps if they need to
516 generated_mipmaps.insert(inputs[i]);
519 for (unsigned phase = 0; phase < phases.size(); ++phase) {
520 glUseProgram(phases[phase].glsl_program_num);
523 // Set up RTT inputs for this phase.
524 for (unsigned sampler = 0; sampler < phases[phase].inputs.size(); ++sampler) {
525 glActiveTexture(GL_TEXTURE0 + sampler);
526 Effect *input = phases[phase].inputs[sampler];
527 assert(effect_output_textures.count(input) != 0);
528 glBindTexture(GL_TEXTURE_2D, effect_output_textures[input]);
530 if (phases[phase].input_needs_mipmaps) {
531 if (generated_mipmaps.count(input) == 0) {
532 glGenerateMipmap(GL_TEXTURE_2D);
534 generated_mipmaps.insert(input);
536 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
539 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
543 assert(effect_ids.count(input));
544 std::string texture_name = std::string("tex_") + effect_ids[input];
545 glUniform1i(glGetUniformLocation(phases[phase].glsl_program_num, texture_name.c_str()), sampler);
549 // And now the output.
550 if (phase == phases.size() - 1) {
551 // Last phase goes directly to the screen.
552 glBindFramebuffer(GL_FRAMEBUFFER, 0);
555 Effect *last_effect = phases[phase].effects.back();
556 assert(effect_output_textures.count(last_effect) != 0);
557 glFramebufferTexture2D(
559 GL_COLOR_ATTACHMENT0,
561 effect_output_textures[last_effect],
566 // Give the required parameters to all the effects.
567 unsigned sampler_num = phases[phase].inputs.size();
568 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
569 Effect *effect = phases[phase].effects[i];
570 effect->set_gl_state(phases[phase].glsl_program_num, effect_ids[effect], &sampler_num);
576 glTexCoord2f(0.0f, 0.0f);
577 glVertex2f(0.0f, 0.0f);
579 glTexCoord2f(1.0f, 0.0f);
580 glVertex2f(1.0f, 0.0f);
582 glTexCoord2f(1.0f, 1.0f);
583 glVertex2f(1.0f, 1.0f);
585 glTexCoord2f(0.0f, 1.0f);
586 glVertex2f(0.0f, 1.0f);
591 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
592 Effect *effect = phases[phase].effects[i];
593 effect->clear_gl_state();