1 #define GL_GLEXT_PROTOTYPES 1
16 #include "effect_chain.h"
17 #include "gamma_expansion_effect.h"
18 #include "gamma_compression_effect.h"
19 #include "colorspace_conversion_effect.h"
22 EffectChain::EffectChain(unsigned width, unsigned height)
27 Input *EffectChain::add_input(const ImageFormat &format)
30 sprintf(eff_id, "src_image%u", (unsigned)inputs.size());
32 Input *input = new Input(format, width, height);
33 effects.push_back(input);
34 inputs.push_back(input);
35 output_color_space.insert(std::make_pair(input, format.color_space));
36 output_gamma_curve.insert(std::make_pair(input, format.gamma_curve));
37 effect_ids.insert(std::make_pair(input, eff_id));
38 incoming_links.insert(std::make_pair(input, std::vector<Effect *>()));
42 void EffectChain::add_output(const ImageFormat &format)
44 output_format = format;
47 void EffectChain::add_effect_raw(Effect *effect, const std::vector<Effect *> &inputs)
50 sprintf(effect_id, "eff%u", (unsigned)effects.size());
52 effects.push_back(effect);
53 effect_ids.insert(std::make_pair(effect, effect_id));
54 assert(inputs.size() == effect->num_inputs());
55 for (unsigned i = 0; i < inputs.size(); ++i) {
56 assert(std::find(effects.begin(), effects.end(), inputs[i]) != effects.end());
57 outgoing_links[inputs[i]].push_back(effect);
59 incoming_links.insert(std::make_pair(effect, inputs));
60 output_gamma_curve[effect] = output_gamma_curve[last_added_effect()];
61 output_color_space[effect] = output_color_space[last_added_effect()];
64 // Set the "use_srgb_texture_format" option on all inputs that feed into this node,
65 // and update the output_gamma_curve[] map as we go.
67 // NOTE: We assume that the only way we could actually get GAMMA_sRGB from an
68 // effect (except from GammaCompressionCurve, which should never be inserted
69 // into a chain when this is called) is by pass-through from a texture.
70 // Thus, we can simply feed the flag up towards all inputs.
71 void EffectChain::set_use_srgb_texture_format(Effect *effect)
73 assert(output_gamma_curve.count(effect) != 0);
74 assert(output_gamma_curve[effect] == GAMMA_sRGB);
75 if (effect->num_inputs() == 0) {
76 effect->set_int("use_srgb_texture_format", 1);
78 assert(incoming_links.count(effect) == 1);
79 std::vector<Effect *> deps = incoming_links[effect];
80 assert(effect->num_inputs() == deps.size());
81 for (unsigned i = 0; i < deps.size(); ++i) {
82 set_use_srgb_texture_format(deps[i]);
83 assert(output_gamma_curve[deps[i]] == GAMMA_LINEAR);
86 output_gamma_curve[effect] = GAMMA_LINEAR;
89 Effect *EffectChain::normalize_to_linear_gamma(Effect *input)
91 assert(output_gamma_curve.count(input) != 0);
92 if (output_gamma_curve[input] == GAMMA_sRGB) {
93 // TODO: check if the extension exists
94 set_use_srgb_texture_format(input);
95 output_gamma_curve[input] = GAMMA_LINEAR;
98 GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
99 gamma_conversion->set_int("source_curve", output_gamma_curve[input]);
100 std::vector<Effect *> inputs;
101 inputs.push_back(input);
102 gamma_conversion->add_self_to_effect_chain(this, inputs);
103 output_gamma_curve[gamma_conversion] = GAMMA_LINEAR;
104 return gamma_conversion;
108 Effect *EffectChain::normalize_to_srgb(Effect *input)
110 assert(output_gamma_curve.count(input) != 0);
111 assert(output_color_space.count(input) != 0);
112 assert(output_gamma_curve[input] == GAMMA_LINEAR);
113 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
114 colorspace_conversion->set_int("source_space", output_color_space[input]);
115 colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
116 std::vector<Effect *> inputs;
117 inputs.push_back(input);
118 colorspace_conversion->add_self_to_effect_chain(this, inputs);
119 output_color_space[colorspace_conversion] = COLORSPACE_sRGB;
120 return colorspace_conversion;
123 Effect *EffectChain::add_effect(Effect *effect, const std::vector<Effect *> &inputs)
125 assert(inputs.size() == effect->num_inputs());
127 std::vector<Effect *> normalized_inputs = inputs;
128 for (unsigned i = 0; i < normalized_inputs.size(); ++i) {
129 assert(output_gamma_curve.count(normalized_inputs[i]) != 0);
130 if (effect->needs_linear_light() && output_gamma_curve[normalized_inputs[i]] != GAMMA_LINEAR) {
131 normalized_inputs[i] = normalize_to_linear_gamma(normalized_inputs[i]);
133 assert(output_color_space.count(normalized_inputs[i]) != 0);
134 if (effect->needs_srgb_primaries() && output_color_space[normalized_inputs[i]] != COLORSPACE_sRGB) {
135 normalized_inputs[i] = normalize_to_srgb(normalized_inputs[i]);
139 effect->add_self_to_effect_chain(this, normalized_inputs);
143 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
144 std::string replace_prefix(const std::string &text, const std::string &prefix)
149 while (start < text.size()) {
150 size_t pos = text.find("PREFIX(", start);
151 if (pos == std::string::npos) {
152 output.append(text.substr(start, std::string::npos));
156 output.append(text.substr(start, pos - start));
157 output.append(prefix);
160 pos += strlen("PREFIX(");
162 // Output stuff until we find the matching ), which we then eat.
164 size_t end_arg_pos = pos;
165 while (end_arg_pos < text.size()) {
166 if (text[end_arg_pos] == '(') {
168 } else if (text[end_arg_pos] == ')') {
176 output.append(text.substr(pos, end_arg_pos - pos));
184 EffectChain::Phase EffectChain::compile_glsl_program(const std::vector<Effect *> &inputs, const std::vector<Effect *> &effects)
186 assert(!effects.empty());
188 // Deduplicate the inputs.
189 std::vector<Effect *> true_inputs = inputs;
190 std::sort(true_inputs.begin(), true_inputs.end());
191 true_inputs.erase(std::unique(true_inputs.begin(), true_inputs.end()), true_inputs.end());
193 bool input_needs_mipmaps = false;
194 std::string frag_shader = read_file("header.frag");
196 // Create functions for all the texture inputs that we need.
197 for (unsigned i = 0; i < true_inputs.size(); ++i) {
198 Effect *effect = true_inputs[i];
199 assert(effect_ids.count(effect) != 0);
200 std::string effect_id = effect_ids[effect];
202 frag_shader += std::string("uniform sampler2D tex_") + effect_id + ";\n";
203 frag_shader += std::string("vec4 ") + effect_id + "(vec2 tc) {\n";
204 if (effect->num_inputs() == 0) {
205 // OpenGL's origin is bottom-left, but most graphics software assumes
206 // a top-left origin. Thus, for inputs that come from the user,
207 // we flip the y coordinate. However, for FBOs, the origin
208 // is all correct, so don't do anything.
209 frag_shader += "\ttc.y = 1.0f - tc.y;\n";
211 frag_shader += "\treturn texture2D(tex_" + effect_id + ", tc);\n";
212 frag_shader += "}\n";
216 std::string last_effect_id;
217 for (unsigned i = 0; i < effects.size(); ++i) {
218 Effect *effect = effects[i];
219 assert(effect != NULL);
220 assert(effect_ids.count(effect) != 0);
221 std::string effect_id = effect_ids[effect];
222 last_effect_id = effect_id;
224 if (incoming_links[effect].size() == 1) {
225 frag_shader += std::string("#define INPUT ") + effect_ids[incoming_links[effect][0]] + "\n";
227 for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
229 sprintf(buf, "#define INPUT%d %s\n", j + 1, effect_ids[incoming_links[effect][j]].c_str());
235 frag_shader += std::string("#define FUNCNAME ") + effect_id + "\n";
236 frag_shader += replace_prefix(effect->output_convenience_uniforms(), effect_id);
237 frag_shader += replace_prefix(effect->output_fragment_shader(), effect_id);
238 frag_shader += "#undef PREFIX\n";
239 frag_shader += "#undef FUNCNAME\n";
240 if (incoming_links[effect].size() == 1) {
241 frag_shader += "#undef INPUT\n";
243 for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
245 sprintf(buf, "#undef INPUT%d\n", j + 1);
251 input_needs_mipmaps |= effect->needs_mipmaps();
253 for (unsigned i = 0; i < effects.size(); ++i) {
254 Effect *effect = effects[i];
255 if (effect->num_inputs() == 0) {
256 effect->set_int("needs_mipmaps", input_needs_mipmaps);
259 assert(!last_effect_id.empty());
260 frag_shader += std::string("#define INPUT ") + last_effect_id + "\n";
261 frag_shader.append(read_file("footer.frag"));
262 printf("%s\n", frag_shader.c_str());
264 GLuint glsl_program_num = glCreateProgram();
265 GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
266 GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
267 glAttachShader(glsl_program_num, vs_obj);
269 glAttachShader(glsl_program_num, fs_obj);
271 glLinkProgram(glsl_program_num);
275 phase.glsl_program_num = glsl_program_num;
276 phase.input_needs_mipmaps = input_needs_mipmaps;
277 phase.inputs = true_inputs;
278 phase.effects = effects;
283 // Construct GLSL programs, starting at the given effect and following
284 // the chain from there. We end a program every time we come to an effect
285 // marked as "needs texture bounce", one that is used by multiple other
286 // effects, and of course at the end.
288 // We follow a quite simple depth-first search from the output, although
289 // without any explicit recursion.
290 void EffectChain::construct_glsl_programs(Effect *output)
292 // Which effects have already been completed in this phase?
293 // We need to keep track of it, as an effect with multiple outputs
294 // could otherwise be calculate multiple times.
295 std::set<Effect *> completed_effects;
297 // Effects in the current phase, as well as inputs (outputs from other phases
298 // that we depend on). Note that since we start iterating from the end,
299 // the effect list will be in the reverse order.
300 std::vector<Effect *> this_phase_inputs;
301 std::vector<Effect *> this_phase_effects;
303 // Effects that we have yet to calculate, but that we know should
304 // be in the current phase.
305 std::stack<Effect *> effects_todo_this_phase;
307 // Effects that we have yet to calculate, but that come from other phases.
308 // We delay these until we have this phase done in its entirety,
309 // at which point we pick any of them and start a new phase from that.
310 std::stack<Effect *> effects_todo_other_phases;
312 effects_todo_this_phase.push(output);
314 for ( ;; ) { // Termination condition within loop.
315 if (!effects_todo_this_phase.empty()) {
316 // OK, we have more to do this phase.
317 Effect *effect = effects_todo_this_phase.top();
318 effects_todo_this_phase.pop();
320 // This should currently only happen for effects that are phase outputs,
321 // and we throw those out separately below.
322 assert(completed_effects.count(effect) == 0);
324 this_phase_effects.push_back(effect);
325 completed_effects.insert(effect);
327 // Find all the dependencies of this effect, and add them to the stack.
328 assert(incoming_links.count(effect) == 1);
329 std::vector<Effect *> deps = incoming_links[effect];
330 assert(effect->num_inputs() == deps.size());
331 for (unsigned i = 0; i < deps.size(); ++i) {
332 bool start_new_phase = false;
334 if (effect->needs_texture_bounce()) {
335 start_new_phase = true;
338 assert(outgoing_links.count(deps[i]) == 1);
339 if (outgoing_links[deps[i]].size() > 1 && deps[i]->num_inputs() > 0) {
340 // More than one effect uses this as the input,
341 // and it is not a texture itself.
342 // The easiest thing to do (and probably also the safest
343 // performance-wise in most cases) is to bounce it to a texture
344 // and then let the next passes read from that.
345 start_new_phase = true;
348 if (start_new_phase) {
349 effects_todo_other_phases.push(deps[i]);
350 this_phase_inputs.push_back(deps[i]);
352 effects_todo_this_phase.push(deps[i]);
358 // No more effects to do this phase. Take all the ones we have,
359 // and create a GLSL program for it.
360 if (!this_phase_effects.empty()) {
361 reverse(this_phase_effects.begin(), this_phase_effects.end());
362 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
363 this_phase_inputs.clear();
364 this_phase_effects.clear();
366 assert(this_phase_inputs.empty());
367 assert(this_phase_effects.empty());
369 // If we have no effects left, exit.
370 if (effects_todo_other_phases.empty()) {
374 Effect *effect = effects_todo_other_phases.top();
375 effects_todo_other_phases.pop();
377 if (completed_effects.count(effect) == 0) {
378 // Start a new phase, calculating from this effect.
379 effects_todo_this_phase.push(effect);
383 // Finally, since the phases are found from the output but must be executed
384 // from the input(s), reverse them, too.
385 std::reverse(phases.begin(), phases.end());
388 void EffectChain::finalize()
390 // Find the output effect. This is, simply, one that has no outgoing links.
391 // If there are multiple ones, the graph is malformed (we do not support
392 // multiple outputs right now).
393 std::vector<Effect *> output_effects;
394 for (unsigned i = 0; i < effects.size(); ++i) {
395 Effect *effect = effects[i];
396 if (outgoing_links.count(effect) == 0 || outgoing_links[effect].size() == 0) {
397 output_effects.push_back(effect);
400 assert(output_effects.size() == 1);
401 Effect *output_effect = output_effects[0];
403 // Add normalizers to get the output format right.
404 assert(output_gamma_curve.count(output_effect) != 0);
405 assert(output_color_space.count(output_effect) != 0);
406 ColorSpace current_color_space = output_color_space[output_effect];
407 if (current_color_space != output_format.color_space) {
408 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
409 colorspace_conversion->set_int("source_space", current_color_space);
410 colorspace_conversion->set_int("destination_space", output_format.color_space);
411 std::vector<Effect *> inputs;
412 inputs.push_back(output_effect);
413 colorspace_conversion->add_self_to_effect_chain(this, inputs);
414 output_color_space[colorspace_conversion] = output_format.color_space;
415 output_effect = colorspace_conversion;
417 GammaCurve current_gamma_curve = output_gamma_curve[output_effect];
418 if (current_gamma_curve != output_format.gamma_curve) {
419 if (current_gamma_curve != GAMMA_LINEAR) {
420 output_effect = normalize_to_linear_gamma(output_effect);
421 current_gamma_curve = GAMMA_LINEAR;
423 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
424 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
425 std::vector<Effect *> inputs;
426 inputs.push_back(output_effect);
427 gamma_conversion->add_self_to_effect_chain(this, inputs);
428 output_gamma_curve[gamma_conversion] = output_format.gamma_curve;
429 output_effect = gamma_conversion;
432 // Construct all needed GLSL programs, starting at the output.
433 construct_glsl_programs(output_effect);
435 // If we have more than one phase, we need intermediate render-to-texture.
436 // Construct an FBO, and then as many textures as we need.
437 // We choose the simplest option of having one texture per output,
438 // since otherwise this turns into an (albeit simple)
439 // register allocation problem.
440 if (phases.size() > 1) {
441 glGenFramebuffers(1, &fbo);
443 for (unsigned i = 0; i < phases.size() - 1; ++i) {
444 Effect *output_effect = phases[i].effects.back();
446 glGenTextures(1, &temp_texture);
448 glBindTexture(GL_TEXTURE_2D, temp_texture);
450 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
452 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
454 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
456 effect_output_textures.insert(std::make_pair(output_effect, temp_texture));
460 for (unsigned i = 0; i < inputs.size(); ++i) {
461 inputs[i]->finalize();
467 void EffectChain::render_to_screen()
474 glDisable(GL_DEPTH_TEST);
476 glDepthMask(GL_FALSE);
479 glMatrixMode(GL_PROJECTION);
481 glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
483 glMatrixMode(GL_MODELVIEW);
486 if (phases.size() > 1) {
487 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
491 std::set<Effect *> generated_mipmaps;
492 for (unsigned i = 0; i < inputs.size(); ++i) {
493 // Inputs generate their own mipmaps if they need to
495 generated_mipmaps.insert(inputs[i]);
498 for (unsigned phase = 0; phase < phases.size(); ++phase) {
499 glUseProgram(phases[phase].glsl_program_num);
502 // Set up RTT inputs for this phase.
503 for (unsigned sampler = 0; sampler < phases[phase].inputs.size(); ++sampler) {
504 glActiveTexture(GL_TEXTURE0 + sampler);
505 Effect *input = phases[phase].inputs[sampler];
506 assert(effect_output_textures.count(input) != 0);
507 glBindTexture(GL_TEXTURE_2D, effect_output_textures[input]);
509 if (phases[phase].input_needs_mipmaps) {
510 if (generated_mipmaps.count(input) == 0) {
511 glGenerateMipmap(GL_TEXTURE_2D);
513 generated_mipmaps.insert(input);
515 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
518 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
522 assert(effect_ids.count(input));
523 std::string texture_name = std::string("tex_") + effect_ids[input];
524 glUniform1i(glGetUniformLocation(phases[phase].glsl_program_num, texture_name.c_str()), sampler);
528 // And now the output.
529 if (phase == phases.size() - 1) {
530 // Last phase goes directly to the screen.
531 glBindFramebuffer(GL_FRAMEBUFFER, 0);
534 Effect *last_effect = phases[phase].effects.back();
535 assert(effect_output_textures.count(last_effect) != 0);
536 glFramebufferTexture2D(
538 GL_COLOR_ATTACHMENT0,
540 effect_output_textures[last_effect],
545 // Give the required parameters to all the effects.
546 unsigned sampler_num = phases[phase].inputs.size();
547 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
548 Effect *effect = phases[phase].effects[i];
549 effect->set_gl_state(phases[phase].glsl_program_num, effect_ids[effect], &sampler_num);
555 glTexCoord2f(0.0f, 0.0f);
556 glVertex2f(0.0f, 0.0f);
558 glTexCoord2f(1.0f, 0.0f);
559 glVertex2f(1.0f, 0.0f);
561 glTexCoord2f(1.0f, 1.0f);
562 glVertex2f(1.0f, 1.0f);
564 glTexCoord2f(0.0f, 1.0f);
565 glVertex2f(0.0f, 1.0f);
570 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
571 Effect *effect = phases[phase].effects[i];
572 effect->clear_gl_state();