]> git.sesse.net Git - movit/blob - effect_chain.cpp
Add a glow effect, and an effect that linearly mixes two sources (because glow needed...
[movit] / effect_chain.cpp
1 #define GL_GLEXT_PROTOTYPES 1
2
3 #include <stdio.h>
4 #include <string.h>
5 #include <assert.h>
6
7 #include <GL/gl.h>
8 #include <GL/glext.h>
9
10 #include <algorithm>
11 #include <set>
12
13 #include "util.h"
14 #include "effect_chain.h"
15 #include "gamma_expansion_effect.h"
16 #include "gamma_compression_effect.h"
17 #include "lift_gamma_gain_effect.h"
18 #include "colorspace_conversion_effect.h"
19 #include "sandbox_effect.h"
20 #include "saturation_effect.h"
21 #include "mirror_effect.h"
22 #include "vignette_effect.h"
23 #include "blur_effect.h"
24 #include "diffusion_effect.h"
25 #include "glow_effect.h"
26 #include "mix_effect.h"
27 #include "input.h"
28
29 EffectChain::EffectChain(unsigned width, unsigned height)
30         : width(width),
31           height(height),
32           finalized(false) {}
33
34 Input *EffectChain::add_input(const ImageFormat &format)
35 {
36         Input *input = new Input(format, width, height);
37         effects.push_back(input);
38         output_color_space.insert(std::make_pair(input, format.color_space));
39         output_gamma_curve.insert(std::make_pair(input, format.gamma_curve));
40         effect_ids.insert(std::make_pair(input, "src_image"));
41         incoming_links.insert(std::make_pair(input, std::vector<Effect *>()));
42         return input;
43 }
44
45 void EffectChain::add_output(const ImageFormat &format)
46 {
47         output_format = format;
48 }
49
50 void EffectChain::add_effect_raw(Effect *effect, const std::vector<Effect *> &inputs)
51 {
52         char effect_id[256];
53         sprintf(effect_id, "eff%u", (unsigned)effects.size());
54
55         effects.push_back(effect);
56         effect_ids.insert(std::make_pair(effect, effect_id));
57         assert(inputs.size() == effect->num_inputs());
58         for (unsigned i = 0; i < inputs.size(); ++i) {
59                 assert(std::find(effects.begin(), effects.end(), inputs[i]) != effects.end());
60                 outgoing_links[inputs[i]].push_back(effect);
61         }
62         incoming_links.insert(std::make_pair(effect, inputs));
63         output_gamma_curve[effect] = output_gamma_curve[last_added_effect()];
64         output_color_space[effect] = output_color_space[last_added_effect()];
65 }
66
67 Effect *instantiate_effect(EffectId effect)
68 {
69         switch (effect) {
70         case EFFECT_GAMMA_EXPANSION:
71                 return new GammaExpansionEffect();
72         case EFFECT_GAMMA_COMPRESSION:
73                 return new GammaCompressionEffect();
74         case EFFECT_COLOR_SPACE_CONVERSION:
75                 return new ColorSpaceConversionEffect();
76         case EFFECT_SANDBOX:
77                 return new SandboxEffect();
78         case EFFECT_LIFT_GAMMA_GAIN:
79                 return new LiftGammaGainEffect();
80         case EFFECT_SATURATION:
81                 return new SaturationEffect();
82         case EFFECT_MIRROR:
83                 return new MirrorEffect();
84         case EFFECT_VIGNETTE:
85                 return new VignetteEffect();
86         case EFFECT_BLUR:
87                 return new BlurEffect();
88         case EFFECT_DIFFUSION:
89                 return new DiffusionEffect();
90         case EFFECT_GLOW:
91                 return new GlowEffect();
92         case EFFECT_MIX:
93                 return new MixEffect();
94         }
95         assert(false);
96 }
97
98 Effect *EffectChain::normalize_to_linear_gamma(Effect *input)
99 {
100         assert(output_gamma_curve.count(input) != 0);
101         if (output_gamma_curve[input] == GAMMA_sRGB) {
102                 // TODO: check if the extension exists
103                 effects[0]->set_int("use_srgb_texture_format", 1);
104                 output_gamma_curve[input] = GAMMA_LINEAR;
105                 return input;
106         } else {
107                 GammaExpansionEffect *gamma_conversion = new GammaExpansionEffect();
108                 gamma_conversion->set_int("source_curve", output_gamma_curve[input]);
109                 std::vector<Effect *> inputs;
110                 inputs.push_back(input);
111                 gamma_conversion->add_self_to_effect_chain(this, inputs);
112                 output_gamma_curve[gamma_conversion] = GAMMA_LINEAR;
113                 return gamma_conversion;
114         }
115 }
116
117 Effect *EffectChain::normalize_to_srgb(Effect *input)
118 {
119         assert(output_gamma_curve.count(input) != 0);
120         assert(output_color_space.count(input) != 0);
121         assert(output_gamma_curve[input] == GAMMA_LINEAR);
122         ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
123         colorspace_conversion->set_int("source_space", output_color_space[input]);
124         colorspace_conversion->set_int("destination_space", COLORSPACE_sRGB);
125         std::vector<Effect *> inputs;
126         inputs.push_back(input);
127         colorspace_conversion->add_self_to_effect_chain(this, inputs);
128         output_color_space[colorspace_conversion] = COLORSPACE_sRGB;
129         return colorspace_conversion;
130 }
131
132 Effect *EffectChain::add_effect(EffectId effect_id, const std::vector<Effect *> &inputs)
133 {
134         Effect *effect = instantiate_effect(effect_id);
135
136         assert(inputs.size() == effect->num_inputs());
137
138         std::vector<Effect *> normalized_inputs = inputs;
139         for (unsigned i = 0; i < normalized_inputs.size(); ++i) {
140                 assert(output_gamma_curve.count(normalized_inputs[i]) != 0);
141                 if (effect->needs_linear_light() && output_gamma_curve[normalized_inputs[i]] != GAMMA_LINEAR) {
142                         normalized_inputs[i] = normalize_to_linear_gamma(normalized_inputs[i]);
143                 }
144                 assert(output_color_space.count(normalized_inputs[i]) != 0);
145                 if (effect->needs_srgb_primaries() && output_color_space[normalized_inputs[i]] != COLORSPACE_sRGB) {
146                         normalized_inputs[i] = normalize_to_srgb(normalized_inputs[i]);
147                 }
148         }
149
150         effect->add_self_to_effect_chain(this, normalized_inputs);
151         return effect;
152 }
153
154 // GLSL pre-1.30 doesn't support token pasting. Replace PREFIX(x) with <effect_id>_x.
155 std::string replace_prefix(const std::string &text, const std::string &prefix)
156 {
157         std::string output;
158         size_t start = 0;
159
160         while (start < text.size()) {
161                 size_t pos = text.find("PREFIX(", start);
162                 if (pos == std::string::npos) {
163                         output.append(text.substr(start, std::string::npos));
164                         break;
165                 }
166
167                 output.append(text.substr(start, pos - start));
168                 output.append(prefix);
169                 output.append("_");
170
171                 pos += strlen("PREFIX(");
172         
173                 // Output stuff until we find the matching ), which we then eat.
174                 int depth = 1;
175                 size_t end_arg_pos = pos;
176                 while (end_arg_pos < text.size()) {
177                         if (text[end_arg_pos] == '(') {
178                                 ++depth;
179                         } else if (text[end_arg_pos] == ')') {
180                                 --depth;
181                                 if (depth == 0) {
182                                         break;
183                                 }
184                         }
185                         ++end_arg_pos;
186                 }
187                 output.append(text.substr(pos, end_arg_pos - pos));
188                 ++end_arg_pos;
189                 assert(depth == 0);
190                 start = end_arg_pos;
191         }
192         return output;
193 }
194
195 EffectChain::Phase EffectChain::compile_glsl_program(const std::vector<Effect *> &inputs, const std::vector<Effect *> &effects)
196 {
197         assert(!inputs.empty());
198         assert(!effects.empty());
199
200         // Figure out the true set of inputs to this phase. These are the ones
201         // that we need somehow but don't calculate ourselves.
202         std::set<Effect *> effect_set(effects.begin(), effects.end());
203         std::set<Effect *> input_set(inputs.begin(), inputs.end());
204         std::vector<Effect *> true_inputs;
205         std::set_difference(input_set.begin(), input_set.end(),
206                 effect_set.begin(), effect_set.end(),
207                 std::back_inserter(true_inputs));
208
209         bool input_needs_mipmaps = false;
210         std::string frag_shader = read_file("header.frag");
211
212         // Create functions for all the texture inputs that we need.
213         for (unsigned i = 0; i < true_inputs.size(); ++i) {
214                 Effect *effect = true_inputs[i];
215                 assert(effect_ids.count(effect) != 0);
216                 std::string effect_id = effect_ids[effect];
217         
218                 frag_shader += std::string("uniform sampler2D tex_") + effect_id + ";\n";       
219                 frag_shader += std::string("vec4 ") + effect_id + "(vec2 tc) {\n";
220                 if (effect->num_inputs() == 0) {
221                         // OpenGL's origin is bottom-left, but most graphics software assumes
222                         // a top-left origin. Thus, for inputs that come from the user,
223                         // we flip the y coordinate. However, for FBOs, the origin
224                         // is all correct, so don't do anything.
225                         frag_shader += "\ttc.y = 1.0f - tc.y;\n";
226                 }
227                 frag_shader += "\treturn texture2D(tex_" + effect_id + ", tc);\n";
228                 frag_shader += "}\n";
229                 frag_shader += "\n";
230         }
231
232         std::string last_effect_id;
233         for (unsigned i = 0; i < effects.size(); ++i) {
234                 Effect *effect = effects[i];
235                 assert(effect != NULL);
236                 assert(effect_ids.count(effect) != 0);
237                 std::string effect_id = effect_ids[effect];
238                 last_effect_id = effect_id;
239
240                 if (incoming_links[effect].size() == 1) {
241                         frag_shader += std::string("#define INPUT ") + effect_ids[incoming_links[effect][0]] + "\n";
242                 } else {
243                         for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
244                                 char buf[256];
245                                 sprintf(buf, "#define INPUT%d %s\n", j + 1, effect_ids[incoming_links[effect][j]].c_str());
246                                 frag_shader += buf;
247                         }
248                 }
249         
250                 frag_shader += "\n";
251                 frag_shader += std::string("#define FUNCNAME ") + effect_id + "\n";
252                 frag_shader += replace_prefix(effect->output_convenience_uniforms(), effect_id);
253                 frag_shader += replace_prefix(effect->output_fragment_shader(), effect_id);
254                 frag_shader += "#undef PREFIX\n";
255                 frag_shader += "#undef FUNCNAME\n";
256                 if (incoming_links[effect].size() == 1) {
257                         frag_shader += "#undef INPUT\n";
258                 } else {
259                         for (unsigned j = 0; j < incoming_links[effect].size(); ++j) {
260                                 char buf[256];
261                                 sprintf(buf, "#undef INPUT%d\n", j + 1);
262                                 frag_shader += buf;
263                         }
264                 }
265                 frag_shader += "\n";
266
267                 input_needs_mipmaps |= effect->needs_mipmaps();
268         }
269         for (unsigned i = 0; i < effects.size(); ++i) {
270                 Effect *effect = effects[i];
271                 if (effect->num_inputs() == 0) {
272                         effect->set_int("needs_mipmaps", input_needs_mipmaps);
273                 }
274         }
275         assert(!last_effect_id.empty());
276         frag_shader += std::string("#define INPUT ") + last_effect_id + "\n";
277         frag_shader.append(read_file("footer.frag"));
278         printf("%s\n", frag_shader.c_str());
279         
280         GLuint glsl_program_num = glCreateProgram();
281         GLuint vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
282         GLuint fs_obj = compile_shader(frag_shader, GL_FRAGMENT_SHADER);
283         glAttachShader(glsl_program_num, vs_obj);
284         check_error();
285         glAttachShader(glsl_program_num, fs_obj);
286         check_error();
287         glLinkProgram(glsl_program_num);
288         check_error();
289
290         Phase phase;
291         phase.glsl_program_num = glsl_program_num;
292         phase.input_needs_mipmaps = input_needs_mipmaps;
293         phase.inputs = true_inputs;
294         phase.effects = effects;
295
296         return phase;
297 }
298
299 // Construct GLSL programs, starting at the given effect and following
300 // the chain from there. We end a program every time we come to an effect
301 // marked as "needs texture bounce", one that is used by multiple other
302 // effects, and of course at the end.
303 void EffectChain::construct_glsl_programs(Effect *start, std::set<Effect *> *completed_effects)
304 {
305         assert(start != NULL);
306         if (completed_effects->count(start) != 0) {
307                 // This has already been done for us.
308                 return;
309         }
310
311         std::vector<Effect *> this_phase_inputs;  // Also includes all intermediates; these will be filtered away later.
312         std::vector<Effect *> this_phase_effects;
313         Effect *node = start;
314         for ( ;; ) {  // Termination condition within loop.
315                 assert(node != NULL);
316
317                 // Check that we have all the inputs we need for this effect.
318                 // If not, we end the phase here right away; the other side
319                 // of the input chain will eventually come and pick the effect up.
320                 assert(incoming_links.count(node) == 1);
321                 std::vector<Effect *> deps = incoming_links[node];
322                 assert(node->num_inputs() == deps.size());
323                 if (!deps.empty()) {
324                         bool have_all_deps = true;
325                         for (unsigned i = 0; i < deps.size(); ++i) {
326                                 if (completed_effects->count(deps[i]) == 0) {
327                                         have_all_deps = false;
328                                         break;
329                                 }
330                         }
331                 
332                         if (!have_all_deps) {
333                                 if (!this_phase_effects.empty()) {
334                                         phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
335                                 }
336                                 return;
337                         }
338                         this_phase_inputs.insert(this_phase_inputs.end(), deps.begin(), deps.end());    
339                 }
340                 this_phase_effects.push_back(node);
341                 completed_effects->insert(node);        
342
343                 // Find all the effects that use this one as a direct input.
344                 if (outgoing_links.count(node) == 0) {
345                         // End of the line; output.
346                         phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
347                         return;
348                 }
349
350                 std::vector<Effect *> next = outgoing_links[node];
351                 assert(!next.empty());
352                 if (next.size() > 1) {
353                         if (node->num_inputs() != 0) {
354                                 // More than one effect uses this as the input, and it is not a texture itself.
355                                 // The easiest thing to do (and probably also the safest
356                                 // performance-wise in most cases) is to bounce it to a texture
357                                 // and then let the next passes read from that.
358                                 phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
359                         }
360
361                         // Start phases for all the effects that need us (in arbitrary order).
362                         for (unsigned i = 0; i < next.size(); ++i) {
363                                 construct_glsl_programs(next[i], completed_effects);
364                         }
365                         return;
366                 }
367         
368                 // OK, only one effect uses this as the input. Keep iterating,
369                 // but first see if it requires a texture bounce; if so, give it
370                 // one by starting a new phase.
371                 node = next[0];
372                 if (node->needs_texture_bounce()) {
373                         phases.push_back(compile_glsl_program(this_phase_inputs, this_phase_effects));
374                         this_phase_inputs.clear();
375                         this_phase_effects.clear();
376                 }
377         }
378 }
379
380 void EffectChain::finalize()
381 {
382         // Add normalizers to get the output format right.
383         assert(output_gamma_curve.count(last_added_effect()) != 0);
384         assert(output_color_space.count(last_added_effect()) != 0);
385         ColorSpace current_color_space = output_color_space[last_added_effect()];  // FIXME
386         if (current_color_space != output_format.color_space) {
387                 ColorSpaceConversionEffect *colorspace_conversion = new ColorSpaceConversionEffect();
388                 colorspace_conversion->set_int("source_space", current_color_space);
389                 colorspace_conversion->set_int("destination_space", output_format.color_space);
390                 std::vector<Effect *> inputs;
391                 inputs.push_back(last_added_effect());
392                 colorspace_conversion->add_self_to_effect_chain(this, inputs);
393                 output_color_space[colorspace_conversion] = output_format.color_space;
394         }
395         GammaCurve current_gamma_curve = output_gamma_curve[last_added_effect()];  // FIXME
396         if (current_gamma_curve != output_format.gamma_curve) {
397                 if (current_gamma_curve != GAMMA_LINEAR) {
398                         normalize_to_linear_gamma(last_added_effect());  // FIXME
399                 }
400                 assert(current_gamma_curve == GAMMA_LINEAR);
401                 GammaCompressionEffect *gamma_conversion = new GammaCompressionEffect();
402                 gamma_conversion->set_int("destination_curve", output_format.gamma_curve);
403                 std::vector<Effect *> inputs;
404                 inputs.push_back(last_added_effect());
405                 gamma_conversion->add_self_to_effect_chain(this, inputs);
406                 output_gamma_curve[gamma_conversion] = output_format.gamma_curve;
407         }
408
409         // Construct all needed GLSL programs, starting at the input.
410         std::set<Effect *> completed_effects;
411         construct_glsl_programs(effects[0], &completed_effects);
412
413         // If we have more than one phase, we need intermediate render-to-texture.
414         // Construct an FBO, and then as many textures as we need.
415         // We choose the simplest option of having one texture per output,
416         // since otherwise this turns into an (albeit simple)
417         // register allocation problem.
418         if (phases.size() > 1) {
419                 glGenFramebuffers(1, &fbo);
420
421                 for (unsigned i = 0; i < phases.size() - 1; ++i) {
422                         Effect *output_effect = phases[i].effects.back();
423                         GLuint temp_texture;
424                         glGenTextures(1, &temp_texture);
425                         check_error();
426                         glBindTexture(GL_TEXTURE_2D, temp_texture);
427                         check_error();
428                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
429                         check_error();
430                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
431                         check_error();
432                         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
433                         check_error();
434                         effect_output_textures.insert(std::make_pair(output_effect, temp_texture));
435                 }
436         }
437                 
438         (static_cast<Input *>(effects[0]))->finalize();
439         
440         finalized = true;
441 }
442
443 void EffectChain::render_to_screen()
444 {
445         assert(finalized);
446
447         // Basic state.
448         glDisable(GL_BLEND);
449         check_error();
450         glDisable(GL_DEPTH_TEST);
451         check_error();
452         glDepthMask(GL_FALSE);
453         check_error();
454
455         glMatrixMode(GL_PROJECTION);
456         glLoadIdentity();
457         glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0);
458
459         glMatrixMode(GL_MODELVIEW);
460         glLoadIdentity();
461
462         if (phases.size() > 1) {
463                 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
464                 check_error();
465         }
466
467         std::set<Effect *> generated_mipmaps;
468         generated_mipmaps.insert(effects[0]);  // Already done further up.
469
470         for (unsigned phase = 0; phase < phases.size(); ++phase) {
471                 glUseProgram(phases[phase].glsl_program_num);
472                 check_error();
473
474                 // Set up RTT inputs for this phase.
475                 for (unsigned sampler = 0; sampler < phases[phase].inputs.size(); ++sampler) {
476                         glActiveTexture(GL_TEXTURE0 + sampler);
477                         Effect *input = phases[phase].inputs[sampler];
478                         assert(effect_output_textures.count(input) != 0);
479                         glBindTexture(GL_TEXTURE_2D, effect_output_textures[input]);
480                         check_error();
481                         if (phases[phase].input_needs_mipmaps) {
482                                 if (generated_mipmaps.count(input) == 0) {
483                                         glGenerateMipmap(GL_TEXTURE_2D);
484                                         check_error();
485                                         generated_mipmaps.insert(input);
486                                 }
487                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
488                                 check_error();
489                         } else {
490                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
491                                 check_error();
492                         }
493
494                         assert(effect_ids.count(input));
495                         std::string texture_name = std::string("tex_") + effect_ids[input];
496                         glUniform1i(glGetUniformLocation(phases[phase].glsl_program_num, texture_name.c_str()), sampler);
497                         check_error();
498                 }
499
500                 // And now the output.
501                 if (phase == phases.size() - 1) {
502                         // Last phase goes directly to the screen.
503                         glBindFramebuffer(GL_FRAMEBUFFER, 0);
504                         check_error();
505                 } else {
506                         Effect *last_effect = phases[phase].effects.back();
507                         assert(effect_output_textures.count(last_effect) != 0);
508                         glFramebufferTexture2D(
509                                 GL_FRAMEBUFFER,
510                                 GL_COLOR_ATTACHMENT0,
511                                 GL_TEXTURE_2D,
512                                 effect_output_textures[last_effect],
513                                 0);
514                         check_error();
515                 }
516
517                 // Give the required parameters to all the effects.
518                 unsigned sampler_num = phases[phase].inputs.size();
519                 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
520                         Effect *effect = phases[phase].effects[i];
521                         effect->set_gl_state(phases[phase].glsl_program_num, effect_ids[effect], &sampler_num);
522                 }
523
524                 // Now draw!
525                 glBegin(GL_QUADS);
526
527                 glTexCoord2f(0.0f, 0.0f);
528                 glVertex2f(0.0f, 0.0f);
529
530                 glTexCoord2f(1.0f, 0.0f);
531                 glVertex2f(1.0f, 0.0f);
532
533                 glTexCoord2f(1.0f, 1.0f);
534                 glVertex2f(1.0f, 1.0f);
535
536                 glTexCoord2f(0.0f, 1.0f);
537                 glVertex2f(0.0f, 1.0f);
538
539                 glEnd();
540                 check_error();
541
542                 for (unsigned i = 0; i < phases[phase].effects.size(); ++i) {
543                         Effect *effect = phases[phase].effects[i];
544                         effect->clear_gl_state();
545                 }
546         }
547 }