]> git.sesse.net Git - nageru/blob - flow.cpp
Move GPUTimers into its own file.
[nageru] / flow.cpp
1 #define NO_SDL_GLEXT 1
2
3 #include <epoxy/gl.h>
4
5 #include <SDL2/SDL.h>
6 #include <SDL2/SDL_error.h>
7 #include <SDL2/SDL_events.h>
8 #include <SDL2/SDL_image.h>
9 #include <SDL2/SDL_keyboard.h>
10 #include <SDL2/SDL_mouse.h>
11 #include <SDL2/SDL_video.h>
12
13 #include <assert.h>
14 #include <getopt.h>
15 #include <stdio.h>
16 #include <unistd.h>
17
18 #include "gpu_timers.h"
19 #include "util.h"
20
21 #include <algorithm>
22 #include <deque>
23 #include <memory>
24 #include <map>
25 #include <stack>
26 #include <vector>
27
28 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
29
30 using namespace std;
31
32 SDL_Window *window;
33
34 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
35 constexpr float patch_overlap_ratio = 0.75f;
36 constexpr unsigned coarsest_level = 5;
37 constexpr unsigned finest_level = 1;
38 constexpr unsigned patch_size_pixels = 12;
39
40 // Weighting constants for the different parts of the variational refinement.
41 // These don't correspond 1:1 to the values given in the DIS paper,
42 // since we have different normalizations and ranges in some cases.
43 // These are found through a simple grid search on some MPI-Sintel data,
44 // although the error (EPE) seems to be fairly insensitive to the precise values.
45 // Only the relative values matter, so we fix alpha (the smoothness constant)
46 // at unity and tweak the others.
47 float vr_alpha = 1.0f, vr_delta = 0.25f, vr_gamma = 0.25f;
48
49 bool enable_timing = true;
50 bool enable_variational_refinement = true;  // Just for debugging.
51 bool enable_interpolation = false;
52
53 // Some global OpenGL objects.
54 // TODO: These should really be part of DISComputeFlow.
55 GLuint nearest_sampler, linear_sampler, zero_border_sampler;
56 GLuint vertex_vbo;
57
58 // Structures for asynchronous readback. We assume everything is the same size (and GL_RG16F).
59 struct ReadInProgress {
60         GLuint pbo;
61         string filename0, filename1;
62         string flow_filename, ppm_filename;  // Either may be empty for no write.
63 };
64 stack<GLuint> spare_pbos;
65 deque<ReadInProgress> reads_in_progress;
66
67 int find_num_levels(int width, int height)
68 {
69         int levels = 1;
70         for (int w = width, h = height; w > 1 || h > 1; ) {
71                 w >>= 1;
72                 h >>= 1;
73                 ++levels;
74         }
75         return levels;
76 }
77
78 string read_file(const string &filename)
79 {
80         FILE *fp = fopen(filename.c_str(), "r");
81         if (fp == nullptr) {
82                 perror(filename.c_str());
83                 exit(1);
84         }
85
86         int ret = fseek(fp, 0, SEEK_END);
87         if (ret == -1) {
88                 perror("fseek(SEEK_END)");
89                 exit(1);
90         }
91
92         int size = ftell(fp);
93
94         ret = fseek(fp, 0, SEEK_SET);
95         if (ret == -1) {
96                 perror("fseek(SEEK_SET)");
97                 exit(1);
98         }
99
100         string str;
101         str.resize(size);
102         ret = fread(&str[0], size, 1, fp);
103         if (ret == -1) {
104                 perror("fread");
105                 exit(1);
106         }
107         if (ret == 0) {
108                 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
109                                 size, filename.c_str());
110                 exit(1);
111         }
112         fclose(fp);
113
114         return str;
115 }
116
117
118 GLuint compile_shader(const string &shader_src, GLenum type)
119 {
120         GLuint obj = glCreateShader(type);
121         const GLchar* source[] = { shader_src.data() };
122         const GLint length[] = { (GLint)shader_src.size() };
123         glShaderSource(obj, 1, source, length);
124         glCompileShader(obj);
125
126         GLchar info_log[4096];
127         GLsizei log_length = sizeof(info_log) - 1;
128         glGetShaderInfoLog(obj, log_length, &log_length, info_log);
129         info_log[log_length] = 0;
130         if (strlen(info_log) > 0) {
131                 fprintf(stderr, "Shader compile log: %s\n", info_log);
132         }
133
134         GLint status;
135         glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
136         if (status == GL_FALSE) {
137                 // Add some line numbers to easier identify compile errors.
138                 string src_with_lines = "/*   1 */ ";
139                 size_t lineno = 1;
140                 for (char ch : shader_src) {
141                         src_with_lines.push_back(ch);
142                         if (ch == '\n') {
143                                 char buf[32];
144                                 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
145                                 src_with_lines += buf;
146                         }
147                 }
148
149                 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
150                 exit(1);
151         }
152
153         return obj;
154 }
155
156 enum MipmapPolicy {
157         WITHOUT_MIPMAPS,
158         WITH_MIPMAPS
159 };
160
161 GLuint load_texture(const char *filename, unsigned *width_ret, unsigned *height_ret, MipmapPolicy mipmaps)
162 {
163         SDL_Surface *surf = IMG_Load(filename);
164         if (surf == nullptr) {
165                 fprintf(stderr, "IMG_Load(%s): %s\n", filename, IMG_GetError());
166                 exit(1);
167         }
168
169         // For whatever reason, SDL doesn't support converting to YUV surfaces
170         // nor grayscale, so we'll do it ourselves.
171         SDL_Surface *rgb_surf = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_RGBA32, /*flags=*/0);
172         if (rgb_surf == nullptr) {
173                 fprintf(stderr, "SDL_ConvertSurfaceFormat(%s): %s\n", filename, SDL_GetError());
174                 exit(1);
175         }
176
177         SDL_FreeSurface(surf);
178
179         unsigned width = rgb_surf->w, height = rgb_surf->h;
180         const uint8_t *sptr = (uint8_t *)rgb_surf->pixels;
181         unique_ptr<uint8_t[]> pix(new uint8_t[width * height * 4]);
182
183         // Extract the Y component, and convert to bottom-left origin.
184         for (unsigned y = 0; y < height; ++y) {
185                 unsigned y2 = height - 1 - y;
186                 memcpy(pix.get() + y * width * 4, sptr + y2 * rgb_surf->pitch, width * 4);
187         }
188         SDL_FreeSurface(rgb_surf);
189
190         int num_levels = (mipmaps == WITH_MIPMAPS) ? find_num_levels(width, height) : 1;
191
192         GLuint tex;
193         glCreateTextures(GL_TEXTURE_2D, 1, &tex);
194         glTextureStorage2D(tex, num_levels, GL_RGBA8, width, height);
195         glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pix.get());
196
197         if (mipmaps == WITH_MIPMAPS) {
198                 glGenerateTextureMipmap(tex);
199         }
200
201         *width_ret = width;
202         *height_ret = height;
203
204         return tex;
205 }
206
207 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
208 {
209         GLuint program = glCreateProgram();
210         glAttachShader(program, vs_obj);
211         glAttachShader(program, fs_obj);
212         glLinkProgram(program);
213         GLint success;
214         glGetProgramiv(program, GL_LINK_STATUS, &success);
215         if (success == GL_FALSE) {
216                 GLchar error_log[1024] = {0};
217                 glGetProgramInfoLog(program, 1024, nullptr, error_log);
218                 fprintf(stderr, "Error linking program: %s\n", error_log);
219                 exit(1);
220         }
221         return program;
222 }
223
224 GLuint generate_vbo(GLint size, GLsizeiptr data_size, const GLvoid *data)
225 {
226         GLuint vbo;
227         glCreateBuffers(1, &vbo);
228         glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
229         glNamedBufferData(vbo, data_size, data, GL_STATIC_DRAW);
230         return vbo;
231 }
232
233 GLuint fill_vertex_attribute(GLuint vao, GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
234 {
235         int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
236         if (attrib == -1) {
237                 return -1;
238         }
239
240         GLuint vbo = generate_vbo(size, data_size, data);
241
242         glBindBuffer(GL_ARRAY_BUFFER, vbo);
243         glEnableVertexArrayAttrib(vao, attrib);
244         glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
245         glBindBuffer(GL_ARRAY_BUFFER, 0);
246
247         return vbo;
248 }
249
250 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
251 {
252         if (location == -1) {
253                 return;
254         }
255
256         glBindTextureUnit(texture_unit, tex);
257         glBindSampler(texture_unit, sampler);
258         glProgramUniform1i(program, location, texture_unit);
259 }
260
261 // A class that caches FBOs that render to a given set of textures.
262 // It never frees anything, so it is only suitable for rendering to
263 // the same (small) set of textures over and over again.
264 template<size_t num_elements>
265 class PersistentFBOSet {
266 public:
267         void render_to(const array<GLuint, num_elements> &textures);
268
269         // Convenience wrappers.
270         void render_to(GLuint texture0, enable_if<num_elements == 1> * = nullptr) {
271                 render_to({{texture0}});
272         }
273
274         void render_to(GLuint texture0, GLuint texture1, enable_if<num_elements == 2> * = nullptr) {
275                 render_to({{texture0, texture1}});
276         }
277
278         void render_to(GLuint texture0, GLuint texture1, GLuint texture2, enable_if<num_elements == 3> * = nullptr) {
279                 render_to({{texture0, texture1, texture2}});
280         }
281
282         void render_to(GLuint texture0, GLuint texture1, GLuint texture2, GLuint texture3, enable_if<num_elements == 4> * = nullptr) {
283                 render_to({{texture0, texture1, texture2, texture3}});
284         }
285
286 private:
287         // TODO: Delete these on destruction.
288         map<array<GLuint, num_elements>, GLuint> fbos;
289 };
290
291 template<size_t num_elements>
292 void PersistentFBOSet<num_elements>::render_to(const array<GLuint, num_elements> &textures)
293 {
294         auto it = fbos.find(textures);
295         if (it != fbos.end()) {
296                 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
297                 return;
298         }
299
300         GLuint fbo;
301         glCreateFramebuffers(1, &fbo);
302         GLenum bufs[num_elements];
303         for (size_t i = 0; i < num_elements; ++i) {
304                 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
305                 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
306         }
307         glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
308
309         fbos[textures] = fbo;
310         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
311 }
312
313 // Convert RGB to grayscale, using Rec. 709 coefficients.
314 class GrayscaleConversion {
315 public:
316         GrayscaleConversion();
317         void exec(GLint tex, GLint gray_tex, int width, int height);
318
319 private:
320         PersistentFBOSet<1> fbos;
321         GLuint gray_vs_obj;
322         GLuint gray_fs_obj;
323         GLuint gray_program;
324         GLuint gray_vao;
325
326         GLuint uniform_tex;
327 };
328
329 GrayscaleConversion::GrayscaleConversion()
330 {
331         gray_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
332         gray_fs_obj = compile_shader(read_file("gray.frag"), GL_FRAGMENT_SHADER);
333         gray_program = link_program(gray_vs_obj, gray_fs_obj);
334
335         // Set up the VAO containing all the required position/texcoord data.
336         glCreateVertexArrays(1, &gray_vao);
337         glBindVertexArray(gray_vao);
338
339         GLint position_attrib = glGetAttribLocation(gray_program, "position");
340         glEnableVertexArrayAttrib(gray_vao, position_attrib);
341         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
342
343         uniform_tex = glGetUniformLocation(gray_program, "tex");
344 }
345
346 void GrayscaleConversion::exec(GLint tex, GLint gray_tex, int width, int height)
347 {
348         glUseProgram(gray_program);
349         bind_sampler(gray_program, uniform_tex, 0, tex, nearest_sampler);
350
351         glViewport(0, 0, width, height);
352         fbos.render_to(gray_tex);
353         glBindVertexArray(gray_vao);
354         glUseProgram(gray_program);
355         glDisable(GL_BLEND);
356         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
357 }
358
359 // Compute gradients in every point, used for the motion search.
360 // The DIS paper doesn't actually mention how these are computed,
361 // but seemingly, a 3x3 Sobel operator is used here (at least in
362 // later versions of the code), while a [1 -8 0 8 -1] kernel is
363 // used for all the derivatives in the variational refinement part
364 // (which borrows code from DeepFlow). This is inconsistent,
365 // but I guess we're better off with staying with the original
366 // decisions until we actually know having different ones would be better.
367 class Sobel {
368 public:
369         Sobel();
370         void exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height);
371
372 private:
373         PersistentFBOSet<1> fbos;
374         GLuint sobel_vs_obj;
375         GLuint sobel_fs_obj;
376         GLuint sobel_program;
377         GLuint sobel_vao;
378
379         GLuint uniform_tex;
380 };
381
382 Sobel::Sobel()
383 {
384         sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
385         sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
386         sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
387
388         // Set up the VAO containing all the required position/texcoord data.
389         glCreateVertexArrays(1, &sobel_vao);
390         glBindVertexArray(sobel_vao);
391
392         GLint position_attrib = glGetAttribLocation(sobel_program, "position");
393         glEnableVertexArrayAttrib(sobel_vao, position_attrib);
394         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
395
396         uniform_tex = glGetUniformLocation(sobel_program, "tex");
397 }
398
399 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
400 {
401         glUseProgram(sobel_program);
402         bind_sampler(sobel_program, uniform_tex, 0, tex0_view, nearest_sampler);
403
404         glViewport(0, 0, level_width, level_height);
405         fbos.render_to(grad0_tex);
406         glBindVertexArray(sobel_vao);
407         glUseProgram(sobel_program);
408         glDisable(GL_BLEND);
409         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
410 }
411
412 // Motion search to find the initial flow. See motion_search.frag for documentation.
413 class MotionSearch {
414 public:
415         MotionSearch();
416         void exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int prev_level_width, int prev_level_height, int width_patches, int height_patches);
417
418 private:
419         PersistentFBOSet<1> fbos;
420
421         GLuint motion_vs_obj;
422         GLuint motion_fs_obj;
423         GLuint motion_search_program;
424         GLuint motion_search_vao;
425
426         GLuint uniform_inv_image_size, uniform_inv_prev_level_size;
427         GLuint uniform_image0_tex, uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
428 };
429
430 MotionSearch::MotionSearch()
431 {
432         motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
433         motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
434         motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
435
436         // Set up the VAO containing all the required position/texcoord data.
437         glCreateVertexArrays(1, &motion_search_vao);
438         glBindVertexArray(motion_search_vao);
439         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
440
441         GLint position_attrib = glGetAttribLocation(motion_search_program, "position");
442         glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
443         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
444
445         uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
446         uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
447         uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
448         uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
449         uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
450         uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
451 }
452
453 void MotionSearch::exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int prev_level_width, int prev_level_height, int width_patches, int height_patches)
454 {
455         glUseProgram(motion_search_program);
456
457         bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
458         bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
459         bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, zero_border_sampler);
460         bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
461
462         glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
463         glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
464
465         glViewport(0, 0, width_patches, height_patches);
466         fbos.render_to(flow_out_tex);
467         glBindVertexArray(motion_search_vao);
468         glUseProgram(motion_search_program);
469         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
470 }
471
472 // Do “densification”, ie., upsampling of the flow patches to the flow field
473 // (the same size as the image at this level). We draw one quad per patch
474 // over its entire covered area (using instancing in the vertex shader),
475 // and then weight the contributions in the pixel shader by post-warp difference.
476 // This is equation (3) in the paper.
477 //
478 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
479 // weight in the B channel. Dividing R and G by B gives the normalized values.
480 class Densify {
481 public:
482         Densify();
483         void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches);
484
485 private:
486         PersistentFBOSet<1> fbos;
487
488         GLuint densify_vs_obj;
489         GLuint densify_fs_obj;
490         GLuint densify_program;
491         GLuint densify_vao;
492
493         GLuint uniform_patch_size;
494         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
495 };
496
497 Densify::Densify()
498 {
499         densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
500         densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
501         densify_program = link_program(densify_vs_obj, densify_fs_obj);
502
503         // Set up the VAO containing all the required position/texcoord data.
504         glCreateVertexArrays(1, &densify_vao);
505         glBindVertexArray(densify_vao);
506         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
507
508         GLint position_attrib = glGetAttribLocation(densify_program, "position");
509         glEnableVertexArrayAttrib(densify_vao, position_attrib);
510         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
511
512         uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
513         uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
514         uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
515         uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
516 }
517
518 void Densify::exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches)
519 {
520         glUseProgram(densify_program);
521
522         bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
523         bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
524         bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
525
526         glProgramUniform2f(densify_program, uniform_patch_size,
527                 float(patch_size_pixels) / level_width,
528                 float(patch_size_pixels) / level_height);
529
530         glViewport(0, 0, level_width, level_height);
531         glEnable(GL_BLEND);
532         glBlendFunc(GL_ONE, GL_ONE);
533         glBindVertexArray(densify_vao);
534         fbos.render_to(dense_flow_tex);
535         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
536 }
537
538 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
539 // I_0 and I_w. The prewarping is what enables us to solve the variational
540 // flow for du,dv instead of u,v.
541 //
542 // Also calculates the normalized flow, ie. divides by z (this is needed because
543 // Densify works by additive blending) and multiplies by the image size.
544 //
545 // See variational_refinement.txt for more information.
546 class Prewarp {
547 public:
548         Prewarp();
549         void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint normalized_flow_tex, GLuint I_tex, GLuint I_t_tex, int level_width, int level_height);
550
551 private:
552         PersistentFBOSet<3> fbos;
553
554         GLuint prewarp_vs_obj;
555         GLuint prewarp_fs_obj;
556         GLuint prewarp_program;
557         GLuint prewarp_vao;
558
559         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
560 };
561
562 Prewarp::Prewarp()
563 {
564         prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
565         prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
566         prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
567
568         // Set up the VAO containing all the required position/texcoord data.
569         glCreateVertexArrays(1, &prewarp_vao);
570         glBindVertexArray(prewarp_vao);
571         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
572
573         GLint position_attrib = glGetAttribLocation(prewarp_program, "position");
574         glEnableVertexArrayAttrib(prewarp_vao, position_attrib);
575         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
576
577         uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
578         uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
579         uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
580 }
581
582 void Prewarp::exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint I_tex, GLuint I_t_tex, GLuint normalized_flow_tex, int level_width, int level_height)
583 {
584         glUseProgram(prewarp_program);
585
586         bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
587         bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
588         bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
589
590         glViewport(0, 0, level_width, level_height);
591         glDisable(GL_BLEND);
592         glBindVertexArray(prewarp_vao);
593         fbos.render_to(I_tex, I_t_tex, normalized_flow_tex);
594         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
595 }
596
597 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
598 // central difference filter, since apparently, that's tradition (I haven't
599 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
600 // The coefficients come from
601 //
602 //   https://en.wikipedia.org/wiki/Finite_difference_coefficient
603 //
604 // Also computes β_0, since it depends only on I_x and I_y.
605 class Derivatives {
606 public:
607         Derivatives();
608         void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
609
610 private:
611         PersistentFBOSet<2> fbos;
612
613         GLuint derivatives_vs_obj;
614         GLuint derivatives_fs_obj;
615         GLuint derivatives_program;
616         GLuint derivatives_vao;
617
618         GLuint uniform_tex;
619 };
620
621 Derivatives::Derivatives()
622 {
623         derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
624         derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
625         derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
626
627         // Set up the VAO containing all the required position/texcoord data.
628         glCreateVertexArrays(1, &derivatives_vao);
629         glBindVertexArray(derivatives_vao);
630         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
631
632         GLint position_attrib = glGetAttribLocation(derivatives_program, "position");
633         glEnableVertexArrayAttrib(derivatives_vao, position_attrib);
634         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
635
636         uniform_tex = glGetUniformLocation(derivatives_program, "tex");
637 }
638
639 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
640 {
641         glUseProgram(derivatives_program);
642
643         bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
644
645         glViewport(0, 0, level_width, level_height);
646         glDisable(GL_BLEND);
647         glBindVertexArray(derivatives_vao);
648         fbos.render_to(I_x_y_tex, beta_0_tex);
649         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
650 }
651
652 // Calculate the smoothness constraints between neighboring pixels;
653 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
654 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
655 // border color (0,0) later, so that there's zero diffusion out of
656 // the border.
657 //
658 // See variational_refinement.txt for more information.
659 class ComputeSmoothness {
660 public:
661         ComputeSmoothness();
662         void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height);
663
664 private:
665         PersistentFBOSet<2> fbos;
666
667         GLuint smoothness_vs_obj;
668         GLuint smoothness_fs_obj;
669         GLuint smoothness_program;
670         GLuint smoothness_vao;
671
672         GLuint uniform_flow_tex, uniform_diff_flow_tex;
673         GLuint uniform_alpha;
674 };
675
676 ComputeSmoothness::ComputeSmoothness()
677 {
678         smoothness_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
679         smoothness_fs_obj = compile_shader(read_file("smoothness.frag"), GL_FRAGMENT_SHADER);
680         smoothness_program = link_program(smoothness_vs_obj, smoothness_fs_obj);
681
682         // Set up the VAO containing all the required position/texcoord data.
683         glCreateVertexArrays(1, &smoothness_vao);
684         glBindVertexArray(smoothness_vao);
685         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
686
687         GLint position_attrib = glGetAttribLocation(smoothness_program, "position");
688         glEnableVertexArrayAttrib(smoothness_vao, position_attrib);
689         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
690
691         uniform_flow_tex = glGetUniformLocation(smoothness_program, "flow_tex");
692         uniform_diff_flow_tex = glGetUniformLocation(smoothness_program, "diff_flow_tex");
693         uniform_alpha = glGetUniformLocation(smoothness_program, "alpha");
694 }
695
696 void ComputeSmoothness::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height)
697 {
698         glUseProgram(smoothness_program);
699
700         bind_sampler(smoothness_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
701         bind_sampler(smoothness_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
702         glProgramUniform1f(smoothness_program, uniform_alpha, vr_alpha);
703
704         glViewport(0, 0, level_width, level_height);
705
706         glDisable(GL_BLEND);
707         glBindVertexArray(smoothness_vao);
708         fbos.render_to(smoothness_x_tex, smoothness_y_tex);
709         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
710
711         // Make sure the smoothness on the right and upper borders is zero.
712         // We could have done this by making (W-1)xH and Wx(H-1) textures instead
713         // (we're sampling smoothness with all-zero border color), but we'd
714         // have to adjust the sampling coordinates, which is annoying.
715         glClearTexSubImage(smoothness_x_tex, 0,  level_width - 1, 0, 0,   1, level_height, 1,  GL_RED, GL_FLOAT, nullptr);
716         glClearTexSubImage(smoothness_y_tex, 0,  0, level_height - 1, 0,  level_width, 1, 1,   GL_RED, GL_FLOAT, nullptr);
717 }
718
719 // Set up the equations set (two equations in two unknowns, per pixel).
720 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
721 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
722 // floats. (Actually, we store the inverse of the diagonal elements, because
723 // we only ever need to divide by them.) This fits into four u32 values;
724 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
725 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
726 // terms that depend on other pixels, are calculated in one pass.
727 //
728 // See variational_refinement.txt for more information.
729 class SetupEquations {
730 public:
731         SetupEquations();
732         void exec(GLuint I_x_y_tex, GLuint I_t_tex, GLuint diff_flow_tex, GLuint flow_tex, GLuint beta_0_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, GLuint equation_tex, int level_width, int level_height);
733
734 private:
735         PersistentFBOSet<1> fbos;
736
737         GLuint equations_vs_obj;
738         GLuint equations_fs_obj;
739         GLuint equations_program;
740         GLuint equations_vao;
741
742         GLuint uniform_I_x_y_tex, uniform_I_t_tex;
743         GLuint uniform_diff_flow_tex, uniform_base_flow_tex;
744         GLuint uniform_beta_0_tex;
745         GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
746         GLuint uniform_gamma, uniform_delta;
747 };
748
749 SetupEquations::SetupEquations()
750 {
751         equations_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
752         equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
753         equations_program = link_program(equations_vs_obj, equations_fs_obj);
754
755         // Set up the VAO containing all the required position/texcoord data.
756         glCreateVertexArrays(1, &equations_vao);
757         glBindVertexArray(equations_vao);
758         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
759
760         GLint position_attrib = glGetAttribLocation(equations_program, "position");
761         glEnableVertexArrayAttrib(equations_vao, position_attrib);
762         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
763
764         uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
765         uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
766         uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
767         uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
768         uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
769         uniform_smoothness_x_tex = glGetUniformLocation(equations_program, "smoothness_x_tex");
770         uniform_smoothness_y_tex = glGetUniformLocation(equations_program, "smoothness_y_tex");
771         uniform_gamma = glGetUniformLocation(equations_program, "gamma");
772         uniform_delta = glGetUniformLocation(equations_program, "delta");
773 }
774
775 void SetupEquations::exec(GLuint I_x_y_tex, GLuint I_t_tex, GLuint diff_flow_tex, GLuint base_flow_tex, GLuint beta_0_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, GLuint equation_tex, int level_width, int level_height)
776 {
777         glUseProgram(equations_program);
778
779         bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
780         bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
781         bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
782         bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
783         bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
784         bind_sampler(equations_program, uniform_smoothness_x_tex, 5, smoothness_x_tex, zero_border_sampler);
785         bind_sampler(equations_program, uniform_smoothness_y_tex, 6, smoothness_y_tex, zero_border_sampler);
786         glProgramUniform1f(equations_program, uniform_delta, vr_delta);
787         glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
788
789         glViewport(0, 0, level_width, level_height);
790         glDisable(GL_BLEND);
791         glBindVertexArray(equations_vao);
792         fbos.render_to(equation_tex);
793         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
794 }
795
796 // Actually solve the equation sets made by SetupEquations, by means of
797 // successive over-relaxation (SOR).
798 //
799 // See variational_refinement.txt for more information.
800 class SOR {
801 public:
802         SOR();
803         void exec(GLuint diff_flow_tex, GLuint equation_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height, int num_iterations);
804
805 private:
806         PersistentFBOSet<1> fbos;
807
808         GLuint sor_vs_obj;
809         GLuint sor_fs_obj;
810         GLuint sor_program;
811         GLuint sor_vao;
812
813         GLuint uniform_diff_flow_tex;
814         GLuint uniform_equation_tex;
815         GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
816         GLuint uniform_phase;
817 };
818
819 SOR::SOR()
820 {
821         sor_vs_obj = compile_shader(read_file("sor.vert"), GL_VERTEX_SHADER);
822         sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
823         sor_program = link_program(sor_vs_obj, sor_fs_obj);
824
825         // Set up the VAO containing all the required position/texcoord data.
826         glCreateVertexArrays(1, &sor_vao);
827         glBindVertexArray(sor_vao);
828         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
829
830         GLint position_attrib = glGetAttribLocation(sor_program, "position");
831         glEnableVertexArrayAttrib(sor_vao, position_attrib);
832         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
833
834         uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
835         uniform_equation_tex = glGetUniformLocation(sor_program, "equation_tex");
836         uniform_smoothness_x_tex = glGetUniformLocation(sor_program, "smoothness_x_tex");
837         uniform_smoothness_y_tex = glGetUniformLocation(sor_program, "smoothness_y_tex");
838         uniform_phase = glGetUniformLocation(sor_program, "phase");
839 }
840
841 void SOR::exec(GLuint diff_flow_tex, GLuint equation_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height, int num_iterations)
842 {
843         glUseProgram(sor_program);
844
845         bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
846         bind_sampler(sor_program, uniform_smoothness_x_tex, 1, smoothness_x_tex, zero_border_sampler);
847         bind_sampler(sor_program, uniform_smoothness_y_tex, 2, smoothness_y_tex, zero_border_sampler);
848         bind_sampler(sor_program, uniform_equation_tex, 3, equation_tex, nearest_sampler);
849
850         // NOTE: We bind to the texture we are rendering from, but we never write any value
851         // that we read in the same shader pass (we call discard for red values when we compute
852         // black, and vice versa), and we have barriers between the passes, so we're fine
853         // as per the spec.
854         glViewport(0, 0, level_width, level_height);
855         glDisable(GL_BLEND);
856         glBindVertexArray(sor_vao);
857         fbos.render_to(diff_flow_tex);
858
859         for (int i = 0; i < num_iterations; ++i) {
860                 glProgramUniform1i(sor_program, uniform_phase, 0);
861                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
862                 glTextureBarrier();
863                 glProgramUniform1i(sor_program, uniform_phase, 1);
864                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
865                 if (i != num_iterations - 1) {
866                         glTextureBarrier();
867                 }
868         }
869 }
870
871 // Simply add the differential flow found by the variational refinement to the base flow.
872 // The output is in base_flow_tex; we don't need to make a new texture.
873 class AddBaseFlow {
874 public:
875         AddBaseFlow();
876         void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
877
878 private:
879         PersistentFBOSet<1> fbos;
880
881         GLuint add_flow_vs_obj;
882         GLuint add_flow_fs_obj;
883         GLuint add_flow_program;
884         GLuint add_flow_vao;
885
886         GLuint uniform_diff_flow_tex;
887 };
888
889 AddBaseFlow::AddBaseFlow()
890 {
891         add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
892         add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
893         add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
894
895         // Set up the VAO containing all the required position/texcoord data.
896         glCreateVertexArrays(1, &add_flow_vao);
897         glBindVertexArray(add_flow_vao);
898         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
899
900         GLint position_attrib = glGetAttribLocation(add_flow_program, "position");
901         glEnableVertexArrayAttrib(add_flow_vao, position_attrib);
902         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
903
904         uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
905 }
906
907 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
908 {
909         glUseProgram(add_flow_program);
910
911         bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
912
913         glViewport(0, 0, level_width, level_height);
914         glEnable(GL_BLEND);
915         glBlendFunc(GL_ONE, GL_ONE);
916         glBindVertexArray(add_flow_vao);
917         fbos.render_to(base_flow_tex);
918
919         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
920 }
921
922 // Take a copy of the flow, bilinearly interpolated and scaled up.
923 class ResizeFlow {
924 public:
925         ResizeFlow();
926         void exec(GLuint in_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height);
927
928 private:
929         PersistentFBOSet<1> fbos;
930
931         GLuint resize_flow_vs_obj;
932         GLuint resize_flow_fs_obj;
933         GLuint resize_flow_program;
934         GLuint resize_flow_vao;
935
936         GLuint uniform_flow_tex;
937         GLuint uniform_scale_factor;
938 };
939
940 ResizeFlow::ResizeFlow()
941 {
942         resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
943         resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
944         resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
945
946         // Set up the VAO containing all the required position/texcoord data.
947         glCreateVertexArrays(1, &resize_flow_vao);
948         glBindVertexArray(resize_flow_vao);
949         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
950
951         GLint position_attrib = glGetAttribLocation(resize_flow_program, "position");
952         glEnableVertexArrayAttrib(resize_flow_vao, position_attrib);
953         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
954
955         uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
956         uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
957 }
958
959 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height)
960 {
961         glUseProgram(resize_flow_program);
962
963         bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
964
965         glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
966
967         glViewport(0, 0, output_width, output_height);
968         glDisable(GL_BLEND);
969         glBindVertexArray(resize_flow_vao);
970         fbos.render_to(out_tex);
971
972         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
973 }
974
975 class TexturePool {
976 public:
977         GLuint get_texture(GLenum format, GLuint width, GLuint height);
978         void release_texture(GLuint tex_num);
979
980 private:
981         struct Texture {
982                 GLuint tex_num;
983                 GLenum format;
984                 GLuint width, height;
985                 bool in_use = false;
986         };
987         vector<Texture> textures;
988 };
989
990 class DISComputeFlow {
991 public:
992         DISComputeFlow(int width, int height);
993
994         enum ResizeStrategy {
995                 DO_NOT_RESIZE_FLOW,
996                 RESIZE_FLOW_TO_FULL_SIZE
997         };
998
999         // Returns a texture that must be released with release_texture()
1000         // after use.
1001         GLuint exec(GLuint tex0, GLuint tex1, ResizeStrategy resize_strategy);
1002
1003         void release_texture(GLuint tex) {
1004                 pool.release_texture(tex);
1005         }
1006
1007 private:
1008         int width, height;
1009         GLuint initial_flow_tex;
1010         TexturePool pool;
1011
1012         // The various passes.
1013         Sobel sobel;
1014         MotionSearch motion_search;
1015         Densify densify;
1016         Prewarp prewarp;
1017         Derivatives derivatives;
1018         ComputeSmoothness compute_smoothness;
1019         SetupEquations setup_equations;
1020         SOR sor;
1021         AddBaseFlow add_base_flow;
1022         ResizeFlow resize_flow;
1023 };
1024
1025 DISComputeFlow::DISComputeFlow(int width, int height)
1026         : width(width), height(height)
1027 {
1028         // Make some samplers.
1029         glCreateSamplers(1, &nearest_sampler);
1030         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1031         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1032         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1033         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1034
1035         glCreateSamplers(1, &linear_sampler);
1036         glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1037         glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1038         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1039         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1040
1041         // The smoothness is sampled so that once we get to a smoothness involving
1042         // a value outside the border, the diffusivity between the two becomes zero.
1043         // Similarly, gradients are zero outside the border, since the edge is taken
1044         // to be constant.
1045         glCreateSamplers(1, &zero_border_sampler);
1046         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1047         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1048         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
1049         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
1050         float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f };
1051         glSamplerParameterfv(zero_border_sampler, GL_TEXTURE_BORDER_COLOR, zero);
1052
1053         // Initial flow is zero, 1x1.
1054         glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
1055         glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
1056         glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
1057 }
1058
1059 GLuint DISComputeFlow::exec(GLuint tex0, GLuint tex1, ResizeStrategy resize_strategy)
1060 {
1061         int prev_level_width = 1, prev_level_height = 1;
1062         GLuint prev_level_flow_tex = initial_flow_tex;
1063
1064         GPUTimers timers;
1065
1066         ScopedTimer total_timer("Total", &timers);
1067         for (int level = coarsest_level; level >= int(finest_level); --level) {
1068                 char timer_name[256];
1069                 snprintf(timer_name, sizeof(timer_name), "Level %d", level);
1070                 ScopedTimer level_timer(timer_name, &total_timer);
1071
1072                 int level_width = width >> level;
1073                 int level_height = height >> level;
1074                 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
1075
1076                 // Make sure we have patches at least every Nth pixel, e.g. for width=9
1077                 // and patch_spacing=3 (the default), we put out patch centers in
1078                 // x=0, x=3, x=6, x=9, which is four patches. The fragment shader will
1079                 // lock all the centers to integer coordinates if needed.
1080                 int width_patches = 1 + ceil(level_width / patch_spacing_pixels);
1081                 int height_patches = 1 + ceil(level_height / patch_spacing_pixels);
1082
1083                 // Make sure we always read from the correct level; the chosen
1084                 // mipmapping could otherwise be rather unpredictable, especially
1085                 // during motion search.
1086                 GLuint tex0_view, tex1_view;
1087                 glGenTextures(1, &tex0_view);
1088                 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
1089                 glGenTextures(1, &tex1_view);
1090                 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
1091
1092                 // Create a new texture; we could be fancy and render use a multi-level
1093                 // texture, but meh.
1094                 GLuint grad0_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1095
1096                 // Find the derivative.
1097                 {
1098                         ScopedTimer timer("Sobel", &level_timer);
1099                         sobel.exec(tex0_view, grad0_tex, level_width, level_height);
1100                 }
1101
1102                 // Motion search to find the initial flow. We use the flow from the previous
1103                 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
1104
1105                 // Create an output flow texture.
1106                 GLuint flow_out_tex = pool.get_texture(GL_RGB16F, width_patches, height_patches);
1107
1108                 // And draw.
1109                 {
1110                         ScopedTimer timer("Motion search", &level_timer);
1111                         motion_search.exec(tex0_view, tex1_view, grad0_tex, prev_level_flow_tex, flow_out_tex, level_width, level_height, prev_level_width, prev_level_height, width_patches, height_patches);
1112                 }
1113                 pool.release_texture(grad0_tex);
1114
1115                 // Densification.
1116
1117                 // Set up an output texture (initially zero).
1118                 GLuint dense_flow_tex = pool.get_texture(GL_RGB16F, level_width, level_height);
1119                 glClearTexImage(dense_flow_tex, 0, GL_RGB, GL_FLOAT, nullptr);
1120
1121                 // And draw.
1122                 {
1123                         ScopedTimer timer("Densification", &level_timer);
1124                         densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
1125                 }
1126                 pool.release_texture(flow_out_tex);
1127
1128                 // Everything below here in the loop belongs to variational refinement.
1129                 ScopedTimer varref_timer("Variational refinement", &level_timer);
1130
1131                 // Prewarping; create I and I_t, and a normalized base flow (so we don't
1132                 // have to normalize it over and over again, and also save some bandwidth).
1133                 //
1134                 // During the entire rest of the variational refinement, flow will be measured
1135                 // in pixels, not 0..1 normalized OpenGL texture coordinates.
1136                 // This is because variational refinement depends so heavily on derivatives,
1137                 // which are measured in intensity levels per pixel.
1138                 GLuint I_tex = pool.get_texture(GL_R16F, level_width, level_height);
1139                 GLuint I_t_tex = pool.get_texture(GL_R16F, level_width, level_height);
1140                 GLuint base_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1141                 {
1142                         ScopedTimer timer("Prewarping", &varref_timer);
1143                         prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height);
1144                 }
1145                 pool.release_texture(dense_flow_tex);
1146                 glDeleteTextures(1, &tex0_view);
1147                 glDeleteTextures(1, &tex1_view);
1148
1149                 // Calculate I_x and I_y. We're only calculating first derivatives;
1150                 // the others will be taken on-the-fly in order to sample from fewer
1151                 // textures overall, since sampling from the L1 cache is cheap.
1152                 // (TODO: Verify that this is indeed faster than making separate
1153                 // double-derivative textures.)
1154                 GLuint I_x_y_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1155                 GLuint beta_0_tex = pool.get_texture(GL_R16F, level_width, level_height);
1156                 {
1157                         ScopedTimer timer("First derivatives", &varref_timer);
1158                         derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
1159                 }
1160                 pool.release_texture(I_tex);
1161
1162                 // We need somewhere to store du and dv (the flow increment, relative
1163                 // to the non-refined base flow u0 and v0). It starts at zero.
1164                 GLuint du_dv_tex = pool.get_texture(GL_RG16F, level_width, level_height);
1165                 glClearTexImage(du_dv_tex, 0, GL_RG, GL_FLOAT, nullptr);
1166
1167                 // And for smoothness.
1168                 GLuint smoothness_x_tex = pool.get_texture(GL_R16F, level_width, level_height);
1169                 GLuint smoothness_y_tex = pool.get_texture(GL_R16F, level_width, level_height);
1170
1171                 // And finally for the equation set. See SetupEquations for
1172                 // the storage format.
1173                 GLuint equation_tex = pool.get_texture(GL_RGBA32UI, level_width, level_height);
1174
1175                 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
1176                         // Calculate the smoothness terms between the neighboring pixels,
1177                         // both in x and y direction.
1178                         {
1179                                 ScopedTimer timer("Compute smoothness", &varref_timer);
1180                                 compute_smoothness.exec(base_flow_tex, du_dv_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height);
1181                         }
1182
1183                         // Set up the 2x2 equation system for each pixel.
1184                         {
1185                                 ScopedTimer timer("Set up equations", &varref_timer);
1186                                 setup_equations.exec(I_x_y_tex, I_t_tex, du_dv_tex, base_flow_tex, beta_0_tex, smoothness_x_tex, smoothness_y_tex, equation_tex, level_width, level_height);
1187                         }
1188
1189                         // Run a few SOR (or quasi-SOR, since we're not really Jacobi) iterations.
1190                         // Note that these are to/from the same texture.
1191                         {
1192                                 ScopedTimer timer("SOR", &varref_timer);
1193                                 sor.exec(du_dv_tex, equation_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height, 5);
1194                         }
1195                 }
1196
1197                 pool.release_texture(I_t_tex);
1198                 pool.release_texture(I_x_y_tex);
1199                 pool.release_texture(beta_0_tex);
1200                 pool.release_texture(smoothness_x_tex);
1201                 pool.release_texture(smoothness_y_tex);
1202                 pool.release_texture(equation_tex);
1203
1204                 // Add the differential flow found by the variational refinement to the base flow,
1205                 // giving the final flow estimate for this level.
1206                 // The output is in diff_flow_tex; we don't need to make a new texture.
1207                 //
1208                 // Disabling this doesn't save any time (although we could easily make it so that
1209                 // it is more efficient), but it helps debug the motion search.
1210                 if (enable_variational_refinement) {
1211                         ScopedTimer timer("Add differential flow", &varref_timer);
1212                         add_base_flow.exec(base_flow_tex, du_dv_tex, level_width, level_height);
1213                 }
1214                 pool.release_texture(du_dv_tex);
1215
1216                 if (prev_level_flow_tex != initial_flow_tex) {
1217                         pool.release_texture(prev_level_flow_tex);
1218                 }
1219                 prev_level_flow_tex = base_flow_tex;
1220                 prev_level_width = level_width;
1221                 prev_level_height = level_height;
1222         }
1223         total_timer.end();
1224
1225         timers.print();
1226
1227         // Scale up the flow to the final size (if needed).
1228         if (finest_level == 0 || resize_strategy == DO_NOT_RESIZE_FLOW) {
1229                 return prev_level_flow_tex;
1230         } else {
1231                 GLuint final_tex = pool.get_texture(GL_RG16F, width, height);
1232                 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width, height);
1233                 pool.release_texture(prev_level_flow_tex);
1234                 return final_tex;
1235         }
1236 }
1237
1238 // Forward-warp the flow half-way (or rather, by alpha). A non-zero “splatting”
1239 // radius fills most of the holes.
1240 class Splat {
1241 public:
1242         Splat();
1243
1244         // alpha is the time of the interpolated frame (0..1).
1245         void exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint flow_tex, GLuint depth_tex, int width, int height, float alpha);
1246
1247 private:
1248         PersistentFBOSet<2> fbos;
1249
1250         GLuint splat_vs_obj;
1251         GLuint splat_fs_obj;
1252         GLuint splat_program;
1253         GLuint splat_vao;
1254
1255         GLuint uniform_invert_flow, uniform_splat_size, uniform_alpha;
1256         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
1257         GLuint uniform_inv_flow_size;
1258 };
1259
1260 Splat::Splat()
1261 {
1262         splat_vs_obj = compile_shader(read_file("splat.vert"), GL_VERTEX_SHADER);
1263         splat_fs_obj = compile_shader(read_file("splat.frag"), GL_FRAGMENT_SHADER);
1264         splat_program = link_program(splat_vs_obj, splat_fs_obj);
1265
1266         // Set up the VAO containing all the required position/texcoord data.
1267         glCreateVertexArrays(1, &splat_vao);
1268         glBindVertexArray(splat_vao);
1269         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1270
1271         GLint position_attrib = glGetAttribLocation(splat_program, "position");
1272         glEnableVertexArrayAttrib(splat_vao, position_attrib);
1273         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1274
1275         uniform_invert_flow = glGetUniformLocation(splat_program, "invert_flow");
1276         uniform_splat_size = glGetUniformLocation(splat_program, "splat_size");
1277         uniform_alpha = glGetUniformLocation(splat_program, "alpha");
1278         uniform_image0_tex = glGetUniformLocation(splat_program, "image0_tex");
1279         uniform_image1_tex = glGetUniformLocation(splat_program, "image1_tex");
1280         uniform_flow_tex = glGetUniformLocation(splat_program, "flow_tex");
1281         uniform_inv_flow_size = glGetUniformLocation(splat_program, "inv_flow_size");
1282 }
1283
1284 void Splat::exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint flow_tex, GLuint depth_tex, int width, int height, float alpha)
1285 {
1286         glUseProgram(splat_program);
1287
1288         bind_sampler(splat_program, uniform_image0_tex, 0, tex0, linear_sampler);
1289         bind_sampler(splat_program, uniform_image1_tex, 1, tex1, linear_sampler);
1290
1291         // FIXME: This is set to 1.0 right now so not to trigger Haswell's “PMA stall”.
1292         // Move to 2.0 later, or even 4.0.
1293         // (Since we have hole filling, it's not critical, but larger values seem to do
1294         // better than hole filling for large motion, blurs etc.)
1295         float splat_size = 1.0f;  // 4x4 splat means 16x overdraw, 2x2 splat means 4x overdraw.
1296         glProgramUniform2f(splat_program, uniform_splat_size, splat_size / width, splat_size / height);
1297         glProgramUniform1f(splat_program, uniform_alpha, alpha);
1298         glProgramUniform2f(splat_program, uniform_inv_flow_size, 1.0f / width, 1.0f / height);
1299
1300         glViewport(0, 0, width, height);
1301         glDisable(GL_BLEND);
1302         glEnable(GL_DEPTH_TEST);
1303         glDepthFunc(GL_LESS);  // We store the difference between I_0 and I_1, where less difference is good. (Default 1.0 is effectively +inf, which always loses.)
1304         glBindVertexArray(splat_vao);
1305
1306         // FIXME: Get this into FBOSet, so we can reuse FBOs across frames.
1307         GLuint fbo;
1308         glCreateFramebuffers(1, &fbo);
1309         glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0, flow_tex, 0);
1310         glNamedFramebufferTexture(fbo, GL_DEPTH_ATTACHMENT, depth_tex, 0);
1311         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1312
1313         // Do forward splatting.
1314         bind_sampler(splat_program, uniform_flow_tex, 2, forward_flow_tex, nearest_sampler);
1315         glProgramUniform1i(splat_program, uniform_invert_flow, 0);
1316         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height);
1317
1318         // Do backward splatting.
1319         bind_sampler(splat_program, uniform_flow_tex, 2, backward_flow_tex, nearest_sampler);
1320         glProgramUniform1i(splat_program, uniform_invert_flow, 1);
1321         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height);
1322
1323         glDisable(GL_DEPTH_TEST);
1324
1325         glDeleteFramebuffers(1, &fbo);
1326 }
1327
1328 // Doing good and fast hole-filling on a GPU is nontrivial. We choose an option
1329 // that's fairly simple (given that most holes are really small) and also hopefully
1330 // cheap should the holes not be so small. Conceptually, we look for the first
1331 // non-hole to the left of us (ie., shoot a ray until we hit something), then
1332 // the first non-hole to the right of us, then up and down, and then average them
1333 // all together. It's going to create “stars” if the holes are big, but OK, that's
1334 // a tradeoff.
1335 //
1336 // Our implementation here is efficient assuming that the hierarchical Z-buffer is
1337 // on even for shaders that do discard (this typically kills early Z, but hopefully
1338 // not hierarchical Z); we set up Z so that only holes are written to, which means
1339 // that as soon as a hole is filled, the rasterizer should just skip it. Most of the
1340 // fullscreen quads should just be discarded outright, really.
1341 class HoleFill {
1342 public:
1343         HoleFill();
1344
1345         // Output will be in flow_tex, temp_tex[0, 1, 2], representing the filling
1346         // from the down, left, right and up, respectively. Use HoleBlend to merge
1347         // them into one.
1348         void exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height);
1349
1350 private:
1351         PersistentFBOSet<2> fbos;
1352
1353         GLuint fill_vs_obj;
1354         GLuint fill_fs_obj;
1355         GLuint fill_program;
1356         GLuint fill_vao;
1357
1358         GLuint uniform_tex;
1359         GLuint uniform_z, uniform_sample_offset;
1360 };
1361
1362 HoleFill::HoleFill()
1363 {
1364         fill_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER);
1365         fill_fs_obj = compile_shader(read_file("hole_fill.frag"), GL_FRAGMENT_SHADER);
1366         fill_program = link_program(fill_vs_obj, fill_fs_obj);
1367
1368         // Set up the VAO containing all the required position/texcoord data.
1369         glCreateVertexArrays(1, &fill_vao);
1370         glBindVertexArray(fill_vao);
1371         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1372
1373         GLint position_attrib = glGetAttribLocation(fill_program, "position");
1374         glEnableVertexArrayAttrib(fill_vao, position_attrib);
1375         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1376
1377         uniform_tex = glGetUniformLocation(fill_program, "tex");
1378         uniform_z = glGetUniformLocation(fill_program, "z");
1379         uniform_sample_offset = glGetUniformLocation(fill_program, "sample_offset");
1380 }
1381
1382 void HoleFill::exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height)
1383 {
1384         glUseProgram(fill_program);
1385
1386         bind_sampler(fill_program, uniform_tex, 0, flow_tex, nearest_sampler);
1387
1388         glProgramUniform1f(fill_program, uniform_z, 1.0f - 1.0f / 1024.0f);
1389
1390         glViewport(0, 0, width, height);
1391         glDisable(GL_BLEND);
1392         glEnable(GL_DEPTH_TEST);
1393         glDepthFunc(GL_LESS);  // Only update the values > 0.999f (ie., only invalid pixels).
1394         glBindVertexArray(fill_vao);
1395
1396         // FIXME: Get this into FBOSet, so we can reuse FBOs across frames.
1397         GLuint fbo;
1398         glCreateFramebuffers(1, &fbo);
1399         glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0, flow_tex, 0);  // NOTE: Reading and writing to the same texture.
1400         glNamedFramebufferTexture(fbo, GL_DEPTH_ATTACHMENT, depth_tex, 0);
1401         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1402
1403         // Fill holes from the left, by shifting 1, 2, 4, 8, etc. pixels to the right.
1404         for (int offs = 1; offs < width; offs *= 2) {
1405                 glProgramUniform2f(fill_program, uniform_sample_offset, -offs / float(width), 0.0f);
1406                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1407                 glTextureBarrier();
1408         }
1409         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[0], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1410
1411         // Similar to the right; adjust Z a bit down, so that we re-fill the pixels that
1412         // were overwritten in the last algorithm.
1413         glProgramUniform1f(fill_program, uniform_z, 1.0f - 2.0f / 1024.0f);
1414         for (int offs = 1; offs < width; offs *= 2) {
1415                 glProgramUniform2f(fill_program, uniform_sample_offset, offs / float(width), 0.0f);
1416                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1417                 glTextureBarrier();
1418         }
1419         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[1], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1420
1421         // Up.
1422         glProgramUniform1f(fill_program, uniform_z, 1.0f - 3.0f / 1024.0f);
1423         for (int offs = 1; offs < height; offs *= 2) {
1424                 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, -offs / float(height));
1425                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1426                 glTextureBarrier();
1427         }
1428         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[2], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
1429
1430         // Down.
1431         glProgramUniform1f(fill_program, uniform_z, 1.0f - 4.0f / 1024.0f);
1432         for (int offs = 1; offs < height; offs *= 2) {
1433                 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, offs / float(height));
1434                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1435                 glTextureBarrier();
1436         }
1437
1438         glDisable(GL_DEPTH_TEST);
1439
1440         glDeleteFramebuffers(1, &fbo);
1441 }
1442
1443 // Blend the four directions from HoleFill into one pixel, so that single-pixel
1444 // holes become the average of their four neighbors.
1445 class HoleBlend {
1446 public:
1447         HoleBlend();
1448
1449         void exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height);
1450
1451 private:
1452         PersistentFBOSet<2> fbos;
1453
1454         GLuint blend_vs_obj;
1455         GLuint blend_fs_obj;
1456         GLuint blend_program;
1457         GLuint blend_vao;
1458
1459         GLuint uniform_left_tex, uniform_right_tex, uniform_up_tex, uniform_down_tex;
1460         GLuint uniform_z, uniform_sample_offset;
1461 };
1462
1463 HoleBlend::HoleBlend()
1464 {
1465         blend_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER);  // Reuse the vertex shader from the fill.
1466         blend_fs_obj = compile_shader(read_file("hole_blend.frag"), GL_FRAGMENT_SHADER);
1467         blend_program = link_program(blend_vs_obj, blend_fs_obj);
1468
1469         // Set up the VAO containing all the required position/texcoord data.
1470         glCreateVertexArrays(1, &blend_vao);
1471         glBindVertexArray(blend_vao);
1472         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1473
1474         GLint position_attrib = glGetAttribLocation(blend_program, "position");
1475         glEnableVertexArrayAttrib(blend_vao, position_attrib);
1476         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1477
1478         uniform_left_tex = glGetUniformLocation(blend_program, "left_tex");
1479         uniform_right_tex = glGetUniformLocation(blend_program, "right_tex");
1480         uniform_up_tex = glGetUniformLocation(blend_program, "up_tex");
1481         uniform_down_tex = glGetUniformLocation(blend_program, "down_tex");
1482         uniform_z = glGetUniformLocation(blend_program, "z");
1483         uniform_sample_offset = glGetUniformLocation(blend_program, "sample_offset");
1484 }
1485
1486 void HoleBlend::exec(GLuint flow_tex, GLuint depth_tex, GLuint temp_tex[3], int width, int height)
1487 {
1488         glUseProgram(blend_program);
1489
1490         bind_sampler(blend_program, uniform_left_tex, 0, temp_tex[0], nearest_sampler);
1491         bind_sampler(blend_program, uniform_right_tex, 1, temp_tex[1], nearest_sampler);
1492         bind_sampler(blend_program, uniform_up_tex, 2, temp_tex[2], nearest_sampler);
1493         bind_sampler(blend_program, uniform_down_tex, 3, flow_tex, nearest_sampler);
1494
1495         glProgramUniform1f(blend_program, uniform_z, 1.0f - 4.0f / 1024.0f);
1496         glProgramUniform2f(blend_program, uniform_sample_offset, 0.0f, 0.0f);
1497
1498         glViewport(0, 0, width, height);
1499         glDisable(GL_BLEND);
1500         glEnable(GL_DEPTH_TEST);
1501         glDepthFunc(GL_LEQUAL);  // Skip over all of the pixels that were never holes to begin with.
1502         glBindVertexArray(blend_vao);
1503
1504         // FIXME: Get this into FBOSet, so we can reuse FBOs across frames.
1505         GLuint fbo;
1506         glCreateFramebuffers(1, &fbo);
1507         glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0, flow_tex, 0);  // NOTE: Reading and writing to the same texture.
1508         glNamedFramebufferTexture(fbo, GL_DEPTH_ATTACHMENT, depth_tex, 0);
1509         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1510
1511         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1512
1513         glDisable(GL_DEPTH_TEST);
1514
1515         glDeleteFramebuffers(1, &fbo);
1516 }
1517
1518 class Blend {
1519 public:
1520         Blend();
1521         void exec(GLuint tex0, GLuint tex1, GLuint flow_tex, GLuint output_tex, int width, int height, float alpha);
1522
1523 private:
1524         PersistentFBOSet<1> fbos;
1525         GLuint blend_vs_obj;
1526         GLuint blend_fs_obj;
1527         GLuint blend_program;
1528         GLuint blend_vao;
1529
1530         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
1531         GLuint uniform_alpha, uniform_flow_consistency_tolerance;
1532 };
1533
1534 Blend::Blend()
1535 {
1536         blend_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
1537         blend_fs_obj = compile_shader(read_file("blend.frag"), GL_FRAGMENT_SHADER);
1538         blend_program = link_program(blend_vs_obj, blend_fs_obj);
1539
1540         // Set up the VAO containing all the required position/texcoord data.
1541         glCreateVertexArrays(1, &blend_vao);
1542         glBindVertexArray(blend_vao);
1543
1544         GLint position_attrib = glGetAttribLocation(blend_program, "position");
1545         glEnableVertexArrayAttrib(blend_vao, position_attrib);
1546         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1547
1548         uniform_image0_tex = glGetUniformLocation(blend_program, "image0_tex");
1549         uniform_image1_tex = glGetUniformLocation(blend_program, "image1_tex");
1550         uniform_flow_tex = glGetUniformLocation(blend_program, "flow_tex");
1551         uniform_alpha = glGetUniformLocation(blend_program, "alpha");
1552         uniform_flow_consistency_tolerance = glGetUniformLocation(blend_program, "flow_consistency_tolerance");
1553 }
1554
1555 void Blend::exec(GLuint tex0, GLuint tex1, GLuint flow_tex, GLuint output_tex, int level_width, int level_height, float alpha)
1556 {
1557         glUseProgram(blend_program);
1558         bind_sampler(blend_program, uniform_image0_tex, 0, tex0, linear_sampler);
1559         bind_sampler(blend_program, uniform_image1_tex, 1, tex1, linear_sampler);
1560         bind_sampler(blend_program, uniform_flow_tex, 2, flow_tex, linear_sampler);  // May be upsampled.
1561         glProgramUniform1f(blend_program, uniform_alpha, alpha);
1562         //glProgramUniform1f(blend_program, uniform_flow_consistency_tolerance, 1.0f / 
1563
1564         glViewport(0, 0, level_width, level_height);
1565         fbos.render_to(output_tex);
1566         glBindVertexArray(blend_vao);
1567         glUseProgram(blend_program);
1568         glDisable(GL_BLEND);  // A bit ironic, perhaps.
1569         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1570 }
1571
1572 class Interpolate {
1573 public:
1574         Interpolate(int width, int height, int flow_level);
1575
1576         // Returns a texture that must be released with release_texture()
1577         // after use. tex0 and tex1 must be RGBA8 textures with mipmaps
1578         // (unless flow_level == 0).
1579         GLuint exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint width, GLuint height, float alpha);
1580
1581         void release_texture(GLuint tex) {
1582                 pool.release_texture(tex);
1583         }
1584
1585 private:
1586         int width, height, flow_level;
1587         TexturePool pool;
1588         Splat splat;
1589         HoleFill hole_fill;
1590         HoleBlend hole_blend;
1591         Blend blend;
1592 };
1593
1594 Interpolate::Interpolate(int width, int height, int flow_level)
1595         : width(width), height(height), flow_level(flow_level) {}
1596
1597 GLuint Interpolate::exec(GLuint tex0, GLuint tex1, GLuint forward_flow_tex, GLuint backward_flow_tex, GLuint width, GLuint height, float alpha)
1598 {
1599         GPUTimers timers;
1600
1601         ScopedTimer total_timer("Total", &timers);
1602
1603         // Pick out the right level to test splatting results on.
1604         GLuint tex0_view, tex1_view;
1605         glGenTextures(1, &tex0_view);
1606         glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_RGBA8, flow_level, 1, 0, 1);
1607         glGenTextures(1, &tex1_view);
1608         glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_RGBA8, flow_level, 1, 0, 1);
1609
1610         int flow_width = width >> flow_level;
1611         int flow_height = height >> flow_level;
1612
1613         GLuint flow_tex = pool.get_texture(GL_RG16F, flow_width, flow_height);
1614         GLuint depth_tex = pool.get_texture(GL_DEPTH_COMPONENT32F, flow_width, flow_height);  // Used for ranking flows.
1615         {
1616                 ScopedTimer timer("Clear", &total_timer);
1617                 float invalid_flow[] = { 1000.0f, 1000.0f };
1618                 glClearTexImage(flow_tex, 0, GL_RG, GL_FLOAT, invalid_flow);
1619                 float infinity = 1.0f;
1620                 glClearTexImage(depth_tex, 0, GL_DEPTH_COMPONENT, GL_FLOAT, &infinity);
1621         }
1622
1623         {
1624                 ScopedTimer timer("Splat", &total_timer);
1625                 splat.exec(tex0_view, tex1_view, forward_flow_tex, backward_flow_tex, flow_tex, depth_tex, flow_width, flow_height, alpha);
1626         }
1627         glDeleteTextures(1, &tex0_view);
1628         glDeleteTextures(1, &tex1_view);
1629
1630         GLuint temp_tex[3];
1631         temp_tex[0] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1632         temp_tex[1] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1633         temp_tex[2] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1634
1635         {
1636                 ScopedTimer timer("Fill holes", &total_timer);
1637                 hole_fill.exec(flow_tex, depth_tex, temp_tex, flow_width, flow_height);
1638                 hole_blend.exec(flow_tex, depth_tex, temp_tex, flow_width, flow_height);
1639         }
1640
1641         pool.release_texture(temp_tex[0]);
1642         pool.release_texture(temp_tex[1]);
1643         pool.release_texture(temp_tex[2]);
1644         pool.release_texture(depth_tex);
1645
1646         GLuint output_tex = pool.get_texture(GL_RGBA8, width, height);
1647         {
1648                 ScopedTimer timer("Blend", &total_timer);
1649                 blend.exec(tex0, tex1, flow_tex, output_tex, width, height, alpha);
1650         }
1651         total_timer.end();
1652         timers.print();
1653
1654         return output_tex;
1655 }
1656
1657 GLuint TexturePool::get_texture(GLenum format, GLuint width, GLuint height)
1658 {
1659         for (Texture &tex : textures) {
1660                 if (!tex.in_use && tex.format == format &&
1661                     tex.width == width && tex.height == height) {
1662                         tex.in_use = true;
1663                         return tex.tex_num;
1664                 }
1665         }
1666
1667         Texture tex;
1668         glCreateTextures(GL_TEXTURE_2D, 1, &tex.tex_num);
1669         glTextureStorage2D(tex.tex_num, 1, format, width, height);
1670         tex.format = format;
1671         tex.width = width;
1672         tex.height = height;
1673         tex.in_use = true;
1674         textures.push_back(tex);
1675         return tex.tex_num;
1676 }
1677
1678 void TexturePool::release_texture(GLuint tex_num)
1679 {
1680         for (Texture &tex : textures) {
1681                 if (tex.tex_num == tex_num) {
1682                         assert(tex.in_use);
1683                         tex.in_use = false;
1684                         return;
1685                 }
1686         }
1687         assert(false);
1688 }
1689
1690 // OpenGL uses a bottom-left coordinate system, .flo files use a top-left coordinate system.
1691 void flip_coordinate_system(float *dense_flow, unsigned width, unsigned height)
1692 {
1693         for (unsigned i = 0; i < width * height; ++i) {
1694                 dense_flow[i * 2 + 1] = -dense_flow[i * 2 + 1];
1695         }
1696 }
1697
1698 // Not relevant for RGB.
1699 void flip_coordinate_system(uint8_t *dense_flow, unsigned width, unsigned height)
1700 {
1701 }
1702
1703 void write_flow(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1704 {
1705         FILE *flowfp = fopen(filename, "wb");
1706         fprintf(flowfp, "FEIH");
1707         fwrite(&width, 4, 1, flowfp);
1708         fwrite(&height, 4, 1, flowfp);
1709         for (unsigned y = 0; y < height; ++y) {
1710                 int yy = height - y - 1;
1711                 fwrite(&dense_flow[yy * width * 2], width * 2 * sizeof(float), 1, flowfp);
1712         }
1713         fclose(flowfp);
1714 }
1715
1716 // Not relevant for RGB.
1717 void write_flow(const char *filename, const uint8_t *dense_flow, unsigned width, unsigned height)
1718 {
1719         assert(false);
1720 }
1721
1722 void write_ppm(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1723 {
1724         FILE *fp = fopen(filename, "wb");
1725         fprintf(fp, "P6\n%d %d\n255\n", width, height);
1726         for (unsigned y = 0; y < unsigned(height); ++y) {
1727                 int yy = height - y - 1;
1728                 for (unsigned x = 0; x < unsigned(width); ++x) {
1729                         float du = dense_flow[(yy * width + x) * 2 + 0];
1730                         float dv = dense_flow[(yy * width + x) * 2 + 1];
1731
1732                         uint8_t r, g, b;
1733                         flow2rgb(du, dv, &r, &g, &b);
1734                         putc(r, fp);
1735                         putc(g, fp);
1736                         putc(b, fp);
1737                 }
1738         }
1739         fclose(fp);
1740 }
1741
1742 void write_ppm(const char *filename, const uint8_t *rgba, unsigned width, unsigned height)
1743 {
1744         unique_ptr<uint8_t[]> rgb_line(new uint8_t[width * 3 + 1]);
1745
1746         FILE *fp = fopen(filename, "wb");
1747         fprintf(fp, "P6\n%d %d\n255\n", width, height);
1748         for (unsigned y = 0; y < height; ++y) {
1749                 unsigned y2 = height - 1 - y;
1750                 for (size_t x = 0; x < width; ++x) {
1751                         memcpy(&rgb_line[x * 3], &rgba[(y2 * width + x) * 4], 4);
1752                 }
1753                 fwrite(rgb_line.get(), width * 3, 1, fp);
1754         }
1755         fclose(fp);
1756 }
1757
1758 struct FlowType {
1759         using type = float;
1760         static constexpr GLenum gl_format = GL_RG;
1761         static constexpr GLenum gl_type = GL_FLOAT;
1762         static constexpr int num_channels = 2;
1763 };
1764
1765 struct RGBAType {
1766         using type = uint8_t;
1767         static constexpr GLenum gl_format = GL_RGBA;
1768         static constexpr GLenum gl_type = GL_UNSIGNED_BYTE;
1769         static constexpr int num_channels = 4;
1770 };
1771
1772 template <class Type>
1773 void finish_one_read(GLuint width, GLuint height)
1774 {
1775         using T = typename Type::type;
1776         constexpr int bytes_per_pixel = Type::num_channels * sizeof(T);
1777
1778         assert(!reads_in_progress.empty());
1779         ReadInProgress read = reads_in_progress.front();
1780         reads_in_progress.pop_front();
1781
1782         unique_ptr<T[]> flow(new typename Type::type[width * height * Type::num_channels]);
1783         void *buf = glMapNamedBufferRange(read.pbo, 0, width * height * bytes_per_pixel, GL_MAP_READ_BIT);  // Blocks if the read isn't done yet.
1784         memcpy(flow.get(), buf, width * height * bytes_per_pixel);  // TODO: Unneeded for RGBType, since flip_coordinate_system() does nothing.:
1785         glUnmapNamedBuffer(read.pbo);
1786         spare_pbos.push(read.pbo);
1787
1788         flip_coordinate_system(flow.get(), width, height);
1789         if (!read.flow_filename.empty()) {
1790                 write_flow(read.flow_filename.c_str(), flow.get(), width, height);
1791                 fprintf(stderr, "%s %s -> %s\n", read.filename0.c_str(), read.filename1.c_str(), read.flow_filename.c_str());
1792         }
1793         if (!read.ppm_filename.empty()) {
1794                 write_ppm(read.ppm_filename.c_str(), flow.get(), width, height);
1795         }
1796 }
1797
1798 template <class Type>
1799 void schedule_read(GLuint tex, GLuint width, GLuint height, const char *filename0, const char *filename1, const char *flow_filename, const char *ppm_filename)
1800 {
1801         using T = typename Type::type;
1802         constexpr int bytes_per_pixel = Type::num_channels * sizeof(T);
1803
1804         if (spare_pbos.empty()) {
1805                 finish_one_read<Type>(width, height);
1806         }
1807         assert(!spare_pbos.empty());
1808         reads_in_progress.emplace_back(ReadInProgress{ spare_pbos.top(), filename0, filename1, flow_filename, ppm_filename });
1809         glBindBuffer(GL_PIXEL_PACK_BUFFER, spare_pbos.top());
1810         spare_pbos.pop();
1811         glGetTextureImage(tex, 0, Type::gl_format, Type::gl_type, width * height * bytes_per_pixel, nullptr);
1812         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
1813 }
1814
1815 void compute_flow_only(int argc, char **argv, int optind)
1816 {
1817         const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1818         const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1819         const char *flow_filename = argc >= (optind + 3) ? argv[optind + 2] : "flow.flo";
1820
1821         // Load pictures.
1822         unsigned width1, height1, width2, height2;
1823         GLuint tex0 = load_texture(filename0, &width1, &height1, WITHOUT_MIPMAPS);
1824         GLuint tex1 = load_texture(filename1, &width2, &height2, WITHOUT_MIPMAPS);
1825
1826         if (width1 != width2 || height1 != height2) {
1827                 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1828                         width1, height1, width2, height2);
1829                 exit(1);
1830         }
1831
1832         // Set up some PBOs to do asynchronous readback.
1833         GLuint pbos[5];
1834         glCreateBuffers(5, pbos);
1835         for (int i = 0; i < 5; ++i) {
1836                 glNamedBufferData(pbos[i], width1 * height1 * 2 * sizeof(float), nullptr, GL_STREAM_READ);
1837                 spare_pbos.push(pbos[i]);
1838         }
1839
1840         int levels = find_num_levels(width1, height1);
1841         GLuint tex0_gray, tex1_gray;
1842         glCreateTextures(GL_TEXTURE_2D, 1, &tex0_gray);
1843         glCreateTextures(GL_TEXTURE_2D, 1, &tex1_gray);
1844         glTextureStorage2D(tex0_gray, levels, GL_R8, width1, height1);
1845         glTextureStorage2D(tex1_gray, levels, GL_R8, width1, height1);
1846
1847         GrayscaleConversion gray;
1848         gray.exec(tex0, tex0_gray, width1, height1);
1849         glDeleteTextures(1, &tex0);
1850         glGenerateTextureMipmap(tex0_gray);
1851
1852         gray.exec(tex1, tex1_gray, width1, height1);
1853         glDeleteTextures(1, &tex1);
1854         glGenerateTextureMipmap(tex1_gray);
1855
1856         DISComputeFlow compute_flow(width1, height1);
1857         GLuint final_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1858
1859         schedule_read<FlowType>(final_tex, width1, height1, filename0, filename1, flow_filename, "flow.ppm");
1860         compute_flow.release_texture(final_tex);
1861
1862         // See if there are more flows on the command line (ie., more than three arguments),
1863         // and if so, process them.
1864         int num_flows = (argc - optind) / 3;
1865         for (int i = 1; i < num_flows; ++i) {
1866                 const char *filename0 = argv[optind + i * 3 + 0];
1867                 const char *filename1 = argv[optind + i * 3 + 1];
1868                 const char *flow_filename = argv[optind + i * 3 + 2];
1869                 GLuint width, height;
1870                 GLuint tex0 = load_texture(filename0, &width, &height, WITHOUT_MIPMAPS);
1871                 if (width != width1 || height != height1) {
1872                         fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1873                                 filename0, width, height, width1, height1);
1874                         exit(1);
1875                 }
1876                 gray.exec(tex0, tex0_gray, width, height);
1877                 glGenerateTextureMipmap(tex0_gray);
1878                 glDeleteTextures(1, &tex0);
1879
1880                 GLuint tex1 = load_texture(filename1, &width, &height, WITHOUT_MIPMAPS);
1881                 if (width != width1 || height != height1) {
1882                         fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1883                                 filename1, width, height, width1, height1);
1884                         exit(1);
1885                 }
1886                 gray.exec(tex1, tex1_gray, width, height);
1887                 glGenerateTextureMipmap(tex1_gray);
1888                 glDeleteTextures(1, &tex1);
1889
1890                 GLuint final_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1891
1892                 schedule_read<FlowType>(final_tex, width1, height1, filename0, filename1, flow_filename, "");
1893                 compute_flow.release_texture(final_tex);
1894         }
1895         glDeleteTextures(1, &tex0_gray);
1896         glDeleteTextures(1, &tex1_gray);
1897
1898         while (!reads_in_progress.empty()) {
1899                 finish_one_read<FlowType>(width1, height1);
1900         }
1901 }
1902
1903 // Interpolate images based on
1904 //
1905 //   Herbst, Seitz, Baker: “Occlusion Reasoning for Temporal Interpolation
1906 //   Using Optical Flow”
1907 //
1908 // or at least a reasonable subset thereof. Unfinished.
1909 void interpolate_image(int argc, char **argv, int optind)
1910 {
1911         const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1912         const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1913         //const char *out_filename = argc >= (optind + 3) ? argv[optind + 2] : "interpolated.png";
1914
1915         // Load pictures.
1916         unsigned width1, height1, width2, height2;
1917         GLuint tex0 = load_texture(filename0, &width1, &height1, WITH_MIPMAPS);
1918         GLuint tex1 = load_texture(filename1, &width2, &height2, WITH_MIPMAPS);
1919
1920         if (width1 != width2 || height1 != height2) {
1921                 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1922                         width1, height1, width2, height2);
1923                 exit(1);
1924         }
1925
1926         // Set up some PBOs to do asynchronous readback.
1927         GLuint pbos[5];
1928         glCreateBuffers(5, pbos);
1929         for (int i = 0; i < 5; ++i) {
1930                 glNamedBufferData(pbos[i], width1 * height1 * 4 * sizeof(uint8_t), nullptr, GL_STREAM_READ);
1931                 spare_pbos.push(pbos[i]);
1932         }
1933
1934         DISComputeFlow compute_flow(width1, height1);
1935         GrayscaleConversion gray;
1936         Interpolate interpolate(width1, height1, finest_level);
1937
1938         int levels = find_num_levels(width1, height1);
1939         GLuint tex0_gray, tex1_gray;
1940         glCreateTextures(GL_TEXTURE_2D, 1, &tex0_gray);
1941         glCreateTextures(GL_TEXTURE_2D, 1, &tex1_gray);
1942         glTextureStorage2D(tex0_gray, levels, GL_R8, width1, height1);
1943         glTextureStorage2D(tex1_gray, levels, GL_R8, width1, height1);
1944
1945         gray.exec(tex0, tex0_gray, width1, height1);
1946         glGenerateTextureMipmap(tex0_gray);
1947
1948         gray.exec(tex1, tex1_gray, width1, height1);
1949         glGenerateTextureMipmap(tex1_gray);
1950
1951         GLuint forward_flow_tex = compute_flow.exec(tex0_gray, tex1_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
1952         GLuint backward_flow_tex = compute_flow.exec(tex1_gray, tex0_gray, DISComputeFlow::DO_NOT_RESIZE_FLOW);
1953
1954         for (int frameno = 1; frameno < 60; ++frameno) {
1955                 char ppm_filename[256];
1956                 snprintf(ppm_filename, sizeof(ppm_filename), "interp%04d.ppm", frameno);
1957
1958                 float alpha = frameno / 60.0f;
1959                 GLuint interpolated_tex = interpolate.exec(tex0, tex1, forward_flow_tex, backward_flow_tex, width1, height1, alpha);
1960
1961                 schedule_read<RGBAType>(interpolated_tex, width1, height1, filename0, filename1, "", ppm_filename);
1962                 interpolate.release_texture(interpolated_tex);
1963         }
1964
1965         while (!reads_in_progress.empty()) {
1966                 finish_one_read<RGBAType>(width1, height1);
1967         }
1968 }
1969
1970 int main(int argc, char **argv)
1971 {
1972         static const option long_options[] = {
1973                 { "smoothness-relative-weight", required_argument, 0, 's' },  // alpha.
1974                 { "intensity-relative-weight", required_argument, 0, 'i' },  // delta.
1975                 { "gradient-relative-weight", required_argument, 0, 'g' },  // gamma.
1976                 { "disable-timing", no_argument, 0, 1000 },
1977                 { "ignore-variational-refinement", no_argument, 0, 1001 },  // Still calculates it, just doesn't apply it.
1978                 { "interpolate", no_argument, 0, 1002 }
1979         };
1980
1981         for ( ;; ) {
1982                 int option_index = 0;
1983                 int c = getopt_long(argc, argv, "s:i:g:", long_options, &option_index);
1984
1985                 if (c == -1) {
1986                         break;
1987                 }
1988                 switch (c) {
1989                 case 's':
1990                         vr_alpha = atof(optarg);
1991                         break;
1992                 case 'i':
1993                         vr_delta = atof(optarg);
1994                         break;
1995                 case 'g':
1996                         vr_gamma = atof(optarg);
1997                         break;
1998                 case 1000:
1999                         enable_timing = false;
2000                         break;
2001                 case 1001:
2002                         enable_variational_refinement = false;
2003                         break;
2004                 case 1002:
2005                         enable_interpolation = true;
2006                         break;
2007                 default:
2008                         fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
2009                         exit(1);
2010                 };
2011         }
2012
2013         if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
2014                 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
2015                 exit(1);
2016         }
2017         SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
2018         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
2019         SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
2020         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
2021
2022         SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
2023         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
2024         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
2025         // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
2026         window = SDL_CreateWindow("OpenGL window",
2027                 SDL_WINDOWPOS_UNDEFINED,
2028                 SDL_WINDOWPOS_UNDEFINED,
2029                 64, 64,
2030                 SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
2031         SDL_GLContext context = SDL_GL_CreateContext(window);
2032         assert(context != nullptr);
2033
2034         // FIXME: Should be part of DISComputeFlow (but needs to be initialized
2035         // before all the render passes).
2036         float vertices[] = {
2037                 0.0f, 1.0f,
2038                 0.0f, 0.0f,
2039                 1.0f, 1.0f,
2040                 1.0f, 0.0f,
2041         };
2042         glCreateBuffers(1, &vertex_vbo);
2043         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
2044         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
2045
2046         if (enable_interpolation) {
2047                 interpolate_image(argc, argv, optind);
2048         } else {
2049                 compute_flow_only(argc, argv, optind);
2050         }
2051 }