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::find_output_size(Phase *phase)
419 Node *output_node = phase->effects.back();
421 // If the last effect explicitly sets an output size,
423 if (output_node->effect->changes_output_size()) {
424 output_node->effect->get_output_size(&phase->output_width, &phase->output_height);
428 // If not, look at the input phases, if any. We select the largest one
429 // (really assuming they all have the same aspect currently), by pixel count.
430 if (!phase->inputs.empty()) {
431 unsigned best_width = 0, best_height = 0;
432 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
433 Node *input = phase->inputs[i];
434 assert(input->phase->output_width != 0);
435 assert(input->phase->output_height != 0);
436 if (input->phase->output_width * input->phase->output_height > best_width * best_height) {
437 best_width = input->phase->output_width;
438 best_height = input->phase->output_height;
441 assert(best_width != 0);
442 assert(best_height != 0);
443 phase->output_width = best_width;
444 phase->output_height = best_height;
448 // OK, no inputs. Just use the global width/height.
449 // TODO: We probably want to use the texture's size eventually.
450 phase->output_width = width;
451 phase->output_height = height;
454 void EffectChain::finalize()
456 // Find the output effect. This is, simply, one that has no outgoing links.
457 // If there are multiple ones, the graph is malformed (we do not support
458 // multiple outputs right now).
459 std::vector<Node *> output_nodes;
460 for (unsigned i = 0; i < nodes.size(); ++i) {
461 Node *node = nodes[i];
462 if (node->outgoing_links.empty()) {
463 output_nodes.push_back(node);
466 assert(output_nodes.size() == 1);
467 Node *output_node = output_nodes[0];
469 // Add normalizers to get the output format right.
470 if (output_node->output_color_space != output_format.color_space) {
471 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
472 colorspace_conversion->set_int("source_space", output_node->output_color_space);
473 colorspace_conversion->set_int("destination_space", output_format.color_space);
474 std::vector<Effect *> inputs;
475 inputs.push_back(output_node->effect);
476 colorspace_conversion->add_self_to_effect_chain(this, inputs);
478 assert(node_map.count(colorspace_conversion) != 0);
479 output_node = node_map[colorspace_conversion];
480 output_node->output_color_space = output_format.color_space;
482 if (output_node->output_gamma_curve != output_format.gamma_curve) {
483 if (output_node->output_gamma_curve != GAMMA_LINEAR) {
484 output_node = normalize_to_linear_gamma(output_node);
486 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
487 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
488 std::vector<Effect *> inputs;
489 inputs.push_back(output_node->effect);
490 gamma_conversion->add_self_to_effect_chain(this, inputs);
492 assert(node_map.count(gamma_conversion) != 0);
493 output_node = node_map[gamma_conversion];
494 output_node->output_gamma_curve = output_format.gamma_curve;
497 // Construct all needed GLSL programs, starting at the output.
498 construct_glsl_programs(output_node);
500 // If we have more than one phase, we need intermediate render-to-texture.
501 // Construct an FBO, and then as many textures as we need.
502 // We choose the simplest option of having one texture per output,
503 // since otherwise this turns into an (albeit simple)
504 // register allocation problem.
505 if (phases.size() > 1) {
506 glGenFramebuffers(1, &fbo);
508 for (unsigned i = 0; i < phases.size() - 1; ++i) {
509 find_output_size(phases[i]);
511 Node *output_node = phases[i]->effects.back();
512 glGenTextures(1, &output_node->output_texture);
514 glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
516 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
518 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
520 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[i]->output_width, phases[i]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
523 output_node->output_texture_width = phases[i]->output_width;
524 output_node->output_texture_height = phases[i]->output_height;
528 for (unsigned i = 0; i < inputs.size(); ++i) {
529 inputs[i]->finalize();
532 assert(phases[0]->inputs.empty());
537 void EffectChain::render_to_screen()
544 glDisable(GL_DEPTH_TEST);
546 glDepthMask(GL_FALSE);
549 glMatrixMode(GL_PROJECTION);
551 glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
553 glMatrixMode(GL_MODELVIEW);
556 if (phases.size() > 1) {
557 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
561 std::set<Node *> generated_mipmaps;
563 for (unsigned phase = 0; phase < phases.size(); ++phase) {
564 // See if the requested output size has changed. If so, we need to recreate
565 // the texture (and before we start setting up inputs).
566 if (phase != phases.size() - 1) {
567 find_output_size(phases[phase]);
569 Node *output_node = phases[phase]->effects.back();
571 if (output_node->output_texture_width != phases[phase]->output_width ||
572 output_node->output_texture_height != phases[phase]->output_height) {
573 glActiveTexture(GL_TEXTURE0);
575 glBindTexture(GL_TEXTURE_2D, output_node->output_texture);
577 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, phases[phase]->output_width, phases[phase]->output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
579 glBindTexture(GL_TEXTURE_2D, 0);
582 output_node->output_texture_width = phases[phase]->output_width;
583 output_node->output_texture_height = phases[phase]->output_height;
587 glUseProgram(phases[phase]->glsl_program_num);
590 // Set up RTT inputs for this phase.
591 for (unsigned sampler = 0; sampler < phases[phase]->inputs.size(); ++sampler) {
592 glActiveTexture(GL_TEXTURE0 + sampler);
593 Node *input = phases[phase]->inputs[sampler];
594 glBindTexture(GL_TEXTURE_2D, input->output_texture);
596 if (phases[phase]->input_needs_mipmaps) {
597 if (generated_mipmaps.count(input) == 0) {
598 glGenerateMipmap(GL_TEXTURE_2D);
600 generated_mipmaps.insert(input);
602 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
605 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
609 std::string texture_name = std::string("tex_") + input->effect_id;
610 glUniform1i(glGetUniformLocation(phases[phase]->glsl_program_num, texture_name.c_str()), sampler);
614 // And now the output.
615 if (phase == phases.size() - 1) {
616 // Last phase goes directly to the screen.
617 glBindFramebuffer(GL_FRAMEBUFFER, 0);
619 glViewport(0, 0, width, height);
621 Node *output_node = phases[phase]->effects.back();
622 glFramebufferTexture2D(
624 GL_COLOR_ATTACHMENT0,
626 output_node->output_texture,
629 glViewport(0, 0, phases[phase]->output_width, phases[phase]->output_height);
632 // Give the required parameters to all the effects.
633 unsigned sampler_num = phases[phase]->inputs.size();
634 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
635 Node *node = phases[phase]->effects[i];
636 node->effect->set_gl_state(phases[phase]->glsl_program_num, node->effect_id, &sampler_num);
643 glTexCoord2f(0.0f, 0.0f);
644 glVertex2f(0.0f, 0.0f);
646 glTexCoord2f(1.0f, 0.0f);
647 glVertex2f(1.0f, 0.0f);
649 glTexCoord2f(1.0f, 1.0f);
650 glVertex2f(1.0f, 1.0f);
652 glTexCoord2f(0.0f, 1.0f);
653 glVertex2f(0.0f, 1.0f);
658 for (unsigned i = 0; i < phases[phase]->effects.size(); ++i) {
659 Node *node = phases[phase]->effects[i];
660 node->effect->clear_gl_state();