]> git.sesse.net Git - movit/blob - effect_chain.h
Stop the FFTPassEffect Repeat test after FFT size 128.
[movit] / effect_chain.h
1 #ifndef _MOVIT_EFFECT_CHAIN_H
2 #define _MOVIT_EFFECT_CHAIN_H 1
3
4 // An EffectChain is the largest basic entity in Movit; it contains everything
5 // needed to connects a series of effects, from inputs to outputs, and render
6 // them. Generally you set up your effect chain once and then call its render
7 // functions once per frame; setting one up can be relatively expensive,
8 // but rendering is fast.
9 //
10 // Threading considerations: EffectChain is “thread-compatible”; you can use
11 // different EffectChains in multiple threads at the same time (assuming the
12 // threads do not use the same OpenGL context, but this is a good idea anyway),
13 // but you may not use one EffectChain from multiple threads simultaneously.
14 // You _are_ allowed to use one EffectChain from multiple threads as long as
15 // you only use it from one at a time (possibly by doing your own locking),
16 // but if so, the threads' contexts need to be set up to share resources, since
17 // the EffectChain holds textures and other OpenGL objects that are tied to the
18 // context.
19
20 #include <GL/glew.h>
21 #include <stdio.h>
22 #include <map>
23 #include <set>
24 #include <string>
25 #include <vector>
26
27 #include "image_format.h"
28
29 namespace movit {
30
31 class Effect;
32 class Input;
33 struct Phase;
34 class ResourcePool;
35
36 // For internal use within Node.
37 enum AlphaType {
38         ALPHA_INVALID = -1,
39         ALPHA_BLANK,
40         ALPHA_PREMULTIPLIED,
41         ALPHA_POSTMULTIPLIED,
42 };
43
44 // Whether you want pre- or postmultiplied alpha in the output
45 // (see effect.h for a discussion of pre- versus postmultiplied alpha).
46 enum OutputAlphaFormat {
47         OUTPUT_ALPHA_FORMAT_PREMULTIPLIED,
48         OUTPUT_ALPHA_FORMAT_POSTMULTIPLIED,
49 };
50
51 // A node in the graph; basically an effect and some associated information.
52 class Node {
53 public:
54         Effect *effect;
55         bool disabled;
56
57         // Edges in the graph (forward and backward).
58         std::vector<Node *> outgoing_links;
59         std::vector<Node *> incoming_links;
60
61 private:
62         // Logical size of the output of this effect, ie. the resolution
63         // you would get if you sampled it as a texture. If it is undefined
64         // (since the inputs differ in resolution), it will be 0x0.
65         // If both this and output_texture_{width,height} are set,
66         // they will be equal.
67         unsigned output_width, output_height;
68
69         // If the effect has is_single_texture(), or if the output went to RTT
70         // and that texture has been bound to a sampler, the sampler number
71         // will be stored here.
72         //
73         // TODO: Can an RTT texture be used as inputs to multiple effects
74         // within the same phase? If so, we have a problem with modifying
75         // sampler state here.
76         int bound_sampler_num;
77
78         // Used during the building of the effect chain.
79         Colorspace output_color_space;
80         GammaCurve output_gamma_curve;
81         AlphaType output_alpha_type;
82
83         friend class EffectChain;
84 };
85
86 // A rendering phase; a single GLSL program rendering a single quad.
87 struct Phase {
88         Node *output_node;
89
90         GLuint glsl_program_num;  // Owned by the resource_pool.
91         bool input_needs_mipmaps;
92
93         // Inputs are only inputs from other phases (ie., those that come from RTT);
94         // input textures are counted as part of <effects>.
95         std::vector<Phase *> inputs;
96         std::vector<Node *> effects;  // In order.
97         unsigned output_width, output_height, virtual_output_width, virtual_output_height;
98
99         // Identifier used to create unique variables in GLSL.
100         // Unique per-phase to increase cacheability of compiled shaders.
101         std::map<Node *, std::string> effect_ids;
102
103         // The geometry needed to draw this quad, bound to the vertex array
104         // object. (Seemingly it's actually a win not to upload geometry every
105         // frame, even for something as small as a quad, due to fewer state
106         // changes.)
107         GLuint vao;
108         GLuint position_vbo, texcoord_vbo;
109 };
110
111 class EffectChain {
112 public:
113         // Aspect: e.g. 16.0f, 9.0f for 16:9.
114         // resource_pool is a pointer to a ResourcePool with which to share shaders
115         // and other resources (see resource_pool.h). If NULL (the default),
116         // will create its own that is not shared with anything else. Does not take
117         // ownership of the passed-in ResourcePool, but will naturally take ownership
118         // of its own internal one if created.
119         EffectChain(float aspect_nom, float aspect_denom, ResourcePool *resource_pool = NULL);
120         ~EffectChain();
121
122         // User API:
123         // input, effects, output, finalize need to come in that specific order.
124
125         // EffectChain takes ownership of the given input.
126         // input is returned back for convenience.
127         Input *add_input(Input *input);
128
129         // EffectChain takes ownership of the given effect.
130         // effect is returned back for convenience.
131         Effect *add_effect(Effect *effect) {
132                 return add_effect(effect, last_added_effect());
133         }
134         Effect *add_effect(Effect *effect, Effect *input) {
135                 std::vector<Effect *> inputs;
136                 inputs.push_back(input);
137                 return add_effect(effect, inputs);
138         }
139         Effect *add_effect(Effect *effect, Effect *input1, Effect *input2) {
140                 std::vector<Effect *> inputs;
141                 inputs.push_back(input1);
142                 inputs.push_back(input2);
143                 return add_effect(effect, inputs);
144         }
145         Effect *add_effect(Effect *effect, Effect *input1, Effect *input2, Effect *input3) {
146                 std::vector<Effect *> inputs;
147                 inputs.push_back(input1);
148                 inputs.push_back(input2);
149                 inputs.push_back(input3);
150                 return add_effect(effect, inputs);
151         }
152         Effect *add_effect(Effect *effect, const std::vector<Effect *> &inputs);
153
154         void add_output(const ImageFormat &format, OutputAlphaFormat alpha_format);
155
156         // Set number of output bits, to scale the dither.
157         // 8 is the right value for most outputs.
158         // The default, 0, is a special value that means no dither.
159         void set_dither_bits(unsigned num_bits)
160         {
161                 this->num_dither_bits = num_bits;
162         }
163
164         void finalize();
165
166
167         //void render(unsigned char *src, unsigned char *dst);
168         void render_to_screen()
169         {
170                 render_to_fbo(0, 0, 0);
171         }
172
173         // Render the effect chain to the given FBO. If width=height=0, keeps
174         // the current viewport.
175         void render_to_fbo(GLuint fbo, unsigned width, unsigned height);
176
177         Effect *last_added_effect() {
178                 if (nodes.empty()) {
179                         return NULL;
180                 } else {
181                         return nodes.back()->effect;
182                 }       
183         }
184
185         // API for manipulating the graph directly. Intended to be used from
186         // effects and by EffectChain itself.
187         //
188         // Note that for nodes with multiple inputs, the order of calls to
189         // connect_nodes() will matter.
190         Node *add_node(Effect *effect);
191         void connect_nodes(Node *sender, Node *receiver);
192         void replace_receiver(Node *old_receiver, Node *new_receiver);
193         void replace_sender(Node *new_sender, Node *receiver);
194         void insert_node_between(Node *sender, Node *middle, Node *receiver);
195         Node *find_node_for_effect(Effect *effect) { return node_map[effect]; }
196
197         // Get the OpenGL sampler (GL_TEXTURE0, GL_TEXTURE1, etc.) for the
198         // input of the given node, so that one can modify the sampler state
199         // directly. Only valid to call during set_gl_state().
200         //
201         // Also, for this to be allowed, <node>'s effect must have
202         // needs_texture_bounce() set, so that it samples directly from a
203         // single-sampler input, or from an RTT texture.
204         GLenum get_input_sampler(Node *node, unsigned input_num) const;
205
206         // Get the current resource pool assigned to this EffectChain.
207         // Primarily to let effects allocate textures as needed.
208         // Any resources you get from the pool must be returned to the pool
209         // no later than in the Effect's destructor.
210         ResourcePool *get_resource_pool() { return resource_pool; }
211
212 private:
213         // Make sure the output rectangle is at least large enough to hold
214         // the given input rectangle in both dimensions, and is of the
215         // current aspect ratio (aspect_nom/aspect_denom).
216         void size_rectangle_to_fit(unsigned width, unsigned height, unsigned *output_width, unsigned *output_height);
217
218         // Compute the input sizes for all inputs for all effects in a given phase,
219         // and inform the effects about the results.    
220         void inform_input_sizes(Phase *phase);
221
222         // Determine the preferred output size of a given phase.
223         // Requires that all input phases (if any) already have output sizes set.
224         void find_output_size(Phase *phase);
225
226         // Find all inputs eventually feeding into this effect that have
227         // output gamma different from GAMMA_LINEAR.
228         void find_all_nonlinear_inputs(Node *effect, std::vector<Node *> *nonlinear_inputs);
229
230         // Create a GLSL program computing the effects for this phase in order.
231         void compile_glsl_program(Phase *phase);
232
233         // Create all GLSL programs needed to compute the given effect, and all outputs
234         // that depend on it (whenever possible). Returns the phase that has <output>
235         // as the last effect. Also pushes all phases in order onto <phases>.
236         Phase *construct_phase(Node *output, std::map<Node *, Phase *> *completed_effects);
237
238         // Execute one phase, ie. set up all inputs, effects and outputs, and render the quad.
239         void execute_phase(Phase *phase, bool last_phase, std::map<Phase *, GLuint> *output_textures, std::set<Phase *> *generated_mipmaps);
240
241         // Set up the given sampler number for sampling from an RTT texture,
242         // and bind it to "tex_" plus the given GLSL variable.
243         void setup_rtt_sampler(GLuint glsl_program_num, int sampler_num, const std::string &effect_id, bool use_mipmaps);
244
245         // Output the current graph to the given file in a Graphviz-compatible format;
246         // only useful for debugging.
247         void output_dot(const char *filename);
248         std::vector<std::string> get_labels_for_edge(const Node *from, const Node *to);
249         void output_dot_edge(FILE *fp,
250                              const std::string &from_node_id,
251                              const std::string &to_node_id,
252                              const std::vector<std::string> &labels);
253
254         // Some of the graph algorithms assume that the nodes array is sorted
255         // topologically (inputs are always before outputs), but some operations
256         // (like graph rewriting) can change that. This function restores that order.
257         void sort_all_nodes_topologically();
258
259         // Do the actual topological sort. <nodes> must be a connected, acyclic subgraph;
260         // links that go to nodes not in the set will be ignored.
261         std::vector<Node *> topological_sort(const std::vector<Node *> &nodes);
262
263         // Utility function used by topological_sort() to do a depth-first search.
264         // The reason why we store nodes left to visit instead of a more conventional
265         // list of nodes to visit is that we want to be able to limit ourselves to
266         // a subgraph instead of all nodes. The set thus serves a dual purpose.
267         void topological_sort_visit_node(Node *node, std::set<Node *> *nodes_left_to_visit, std::vector<Node *> *sorted_list);
268
269         // Used during finalize().
270         void find_color_spaces_for_inputs();
271         void propagate_alpha();
272         void propagate_gamma_and_color_space();
273         Node *find_output_node();
274
275         bool node_needs_colorspace_fix(Node *node);
276         void fix_internal_color_spaces();
277         void fix_output_color_space();
278
279         bool node_needs_alpha_fix(Node *node);
280         void fix_internal_alpha(unsigned step);
281         void fix_output_alpha();
282
283         bool node_needs_gamma_fix(Node *node);
284         void fix_internal_gamma_by_asking_inputs(unsigned step);
285         void fix_internal_gamma_by_inserting_nodes(unsigned step);
286         void fix_output_gamma();
287         void add_dither_if_needed();
288
289         float aspect_nom, aspect_denom;
290         ImageFormat output_format;
291         OutputAlphaFormat output_alpha_format;
292
293         std::vector<Node *> nodes;
294         std::map<Effect *, Node *> node_map;
295         Effect *dither_effect;
296
297         std::vector<Input *> inputs;  // Also contained in nodes.
298         std::vector<Phase *> phases;
299
300         unsigned num_dither_bits;
301         bool finalized;
302
303         ResourcePool *resource_pool;
304         bool owns_resource_pool;
305 };
306
307 }  // namespace movit
308
309 #endif // !defined(_MOVIT_EFFECT_CHAIN_H)