15 #include "alpha_division_effect.h"
16 #include "alpha_multiplication_effect.h"
17 #include "colorspace_conversion_effect.h"
18 #include "dither_effect.h"
20 #include "effect_chain.h"
21 #include "effect_util.h"
22 #include "gamma_compression_effect.h"
23 #include "gamma_expansion_effect.h"
26 #include "resource_pool.h"
28 #include "ycbcr_conversion_effect.h"
30 using namespace Eigen;
37 // An effect whose only purpose is to sit in a phase on its own and take the
38 // texture output from a compute shader and display it to the normal backbuffer
39 // (or any FBO). That phase can be skipped when rendering using render_to_textures().
40 class ComputeShaderOutputDisplayEffect : public Effect {
42 ComputeShaderOutputDisplayEffect() {}
43 string effect_type_id() const override { return "ComputeShaderOutputDisplayEffect"; }
44 string output_fragment_shader() override { return read_file("identity.frag"); }
45 bool needs_texture_bounce() const override { return true; }
50 EffectChain::EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool)
51 : aspect_nom(aspect_nom),
52 aspect_denom(aspect_denom),
53 output_color_rgba(false),
54 num_output_color_ycbcr(0),
55 dither_effect(nullptr),
56 ycbcr_conversion_effect_node(nullptr),
57 intermediate_format(GL_RGBA16F),
58 intermediate_transformation(NO_FRAMEBUFFER_TRANSFORMATION),
60 output_origin(OUTPUT_ORIGIN_BOTTOM_LEFT),
62 resource_pool(resource_pool),
63 do_phase_timing(false) {
64 if (resource_pool == nullptr) {
65 this->resource_pool = new ResourcePool();
66 owns_resource_pool = true;
68 owns_resource_pool = false;
71 // Generate a VBO with some data in (shared position and texture coordinate data).
77 vbo = generate_vbo(2, GL_FLOAT, sizeof(vertices), vertices);
80 EffectChain::~EffectChain()
82 for (unsigned i = 0; i < nodes.size(); ++i) {
83 delete nodes[i]->effect;
86 for (unsigned i = 0; i < phases.size(); ++i) {
87 resource_pool->release_glsl_program(phases[i]->glsl_program_num);
90 if (owns_resource_pool) {
93 glDeleteBuffers(1, &vbo);
97 Input *EffectChain::add_input(Input *input)
100 inputs.push_back(input);
105 void EffectChain::add_output(const ImageFormat &format, OutputAlphaFormat alpha_format)
108 assert(!output_color_rgba);
109 output_format = format;
110 output_alpha_format = alpha_format;
111 output_color_rgba = true;
114 void EffectChain::add_ycbcr_output(const ImageFormat &format, OutputAlphaFormat alpha_format,
115 const YCbCrFormat &ycbcr_format, YCbCrOutputSplitting output_splitting,
119 assert(num_output_color_ycbcr < 2);
120 output_format = format;
121 output_alpha_format = alpha_format;
123 if (num_output_color_ycbcr == 1) {
124 // Check that the format is the same.
125 assert(output_ycbcr_format.luma_coefficients == ycbcr_format.luma_coefficients);
126 assert(output_ycbcr_format.full_range == ycbcr_format.full_range);
127 assert(output_ycbcr_format.num_levels == ycbcr_format.num_levels);
128 assert(output_ycbcr_format.chroma_subsampling_x == 1);
129 assert(output_ycbcr_format.chroma_subsampling_y == 1);
130 assert(output_ycbcr_type == output_type);
132 output_ycbcr_format = ycbcr_format;
133 output_ycbcr_type = output_type;
135 output_ycbcr_splitting[num_output_color_ycbcr++] = output_splitting;
137 assert(ycbcr_format.chroma_subsampling_x == 1);
138 assert(ycbcr_format.chroma_subsampling_y == 1);
141 void EffectChain::change_ycbcr_output_format(const YCbCrFormat &ycbcr_format)
143 assert(num_output_color_ycbcr > 0);
144 assert(output_ycbcr_format.chroma_subsampling_x == 1);
145 assert(output_ycbcr_format.chroma_subsampling_y == 1);
147 output_ycbcr_format = ycbcr_format;
149 YCbCrConversionEffect *effect = (YCbCrConversionEffect *)(ycbcr_conversion_effect_node->effect);
150 effect->change_output_format(ycbcr_format);
154 Node *EffectChain::add_node(Effect *effect)
156 for (unsigned i = 0; i < nodes.size(); ++i) {
157 assert(nodes[i]->effect != effect);
160 Node *node = new Node;
161 node->effect = effect;
162 node->disabled = false;
163 node->output_color_space = COLORSPACE_INVALID;
164 node->output_gamma_curve = GAMMA_INVALID;
165 node->output_alpha_type = ALPHA_INVALID;
166 node->needs_mipmaps = Effect::DOES_NOT_NEED_MIPMAPS;
167 node->one_to_one_sampling = false;
168 node->strong_one_to_one_sampling = false;
170 nodes.push_back(node);
171 node_map[effect] = node;
172 effect->inform_added(this);
176 void EffectChain::connect_nodes(Node *sender, Node *receiver)
178 sender->outgoing_links.push_back(receiver);
179 receiver->incoming_links.push_back(sender);
182 void EffectChain::replace_receiver(Node *old_receiver, Node *new_receiver)
184 new_receiver->incoming_links = old_receiver->incoming_links;
185 old_receiver->incoming_links.clear();
187 for (unsigned i = 0; i < new_receiver->incoming_links.size(); ++i) {
188 Node *sender = new_receiver->incoming_links[i];
189 for (unsigned j = 0; j < sender->outgoing_links.size(); ++j) {
190 if (sender->outgoing_links[j] == old_receiver) {
191 sender->outgoing_links[j] = new_receiver;
197 void EffectChain::replace_sender(Node *old_sender, Node *new_sender)
199 new_sender->outgoing_links = old_sender->outgoing_links;
200 old_sender->outgoing_links.clear();
202 for (unsigned i = 0; i < new_sender->outgoing_links.size(); ++i) {
203 Node *receiver = new_sender->outgoing_links[i];
204 for (unsigned j = 0; j < receiver->incoming_links.size(); ++j) {
205 if (receiver->incoming_links[j] == old_sender) {
206 receiver->incoming_links[j] = new_sender;
212 void EffectChain::insert_node_between(Node *sender, Node *middle, Node *receiver)
214 for (unsigned i = 0; i < sender->outgoing_links.size(); ++i) {
215 if (sender->outgoing_links[i] == receiver) {
216 sender->outgoing_links[i] = middle;
217 middle->incoming_links.push_back(sender);
220 for (unsigned i = 0; i < receiver->incoming_links.size(); ++i) {
221 if (receiver->incoming_links[i] == sender) {
222 receiver->incoming_links[i] = middle;
223 middle->outgoing_links.push_back(receiver);
227 assert(middle->incoming_links.size() == middle->effect->num_inputs());
230 GLenum EffectChain::get_input_sampler(Node *node, unsigned input_num) const
232 assert(node->effect->needs_texture_bounce());
233 assert(input_num < node->incoming_links.size());
234 assert(node->incoming_links[input_num]->bound_sampler_num >= 0);
235 assert(node->incoming_links[input_num]->bound_sampler_num < 8);
236 return GL_TEXTURE0 + node->incoming_links[input_num]->bound_sampler_num;
239 GLenum EffectChain::has_input_sampler(Node *node, unsigned input_num) const
241 assert(input_num < node->incoming_links.size());
242 return node->incoming_links[input_num]->bound_sampler_num >= 0 &&
243 node->incoming_links[input_num]->bound_sampler_num < 8;
246 void EffectChain::find_all_nonlinear_inputs(Node *node, vector<Node *> *nonlinear_inputs)
248 if (node->output_gamma_curve == GAMMA_LINEAR &&
249 node->effect->effect_type_id() != "GammaCompressionEffect") {
252 if (node->effect->num_inputs() == 0) {
253 nonlinear_inputs->push_back(node);
255 assert(node->effect->num_inputs() == node->incoming_links.size());
256 for (unsigned i = 0; i < node->incoming_links.size(); ++i) {
257 find_all_nonlinear_inputs(node->incoming_links[i], nonlinear_inputs);
262 Effect *EffectChain::add_effect(Effect *effect, const vector<Effect *> &inputs)
265 assert(inputs.size() == effect->num_inputs());
266 Node *node = add_node(effect);
267 for (unsigned i = 0; i < inputs.size(); ++i) {
268 assert(node_map.count(inputs[i]) != 0);
269 connect_nodes(node_map[inputs[i]], node);
274 // ESSL doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
275 string replace_prefix(const string &text, const string &prefix)
280 while (start < text.size()) {
281 size_t pos = text.find("PREFIX(", start);
282 if (pos == string::npos) {
283 output.append(text.substr(start, string::npos));
287 output.append(text.substr(start, pos - start));
288 output.append(prefix);
291 pos += strlen("PREFIX(");
293 // Output stuff until we find the matching ), which we then eat.
295 size_t end_arg_pos = pos;
296 while (end_arg_pos < text.size()) {
297 if (text[end_arg_pos] == '(') {
299 } else if (text[end_arg_pos] == ')') {
307 output.append(text.substr(pos, end_arg_pos - pos));
318 void extract_uniform_declarations(const vector<Uniform<T>> &effect_uniforms,
319 const string &type_specifier,
320 const string &effect_id,
321 vector<Uniform<T>> *phase_uniforms,
324 for (unsigned i = 0; i < effect_uniforms.size(); ++i) {
325 phase_uniforms->push_back(effect_uniforms[i]);
326 phase_uniforms->back().prefix = effect_id;
328 *glsl_string += string("uniform ") + type_specifier + " " + effect_id
329 + "_" + effect_uniforms[i].name + ";\n";
334 void extract_uniform_array_declarations(const vector<Uniform<T>> &effect_uniforms,
335 const string &type_specifier,
336 const string &effect_id,
337 vector<Uniform<T>> *phase_uniforms,
340 for (unsigned i = 0; i < effect_uniforms.size(); ++i) {
341 phase_uniforms->push_back(effect_uniforms[i]);
342 phase_uniforms->back().prefix = effect_id;
345 snprintf(buf, sizeof(buf), "uniform %s %s_%s[%d];\n",
346 type_specifier.c_str(), effect_id.c_str(),
347 effect_uniforms[i].name.c_str(),
348 int(effect_uniforms[i].num_values));
354 void collect_uniform_locations(GLuint glsl_program_num, vector<Uniform<T>> *phase_uniforms)
356 for (unsigned i = 0; i < phase_uniforms->size(); ++i) {
357 Uniform<T> &uniform = (*phase_uniforms)[i];
358 uniform.location = get_uniform_location(glsl_program_num, uniform.prefix, uniform.name);
364 void EffectChain::compile_glsl_program(Phase *phase)
366 string frag_shader_header;
367 if (phase->is_compute_shader) {
368 frag_shader_header = read_file("header.comp");
370 frag_shader_header = read_version_dependent_file("header", "frag");
372 string frag_shader = "";
374 // Create functions and uniforms for all the texture inputs that we need.
375 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
376 Node *input = phase->inputs[i]->output_node;
378 sprintf(effect_id, "in%u", i);
379 phase->effect_ids.insert(make_pair(make_pair(input, IN_ANOTHER_PHASE), effect_id));
381 frag_shader += string("uniform sampler2D tex_") + effect_id + ";\n";
382 frag_shader += string("vec4 ") + effect_id + "(vec2 tc) {\n";
383 frag_shader += "\tvec4 tmp = tex2D(tex_" + string(effect_id) + ", tc);\n";
385 if (intermediate_transformation == SQUARE_ROOT_FRAMEBUFFER_TRANSFORMATION &&
386 phase->inputs[i]->output_node->output_gamma_curve == GAMMA_LINEAR) {
387 frag_shader += "\ttmp.rgb *= tmp.rgb;\n";
390 frag_shader += "\treturn tmp;\n";
391 frag_shader += "}\n";
394 Uniform<int> uniform;
395 uniform.name = effect_id;
396 uniform.value = &phase->input_samplers[i];
397 uniform.prefix = "tex";
398 uniform.num_values = 1;
399 uniform.location = -1;
400 phase->uniforms_sampler2d.push_back(uniform);
403 // Give each effect in the phase its own ID.
404 for (unsigned i = 0; i < phase->effects.size(); ++i) {
405 Node *node = phase->effects[i];
407 sprintf(effect_id, "eff%u", i);
408 bool inserted = phase->effect_ids.insert(make_pair(make_pair(node, IN_SAME_PHASE), effect_id)).second;
412 for (unsigned i = 0; i < phase->effects.size(); ++i) {
413 Node *node = phase->effects[i];
414 const string effect_id = phase->effect_ids[make_pair(node, IN_SAME_PHASE)];
415 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
416 if (node->incoming_links.size() == 1) {
417 frag_shader += "#define INPUT";
420 sprintf(buf, "#define INPUT%d", j + 1);
424 Node *input = node->incoming_links[j];
425 NodeLinkType link_type = node->incoming_link_type[j];
427 input->effect->is_compute_shader() &&
428 node->incoming_link_type[j] == IN_SAME_PHASE) {
429 // First effect after the compute shader reads the value
430 // that cs_output() wrote to a global variable,
431 // ignoring the tc (since all such effects have to be
432 // strong one-to-one).
433 frag_shader += "(tc) CS_OUTPUT_VAL\n";
435 assert(phase->effect_ids.count(make_pair(input, link_type)));
436 frag_shader += string(" ") + phase->effect_ids[make_pair(input, link_type)] + "\n";
441 frag_shader += string("#define FUNCNAME ") + effect_id + "\n";
442 if (node->effect->is_compute_shader()) {
443 frag_shader += string("#define NORMALIZE_TEXTURE_COORDS(tc) ((tc) * ") + effect_id + "_inv_output_size + " + effect_id + "_output_texcoord_adjust)\n";
445 frag_shader += replace_prefix(node->effect->output_fragment_shader(), effect_id);
446 frag_shader += "#undef FUNCNAME\n";
447 if (node->incoming_links.size() == 1) {
448 frag_shader += "#undef INPUT\n";
450 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
452 sprintf(buf, "#undef INPUT%d\n", j + 1);
458 if (phase->is_compute_shader) {
459 assert(phase->effect_ids.count(make_pair(phase->compute_shader_node, IN_SAME_PHASE)));
460 frag_shader += string("#define INPUT ") + phase->effect_ids[make_pair(phase->compute_shader_node, IN_SAME_PHASE)] + "\n";
461 if (phase->compute_shader_node == phase->effects.back()) {
462 // No postprocessing.
463 frag_shader += "#define CS_POSTPROC(tc) CS_OUTPUT_VAL\n";
465 frag_shader += string("#define CS_POSTPROC ") + phase->effect_ids[make_pair(phase->effects.back(), IN_SAME_PHASE)] + "\n";
468 assert(phase->effect_ids.count(make_pair(phase->effects.back(), IN_SAME_PHASE)));
469 frag_shader += string("#define INPUT ") + phase->effect_ids[make_pair(phase->effects.back(), IN_SAME_PHASE)] + "\n";
472 // If we're the last phase, add the right #defines for Y'CbCr multi-output as needed.
473 vector<string> frag_shader_outputs; // In order.
474 if (phase->output_node->outgoing_links.empty() && num_output_color_ycbcr > 0) {
475 switch (output_ycbcr_splitting[0]) {
476 case YCBCR_OUTPUT_INTERLEAVED:
478 frag_shader_outputs.push_back("FragColor");
480 case YCBCR_OUTPUT_SPLIT_Y_AND_CBCR:
481 frag_shader += "#define YCBCR_OUTPUT_SPLIT_Y_AND_CBCR 1\n";
482 frag_shader_outputs.push_back("Y");
483 frag_shader_outputs.push_back("Chroma");
485 case YCBCR_OUTPUT_PLANAR:
486 frag_shader += "#define YCBCR_OUTPUT_PLANAR 1\n";
487 frag_shader_outputs.push_back("Y");
488 frag_shader_outputs.push_back("Cb");
489 frag_shader_outputs.push_back("Cr");
495 if (num_output_color_ycbcr > 1) {
496 switch (output_ycbcr_splitting[1]) {
497 case YCBCR_OUTPUT_INTERLEAVED:
498 frag_shader += "#define SECOND_YCBCR_OUTPUT_INTERLEAVED 1\n";
499 frag_shader_outputs.push_back("YCbCr2");
501 case YCBCR_OUTPUT_SPLIT_Y_AND_CBCR:
502 frag_shader += "#define SECOND_YCBCR_OUTPUT_SPLIT_Y_AND_CBCR 1\n";
503 frag_shader_outputs.push_back("Y2");
504 frag_shader_outputs.push_back("Chroma2");
506 case YCBCR_OUTPUT_PLANAR:
507 frag_shader += "#define SECOND_YCBCR_OUTPUT_PLANAR 1\n";
508 frag_shader_outputs.push_back("Y2");
509 frag_shader_outputs.push_back("Cb2");
510 frag_shader_outputs.push_back("Cr2");
517 if (output_color_rgba) {
518 // Note: Needs to come in the header, because not only the
519 // output needs to see it (YCbCrConversionEffect and DitherEffect
521 frag_shader_header += "#define YCBCR_ALSO_OUTPUT_RGBA 1\n";
522 frag_shader_outputs.push_back("RGBA");
526 // If we're bouncing to a temporary texture, signal transformation if desired.
527 if (!phase->output_node->outgoing_links.empty()) {
528 if (intermediate_transformation == SQUARE_ROOT_FRAMEBUFFER_TRANSFORMATION &&
529 phase->output_node->output_gamma_curve == GAMMA_LINEAR) {
530 frag_shader += "#define SQUARE_ROOT_TRANSFORMATION 1\n";
534 if (phase->is_compute_shader) {
535 frag_shader.append(read_file("footer.comp"));
536 phase->compute_shader_node->effect->register_uniform_ivec2("output_size", phase->uniform_output_size);
537 phase->compute_shader_node->effect->register_uniform_vec2("inv_output_size", (float *)&phase->inv_output_size);
538 phase->compute_shader_node->effect->register_uniform_vec2("output_texcoord_adjust", (float *)&phase->output_texcoord_adjust);
540 frag_shader.append(read_file("footer.frag"));
543 // Collect uniforms from all effects and output them. Note that this needs
544 // to happen after output_fragment_shader(), even though the uniforms come
545 // before in the output source, since output_fragment_shader() is allowed
546 // to register new uniforms (e.g. arrays that are of unknown length until
547 // finalization time).
548 // TODO: Make a uniform block for platforms that support it.
549 string frag_shader_uniforms = "";
550 for (unsigned i = 0; i < phase->effects.size(); ++i) {
551 Node *node = phase->effects[i];
552 Effect *effect = node->effect;
553 const string effect_id = phase->effect_ids[make_pair(node, IN_SAME_PHASE)];
554 extract_uniform_declarations(effect->uniforms_image2d, "image2D", effect_id, &phase->uniforms_image2d, &frag_shader_uniforms);
555 extract_uniform_declarations(effect->uniforms_sampler2d, "sampler2D", effect_id, &phase->uniforms_sampler2d, &frag_shader_uniforms);
556 extract_uniform_declarations(effect->uniforms_bool, "bool", effect_id, &phase->uniforms_bool, &frag_shader_uniforms);
557 extract_uniform_declarations(effect->uniforms_int, "int", effect_id, &phase->uniforms_int, &frag_shader_uniforms);
558 extract_uniform_declarations(effect->uniforms_ivec2, "ivec2", effect_id, &phase->uniforms_ivec2, &frag_shader_uniforms);
559 extract_uniform_declarations(effect->uniforms_float, "float", effect_id, &phase->uniforms_float, &frag_shader_uniforms);
560 extract_uniform_declarations(effect->uniforms_vec2, "vec2", effect_id, &phase->uniforms_vec2, &frag_shader_uniforms);
561 extract_uniform_declarations(effect->uniforms_vec3, "vec3", effect_id, &phase->uniforms_vec3, &frag_shader_uniforms);
562 extract_uniform_declarations(effect->uniforms_vec4, "vec4", effect_id, &phase->uniforms_vec4, &frag_shader_uniforms);
563 extract_uniform_array_declarations(effect->uniforms_float_array, "float", effect_id, &phase->uniforms_float, &frag_shader_uniforms);
564 extract_uniform_array_declarations(effect->uniforms_vec2_array, "vec2", effect_id, &phase->uniforms_vec2, &frag_shader_uniforms);
565 extract_uniform_array_declarations(effect->uniforms_vec3_array, "vec3", effect_id, &phase->uniforms_vec3, &frag_shader_uniforms);
566 extract_uniform_array_declarations(effect->uniforms_vec4_array, "vec4", effect_id, &phase->uniforms_vec4, &frag_shader_uniforms);
567 extract_uniform_declarations(effect->uniforms_mat3, "mat3", effect_id, &phase->uniforms_mat3, &frag_shader_uniforms);
570 string vert_shader = read_version_dependent_file("vs", "vert");
572 // If we're the last phase and need to flip the picture to compensate for
573 // the origin, tell the vertex or compute shader so.
575 if (has_dummy_effect) {
576 is_last_phase = (phase->output_node->outgoing_links.size() == 1 &&
577 phase->output_node->outgoing_links[0]->effect->effect_type_id() == "ComputeShaderOutputDisplayEffect");
579 is_last_phase = phase->output_node->outgoing_links.empty();
581 if (is_last_phase && output_origin == OUTPUT_ORIGIN_TOP_LEFT) {
582 if (phase->is_compute_shader) {
583 frag_shader_header += "#define FLIP_ORIGIN 1\n";
585 const string needle = "#define FLIP_ORIGIN 0";
586 size_t pos = vert_shader.find(needle);
587 assert(pos != string::npos);
589 vert_shader[pos + needle.size() - 1] = '1';
593 frag_shader = frag_shader_header + frag_shader_uniforms + frag_shader;
595 if (phase->is_compute_shader) {
596 phase->glsl_program_num = resource_pool->compile_glsl_compute_program(frag_shader);
598 Uniform<int> uniform;
599 uniform.name = "outbuf";
600 uniform.value = &phase->outbuf_image_unit;
601 uniform.prefix = "tex";
602 uniform.num_values = 1;
603 uniform.location = -1;
604 phase->uniforms_image2d.push_back(uniform);
606 phase->glsl_program_num = resource_pool->compile_glsl_program(vert_shader, frag_shader, frag_shader_outputs);
608 GLint position_attribute_index = glGetAttribLocation(phase->glsl_program_num, "position");
609 GLint texcoord_attribute_index = glGetAttribLocation(phase->glsl_program_num, "texcoord");
610 if (position_attribute_index != -1) {
611 phase->attribute_indexes.insert(position_attribute_index);
613 if (texcoord_attribute_index != -1) {
614 phase->attribute_indexes.insert(texcoord_attribute_index);
617 // Collect the resulting location numbers for each uniform.
618 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_image2d);
619 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_sampler2d);
620 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_bool);
621 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_int);
622 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_ivec2);
623 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_float);
624 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec2);
625 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec3);
626 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_vec4);
627 collect_uniform_locations(phase->glsl_program_num, &phase->uniforms_mat3);
630 // Construct GLSL programs, starting at the given effect and following
631 // the chain from there. We end a program every time we come to an effect
632 // marked as "needs texture bounce", one that is used by multiple other
633 // effects, every time we need to bounce due to output size change
634 // (not all size changes require ending), and of course at the end.
636 // We follow a quite simple depth-first search from the output, although
637 // without recursing explicitly within each phase.
638 Phase *EffectChain::construct_phase(Node *output, map<Node *, Phase *> *completed_effects)
640 if (completed_effects->count(output)) {
641 return (*completed_effects)[output];
644 Phase *phase = new Phase;
645 phase->output_node = output;
646 phase->is_compute_shader = false;
647 phase->compute_shader_node = nullptr;
649 // If the output effect has one-to-one sampling, we try to trace this
650 // status down through the dependency chain. This is important in case
651 // we hit an effect that changes output size (and not sets a virtual
652 // output size); if we have one-to-one sampling, we don't have to break
654 output->one_to_one_sampling = output->effect->one_to_one_sampling();
655 output->strong_one_to_one_sampling = output->effect->strong_one_to_one_sampling();
657 // Effects that we have yet to calculate, but that we know should
658 // be in the current phase.
659 stack<Node *> effects_todo_this_phase;
660 effects_todo_this_phase.push(output);
662 while (!effects_todo_this_phase.empty()) {
663 Node *node = effects_todo_this_phase.top();
664 effects_todo_this_phase.pop();
666 assert(node->effect->one_to_one_sampling() >= node->effect->strong_one_to_one_sampling());
668 if (node->effect->needs_mipmaps() != Effect::DOES_NOT_NEED_MIPMAPS) {
669 // Can't have incompatible requirements imposed on us from a dependent effect;
670 // if so, it should have started a new phase instead.
671 assert(node->needs_mipmaps == Effect::DOES_NOT_NEED_MIPMAPS ||
672 node->needs_mipmaps == node->effect->needs_mipmaps());
673 node->needs_mipmaps = node->effect->needs_mipmaps();
676 // This should currently only happen for effects that are inputs
677 // (either true inputs or phase outputs). We special-case inputs,
678 // and then deduplicate phase outputs below.
679 if (node->effect->num_inputs() == 0) {
680 if (find(phase->effects.begin(), phase->effects.end(), node) != phase->effects.end()) {
684 assert(completed_effects->count(node) == 0);
687 phase->effects.push_back(node);
688 if (node->effect->is_compute_shader()) {
689 assert(phase->compute_shader_node == nullptr ||
690 phase->compute_shader_node == node);
691 phase->is_compute_shader = true;
692 phase->compute_shader_node = node;
695 // Find all the dependencies of this effect, and add them to the stack.
696 vector<Node *> deps = node->incoming_links;
697 assert(node->effect->num_inputs() == deps.size());
698 for (unsigned i = 0; i < deps.size(); ++i) {
699 bool start_new_phase = false;
701 Effect::MipmapRequirements save_needs_mipmaps = deps[i]->needs_mipmaps;
703 if (node->effect->needs_texture_bounce() &&
704 !deps[i]->effect->is_single_texture() &&
705 !deps[i]->effect->override_disable_bounce()) {
706 start_new_phase = true;
709 // Propagate information about needing mipmaps down the chain,
710 // breaking the phase if we notice an incompatibility.
712 // Note that we cannot do this propagation as a normal pass,
713 // because it needs information about where the phases end
714 // (we should not propagate the flag across phases).
715 if (node->needs_mipmaps != Effect::DOES_NOT_NEED_MIPMAPS) {
716 // The node can have a value set (ie. not DOES_NOT_NEED_MIPMAPS)
717 // if we have diamonds in the graph; if so, choose that.
718 // If not, the effect on the node can also decide (this is the
719 // more common case).
720 Effect::MipmapRequirements dep_mipmaps = deps[i]->needs_mipmaps;
721 if (dep_mipmaps == Effect::DOES_NOT_NEED_MIPMAPS) {
722 if (deps[i]->effect->num_inputs() == 0) {
723 Input *input = static_cast<Input *>(deps[i]->effect);
724 dep_mipmaps = input->can_supply_mipmaps() ? Effect::DOES_NOT_NEED_MIPMAPS : Effect::CANNOT_ACCEPT_MIPMAPS;
726 dep_mipmaps = deps[i]->effect->needs_mipmaps();
729 if (dep_mipmaps == Effect::DOES_NOT_NEED_MIPMAPS) {
730 deps[i]->needs_mipmaps = node->needs_mipmaps;
731 } else if (dep_mipmaps != node->needs_mipmaps) {
732 // The dependency cannot supply our mipmap demands
733 // (either because it's an input that can't do mipmaps,
734 // or because there's a conflict between mipmap-needing
735 // and mipmap-refusing effects somewhere in the graph),
736 // so they cannot be in the same phase.
737 start_new_phase = true;
741 if (deps[i]->outgoing_links.size() > 1) {
742 if (!deps[i]->effect->is_single_texture()) {
743 // More than one effect uses this as the input,
744 // and it is not a texture itself.
745 // The easiest thing to do (and probably also the safest
746 // performance-wise in most cases) is to bounce it to a texture
747 // and then let the next passes read from that.
748 start_new_phase = true;
750 assert(deps[i]->effect->num_inputs() == 0);
752 // For textures, we try to be slightly more clever;
753 // if none of our outputs need a bounce, we don't bounce
754 // but instead simply use the effect many times.
756 // Strictly speaking, we could bounce it for some outputs
757 // and use it directly for others, but the processing becomes
758 // somewhat simpler if the effect is only used in one such way.
759 for (unsigned j = 0; j < deps[i]->outgoing_links.size(); ++j) {
760 Node *rdep = deps[i]->outgoing_links[j];
761 start_new_phase |= rdep->effect->needs_texture_bounce();
766 if (deps[i]->effect->is_compute_shader()) {
767 if (phase->is_compute_shader) {
768 // Only one compute shader per phase.
769 start_new_phase = true;
770 } else if (!node->strong_one_to_one_sampling) {
771 // If all nodes so far are strong one-to-one, we can put them after
772 // the compute shader (ie., process them on the output).
773 start_new_phase = true;
774 } else if (!start_new_phase) {
775 phase->is_compute_shader = true;
776 phase->compute_shader_node = deps[i];
778 } else if (deps[i]->effect->sets_virtual_output_size()) {
779 assert(deps[i]->effect->changes_output_size());
780 // If the next effect sets a virtual size to rely on OpenGL's
781 // bilinear sampling, we'll really need to break the phase here.
782 start_new_phase = true;
783 } else if (deps[i]->effect->changes_output_size() && !node->one_to_one_sampling) {
784 // If the next effect changes size and we don't have one-to-one sampling,
785 // we also need to break here.
786 start_new_phase = true;
789 if (start_new_phase) {
790 // Since we're starting a new phase here, we don't need to impose any
791 // new demands on this effect. Restore the status we had before we
792 // started looking at it.
793 deps[i]->needs_mipmaps = save_needs_mipmaps;
795 phase->inputs.push_back(construct_phase(deps[i], completed_effects));
797 effects_todo_this_phase.push(deps[i]);
799 // Propagate the one-to-one status down through the dependency.
800 deps[i]->one_to_one_sampling = node->one_to_one_sampling &&
801 deps[i]->effect->one_to_one_sampling();
802 deps[i]->strong_one_to_one_sampling = node->strong_one_to_one_sampling &&
803 deps[i]->effect->strong_one_to_one_sampling();
806 node->incoming_link_type.push_back(start_new_phase ? IN_ANOTHER_PHASE : IN_SAME_PHASE);
810 // No more effects to do this phase. Take all the ones we have,
811 // and create a GLSL program for it.
812 assert(!phase->effects.empty());
814 // Deduplicate the inputs, but don't change the ordering e.g. by sorting;
815 // that would be nondeterministic and thus reduce cacheability.
816 // TODO: Make this even more deterministic.
817 vector<Phase *> dedup_inputs;
818 set<Phase *> seen_inputs;
819 for (size_t i = 0; i < phase->inputs.size(); ++i) {
820 if (seen_inputs.insert(phase->inputs[i]).second) {
821 dedup_inputs.push_back(phase->inputs[i]);
824 swap(phase->inputs, dedup_inputs);
826 // Allocate samplers for each input.
827 phase->input_samplers.resize(phase->inputs.size());
829 // We added the effects from the output and back, but we need to output
830 // them in topological sort order in the shader.
831 phase->effects = topological_sort(phase->effects);
833 // Figure out if we need mipmaps or not, and if so, tell the inputs that.
834 // (RTT inputs have different logic, which is checked in execute_phase().)
835 for (unsigned i = 0; i < phase->effects.size(); ++i) {
836 Node *node = phase->effects[i];
837 if (node->effect->num_inputs() == 0) {
838 Input *input = static_cast<Input *>(node->effect);
839 assert(node->needs_mipmaps != Effect::NEEDS_MIPMAPS || input->can_supply_mipmaps());
840 CHECK(input->set_int("needs_mipmaps", node->needs_mipmaps == Effect::NEEDS_MIPMAPS));
844 // Tell each node which phase it ended up in, so that the unit test
845 // can check that the phases were split in the right place.
846 // Note that this ignores that effects may be part of multiple phases;
847 // if the unit tests need to test such cases, we'll reconsider.
848 for (unsigned i = 0; i < phase->effects.size(); ++i) {
849 phase->effects[i]->containing_phase = phase;
852 // Actually make the shader for this phase.
853 compile_glsl_program(phase);
855 // Initialize timers.
856 if (movit_timer_queries_supported) {
857 phase->time_elapsed_ns = 0;
858 phase->num_measured_iterations = 0;
861 assert(completed_effects->count(output) == 0);
862 completed_effects->insert(make_pair(output, phase));
863 phases.push_back(phase);
867 void EffectChain::output_dot(const char *filename)
869 if (movit_debug_level != MOVIT_DEBUG_ON) {
873 FILE *fp = fopen(filename, "w");
879 fprintf(fp, "digraph G {\n");
880 fprintf(fp, " output [shape=box label=\"(output)\"];\n");
881 for (unsigned i = 0; i < nodes.size(); ++i) {
882 // Find out which phase this event belongs to.
883 vector<int> in_phases;
884 for (unsigned j = 0; j < phases.size(); ++j) {
885 const Phase* p = phases[j];
886 if (find(p->effects.begin(), p->effects.end(), nodes[i]) != p->effects.end()) {
887 in_phases.push_back(j);
891 if (in_phases.empty()) {
892 fprintf(fp, " n%ld [label=\"%s\"];\n", (long)nodes[i], nodes[i]->effect->effect_type_id().c_str());
893 } else if (in_phases.size() == 1) {
894 fprintf(fp, " n%ld [label=\"%s\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
895 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
896 (in_phases[0] % 8) + 1);
898 // If we had new enough Graphviz, style="wedged" would probably be ideal here.
900 fprintf(fp, " n%ld [label=\"%s [in multiple phases]\" style=\"filled\" fillcolor=\"/accent8/%d\"];\n",
901 (long)nodes[i], nodes[i]->effect->effect_type_id().c_str(),
902 (in_phases[0] % 8) + 1);
905 char from_node_id[256];
906 snprintf(from_node_id, 256, "n%ld", (long)nodes[i]);
908 for (unsigned j = 0; j < nodes[i]->outgoing_links.size(); ++j) {
909 char to_node_id[256];
910 snprintf(to_node_id, 256, "n%ld", (long)nodes[i]->outgoing_links[j]);
912 vector<string> labels = get_labels_for_edge(nodes[i], nodes[i]->outgoing_links[j]);
913 output_dot_edge(fp, from_node_id, to_node_id, labels);
916 if (nodes[i]->outgoing_links.empty() && !nodes[i]->disabled) {
918 vector<string> labels = get_labels_for_edge(nodes[i], nullptr);
919 output_dot_edge(fp, from_node_id, "output", labels);
927 vector<string> EffectChain::get_labels_for_edge(const Node *from, const Node *to)
929 vector<string> labels;
931 if (to != nullptr && to->effect->needs_texture_bounce()) {
932 labels.push_back("needs_bounce");
934 if (from->effect->changes_output_size()) {
935 labels.push_back("resize");
938 switch (from->output_color_space) {
939 case COLORSPACE_INVALID:
940 labels.push_back("spc[invalid]");
942 case COLORSPACE_REC_601_525:
943 labels.push_back("spc[rec601-525]");
945 case COLORSPACE_REC_601_625:
946 labels.push_back("spc[rec601-625]");
952 switch (from->output_gamma_curve) {
954 labels.push_back("gamma[invalid]");
957 labels.push_back("gamma[sRGB]");
959 case GAMMA_REC_601: // and GAMMA_REC_709
960 labels.push_back("gamma[rec601/709]");
966 switch (from->output_alpha_type) {
968 labels.push_back("alpha[invalid]");
971 labels.push_back("alpha[blank]");
973 case ALPHA_POSTMULTIPLIED:
974 labels.push_back("alpha[postmult]");
983 void EffectChain::output_dot_edge(FILE *fp,
984 const string &from_node_id,
985 const string &to_node_id,
986 const vector<string> &labels)
988 if (labels.empty()) {
989 fprintf(fp, " %s -> %s;\n", from_node_id.c_str(), to_node_id.c_str());
991 string label = labels[0];
992 for (unsigned k = 1; k < labels.size(); ++k) {
993 label += ", " + labels[k];
995 fprintf(fp, " %s -> %s [label=\"%s\"];\n", from_node_id.c_str(), to_node_id.c_str(), label.c_str());
999 void EffectChain::size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height)
1001 unsigned scaled_width, scaled_height;
1003 if (float(width) * aspect_denom >= float(height) * aspect_nom) {
1004 // Same aspect, or W/H > aspect (image is wider than the frame).
1005 // In either case, keep width, and adjust height.
1006 scaled_width = width;
1007 scaled_height = lrintf(width * aspect_denom / aspect_nom);
1009 // W/H < aspect (image is taller than the frame), so keep height,
1010 // and adjust width.
1011 scaled_width = lrintf(height * aspect_nom / aspect_denom);
1012 scaled_height = height;
1015 // We should be consistently larger or smaller then the existing choice,
1016 // since we have the same aspect.
1017 assert(!(scaled_width < *output_width && scaled_height > *output_height));
1018 assert(!(scaled_height < *output_height && scaled_width > *output_width));
1020 if (scaled_width >= *output_width && scaled_height >= *output_height) {
1021 *output_width = scaled_width;
1022 *output_height = scaled_height;
1026 // Propagate input texture sizes throughout, and inform effects downstream.
1027 // (Like a lot of other code, we depend on effects being in topological order.)
1028 void EffectChain::inform_input_sizes(Phase *phase)
1030 // All effects that have a defined size (inputs and RTT inputs)
1031 // get that. Reset all others.
1032 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1033 Node *node = phase->effects[i];
1034 if (node->effect->num_inputs() == 0) {
1035 Input *input = static_cast<Input *>(node->effect);
1036 node->output_width = input->get_width();
1037 node->output_height = input->get_height();
1038 assert(node->output_width != 0);
1039 assert(node->output_height != 0);
1041 node->output_width = node->output_height = 0;
1044 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
1045 Phase *input = phase->inputs[i];
1046 input->output_node->output_width = input->virtual_output_width;
1047 input->output_node->output_height = input->virtual_output_height;
1048 assert(input->output_node->output_width != 0);
1049 assert(input->output_node->output_height != 0);
1052 // Now propagate from the inputs towards the end, and inform as we go.
1053 // The rules are simple:
1055 // 1. Don't touch effects that already have given sizes (ie., inputs
1056 // or effects that change the output size).
1057 // 2. If all of your inputs have the same size, that will be your output size.
1058 // 3. Otherwise, your output size is 0x0.
1059 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1060 Node *node = phase->effects[i];
1061 if (node->effect->num_inputs() == 0) {
1064 unsigned this_output_width = 0;
1065 unsigned this_output_height = 0;
1066 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1067 Node *input = node->incoming_links[j];
1068 node->effect->inform_input_size(j, input->output_width, input->output_height);
1070 this_output_width = input->output_width;
1071 this_output_height = input->output_height;
1072 } else if (input->output_width != this_output_width || input->output_height != this_output_height) {
1074 this_output_width = 0;
1075 this_output_height = 0;
1078 if (node->effect->changes_output_size()) {
1079 // We cannot call get_output_size() before we've done inform_input_size()
1081 unsigned real_width, real_height;
1082 node->effect->get_output_size(&real_width, &real_height,
1083 &node->output_width, &node->output_height);
1084 assert(node->effect->sets_virtual_output_size() ||
1085 (real_width == node->output_width &&
1086 real_height == node->output_height));
1088 node->output_width = this_output_width;
1089 node->output_height = this_output_height;
1094 // Note: You should call inform_input_sizes() before this, as the last effect's
1095 // desired output size might change based on the inputs.
1096 void EffectChain::find_output_size(Phase *phase)
1098 Node *output_node = phase->is_compute_shader ? phase->compute_shader_node : phase->effects.back();
1100 // If the last effect explicitly sets an output size, use that.
1101 if (output_node->effect->changes_output_size()) {
1102 output_node->effect->get_output_size(&phase->output_width, &phase->output_height,
1103 &phase->virtual_output_width, &phase->virtual_output_height);
1104 assert(output_node->effect->sets_virtual_output_size() ||
1105 (phase->output_width == phase->virtual_output_width &&
1106 phase->output_height == phase->virtual_output_height));
1110 // If all effects have the same size, use that.
1111 unsigned output_width = 0, output_height = 0;
1112 bool all_inputs_same_size = true;
1114 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
1115 Phase *input = phase->inputs[i];
1116 assert(input->output_width != 0);
1117 assert(input->output_height != 0);
1118 if (output_width == 0 && output_height == 0) {
1119 output_width = input->virtual_output_width;
1120 output_height = input->virtual_output_height;
1121 } else if (output_width != input->virtual_output_width ||
1122 output_height != input->virtual_output_height) {
1123 all_inputs_same_size = false;
1126 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1127 Effect *effect = phase->effects[i]->effect;
1128 if (effect->num_inputs() != 0) {
1132 Input *input = static_cast<Input *>(effect);
1133 if (output_width == 0 && output_height == 0) {
1134 output_width = input->get_width();
1135 output_height = input->get_height();
1136 } else if (output_width != input->get_width() ||
1137 output_height != input->get_height()) {
1138 all_inputs_same_size = false;
1142 if (all_inputs_same_size) {
1143 assert(output_width != 0);
1144 assert(output_height != 0);
1145 phase->virtual_output_width = phase->output_width = output_width;
1146 phase->virtual_output_height = phase->output_height = output_height;
1150 // If not, fit all the inputs into the current aspect, and select the largest one.
1153 for (unsigned i = 0; i < phase->inputs.size(); ++i) {
1154 Phase *input = phase->inputs[i];
1155 assert(input->output_width != 0);
1156 assert(input->output_height != 0);
1157 size_rectangle_to_fit(input->output_width, input->output_height, &output_width, &output_height);
1159 for (unsigned i = 0; i < phase->effects.size(); ++i) {
1160 Effect *effect = phase->effects[i]->effect;
1161 if (effect->num_inputs() != 0) {
1165 Input *input = static_cast<Input *>(effect);
1166 size_rectangle_to_fit(input->get_width(), input->get_height(), &output_width, &output_height);
1168 assert(output_width != 0);
1169 assert(output_height != 0);
1170 phase->virtual_output_width = phase->output_width = output_width;
1171 phase->virtual_output_height = phase->output_height = output_height;
1174 void EffectChain::sort_all_nodes_topologically()
1176 nodes = topological_sort(nodes);
1179 vector<Node *> EffectChain::topological_sort(const vector<Node *> &nodes)
1181 set<Node *> nodes_left_to_visit(nodes.begin(), nodes.end());
1182 vector<Node *> sorted_list;
1183 for (unsigned i = 0; i < nodes.size(); ++i) {
1184 topological_sort_visit_node(nodes[i], &nodes_left_to_visit, &sorted_list);
1186 reverse(sorted_list.begin(), sorted_list.end());
1190 void EffectChain::topological_sort_visit_node(Node *node, set<Node *> *nodes_left_to_visit, vector<Node *> *sorted_list)
1192 if (nodes_left_to_visit->count(node) == 0) {
1195 nodes_left_to_visit->erase(node);
1196 for (unsigned i = 0; i < node->outgoing_links.size(); ++i) {
1197 topological_sort_visit_node(node->outgoing_links[i], nodes_left_to_visit, sorted_list);
1199 sorted_list->push_back(node);
1202 void EffectChain::find_color_spaces_for_inputs()
1204 for (unsigned i = 0; i < nodes.size(); ++i) {
1205 Node *node = nodes[i];
1206 if (node->disabled) {
1209 if (node->incoming_links.size() == 0) {
1210 Input *input = static_cast<Input *>(node->effect);
1211 node->output_color_space = input->get_color_space();
1212 node->output_gamma_curve = input->get_gamma_curve();
1214 Effect::AlphaHandling alpha_handling = input->alpha_handling();
1215 switch (alpha_handling) {
1216 case Effect::OUTPUT_BLANK_ALPHA:
1217 node->output_alpha_type = ALPHA_BLANK;
1219 case Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA:
1220 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1222 case Effect::OUTPUT_POSTMULTIPLIED_ALPHA:
1223 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1225 case Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK:
1226 case Effect::DONT_CARE_ALPHA_TYPE:
1231 if (node->output_alpha_type == ALPHA_PREMULTIPLIED) {
1232 assert(node->output_gamma_curve == GAMMA_LINEAR);
1238 // Propagate gamma and color space information as far as we can in the graph.
1239 // The rules are simple: Anything where all the inputs agree, get that as
1240 // output as well. Anything else keeps having *_INVALID.
1241 void EffectChain::propagate_gamma_and_color_space()
1243 // We depend on going through the nodes in order.
1244 sort_all_nodes_topologically();
1246 for (unsigned i = 0; i < nodes.size(); ++i) {
1247 Node *node = nodes[i];
1248 if (node->disabled) {
1251 assert(node->incoming_links.size() == node->effect->num_inputs());
1252 if (node->incoming_links.size() == 0) {
1253 assert(node->output_color_space != COLORSPACE_INVALID);
1254 assert(node->output_gamma_curve != GAMMA_INVALID);
1258 Colorspace color_space = node->incoming_links[0]->output_color_space;
1259 GammaCurve gamma_curve = node->incoming_links[0]->output_gamma_curve;
1260 for (unsigned j = 1; j < node->incoming_links.size(); ++j) {
1261 if (node->incoming_links[j]->output_color_space != color_space) {
1262 color_space = COLORSPACE_INVALID;
1264 if (node->incoming_links[j]->output_gamma_curve != gamma_curve) {
1265 gamma_curve = GAMMA_INVALID;
1269 // The conversion effects already have their outputs set correctly,
1270 // so leave them alone.
1271 if (node->effect->effect_type_id() != "ColorspaceConversionEffect") {
1272 node->output_color_space = color_space;
1274 if (node->effect->effect_type_id() != "GammaCompressionEffect" &&
1275 node->effect->effect_type_id() != "GammaExpansionEffect") {
1276 node->output_gamma_curve = gamma_curve;
1281 // Propagate alpha information as far as we can in the graph.
1282 // Similar to propagate_gamma_and_color_space().
1283 void EffectChain::propagate_alpha()
1285 // We depend on going through the nodes in order.
1286 sort_all_nodes_topologically();
1288 for (unsigned i = 0; i < nodes.size(); ++i) {
1289 Node *node = nodes[i];
1290 if (node->disabled) {
1293 assert(node->incoming_links.size() == node->effect->num_inputs());
1294 if (node->incoming_links.size() == 0) {
1295 assert(node->output_alpha_type != ALPHA_INVALID);
1299 // The alpha multiplication/division effects are special cases.
1300 if (node->effect->effect_type_id() == "AlphaMultiplicationEffect") {
1301 assert(node->incoming_links.size() == 1);
1302 assert(node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED);
1303 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1306 if (node->effect->effect_type_id() == "AlphaDivisionEffect") {
1307 assert(node->incoming_links.size() == 1);
1308 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1309 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1313 // GammaCompressionEffect and GammaExpansionEffect are also a special case,
1314 // because they are the only one that _need_ postmultiplied alpha.
1315 if (node->effect->effect_type_id() == "GammaCompressionEffect" ||
1316 node->effect->effect_type_id() == "GammaExpansionEffect") {
1317 assert(node->incoming_links.size() == 1);
1318 if (node->incoming_links[0]->output_alpha_type == ALPHA_BLANK) {
1319 node->output_alpha_type = ALPHA_BLANK;
1320 } else if (node->incoming_links[0]->output_alpha_type == ALPHA_POSTMULTIPLIED) {
1321 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1323 node->output_alpha_type = ALPHA_INVALID;
1328 // Only inputs can have unconditional alpha output (OUTPUT_BLANK_ALPHA
1329 // or OUTPUT_POSTMULTIPLIED_ALPHA), and they have already been
1330 // taken care of above. Rationale: Even if you could imagine
1331 // e.g. an effect that took in an image and set alpha=1.0
1332 // unconditionally, it wouldn't make any sense to have it as
1333 // e.g. OUTPUT_BLANK_ALPHA, since it wouldn't know whether it
1334 // got its input pre- or postmultiplied, so it wouldn't know
1335 // whether to divide away the old alpha or not.
1336 Effect::AlphaHandling alpha_handling = node->effect->alpha_handling();
1337 assert(alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1338 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK ||
1339 alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1341 // If the node has multiple inputs, check that they are all valid and
1343 bool any_invalid = false;
1344 bool any_premultiplied = false;
1345 bool any_postmultiplied = false;
1347 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1348 switch (node->incoming_links[j]->output_alpha_type) {
1353 // Blank is good as both pre- and postmultiplied alpha,
1354 // so just ignore it.
1356 case ALPHA_PREMULTIPLIED:
1357 any_premultiplied = true;
1359 case ALPHA_POSTMULTIPLIED:
1360 any_postmultiplied = true;
1368 node->output_alpha_type = ALPHA_INVALID;
1372 // Inputs must be of the same type.
1373 if (any_premultiplied && any_postmultiplied) {
1374 node->output_alpha_type = ALPHA_INVALID;
1378 if (alpha_handling == Effect::INPUT_AND_OUTPUT_PREMULTIPLIED_ALPHA ||
1379 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1380 // This combination (requiring premultiplied alpha, but _not_ requiring
1381 // linear light) is illegal, since the combination of premultiplied alpha
1382 // and nonlinear inputs is meaningless.
1383 assert(node->effect->needs_linear_light());
1385 // If the effect has asked for premultiplied alpha, check that it has got it.
1386 if (any_postmultiplied) {
1387 node->output_alpha_type = ALPHA_INVALID;
1388 } else if (!any_premultiplied &&
1389 alpha_handling == Effect::INPUT_PREMULTIPLIED_ALPHA_KEEP_BLANK) {
1390 // Blank input alpha, and the effect preserves blank alpha.
1391 node->output_alpha_type = ALPHA_BLANK;
1393 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1396 // OK, all inputs are the same, and this effect is not going
1398 assert(alpha_handling == Effect::DONT_CARE_ALPHA_TYPE);
1399 if (any_premultiplied) {
1400 node->output_alpha_type = ALPHA_PREMULTIPLIED;
1401 } else if (any_postmultiplied) {
1402 node->output_alpha_type = ALPHA_POSTMULTIPLIED;
1404 node->output_alpha_type = ALPHA_BLANK;
1410 bool EffectChain::node_needs_colorspace_fix(Node *node)
1412 if (node->disabled) {
1415 if (node->effect->num_inputs() == 0) {
1419 // propagate_gamma_and_color_space() has already set our output
1420 // to COLORSPACE_INVALID if the inputs differ, so we can rely on that.
1421 if (node->output_color_space == COLORSPACE_INVALID) {
1424 return (node->effect->needs_srgb_primaries() && node->output_color_space != COLORSPACE_sRGB);
1427 // Fix up color spaces so that there are no COLORSPACE_INVALID nodes left in
1428 // the graph. Our strategy is not always optimal, but quite simple:
1429 // Find an effect that's as early as possible where the inputs are of
1430 // unacceptable colorspaces (that is, either different, or, if the effect only
1431 // wants sRGB, not sRGB.) Add appropriate conversions on all its inputs,
1432 // propagate the information anew, and repeat until there are no more such
1434 void EffectChain::fix_internal_color_spaces()
1436 unsigned colorspace_propagation_pass = 0;
1440 for (unsigned i = 0; i < nodes.size(); ++i) {
1441 Node *node = nodes[i];
1442 if (!node_needs_colorspace_fix(node)) {
1446 // Go through each input that is not sRGB, and insert
1447 // a colorspace conversion after it.
1448 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1449 Node *input = node->incoming_links[j];
1450 assert(input->output_color_space != COLORSPACE_INVALID);
1451 if (input->output_color_space == COLORSPACE_sRGB) {
1454 Node *conversion = add_node(new ColorspaceConversionEffect());
1455 CHECK(conversion->effect->set_int("source_space", input->output_color_space));
1456 CHECK(conversion->effect->set_int("destination_space", COLORSPACE_sRGB));
1457 conversion->output_color_space = COLORSPACE_sRGB;
1458 replace_sender(input, conversion);
1459 connect_nodes(input, conversion);
1462 // Re-sort topologically, and propagate the new information.
1463 propagate_gamma_and_color_space();
1470 sprintf(filename, "step5-colorspacefix-iter%u.dot", ++colorspace_propagation_pass);
1471 output_dot(filename);
1472 assert(colorspace_propagation_pass < 100);
1473 } while (found_any);
1475 for (unsigned i = 0; i < nodes.size(); ++i) {
1476 Node *node = nodes[i];
1477 if (node->disabled) {
1480 assert(node->output_color_space != COLORSPACE_INVALID);
1484 bool EffectChain::node_needs_alpha_fix(Node *node)
1486 if (node->disabled) {
1490 // propagate_alpha() has already set our output to ALPHA_INVALID if the
1491 // inputs differ or we are otherwise in mismatch, so we can rely on that.
1492 return (node->output_alpha_type == ALPHA_INVALID);
1495 // Fix up alpha so that there are no ALPHA_INVALID nodes left in
1496 // the graph. Similar to fix_internal_color_spaces().
1497 void EffectChain::fix_internal_alpha(unsigned step)
1499 unsigned alpha_propagation_pass = 0;
1503 for (unsigned i = 0; i < nodes.size(); ++i) {
1504 Node *node = nodes[i];
1505 if (!node_needs_alpha_fix(node)) {
1509 // If we need to fix up GammaExpansionEffect, then clearly something
1510 // is wrong, since the combination of premultiplied alpha and nonlinear inputs
1512 assert(node->effect->effect_type_id() != "GammaExpansionEffect");
1514 AlphaType desired_type = ALPHA_PREMULTIPLIED;
1516 // GammaCompressionEffect is special; it needs postmultiplied alpha.
1517 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1518 assert(node->incoming_links.size() == 1);
1519 assert(node->incoming_links[0]->output_alpha_type == ALPHA_PREMULTIPLIED);
1520 desired_type = ALPHA_POSTMULTIPLIED;
1523 // Go through each input that is not premultiplied alpha, and insert
1524 // a conversion before it.
1525 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1526 Node *input = node->incoming_links[j];
1527 assert(input->output_alpha_type != ALPHA_INVALID);
1528 if (input->output_alpha_type == desired_type ||
1529 input->output_alpha_type == ALPHA_BLANK) {
1533 if (desired_type == ALPHA_PREMULTIPLIED) {
1534 conversion = add_node(new AlphaMultiplicationEffect());
1536 conversion = add_node(new AlphaDivisionEffect());
1538 conversion->output_alpha_type = desired_type;
1539 replace_sender(input, conversion);
1540 connect_nodes(input, conversion);
1543 // Re-sort topologically, and propagate the new information.
1544 propagate_gamma_and_color_space();
1552 sprintf(filename, "step%u-alphafix-iter%u.dot", step, ++alpha_propagation_pass);
1553 output_dot(filename);
1554 assert(alpha_propagation_pass < 100);
1555 } while (found_any);
1557 for (unsigned i = 0; i < nodes.size(); ++i) {
1558 Node *node = nodes[i];
1559 if (node->disabled) {
1562 assert(node->output_alpha_type != ALPHA_INVALID);
1566 // Make so that the output is in the desired color space.
1567 void EffectChain::fix_output_color_space()
1569 Node *output = find_output_node();
1570 if (output->output_color_space != output_format.color_space) {
1571 Node *conversion = add_node(new ColorspaceConversionEffect());
1572 CHECK(conversion->effect->set_int("source_space", output->output_color_space));
1573 CHECK(conversion->effect->set_int("destination_space", output_format.color_space));
1574 conversion->output_color_space = output_format.color_space;
1575 connect_nodes(output, conversion);
1577 propagate_gamma_and_color_space();
1581 // Make so that the output is in the desired pre-/postmultiplication alpha state.
1582 void EffectChain::fix_output_alpha()
1584 Node *output = find_output_node();
1585 assert(output->output_alpha_type != ALPHA_INVALID);
1586 if (output->output_alpha_type == ALPHA_BLANK) {
1587 // No alpha output, so we don't care.
1590 if (output->output_alpha_type == ALPHA_PREMULTIPLIED &&
1591 output_alpha_format == OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED) {
1592 Node *conversion = add_node(new AlphaDivisionEffect());
1593 connect_nodes(output, conversion);
1595 propagate_gamma_and_color_space();
1597 if (output->output_alpha_type == ALPHA_POSTMULTIPLIED &&
1598 output_alpha_format == OUTPUT_ALPHA_FORMAT_PREMULTIPLIED) {
1599 Node *conversion = add_node(new AlphaMultiplicationEffect());
1600 connect_nodes(output, conversion);
1602 propagate_gamma_and_color_space();
1606 bool EffectChain::node_needs_gamma_fix(Node *node)
1608 if (node->disabled) {
1612 // Small hack since the output is not an explicit node:
1613 // If we are the last node and our output is in the wrong
1614 // space compared to EffectChain's output, we need to fix it.
1615 // This will only take us to linear, but fix_output_gamma()
1616 // will come and take us to the desired output gamma
1619 // This needs to be before everything else, since it could
1620 // even apply to inputs (if they are the only effect).
1621 if (node->outgoing_links.empty() &&
1622 node->output_gamma_curve != output_format.gamma_curve &&
1623 node->output_gamma_curve != GAMMA_LINEAR) {
1627 if (node->effect->num_inputs() == 0) {
1631 // propagate_gamma_and_color_space() has already set our output
1632 // to GAMMA_INVALID if the inputs differ, so we can rely on that,
1633 // except for GammaCompressionEffect.
1634 if (node->output_gamma_curve == GAMMA_INVALID) {
1637 if (node->effect->effect_type_id() == "GammaCompressionEffect") {
1638 assert(node->incoming_links.size() == 1);
1639 return node->incoming_links[0]->output_gamma_curve != GAMMA_LINEAR;
1642 return (node->effect->needs_linear_light() && node->output_gamma_curve != GAMMA_LINEAR);
1645 // Very similar to fix_internal_color_spaces(), but for gamma.
1646 // There is one difference, though; before we start adding conversion nodes,
1647 // we see if we can get anything out of asking the sources to deliver
1648 // linear gamma directly. fix_internal_gamma_by_asking_inputs()
1649 // does that part, while fix_internal_gamma_by_inserting_nodes()
1650 // inserts nodes as needed afterwards.
1651 void EffectChain::fix_internal_gamma_by_asking_inputs(unsigned step)
1653 unsigned gamma_propagation_pass = 0;
1657 for (unsigned i = 0; i < nodes.size(); ++i) {
1658 Node *node = nodes[i];
1659 if (!node_needs_gamma_fix(node)) {
1663 // See if all inputs can give us linear gamma. If not, leave it.
1664 vector<Node *> nonlinear_inputs;
1665 find_all_nonlinear_inputs(node, &nonlinear_inputs);
1666 assert(!nonlinear_inputs.empty());
1669 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1670 Input *input = static_cast<Input *>(nonlinear_inputs[i]->effect);
1671 all_ok &= input->can_output_linear_gamma();
1678 for (unsigned i = 0; i < nonlinear_inputs.size(); ++i) {
1679 CHECK(nonlinear_inputs[i]->effect->set_int("output_linear_gamma", 1));
1680 nonlinear_inputs[i]->output_gamma_curve = GAMMA_LINEAR;
1683 // Re-sort topologically, and propagate the new information.
1684 propagate_gamma_and_color_space();
1691 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1692 output_dot(filename);
1693 assert(gamma_propagation_pass < 100);
1694 } while (found_any);
1697 void EffectChain::fix_internal_gamma_by_inserting_nodes(unsigned step)
1699 unsigned gamma_propagation_pass = 0;
1703 for (unsigned i = 0; i < nodes.size(); ++i) {
1704 Node *node = nodes[i];
1705 if (!node_needs_gamma_fix(node)) {
1709 // Special case: We could be an input and still be asked to
1710 // fix our gamma; if so, we should be the only node
1711 // (as node_needs_gamma_fix() would only return true in
1712 // for an input in that case). That means we should insert
1713 // a conversion node _after_ ourselves.
1714 if (node->incoming_links.empty()) {
1715 assert(node->outgoing_links.empty());
1716 Node *conversion = add_node(new GammaExpansionEffect());
1717 CHECK(conversion->effect->set_int("source_curve", node->output_gamma_curve));
1718 conversion->output_gamma_curve = GAMMA_LINEAR;
1719 connect_nodes(node, conversion);
1722 // If not, go through each input that is not linear gamma,
1723 // and insert a gamma conversion after it.
1724 for (unsigned j = 0; j < node->incoming_links.size(); ++j) {
1725 Node *input = node->incoming_links[j];
1726 assert(input->output_gamma_curve != GAMMA_INVALID);
1727 if (input->output_gamma_curve == GAMMA_LINEAR) {
1730 Node *conversion = add_node(new GammaExpansionEffect());
1731 CHECK(conversion->effect->set_int("source_curve", input->output_gamma_curve));
1732 conversion->output_gamma_curve = GAMMA_LINEAR;
1733 replace_sender(input, conversion);
1734 connect_nodes(input, conversion);
1737 // Re-sort topologically, and propagate the new information.
1739 propagate_gamma_and_color_space();
1746 sprintf(filename, "step%u-gammafix-iter%u.dot", step, ++gamma_propagation_pass);
1747 output_dot(filename);
1748 assert(gamma_propagation_pass < 100);
1749 } while (found_any);
1751 for (unsigned i = 0; i < nodes.size(); ++i) {
1752 Node *node = nodes[i];
1753 if (node->disabled) {
1756 assert(node->output_gamma_curve != GAMMA_INVALID);
1760 // Make so that the output is in the desired gamma.
1761 // Note that this assumes linear input gamma, so it might create the need
1762 // for another pass of fix_internal_gamma().
1763 void EffectChain::fix_output_gamma()
1765 Node *output = find_output_node();
1766 if (output->output_gamma_curve != output_format.gamma_curve) {
1767 Node *conversion = add_node(new GammaCompressionEffect());
1768 CHECK(conversion->effect->set_int("destination_curve", output_format.gamma_curve));
1769 conversion->output_gamma_curve = output_format.gamma_curve;
1770 connect_nodes(output, conversion);
1774 // If the user has requested Y'CbCr output, we need to do this conversion
1775 // _after_ GammaCompressionEffect etc., but before dither (see below).
1776 // This is because Y'CbCr, with the exception of a special optional mode
1777 // in Rec. 2020 (which we currently don't support), is defined to work on
1778 // gamma-encoded data.
1779 void EffectChain::add_ycbcr_conversion_if_needed()
1781 assert(output_color_rgba || num_output_color_ycbcr > 0);
1782 if (num_output_color_ycbcr == 0) {
1785 Node *output = find_output_node();
1786 ycbcr_conversion_effect_node = add_node(new YCbCrConversionEffect(output_ycbcr_format, output_ycbcr_type));
1787 connect_nodes(output, ycbcr_conversion_effect_node);
1790 // If the user has requested dither, add a DitherEffect right at the end
1791 // (after GammaCompressionEffect etc.). This needs to be done after everything else,
1792 // since dither is about the only effect that can _not_ be done in linear space.
1793 void EffectChain::add_dither_if_needed()
1795 if (num_dither_bits == 0) {
1798 Node *output = find_output_node();
1799 Node *dither = add_node(new DitherEffect());
1800 CHECK(dither->effect->set_int("num_bits", num_dither_bits));
1801 connect_nodes(output, dither);
1803 dither_effect = dither->effect;
1808 // Whether this effect will cause the phase it is in to become a compute shader phase.
1809 bool induces_compute_shader(Node *node)
1811 if (node->effect->is_compute_shader()) {
1814 if (!node->effect->strong_one_to_one_sampling()) {
1815 // This effect can't be chained after a compute shader.
1818 // If at least one of the effects we depend on is a compute shader,
1819 // one of them will be put in the same phase as us (the other ones,
1820 // if any, will be bounced).
1821 for (Node *dep : node->incoming_links) {
1822 if (induces_compute_shader(dep)) {
1831 // Compute shaders can't output to the framebuffer, so if the last
1832 // phase ends in a compute shader, add a dummy phase at the end that
1833 // only blits directly from the temporary texture.
1834 void EffectChain::add_dummy_effect_if_needed()
1836 Node *output = find_output_node();
1837 if (induces_compute_shader(output)) {
1838 Node *dummy = add_node(new ComputeShaderOutputDisplayEffect());
1839 connect_nodes(output, dummy);
1840 has_dummy_effect = true;
1844 // Find the output node. This is, simply, one that has no outgoing links.
1845 // If there are multiple ones, the graph is malformed (we do not support
1846 // multiple outputs right now).
1847 Node *EffectChain::find_output_node()
1849 vector<Node *> output_nodes;
1850 for (unsigned i = 0; i < nodes.size(); ++i) {
1851 Node *node = nodes[i];
1852 if (node->disabled) {
1855 if (node->outgoing_links.empty()) {
1856 output_nodes.push_back(node);
1859 assert(output_nodes.size() == 1);
1860 return output_nodes[0];
1863 void EffectChain::finalize()
1865 // Output the graph as it is before we do any conversions on it.
1866 output_dot("step0-start.dot");
1868 // Give each effect in turn a chance to rewrite its own part of the graph.
1869 // Note that if more effects are added as part of this, they will be
1870 // picked up as part of the same for loop, since they are added at the end.
1871 for (unsigned i = 0; i < nodes.size(); ++i) {
1872 nodes[i]->effect->rewrite_graph(this, nodes[i]);
1874 output_dot("step1-rewritten.dot");
1876 find_color_spaces_for_inputs();
1877 output_dot("step2-input-colorspace.dot");
1880 output_dot("step3-propagated-alpha.dot");
1882 propagate_gamma_and_color_space();
1883 output_dot("step4-propagated-all.dot");
1885 fix_internal_color_spaces();
1886 fix_internal_alpha(6);
1887 fix_output_color_space();
1888 output_dot("step7-output-colorspacefix.dot");
1890 output_dot("step8-output-alphafix.dot");
1892 // Note that we need to fix gamma after colorspace conversion,
1893 // because colorspace conversions might create needs for gamma conversions.
1894 // Also, we need to run an extra pass of fix_internal_gamma() after
1895 // fixing the output gamma, as we only have conversions to/from linear,
1896 // and fix_internal_alpha() since GammaCompressionEffect needs
1897 // postmultiplied input.
1898 fix_internal_gamma_by_asking_inputs(9);
1899 fix_internal_gamma_by_inserting_nodes(10);
1901 output_dot("step11-output-gammafix.dot");
1903 output_dot("step12-output-alpha-propagated.dot");
1904 fix_internal_alpha(13);
1905 output_dot("step14-output-alpha-fixed.dot");
1906 fix_internal_gamma_by_asking_inputs(15);
1907 fix_internal_gamma_by_inserting_nodes(16);
1909 output_dot("step17-before-ycbcr.dot");
1910 add_ycbcr_conversion_if_needed();
1912 output_dot("step18-before-dither.dot");
1913 add_dither_if_needed();
1915 output_dot("step19-before-dummy-effect.dot");
1916 add_dummy_effect_if_needed();
1918 output_dot("step20-final.dot");
1920 // Construct all needed GLSL programs, starting at the output.
1921 // We need to keep track of which effects have already been computed,
1922 // as an effect with multiple users could otherwise be calculated
1924 map<Node *, Phase *> completed_effects;
1925 construct_phase(find_output_node(), &completed_effects);
1927 output_dot("step21-split-to-phases.dot");
1929 // There are some corner cases where we thought we needed to add a dummy
1930 // effect, but then it turned out later we didn't (e.g. induces_compute_shader()
1931 // didn't see a mipmap conflict coming, which would cause the compute shader
1932 // to be split off from the inal phase); if so, remove the extra phase
1933 // at the end, since it will give us some trouble during execution.
1935 // TODO: Remove induces_compute_shader() and replace it with precise tracking.
1936 if (has_dummy_effect && !phases[phases.size() - 2]->is_compute_shader) {
1937 resource_pool->release_glsl_program(phases.back()->glsl_program_num);
1938 delete phases.back();
1940 has_dummy_effect = false;
1943 output_dot("step22-dummy-phase-removal.dot");
1945 assert(phases[0]->inputs.empty());
1950 void EffectChain::render_to_fbo(GLuint dest_fbo, unsigned width, unsigned height)
1952 // Save original viewport.
1953 GLuint x = 0, y = 0;
1955 if (width == 0 && height == 0) {
1957 glGetIntegerv(GL_VIEWPORT, viewport);
1960 width = viewport[2];
1961 height = viewport[3];
1964 render(dest_fbo, {}, x, y, width, height);
1967 void EffectChain::render_to_texture(const vector<DestinationTexture> &destinations, unsigned width, unsigned height)
1970 assert(!destinations.empty());
1972 if (!has_dummy_effect) {
1973 // We don't end in a compute shader, so there's nothing specific for us to do.
1974 // Create an FBO for this set of textures, and just render to that.
1975 GLuint texnums[4] = { 0, 0, 0, 0 };
1976 for (unsigned i = 0; i < destinations.size() && i < 4; ++i) {
1977 texnums[i] = destinations[i].texnum;
1979 GLuint dest_fbo = resource_pool->create_fbo(texnums[0], texnums[1], texnums[2], texnums[3]);
1980 render(dest_fbo, {}, 0, 0, width, height);
1981 resource_pool->release_fbo(dest_fbo);
1983 render((GLuint)-1, destinations, 0, 0, width, height);
1987 void EffectChain::render(GLuint dest_fbo, const vector<DestinationTexture> &destinations, unsigned x, unsigned y, unsigned width, unsigned height)
1990 assert(destinations.size() <= 1);
1992 // This needs to be set anew, in case we are coming from a different context
1993 // from when we initialized.
1995 glDisable(GL_DITHER);
1998 const bool final_srgb = glIsEnabled(GL_FRAMEBUFFER_SRGB);
2000 bool current_srgb = final_srgb;
2004 glDisable(GL_BLEND);
2006 glDisable(GL_DEPTH_TEST);
2008 glDepthMask(GL_FALSE);
2011 set<Phase *> generated_mipmaps;
2013 // We keep one texture per output, but only for as long as we actually have any
2014 // phases that need it as an input. (We don't make any effort to reorder phases
2015 // to minimize the number of textures in play, as register allocation can be
2016 // complicated and we rarely have much to gain, since our graphs are typically
2018 map<Phase *, GLuint> output_textures;
2019 map<Phase *, int> ref_counts;
2020 for (Phase *phase : phases) {
2021 for (Phase *input : phase->inputs) {
2022 ++ref_counts[input];
2026 size_t num_phases = phases.size();
2027 if (destinations.empty()) {
2028 assert(dest_fbo != (GLuint)-1);
2030 assert(has_dummy_effect);
2033 assert(num_phases >= 2);
2034 assert(!phases.back()->is_compute_shader);
2035 assert(phases[phases.size() - 2]->is_compute_shader);
2036 assert(phases.back()->effects.size() == 1);
2037 assert(phases.back()->effects[0]->effect->effect_type_id() == "ComputeShaderOutputDisplayEffect");
2039 // We are rendering to a set of textures, so we can run the compute shader
2040 // directly and skip the dummy phase.
2044 for (unsigned phase_num = 0; phase_num < num_phases; ++phase_num) {
2045 Phase *phase = phases[phase_num];
2047 if (do_phase_timing) {
2048 GLuint timer_query_object;
2049 if (phase->timer_query_objects_free.empty()) {
2050 glGenQueries(1, &timer_query_object);
2052 timer_query_object = phase->timer_query_objects_free.front();
2053 phase->timer_query_objects_free.pop_front();
2055 glBeginQuery(GL_TIME_ELAPSED, timer_query_object);
2056 phase->timer_query_objects_running.push_back(timer_query_object);
2058 bool last_phase = (phase_num == num_phases - 1);
2060 // Last phase goes to the output the user specified.
2061 if (!phase->is_compute_shader) {
2062 assert(dest_fbo != (GLuint)-1);
2063 glBindFramebuffer(GL_FRAMEBUFFER, dest_fbo);
2065 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
2066 assert(status == GL_FRAMEBUFFER_COMPLETE);
2067 glViewport(x, y, width, height);
2069 if (dither_effect != nullptr) {
2070 CHECK(dither_effect->set_int("output_width", width));
2071 CHECK(dither_effect->set_int("output_height", height));
2075 // Enable sRGB rendering for intermediates in case we are
2076 // rendering to an sRGB format.
2077 // TODO: Support this for compute shaders.
2078 bool needs_srgb = last_phase ? final_srgb : true;
2079 if (needs_srgb && !current_srgb) {
2080 glEnable(GL_FRAMEBUFFER_SRGB);
2082 current_srgb = true;
2083 } else if (!needs_srgb && current_srgb) {
2084 glDisable(GL_FRAMEBUFFER_SRGB);
2086 current_srgb = true;
2089 // Find a texture for this phase.
2090 inform_input_sizes(phase);
2091 find_output_size(phase);
2092 vector<DestinationTexture> phase_destinations;
2094 GLuint tex_num = resource_pool->create_2d_texture(intermediate_format, phase->output_width, phase->output_height);
2095 output_textures.insert(make_pair(phase, tex_num));
2096 phase_destinations.push_back(DestinationTexture{ tex_num, intermediate_format });
2098 // The output texture needs to have valid state to be written to by a compute shader.
2099 glActiveTexture(GL_TEXTURE0);
2101 glBindTexture(GL_TEXTURE_2D, tex_num);
2103 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2105 } else if (phase->is_compute_shader) {
2106 assert(!destinations.empty());
2107 phase_destinations = destinations;
2110 execute_phase(phase, output_textures, phase_destinations, &generated_mipmaps);
2111 if (do_phase_timing) {
2112 glEndQuery(GL_TIME_ELAPSED);
2115 // Drop any input textures we don't need anymore.
2116 for (Phase *input : phase->inputs) {
2117 assert(ref_counts[input] > 0);
2118 if (--ref_counts[input] == 0) {
2119 resource_pool->release_2d_texture(output_textures[input]);
2120 output_textures.erase(input);
2125 for (const auto &phase_and_texnum : output_textures) {
2126 resource_pool->release_2d_texture(phase_and_texnum.second);
2129 glBindFramebuffer(GL_FRAMEBUFFER, 0);
2134 glBindBuffer(GL_ARRAY_BUFFER, 0);
2136 glBindVertexArray(0);
2139 if (do_phase_timing) {
2140 // Get back the timer queries.
2141 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
2142 Phase *phase = phases[phase_num];
2143 for (auto timer_it = phase->timer_query_objects_running.cbegin();
2144 timer_it != phase->timer_query_objects_running.cend(); ) {
2145 GLint timer_query_object = *timer_it;
2147 glGetQueryObjectiv(timer_query_object, GL_QUERY_RESULT_AVAILABLE, &available);
2149 GLuint64 time_elapsed;
2150 glGetQueryObjectui64v(timer_query_object, GL_QUERY_RESULT, &time_elapsed);
2151 phase->time_elapsed_ns += time_elapsed;
2152 ++phase->num_measured_iterations;
2153 phase->timer_query_objects_free.push_back(timer_query_object);
2154 phase->timer_query_objects_running.erase(timer_it++);
2163 void EffectChain::enable_phase_timing(bool enable)
2166 assert(movit_timer_queries_supported);
2168 this->do_phase_timing = enable;
2171 void EffectChain::reset_phase_timing()
2173 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
2174 Phase *phase = phases[phase_num];
2175 phase->time_elapsed_ns = 0;
2176 phase->num_measured_iterations = 0;
2180 void EffectChain::print_phase_timing()
2182 double total_time_ms = 0.0;
2183 for (unsigned phase_num = 0; phase_num < phases.size(); ++phase_num) {
2184 Phase *phase = phases[phase_num];
2185 double avg_time_ms = phase->time_elapsed_ns * 1e-6 / phase->num_measured_iterations;
2186 printf("Phase %d: %5.1f ms [", phase_num, avg_time_ms);
2187 for (unsigned effect_num = 0; effect_num < phase->effects.size(); ++effect_num) {
2188 if (effect_num != 0) {
2191 printf("%s", phase->effects[effect_num]->effect->effect_type_id().c_str());
2194 total_time_ms += avg_time_ms;
2196 printf("Total: %5.1f ms\n", total_time_ms);
2199 void EffectChain::execute_phase(Phase *phase,
2200 const map<Phase *, GLuint> &output_textures,
2201 const vector<DestinationTexture> &destinations,
2202 set<Phase *> *generated_mipmaps)
2204 // Set up RTT inputs for this phase.
2205 for (unsigned sampler = 0; sampler < phase->inputs.size(); ++sampler) {
2206 glActiveTexture(GL_TEXTURE0 + sampler);
2207 Phase *input = phase->inputs[sampler];
2208 input->output_node->bound_sampler_num = sampler;
2209 const auto it = output_textures.find(input);
2210 assert(it != output_textures.end());
2211 glBindTexture(GL_TEXTURE_2D, it->second);
2214 // See if anything using this RTT input (in this phase) needs mipmaps.
2215 // TODO: It could be that we get conflicting logic here, if we have
2216 // multiple effects with incompatible mipmaps using the same
2217 // RTT input. However, that is obscure enough that we can deal
2218 // with it at some future point (preferably when we have
2219 // universal support for separate sampler objects!). For now,
2220 // an assert is good enough. See also the TODO at bound_sampler_num.
2221 bool any_needs_mipmaps = false, any_refuses_mipmaps = false;
2222 for (Node *node : phase->effects) {
2223 assert(node->incoming_links.size() == node->incoming_link_type.size());
2224 for (size_t i = 0; i < node->incoming_links.size(); ++i) {
2225 if (node->incoming_links[i] == input->output_node &&
2226 node->incoming_link_type[i] == IN_ANOTHER_PHASE) {
2227 if (node->needs_mipmaps == Effect::NEEDS_MIPMAPS) {
2228 any_needs_mipmaps = true;
2229 } else if (node->needs_mipmaps == Effect::CANNOT_ACCEPT_MIPMAPS) {
2230 any_refuses_mipmaps = true;
2235 assert(!(any_needs_mipmaps && any_refuses_mipmaps));
2237 if (any_needs_mipmaps && generated_mipmaps->count(input) == 0) {
2238 glGenerateMipmap(GL_TEXTURE_2D);
2240 generated_mipmaps->insert(input);
2242 setup_rtt_sampler(sampler, any_needs_mipmaps);
2243 phase->input_samplers[sampler] = sampler; // Bind the sampler to the right uniform.
2246 GLuint instance_program_num = resource_pool->use_glsl_program(phase->glsl_program_num);
2249 // And now the output.
2251 if (phase->is_compute_shader) {
2252 assert(!destinations.empty());
2254 // This is currently the only place where we use image units,
2255 // so we can always start at 0. TODO: Support multiple destinations.
2256 phase->outbuf_image_unit = 0;
2257 glBindImageTexture(phase->outbuf_image_unit, destinations[0].texnum, 0, GL_FALSE, 0, GL_WRITE_ONLY, destinations[0].format);
2259 phase->uniform_output_size[0] = phase->output_width;
2260 phase->uniform_output_size[1] = phase->output_height;
2261 phase->inv_output_size.x = 1.0f / phase->output_width;
2262 phase->inv_output_size.y = 1.0f / phase->output_height;
2263 phase->output_texcoord_adjust.x = 0.5f / phase->output_width;
2264 phase->output_texcoord_adjust.y = 0.5f / phase->output_height;
2265 } else if (!destinations.empty()) {
2266 assert(destinations.size() == 1);
2267 fbo = resource_pool->create_fbo(destinations[0].texnum);
2268 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
2269 glViewport(0, 0, phase->output_width, phase->output_height);
2272 // Give the required parameters to all the effects.
2273 unsigned sampler_num = phase->inputs.size();
2274 for (unsigned i = 0; i < phase->effects.size(); ++i) {
2275 Node *node = phase->effects[i];
2276 unsigned old_sampler_num = sampler_num;
2277 node->effect->set_gl_state(instance_program_num, phase->effect_ids[make_pair(node, IN_SAME_PHASE)], &sampler_num);
2280 if (node->effect->is_single_texture()) {
2281 assert(sampler_num - old_sampler_num == 1);
2282 node->bound_sampler_num = old_sampler_num;
2284 node->bound_sampler_num = -1;
2288 if (phase->is_compute_shader) {
2290 phase->compute_shader_node->effect->get_compute_dimensions(phase->output_width, phase->output_height, &x, &y, &z);
2292 // Uniforms need to come after set_gl_state() _and_ get_compute_dimensions(),
2293 // since they can be updated from there.
2294 setup_uniforms(phase);
2295 glDispatchCompute(x, y, z);
2297 glMemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT | GL_TEXTURE_UPDATE_BARRIER_BIT);
2300 // Uniforms need to come after set_gl_state(), since they can be updated
2302 setup_uniforms(phase);
2304 // Bind the vertex data.
2305 GLuint vao = resource_pool->create_vec2_vao(phase->attribute_indexes, vbo);
2306 glBindVertexArray(vao);
2308 glDrawArrays(GL_TRIANGLES, 0, 3);
2311 resource_pool->release_vec2_vao(vao);
2314 for (unsigned i = 0; i < phase->effects.size(); ++i) {
2315 Node *node = phase->effects[i];
2316 node->effect->clear_gl_state();
2319 resource_pool->unuse_glsl_program(instance_program_num);
2322 resource_pool->release_fbo(fbo);
2326 void EffectChain::setup_uniforms(Phase *phase)
2328 // TODO: Use UBO blocks.
2329 for (size_t i = 0; i < phase->uniforms_image2d.size(); ++i) {
2330 const Uniform<int> &uniform = phase->uniforms_image2d[i];
2331 if (uniform.location != -1) {
2332 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2335 for (size_t i = 0; i < phase->uniforms_sampler2d.size(); ++i) {
2336 const Uniform<int> &uniform = phase->uniforms_sampler2d[i];
2337 if (uniform.location != -1) {
2338 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2341 for (size_t i = 0; i < phase->uniforms_bool.size(); ++i) {
2342 const Uniform<bool> &uniform = phase->uniforms_bool[i];
2343 assert(uniform.num_values == 1);
2344 if (uniform.location != -1) {
2345 glUniform1i(uniform.location, *uniform.value);
2348 for (size_t i = 0; i < phase->uniforms_int.size(); ++i) {
2349 const Uniform<int> &uniform = phase->uniforms_int[i];
2350 if (uniform.location != -1) {
2351 glUniform1iv(uniform.location, uniform.num_values, uniform.value);
2354 for (size_t i = 0; i < phase->uniforms_ivec2.size(); ++i) {
2355 const Uniform<int> &uniform = phase->uniforms_ivec2[i];
2356 if (uniform.location != -1) {
2357 glUniform2iv(uniform.location, uniform.num_values, uniform.value);
2360 for (size_t i = 0; i < phase->uniforms_float.size(); ++i) {
2361 const Uniform<float> &uniform = phase->uniforms_float[i];
2362 if (uniform.location != -1) {
2363 glUniform1fv(uniform.location, uniform.num_values, uniform.value);
2366 for (size_t i = 0; i < phase->uniforms_vec2.size(); ++i) {
2367 const Uniform<float> &uniform = phase->uniforms_vec2[i];
2368 if (uniform.location != -1) {
2369 glUniform2fv(uniform.location, uniform.num_values, uniform.value);
2372 for (size_t i = 0; i < phase->uniforms_vec3.size(); ++i) {
2373 const Uniform<float> &uniform = phase->uniforms_vec3[i];
2374 if (uniform.location != -1) {
2375 glUniform3fv(uniform.location, uniform.num_values, uniform.value);
2378 for (size_t i = 0; i < phase->uniforms_vec4.size(); ++i) {
2379 const Uniform<float> &uniform = phase->uniforms_vec4[i];
2380 if (uniform.location != -1) {
2381 glUniform4fv(uniform.location, uniform.num_values, uniform.value);
2384 for (size_t i = 0; i < phase->uniforms_mat3.size(); ++i) {
2385 const Uniform<Matrix3d> &uniform = phase->uniforms_mat3[i];
2386 assert(uniform.num_values == 1);
2387 if (uniform.location != -1) {
2388 // Convert to float (GLSL has no double matrices).
2390 for (unsigned y = 0; y < 3; ++y) {
2391 for (unsigned x = 0; x < 3; ++x) {
2392 matrixf[y + x * 3] = (*uniform.value)(y, x);
2395 glUniformMatrix3fv(uniform.location, 1, GL_FALSE, matrixf);
2400 void EffectChain::setup_rtt_sampler(int sampler_num, bool use_mipmaps)
2402 glActiveTexture(GL_TEXTURE0 + sampler_num);
2405 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
2408 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
2411 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2413 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2417 } // namespace movit