1 #define GL_GLEXT_PROTOTYPES 1
13 #include "effect_chain.h"
14 #include "gamma_expansion_effect.h"
15 #include "gamma_compression_effect.h"
16 #include "colorspace_conversion_effect.h"
20 EffectChain::EffectChain(unsigned width, unsigned height)
25 Input *EffectChain::add_input(Input *input)
28 sprintf(eff_id, "src_image%u", (unsigned)inputs.size());
30 inputs.push_back(input);
32 Node *node = new Node;
34 node->effect_id = eff_id;
35 node->output_color_space = input->get_color_space();
36 node->output_gamma_curve = input->get_gamma_curve();
38 nodes.push_back(node);
39 node_map[input] = node;
44 void EffectChain::add_output(const ImageFormat &format)
46 output_format = format;
49 void EffectChain::add_effect_raw(Effect *effect, const std::vector<Effect *> &inputs)
52 sprintf(effect_id, "eff%u", (unsigned)nodes.size());
54 Node *node = new Node;
55 node->effect = effect;
56 node->effect_id = effect_id;
58 assert(inputs.size() == effect->num_inputs());
59 assert(inputs.size() >= 1);
60 for (unsigned i = 0; i < inputs.size(); ++i) {
61 assert(node_map.count(inputs[i]) != 0);
62 node_map[inputs[i]]->outgoing_links.push_back(node);
63 node->incoming_links.push_back(node_map[inputs[i]]);
65 node->output_gamma_curve = node_map[inputs[i]]->output_gamma_curve;
66 node->output_color_space = node_map[inputs[i]]->output_color_space;
68 assert(node->output_gamma_curve == node_map[inputs[i]]->output_gamma_curve);
69 assert(node->output_color_space == node_map[inputs[i]]->output_color_space);
73 nodes.push_back(node);
74 node_map[effect] = node;
77 void EffectChain::find_all_nonlinear_inputs(Node *node,
78 std::vector<Node *> *nonlinear_inputs,
79 std::vector<Node *> *intermediates)
81 if (node->output_gamma_curve == GAMMA_LINEAR) {
84 if (node->effect->num_inputs() == 0) {
85 nonlinear_inputs->push_back(node);
87 intermediates->push_back(node);
88 assert(node->effect->num_inputs() == node->incoming_links.size());
89 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
90 find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs, intermediates);
95 Node *EffectChain::normalize_to_linear_gamma(Node *input)
97 // Find out if all the inputs can be set to deliver sRGB inputs.
98 // If so, we can just ask them to do that instead of inserting a
99 // (possibly expensive) conversion operation.
101 // NOTE: We assume that effects generally don't mess with the gamma
102 // curve (except GammaCompressionEffect, which should never be
103 // inserted into a chain when this is called), so that we can just
104 // update the output gamma as we go.
106 // TODO: Setting this flag for one source might confuse a different
107 // part of the pipeline using the same source.
108 std::vector<Node *> nonlinear_inputs;
109 std::vector<Node *> intermediates;
110 find_all_nonlinear_inputs(input, &nonlinear_inputs, &intermediates);
113 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
114 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
115 all_ok &= input->can_output_linear_gamma();
119 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
120 bool ok = nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1);
122 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
124 for (unsigned i = 0; i < intermediates.size(); ++i) {
125 intermediates[i]->output_gamma_curve = GAMMA_LINEAR;
130 // OK, that didn't work. Insert a conversion effect.
131 GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
132 gamma_conversion->set_int("source_curve", input->output_gamma_curve);
133 std::vector<Effect *> inputs;
134 inputs.push_back(input->effect);
135 gamma_conversion->add_self_to_effect_chain(this, inputs);
137 assert(node_map.count(gamma_conversion) != 0);
138 Node *node = node_map[gamma_conversion];
139 node->output_gamma_curve = GAMMA_LINEAR;
143 Node *EffectChain::normalize_to_srgb(Node *input)
145 assert(input->output_gamma_curve == GAMMA_LINEAR);
146 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
147 colorspace_conversion->set_int("source_space", input->output_color_space);
148 colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
149 std::vector<Effect *> inputs;
150 inputs.push_back(input->effect);
151 colorspace_conversion->add_self_to_effect_chain(this, inputs);
153 assert(node_map.count(colorspace_conversion) != 0);
154 Node *node = node_map[colorspace_conversion];
155 node->output_color_space = COLORSPACE_sRGB;
159 Effect *EffectChain::add_effect(Effect *effect, const std::vector<Effect *> &inputs)
161 assert(inputs.size() == effect->num_inputs());
163 std::vector<Effect *> normalized_inputs = inputs;
164 for (unsigned i = 0; i < normalized_inputs.size(); ++i) {
165 assert(node_map.count(normalized_inputs[i]) != 0);
166 Node *input = node_map[normalized_inputs[i]];
167 if (effect->needs_linear_light() && input->output_gamma_curve != GAMMA_LINEAR) {
168 input = normalize_to_linear_gamma(input);
170 if (effect->needs_srgb_primaries() && input->output_color_space != COLORSPACE_sRGB) {
171 input = normalize_to_srgb(input);
173 normalized_inputs[i] = input->effect;
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 Phase *EffectChain::compile_glsl_program(
222 const std::vector<Node *> &inputs,
223 const std::vector<Node *> &effects)
225 assert(!effects.empty());
227 // Deduplicate the inputs.
228 std::vector<Node *> true_inputs = inputs;
229 std::sort(true_inputs.begin(), true_inputs.end());
230 true_inputs.erase(std::unique(true_inputs.begin(), true_inputs.end()), true_inputs.end());
232 bool input_needs_mipmaps = false;
233 std::string frag_shader = read_file("header.frag");
235 // Create functions for all the texture inputs that we need.
236 for (unsigned i = 0; i < true_inputs.size(); ++i) {
237 Node *input = true_inputs[i];
239 frag_shader += std::string("uniform sampler2D tex_") + input->effect_id + ";\n";
240 frag_shader += std::string("vec4 ") + input->effect_id + "(vec2 tc) {\n";
241 frag_shader += "\treturn texture2D(tex_" + input->effect_id + ", tc);\n";
242 frag_shader += "}\n";
246 for (unsigned i = 0; i < effects.size(); ++i) {
247 Node *node = effects[i];
249 if (node->incoming_links.size() == 1) {
250 frag_shader += std::string("#define INPUT ") + node->incoming_links[0]->effect_id + "\n";
252 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
254 sprintf(buf, "#define INPUT%d %s\n", j + 1, node->incoming_links[j]->effect_id.c_str());
260 frag_shader += std::string("#define FUNCNAME ") + node->effect_id + "\n";
261 frag_shader += replace_prefix(node->effect->output_convenience_uniforms(), node->effect_id);
262 frag_shader += replace_prefix(node->effect->output_fragment_shader(), node->effect_id);
263 frag_shader += "#undef PREFIX\n";
264 frag_shader += "#undef FUNCNAME\n";
265 if (node->incoming_links.size() == 1) {
266 frag_shader += "#undef INPUT\n";
268 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
270 sprintf(buf, "#undef INPUT%d\n", j + 1);
276 input_needs_mipmaps |= node->effect->needs_mipmaps();
278 for (unsigned i = 0; i < effects.size(); ++i) {
279 Node *node = effects[i];
280 if (node->effect->num_inputs() == 0) {
281 node->effect->set_int("needs_mipmaps", input_needs_mipmaps);
284 frag_shader += std::string("#define INPUT ") + effects.back()->effect_id + "\n";
285 frag_shader.append(read_file("footer.frag"));
286 printf("%s\n", frag_shader.c_str());
288 GLuint glsl_program_num = glCreateProgram();
289 GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
290 GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
291 glAttachShader(glsl_program_num, vs_obj);
293 glAttachShader(glsl_program_num, fs_obj);
295 glLinkProgram(glsl_program_num);
298 Phase *phase = new Phase;
299 phase->glsl_program_num = glsl_program_num;
300 phase->input_needs_mipmaps = input_needs_mipmaps;
301 phase->inputs = true_inputs;
302 phase->effects = effects;
307 // Construct GLSL programs, starting at the given effect and following
308 // the chain from there. We end a program every time we come to an effect
309 // marked as "needs texture bounce", one that is used by multiple other
310 // effects, every time an effect wants to change the output size,
311 // and of course at the end.
313 // We follow a quite simple depth-first search from the output, although
314 // without any explicit recursion.
315 void EffectChain::construct_glsl_programs(Node *output)
317 // Which effects have already been completed in this phase?
318 // We need to keep track of it, as an effect with multiple outputs
319 // could otherwise be calculate multiple times.
320 std::set<Node *> completed_effects;
322 // Effects in the current phase, as well as inputs (outputs from other phases
323 // that we depend on). Note that since we start iterating from the end,
324 // the effect list will be in the reverse order.
325 std::vector<Node *> this_phase_inputs;
326 std::vector<Node *> this_phase_effects;
328 // Effects that we have yet to calculate, but that we know should
329 // be in the current phase.
330 std::stack<Node *> effects_todo_this_phase;
332 // Effects that we have yet to calculate, but that come from other phases.
333 // We delay these until we have this phase done in its entirety,
334 // at which point we pick any of them and start a new phase from that.
335 std::stack<Node *> effects_todo_other_phases;
337 effects_todo_this_phase.push(output);
339 for ( ;; ) { // Termination condition within loop.
340 if (!effects_todo_this_phase.empty()) {
341 // OK, we have more to do this phase.
342 Node *node = effects_todo_this_phase.top();
343 effects_todo_this_phase.pop();
345 // This should currently only happen for effects that are phase outputs,
346 // and we throw those out separately below.
347 assert(completed_effects.count(node) == 0);
349 this_phase_effects.push_back(node);
350 completed_effects.insert(node);
352 // Find all the dependencies of this effect, and add them to the stack.
353 std::vector<Node *> deps = node->incoming_links;
354 assert(node->effect->num_inputs() == deps.size());
355 for (unsigned i = 0; i < deps.size(); ++i) {
356 bool start_new_phase = false;
358 // FIXME: If we sample directly from a texture, we won't need this.
359 if (node->effect->needs_texture_bounce()) {
360 start_new_phase = true;
363 if (deps[i]->outgoing_links.size() > 1 && deps[i]->effect->num_inputs() > 0) {
364 // More than one effect uses this as the input,
365 // and it is not a texture itself.
366 // The easiest thing to do (and probably also the safest
367 // performance-wise in most cases) is to bounce it to a texture
368 // and then let the next passes read from that.
369 start_new_phase = true;
372 if (deps[i]->effect->changes_output_size()) {
373 start_new_phase = true;
376 if (start_new_phase) {
377 effects_todo_other_phases.push(deps[i]);
378 this_phase_inputs.push_back(deps[i]);
380 effects_todo_this_phase.push(deps[i]);
386 // No more effects to do this phase. Take all the ones we have,
387 // and create a GLSL program for it.
388 if (!this_phase_effects.empty()) {
389 reverse(this_phase_effects.begin(), this_phase_effects.end());
390 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
391 this_phase_effects.back()->phase = phases.back();
392 this_phase_inputs.clear();
393 this_phase_effects.clear();
395 assert(this_phase_inputs.empty());
396 assert(this_phase_effects.empty());
398 // If we have no effects left, exit.
399 if (effects_todo_other_phases.empty()) {
403 Node *node = effects_todo_other_phases.top();
404 effects_todo_other_phases.pop();
406 if (completed_effects.count(node) == 0) {
407 // Start a new phase, calculating from this effect.
408 effects_todo_this_phase.push(node);
412 // Finally, since the phases are found from the output but must be executed
413 // from the input(s), reverse them, too.
414 std::reverse(phases.begin(), phases.end());
417 void EffectChain::output_dot(const char *filename)
419 FILE *fp = fopen(filename, "w");
425 fprintf(fp, "digraph G {\n");
426 for (unsigned i = 0; i < nodes.size(); ++i) {
427 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
428 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
429 std::vector<std::string> labels;
431 if (nodes[i]->outgoing_links[j]->effect->needs_texture_bounce()) {
432 labels.push_back("needs_bounce");
434 if (nodes[i]->effect->changes_output_size()) {
435 labels.push_back("resize");
438 switch (nodes[i]->output_color_space) {
439 case COLORSPACE_REC_709:
440 labels.push_back("spc[rec709]");
442 case COLORSPACE_REC_601_525:
443 labels.push_back("spc[rec601-525]");
445 case COLORSPACE_REC_601_625:
446 labels.push_back("spc[rec601-625]");
452 switch (nodes[i]->output_gamma_curve) {
454 labels.push_back("gamma[sRGB]");
456 case GAMMA_REC_601: // and GAMMA_REC_709
457 labels.push_back("gamma[rec601/709]");
463 if (labels.empty()) {
464 fprintf(fp, " n%ld -> n%ld;\n", (long)nodes[i], (long)nodes[i]->outgoing_links[j]);
466 std::string label = labels[0];
467 for (unsigned k = 1; k < labels.size(); ++k) {
468 label += ", " + labels[k];
470 fprintf(fp, " n%ld -> n%ld [label=\"%s\"];\n", (long)nodes[i], (long)nodes[i]->outgoing_links[j], label.c_str());
479 void EffectChain::find_output_size(Phase *phase)
481 Node *output_node = phase->effects.back();
483 // If the last effect explicitly sets an output size,
485 if (output_node->effect->changes_output_size()) {
486 output_node->effect->get_output_size(&phase->output_width, &phase->output_height);
490 // If not, look at the input phases, if any. We select the largest one
491 // (really assuming they all have the same aspect currently), by pixel count.
492 if (!phase->inputs.empty()) {
493 unsigned best_width = 0, best_height = 0;
494 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
495 Node *input = phase->inputs[i];
496 assert(input->phase->output_width != 0);
497 assert(input->phase->output_height != 0);
498 if (input->phase->output_width * input->phase->output_height > best_width * best_height) {
499 best_width = input->phase->output_width;
500 best_height = input->phase->output_height;
503 assert(best_width != 0);
504 assert(best_height != 0);
505 phase->output_width = best_width;
506 phase->output_height = best_height;
510 // OK, no inputs. Just use the global width/height.
511 // TODO: We probably want to use the texture's size eventually.
512 phase->output_width = width;
513 phase->output_height = height;
516 void EffectChain::finalize()
518 output_dot("final.dot");
520 // Find the output effect. This is, simply, one that has no outgoing links.
521 // If there are multiple ones, the graph is malformed (we do not support
522 // multiple outputs right now).
523 std::vector<Node *> output_nodes;
524 for (unsigned i = 0; i < nodes.size(); ++i) {
525 Node *node = nodes[i];
526 if (node->outgoing_links.empty()) {
527 output_nodes.push_back(node);
530 assert(output_nodes.size() == 1);
531 Node *output_node = output_nodes[0];
533 // Add normalizers to get the output format right.
534 if (output_node->output_color_space != output_format.color_space) {
535 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
536 colorspace_conversion->set_int("source_space", output_node->output_color_space);
537 colorspace_conversion->set_int("destination_space", output_format.color_space);
538 std::vector<Effect *> inputs;
539 inputs.push_back(output_node->effect);
540 colorspace_conversion->add_self_to_effect_chain(this, inputs);
542 assert(node_map.count(colorspace_conversion) != 0);
543 output_node = node_map[colorspace_conversion];
544 output_node->output_color_space = output_format.color_space;
546 if (output_node->output_gamma_curve != output_format.gamma_curve) {
547 if (output_node->output_gamma_curve != GAMMA_LINEAR) {
548 output_node = normalize_to_linear_gamma(output_node);
550 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
551 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
552 std::vector<Effect *> inputs;
553 inputs.push_back(output_node->effect);
554 gamma_conversion->add_self_to_effect_chain(this, inputs);
556 assert(node_map.count(gamma_conversion) != 0);
557 output_node = node_map[gamma_conversion];
558 output_node->output_gamma_curve = output_format.gamma_curve;
561 // Construct all needed GLSL programs, starting at the output.
562 construct_glsl_programs(output_node);
564 // If we have more than one phase, we need intermediate render-to-texture.
565 // Construct an FBO, and then as many textures as we need.
566 // We choose the simplest option of having one texture per output,
567 // since otherwise this turns into an (albeit simple)
568 // register allocation problem.
569 if (phases.size() > 1) {
570 glGenFramebuffers(1, &fbo);
572 for (unsigned i = 0; i < phases.size() - 1; ++i) {
573 find_output_size(phases[i]);
575 Node *output_node = phases[i]->effects.back();
576 glGenTextures(1, &output_node->output_texture);
578 glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
580 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
582 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
584 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[i]->output_width, phases[i]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
587 output_node->output_texture_width = phases[i]->output_width;
588 output_node->output_texture_height = phases[i]->output_height;
592 for (unsigned i = 0; i < inputs.size(); ++i) {
593 inputs[i]->finalize();
596 assert(phases[0]->inputs.empty());
601 void EffectChain::render_to_screen()
608 glDisable(GL_DEPTH_TEST);
610 glDepthMask(GL_FALSE);
613 glMatrixMode(GL_PROJECTION);
615 glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
617 glMatrixMode(GL_MODELVIEW);
620 if (phases.size() > 1) {
621 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
625 std::set<Node *> generated_mipmaps;
627 for (unsigned phase = 0; phase < phases.size(); ++phase) {
628 // See if the requested output size has changed. If so, we need to recreate
629 // the texture (and before we start setting up inputs).
630 if (phase != phases.size() - 1) {
631 find_output_size(phases[phase]);
633 Node *output_node = phases[phase]->effects.back();
635 if (output_node->output_texture_width != phases[phase]->output_width ||
636 output_node->output_texture_height != phases[phase]->output_height) {
637 glActiveTexture(GL_TEXTURE0);
639 glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
641 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[phase]->output_width, phases[phase]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
643 glBindTexture(GL_TEXTURE_2D, 0);
646 output_node->output_texture_width = phases[phase]->output_width;
647 output_node->output_texture_height = phases[phase]->output_height;
651 glUseProgram(phases[phase]->glsl_program_num);
654 // Set up RTT inputs for this phase.
655 for (unsigned sampler = 0; sampler < phases[phase]->inputs.size(); ++sampler) {
656 glActiveTexture(GL_TEXTURE0 + sampler);
657 Node *input = phases[phase]->inputs[sampler];
658 glBindTexture(GL_TEXTURE_2D, input->output_texture);
660 if (phases[phase]->input_needs_mipmaps) {
661 if (generated_mipmaps.count(input) == 0) {
662 glGenerateMipmap(GL_TEXTURE_2D);
664 generated_mipmaps.insert(input);
666 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
669 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
673 std::string texture_name = std::string("tex_") + input->effect_id;
674 glUniform1i(glGetUniformLocation(phases[phase]->glsl_program_num, texture_name.c_str()), sampler);
678 // And now the output.
679 if (phase == phases.size() - 1) {
680 // Last phase goes directly to the screen.
681 glBindFramebuffer(GL_FRAMEBUFFER, 0);
683 glViewport(0, 0, width, height);
685 Node *output_node = phases[phase]->effects.back();
686 glFramebufferTexture2D(
688 GL_COLOR_ATTACHMENT0,
690 output_node->output_texture,
693 glViewport(0, 0, phases[phase]->output_width, phases[phase]->output_height);
696 // Give the required parameters to all the effects.
697 unsigned sampler_num = phases[phase]->inputs.size();
698 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
699 Node *node = phases[phase]->effects[i];
700 node->effect->set_gl_state(phases[phase]->glsl_program_num, node->effect_id, &sampler_num);
707 glTexCoord2f(0.0f, 0.0f);
708 glVertex2f(0.0f, 0.0f);
710 glTexCoord2f(1.0f, 0.0f);
711 glVertex2f(1.0f, 0.0f);
713 glTexCoord2f(1.0f, 1.0f);
714 glVertex2f(1.0f, 1.0f);
716 glTexCoord2f(0.0f, 1.0f);
717 glVertex2f(0.0f, 1.0f);
722 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
723 Node *node = phases[phase]->effects[i];
724 node->effect->clear_gl_state();