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