]> git.sesse.net Git - nageru/blob - flow.cpp
Start parametrizing the operating points for DIS.
[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 "flow.h"
19 #include "gpu_timers.h"
20 #include "util.h"
21
22 #include <algorithm>
23 #include <deque>
24 #include <memory>
25 #include <map>
26 #include <stack>
27 #include <vector>
28
29 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
30
31 using namespace std;
32
33 SDL_Window *window;
34
35 // Weighting constants for the different parts of the variational refinement.
36 // These don't correspond 1:1 to the values given in the DIS paper,
37 // since we have different normalizations and ranges in some cases.
38 // These are found through a simple grid search on some MPI-Sintel data,
39 // although the error (EPE) seems to be fairly insensitive to the precise values.
40 // Only the relative values matter, so we fix alpha (the smoothness constant)
41 // at unity and tweak the others.
42 static float vr_alpha = 1.0f, vr_delta = 0.25f, vr_gamma = 0.25f;
43
44 bool enable_timing = true;
45 bool detailed_timing = false;
46 bool enable_warmup = false;
47 bool in_warmup = false;
48 bool enable_variational_refinement = true;  // Just for debugging.
49 bool enable_interpolation = false;
50
51 // Some global OpenGL objects.
52 // TODO: These should really be part of DISComputeFlow.
53 GLuint nearest_sampler, linear_sampler, zero_border_sampler;
54 GLuint vertex_vbo;
55
56 // Structures for asynchronous readback. We assume everything is the same size (and GL_RG16F).
57 struct ReadInProgress {
58         GLuint pbo;
59         string filename0, filename1;
60         string flow_filename, ppm_filename;  // Either may be empty for no write.
61 };
62 stack<GLuint> spare_pbos;
63 deque<ReadInProgress> reads_in_progress;
64
65 int find_num_levels(int width, int height)
66 {
67         int levels = 1;
68         for (int w = width, h = height; w > 1 || h > 1; ) {
69                 w >>= 1;
70                 h >>= 1;
71                 ++levels;
72         }
73         return levels;
74 }
75
76 string read_file(const string &filename)
77 {
78         FILE *fp = fopen(filename.c_str(), "r");
79         if (fp == nullptr) {
80                 perror(filename.c_str());
81                 exit(1);
82         }
83
84         int ret = fseek(fp, 0, SEEK_END);
85         if (ret == -1) {
86                 perror("fseek(SEEK_END)");
87                 exit(1);
88         }
89
90         int size = ftell(fp);
91
92         ret = fseek(fp, 0, SEEK_SET);
93         if (ret == -1) {
94                 perror("fseek(SEEK_SET)");
95                 exit(1);
96         }
97
98         string str;
99         str.resize(size);
100         ret = fread(&str[0], size, 1, fp);
101         if (ret == -1) {
102                 perror("fread");
103                 exit(1);
104         }
105         if (ret == 0) {
106                 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
107                                 size, filename.c_str());
108                 exit(1);
109         }
110         fclose(fp);
111
112         return str;
113 }
114
115
116 GLuint compile_shader(const string &shader_src, GLenum type)
117 {
118         GLuint obj = glCreateShader(type);
119         const GLchar* source[] = { shader_src.data() };
120         const GLint length[] = { (GLint)shader_src.size() };
121         glShaderSource(obj, 1, source, length);
122         glCompileShader(obj);
123
124         GLchar info_log[4096];
125         GLsizei log_length = sizeof(info_log) - 1;
126         glGetShaderInfoLog(obj, log_length, &log_length, info_log);
127         info_log[log_length] = 0;
128         if (strlen(info_log) > 0) {
129                 fprintf(stderr, "Shader compile log: %s\n", info_log);
130         }
131
132         GLint status;
133         glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
134         if (status == GL_FALSE) {
135                 // Add some line numbers to easier identify compile errors.
136                 string src_with_lines = "/*   1 */ ";
137                 size_t lineno = 1;
138                 for (char ch : shader_src) {
139                         src_with_lines.push_back(ch);
140                         if (ch == '\n') {
141                                 char buf[32];
142                                 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
143                                 src_with_lines += buf;
144                         }
145                 }
146
147                 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
148                 exit(1);
149         }
150
151         return obj;
152 }
153
154 enum MipmapPolicy {
155         WITHOUT_MIPMAPS,
156         WITH_MIPMAPS
157 };
158
159 GLuint load_texture(const char *filename, unsigned *width_ret, unsigned *height_ret, MipmapPolicy mipmaps)
160 {
161         SDL_Surface *surf = IMG_Load(filename);
162         if (surf == nullptr) {
163                 fprintf(stderr, "IMG_Load(%s): %s\n", filename, IMG_GetError());
164                 exit(1);
165         }
166
167         // For whatever reason, SDL doesn't support converting to YUV surfaces
168         // nor grayscale, so we'll do it ourselves.
169         SDL_Surface *rgb_surf = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_RGBA32, /*flags=*/0);
170         if (rgb_surf == nullptr) {
171                 fprintf(stderr, "SDL_ConvertSurfaceFormat(%s): %s\n", filename, SDL_GetError());
172                 exit(1);
173         }
174
175         SDL_FreeSurface(surf);
176
177         unsigned width = rgb_surf->w, height = rgb_surf->h;
178         const uint8_t *sptr = (uint8_t *)rgb_surf->pixels;
179         unique_ptr<uint8_t[]> pix(new uint8_t[width * height * 4]);
180
181         // Extract the Y component, and convert to bottom-left origin.
182         for (unsigned y = 0; y < height; ++y) {
183                 unsigned y2 = height - 1 - y;
184                 memcpy(pix.get() + y * width * 4, sptr + y2 * rgb_surf->pitch, width * 4);
185         }
186         SDL_FreeSurface(rgb_surf);
187
188         int num_levels = (mipmaps == WITH_MIPMAPS) ? find_num_levels(width, height) : 1;
189
190         GLuint tex;
191         glCreateTextures(GL_TEXTURE_2D, 1, &tex);
192         glTextureStorage2D(tex, num_levels, GL_RGBA8, width, height);
193         glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pix.get());
194
195         if (mipmaps == WITH_MIPMAPS) {
196                 glGenerateTextureMipmap(tex);
197         }
198
199         *width_ret = width;
200         *height_ret = height;
201
202         return tex;
203 }
204
205 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
206 {
207         GLuint program = glCreateProgram();
208         glAttachShader(program, vs_obj);
209         glAttachShader(program, fs_obj);
210         glLinkProgram(program);
211         GLint success;
212         glGetProgramiv(program, GL_LINK_STATUS, &success);
213         if (success == GL_FALSE) {
214                 GLchar error_log[1024] = {0};
215                 glGetProgramInfoLog(program, 1024, nullptr, error_log);
216                 fprintf(stderr, "Error linking program: %s\n", error_log);
217                 exit(1);
218         }
219         return program;
220 }
221
222 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
223 {
224         if (location == -1) {
225                 return;
226         }
227
228         glBindTextureUnit(texture_unit, tex);
229         glBindSampler(texture_unit, sampler);
230         glProgramUniform1i(program, location, texture_unit);
231 }
232
233 template<size_t num_elements>
234 void PersistentFBOSet<num_elements>::render_to(const array<GLuint, num_elements> &textures)
235 {
236         auto it = fbos.find(textures);
237         if (it != fbos.end()) {
238                 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
239                 return;
240         }
241
242         GLuint fbo;
243         glCreateFramebuffers(1, &fbo);
244         GLenum bufs[num_elements];
245         for (size_t i = 0; i < num_elements; ++i) {
246                 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
247                 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
248         }
249         glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
250
251         fbos[textures] = fbo;
252         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
253 }
254
255 template<size_t num_elements>
256 void PersistentFBOSetWithDepth<num_elements>::render_to(GLuint depth_rb, const array<GLuint, num_elements> &textures)
257 {
258         auto key = make_pair(depth_rb, textures);
259
260         auto it = fbos.find(key);
261         if (it != fbos.end()) {
262                 glBindFramebuffer(GL_FRAMEBUFFER, it->second);
263                 return;
264         }
265
266         GLuint fbo;
267         glCreateFramebuffers(1, &fbo);
268         GLenum bufs[num_elements];
269         glNamedFramebufferRenderbuffer(fbo, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_rb);
270         for (size_t i = 0; i < num_elements; ++i) {
271                 glNamedFramebufferTexture(fbo, GL_COLOR_ATTACHMENT0 + i, textures[i], 0);
272                 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
273         }
274         glNamedFramebufferDrawBuffers(fbo, num_elements, bufs);
275
276         fbos[key] = fbo;
277         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
278 }
279
280 GrayscaleConversion::GrayscaleConversion()
281 {
282         gray_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
283         gray_fs_obj = compile_shader(read_file("gray.frag"), GL_FRAGMENT_SHADER);
284         gray_program = link_program(gray_vs_obj, gray_fs_obj);
285
286         // Set up the VAO containing all the required position/texcoord data.
287         glCreateVertexArrays(1, &gray_vao);
288         glBindVertexArray(gray_vao);
289
290         GLint position_attrib = glGetAttribLocation(gray_program, "position");
291         glEnableVertexArrayAttrib(gray_vao, position_attrib);
292         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
293
294         uniform_tex = glGetUniformLocation(gray_program, "tex");
295 }
296
297 void GrayscaleConversion::exec(GLint tex, GLint gray_tex, int width, int height, int num_layers)
298 {
299         glUseProgram(gray_program);
300         bind_sampler(gray_program, uniform_tex, 0, tex, nearest_sampler);
301
302         glViewport(0, 0, width, height);
303         fbos.render_to(gray_tex);
304         glBindVertexArray(gray_vao);
305         glDisable(GL_BLEND);
306         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
307 }
308
309 Sobel::Sobel()
310 {
311         sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
312         sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
313         sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
314
315         uniform_tex = glGetUniformLocation(sobel_program, "tex");
316 }
317
318 void Sobel::exec(GLint tex_view, GLint grad_tex, int level_width, int level_height, int num_layers)
319 {
320         glUseProgram(sobel_program);
321         bind_sampler(sobel_program, uniform_tex, 0, tex_view, nearest_sampler);
322
323         glViewport(0, 0, level_width, level_height);
324         fbos.render_to(grad_tex);
325         glDisable(GL_BLEND);
326         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
327 }
328
329 MotionSearch::MotionSearch()
330 {
331         motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
332         motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
333         motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
334
335         uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
336         uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
337         uniform_out_flow_size = glGetUniformLocation(motion_search_program, "out_flow_size");
338         uniform_image_tex = glGetUniformLocation(motion_search_program, "image_tex");
339         uniform_grad_tex = glGetUniformLocation(motion_search_program, "grad_tex");
340         uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
341 }
342
343 void MotionSearch::exec(GLuint tex_view, GLuint grad_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, int num_layers)
344 {
345         glUseProgram(motion_search_program);
346
347         bind_sampler(motion_search_program, uniform_image_tex, 0, tex_view, linear_sampler);
348         bind_sampler(motion_search_program, uniform_grad_tex, 1, grad_tex, nearest_sampler);
349         bind_sampler(motion_search_program, uniform_flow_tex, 2, flow_tex, linear_sampler);
350
351         glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
352         glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
353         glProgramUniform2f(motion_search_program, uniform_out_flow_size, width_patches, height_patches);
354
355         glViewport(0, 0, width_patches, height_patches);
356         fbos.render_to(flow_out_tex);
357         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
358 }
359
360 Densify::Densify(const OperatingPoint &op)
361         : op(op)
362 {
363         densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
364         densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
365         densify_program = link_program(densify_vs_obj, densify_fs_obj);
366
367         uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
368         uniform_image_tex = glGetUniformLocation(densify_program, "image_tex");
369         uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
370 }
371
372 void Densify::exec(GLuint tex_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches, int num_layers)
373 {
374         glUseProgram(densify_program);
375
376         bind_sampler(densify_program, uniform_image_tex, 0, tex_view, linear_sampler);
377         bind_sampler(densify_program, uniform_flow_tex, 1, flow_tex, nearest_sampler);
378
379         glProgramUniform2f(densify_program, uniform_patch_size,
380                 float(op.patch_size_pixels) / level_width,
381                 float(op.patch_size_pixels) / level_height);
382
383         glViewport(0, 0, level_width, level_height);
384         glEnable(GL_BLEND);
385         glBlendFunc(GL_ONE, GL_ONE);
386         fbos.render_to(dense_flow_tex);
387         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
388         glClear(GL_COLOR_BUFFER_BIT);
389         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches * num_layers);
390 }
391
392 Prewarp::Prewarp()
393 {
394         prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
395         prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
396         prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
397
398         uniform_image_tex = glGetUniformLocation(prewarp_program, "image_tex");
399         uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
400 }
401
402 void Prewarp::exec(GLuint tex_view, GLuint flow_tex, GLuint I_tex, GLuint I_t_tex, GLuint normalized_flow_tex, int level_width, int level_height, int num_layers)
403 {
404         glUseProgram(prewarp_program);
405
406         bind_sampler(prewarp_program, uniform_image_tex, 0, tex_view, linear_sampler);
407         bind_sampler(prewarp_program, uniform_flow_tex, 1, flow_tex, nearest_sampler);
408
409         glViewport(0, 0, level_width, level_height);
410         glDisable(GL_BLEND);
411         fbos.render_to(I_tex, I_t_tex, normalized_flow_tex);
412         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
413 }
414
415 Derivatives::Derivatives()
416 {
417         derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
418         derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
419         derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
420
421         uniform_tex = glGetUniformLocation(derivatives_program, "tex");
422 }
423
424 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height, int num_layers)
425 {
426         glUseProgram(derivatives_program);
427
428         bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
429
430         glViewport(0, 0, level_width, level_height);
431         glDisable(GL_BLEND);
432         fbos.render_to(I_x_y_tex, beta_0_tex);
433         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
434 }
435
436 ComputeDiffusivity::ComputeDiffusivity()
437 {
438         diffusivity_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
439         diffusivity_fs_obj = compile_shader(read_file("diffusivity.frag"), GL_FRAGMENT_SHADER);
440         diffusivity_program = link_program(diffusivity_vs_obj, diffusivity_fs_obj);
441
442         uniform_flow_tex = glGetUniformLocation(diffusivity_program, "flow_tex");
443         uniform_diff_flow_tex = glGetUniformLocation(diffusivity_program, "diff_flow_tex");
444         uniform_alpha = glGetUniformLocation(diffusivity_program, "alpha");
445         uniform_zero_diff_flow = glGetUniformLocation(diffusivity_program, "zero_diff_flow");
446 }
447
448 void ComputeDiffusivity::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint diffusivity_tex, int level_width, int level_height, bool zero_diff_flow, int num_layers)
449 {
450         glUseProgram(diffusivity_program);
451
452         bind_sampler(diffusivity_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
453         bind_sampler(diffusivity_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
454         glProgramUniform1f(diffusivity_program, uniform_alpha, vr_alpha);
455         glProgramUniform1i(diffusivity_program, uniform_zero_diff_flow, zero_diff_flow);
456
457         glViewport(0, 0, level_width, level_height);
458
459         glDisable(GL_BLEND);
460         fbos.render_to(diffusivity_tex);
461         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
462 }
463
464 SetupEquations::SetupEquations()
465 {
466         equations_vs_obj = compile_shader(read_file("equations.vert"), GL_VERTEX_SHADER);
467         equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
468         equations_program = link_program(equations_vs_obj, equations_fs_obj);
469
470         uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
471         uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
472         uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
473         uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
474         uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
475         uniform_diffusivity_tex = glGetUniformLocation(equations_program, "diffusivity_tex");
476         uniform_gamma = glGetUniformLocation(equations_program, "gamma");
477         uniform_delta = glGetUniformLocation(equations_program, "delta");
478         uniform_zero_diff_flow = glGetUniformLocation(equations_program, "zero_diff_flow");
479 }
480
481 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 diffusivity_tex, GLuint equation_red_tex, GLuint equation_black_tex, int level_width, int level_height, bool zero_diff_flow, int num_layers)
482 {
483         glUseProgram(equations_program);
484
485         bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
486         bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
487         bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
488         bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
489         bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
490         bind_sampler(equations_program, uniform_diffusivity_tex, 5, diffusivity_tex, zero_border_sampler);
491         glProgramUniform1f(equations_program, uniform_delta, vr_delta);
492         glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
493         glProgramUniform1i(equations_program, uniform_zero_diff_flow, zero_diff_flow);
494
495         glViewport(0, 0, (level_width + 1) / 2, level_height);
496         glDisable(GL_BLEND);
497         fbos.render_to(equation_red_tex, equation_black_tex);
498         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
499 }
500
501 SOR::SOR()
502 {
503         sor_vs_obj = compile_shader(read_file("sor.vert"), GL_VERTEX_SHADER);
504         sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
505         sor_program = link_program(sor_vs_obj, sor_fs_obj);
506
507         uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
508         uniform_equation_red_tex = glGetUniformLocation(sor_program, "equation_red_tex");
509         uniform_equation_black_tex = glGetUniformLocation(sor_program, "equation_black_tex");
510         uniform_diffusivity_tex = glGetUniformLocation(sor_program, "diffusivity_tex");
511         uniform_phase = glGetUniformLocation(sor_program, "phase");
512         uniform_num_nonzero_phases = glGetUniformLocation(sor_program, "num_nonzero_phases");
513 }
514
515 void SOR::exec(GLuint diff_flow_tex, GLuint equation_red_tex, GLuint equation_black_tex, GLuint diffusivity_tex, int level_width, int level_height, int num_iterations, bool zero_diff_flow, int num_layers, ScopedTimer *sor_timer)
516 {
517         glUseProgram(sor_program);
518
519         bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
520         bind_sampler(sor_program, uniform_diffusivity_tex, 1, diffusivity_tex, zero_border_sampler);
521         bind_sampler(sor_program, uniform_equation_red_tex, 2, equation_red_tex, nearest_sampler);
522         bind_sampler(sor_program, uniform_equation_black_tex, 3, equation_black_tex, nearest_sampler);
523
524         if (!zero_diff_flow) {
525                 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 2);
526         }
527
528         // NOTE: We bind to the texture we are rendering from, but we never write any value
529         // that we read in the same shader pass (we call discard for red values when we compute
530         // black, and vice versa), and we have barriers between the passes, so we're fine
531         // as per the spec.
532         glViewport(0, 0, level_width, level_height);
533         glDisable(GL_BLEND);
534         fbos.render_to(diff_flow_tex);
535
536         for (int i = 0; i < num_iterations; ++i) {
537                 {
538                         ScopedTimer timer("Red pass", sor_timer);
539                         if (zero_diff_flow && i == 0) {
540                                 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 0);
541                         }
542                         glProgramUniform1i(sor_program, uniform_phase, 0);
543                         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
544                         glTextureBarrier();
545                 }
546                 {
547                         ScopedTimer timer("Black pass", sor_timer);
548                         if (zero_diff_flow && i == 0) {
549                                 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 1);
550                         }
551                         glProgramUniform1i(sor_program, uniform_phase, 1);
552                         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
553                         if (zero_diff_flow && i == 0) {
554                                 glProgramUniform1i(sor_program, uniform_num_nonzero_phases, 2);
555                         }
556                         if (i != num_iterations - 1) {
557                                 glTextureBarrier();
558                         }
559                 }
560         }
561 }
562
563 AddBaseFlow::AddBaseFlow()
564 {
565         add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
566         add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
567         add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
568
569         uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
570 }
571
572 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height, int num_layers)
573 {
574         glUseProgram(add_flow_program);
575
576         bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
577
578         glViewport(0, 0, level_width, level_height);
579         glEnable(GL_BLEND);
580         glBlendFunc(GL_ONE, GL_ONE);
581         fbos.render_to(base_flow_tex);
582
583         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
584 }
585
586 ResizeFlow::ResizeFlow()
587 {
588         resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
589         resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
590         resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
591
592         uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
593         uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
594 }
595
596 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height, int num_layers)
597 {
598         glUseProgram(resize_flow_program);
599
600         bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
601
602         glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
603
604         glViewport(0, 0, output_width, output_height);
605         glDisable(GL_BLEND);
606         fbos.render_to(out_tex);
607
608         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, num_layers);
609 }
610
611 DISComputeFlow::DISComputeFlow(int width, int height, const OperatingPoint &op)
612         : width(width), height(height), op(op), densify(op)
613 {
614         // Make some samplers.
615         glCreateSamplers(1, &nearest_sampler);
616         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
617         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
618         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
619         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
620
621         glCreateSamplers(1, &linear_sampler);
622         glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
623         glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
624         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
625         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
626
627         // The smoothness is sampled so that once we get to a smoothness involving
628         // a value outside the border, the diffusivity between the two becomes zero.
629         // Similarly, gradients are zero outside the border, since the edge is taken
630         // to be constant.
631         glCreateSamplers(1, &zero_border_sampler);
632         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
633         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
634         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
635         glSamplerParameteri(zero_border_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
636         float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f };  // Note that zero alpha means we can also see whether we sampled outside the border or not.
637         glSamplerParameterfv(zero_border_sampler, GL_TEXTURE_BORDER_COLOR, zero);
638
639         // Initial flow is zero, 1x1.
640         glCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &initial_flow_tex);
641         glTextureStorage3D(initial_flow_tex, 1, GL_RG16F, 1, 1, 1);
642         glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
643
644         // Set up the vertex data that will be shared between all passes.
645         float vertices[] = {
646                 0.0f, 1.0f,
647                 0.0f, 0.0f,
648                 1.0f, 1.0f,
649                 1.0f, 0.0f,
650         };
651         glCreateBuffers(1, &vertex_vbo);
652         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
653
654         glCreateVertexArrays(1, &vao);
655         glBindVertexArray(vao);
656         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
657
658         GLint position_attrib = 0;  // Hard-coded in every vertex shader.
659         glEnableVertexArrayAttrib(vao, position_attrib);
660         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
661 }
662
663 GLuint DISComputeFlow::exec(GLuint tex, FlowDirection flow_direction, ResizeStrategy resize_strategy)
664 {
665         int num_layers = (flow_direction == FORWARD_AND_BACKWARD) ? 2 : 1;
666         int prev_level_width = 1, prev_level_height = 1;
667         GLuint prev_level_flow_tex = initial_flow_tex;
668
669         GPUTimers timers;
670
671         glBindVertexArray(vao);
672
673         ScopedTimer total_timer("Compute flow", &timers);
674         for (int level = op.coarsest_level; level >= int(op.finest_level); --level) {
675                 char timer_name[256];
676                 snprintf(timer_name, sizeof(timer_name), "Level %d (%d x %d)", level, width >> level, height >> level);
677                 ScopedTimer level_timer(timer_name, &total_timer);
678
679                 int level_width = width >> level;
680                 int level_height = height >> level;
681                 float patch_spacing_pixels = op.patch_size_pixels * (1.0f - op.patch_overlap_ratio);
682
683                 // Make sure we have patches at least every Nth pixel, e.g. for width=9
684                 // and patch_spacing=3 (the default), we put out patch centers in
685                 // x=0, x=3, x=6, x=9, which is four patches. The fragment shader will
686                 // lock all the centers to integer coordinates if needed.
687                 int width_patches = 1 + ceil(level_width / patch_spacing_pixels);
688                 int height_patches = 1 + ceil(level_height / patch_spacing_pixels);
689
690                 // Make sure we always read from the correct level; the chosen
691                 // mipmapping could otherwise be rather unpredictable, especially
692                 // during motion search.
693                 GLuint tex_view;
694                 glGenTextures(1, &tex_view);
695                 glTextureView(tex_view, GL_TEXTURE_2D_ARRAY, tex, GL_R8, level, 1, 0, 2);
696
697                 // Create a new texture to hold the gradients.
698                 GLuint grad_tex = pool.get_texture(GL_R32UI, level_width, level_height, num_layers);
699
700                 // Find the derivative.
701                 {
702                         ScopedTimer timer("Sobel", &level_timer);
703                         sobel.exec(tex_view, grad_tex, level_width, level_height, num_layers);
704                 }
705
706                 // Motion search to find the initial flow. We use the flow from the previous
707                 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
708
709                 // Create an output flow texture.
710                 GLuint flow_out_tex = pool.get_texture(GL_RGB16F, width_patches, height_patches, num_layers);
711
712                 // And draw.
713                 {
714                         ScopedTimer timer("Motion search", &level_timer);
715                         motion_search.exec(tex_view, grad_tex, prev_level_flow_tex, flow_out_tex, level_width, level_height, prev_level_width, prev_level_height, width_patches, height_patches, num_layers);
716                 }
717                 pool.release_texture(grad_tex);
718
719                 // Densification.
720
721                 // Set up an output texture (cleared in Densify).
722                 GLuint dense_flow_tex = pool.get_texture(GL_RGB16F, level_width, level_height, num_layers);
723
724                 // And draw.
725                 {
726                         ScopedTimer timer("Densification", &level_timer);
727                         densify.exec(tex_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches, num_layers);
728                 }
729                 pool.release_texture(flow_out_tex);
730
731                 // Everything below here in the loop belongs to variational refinement.
732                 ScopedTimer varref_timer("Variational refinement", &level_timer);
733
734                 // Prewarping; create I and I_t, and a normalized base flow (so we don't
735                 // have to normalize it over and over again, and also save some bandwidth).
736                 //
737                 // During the entire rest of the variational refinement, flow will be measured
738                 // in pixels, not 0..1 normalized OpenGL texture coordinates.
739                 // This is because variational refinement depends so heavily on derivatives,
740                 // which are measured in intensity levels per pixel.
741                 GLuint I_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
742                 GLuint I_t_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
743                 GLuint base_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height, num_layers);
744                 {
745                         ScopedTimer timer("Prewarping", &varref_timer);
746                         prewarp.exec(tex_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height, num_layers);
747                 }
748                 pool.release_texture(dense_flow_tex);
749                 glDeleteTextures(1, &tex_view);
750
751                 // Calculate I_x and I_y. We're only calculating first derivatives;
752                 // the others will be taken on-the-fly in order to sample from fewer
753                 // textures overall, since sampling from the L1 cache is cheap.
754                 // (TODO: Verify that this is indeed faster than making separate
755                 // double-derivative textures.)
756                 GLuint I_x_y_tex = pool.get_texture(GL_RG16F, level_width, level_height, num_layers);
757                 GLuint beta_0_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
758                 {
759                         ScopedTimer timer("First derivatives", &varref_timer);
760                         derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height, num_layers);
761                 }
762                 pool.release_texture(I_tex);
763
764                 // We need somewhere to store du and dv (the flow increment, relative
765                 // to the non-refined base flow u0 and v0). It's initially garbage,
766                 // but not read until we've written something sane to it.
767                 GLuint diff_flow_tex = pool.get_texture(GL_RG16F, level_width, level_height, num_layers);
768
769                 // And for diffusivity.
770                 GLuint diffusivity_tex = pool.get_texture(GL_R16F, level_width, level_height, num_layers);
771
772                 // And finally for the equation set. See SetupEquations for
773                 // the storage format.
774                 GLuint equation_red_tex = pool.get_texture(GL_RGBA32UI, (level_width + 1) / 2, level_height, num_layers);
775                 GLuint equation_black_tex = pool.get_texture(GL_RGBA32UI, (level_width + 1) / 2, level_height, num_layers);
776
777                 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
778                         // Calculate the diffusivity term for each pixel.
779                         {
780                                 ScopedTimer timer("Compute diffusivity", &varref_timer);
781                                 compute_diffusivity.exec(base_flow_tex, diff_flow_tex, diffusivity_tex, level_width, level_height, outer_idx == 0, num_layers);
782                         }
783
784                         // Set up the 2x2 equation system for each pixel.
785                         {
786                                 ScopedTimer timer("Set up equations", &varref_timer);
787                                 setup_equations.exec(I_x_y_tex, I_t_tex, diff_flow_tex, base_flow_tex, beta_0_tex, diffusivity_tex, equation_red_tex, equation_black_tex, level_width, level_height, outer_idx == 0, num_layers);
788                         }
789
790                         // Run a few SOR iterations. Note that these are to/from the same texture.
791                         {
792                                 ScopedTimer timer("SOR", &varref_timer);
793                                 sor.exec(diff_flow_tex, equation_red_tex, equation_black_tex, diffusivity_tex, level_width, level_height, 5, outer_idx == 0, num_layers, &timer);
794                         }
795                 }
796
797                 pool.release_texture(I_t_tex);
798                 pool.release_texture(I_x_y_tex);
799                 pool.release_texture(beta_0_tex);
800                 pool.release_texture(diffusivity_tex);
801                 pool.release_texture(equation_red_tex);
802                 pool.release_texture(equation_black_tex);
803
804                 // Add the differential flow found by the variational refinement to the base flow,
805                 // giving the final flow estimate for this level.
806                 // The output is in diff_flow_tex; we don't need to make a new texture.
807                 //
808                 // Disabling this doesn't save any time (although we could easily make it so that
809                 // it is more efficient), but it helps debug the motion search.
810                 if (op.variational_refinement) {
811                         ScopedTimer timer("Add differential flow", &varref_timer);
812                         add_base_flow.exec(base_flow_tex, diff_flow_tex, level_width, level_height, num_layers);
813                 }
814                 pool.release_texture(diff_flow_tex);
815
816                 if (prev_level_flow_tex != initial_flow_tex) {
817                         pool.release_texture(prev_level_flow_tex);
818                 }
819                 prev_level_flow_tex = base_flow_tex;
820                 prev_level_width = level_width;
821                 prev_level_height = level_height;
822         }
823         total_timer.end();
824
825         if (!in_warmup) {
826                 timers.print();
827         }
828
829         // Scale up the flow to the final size (if needed).
830         if (op.finest_level == 0 || resize_strategy == DO_NOT_RESIZE_FLOW) {
831                 return prev_level_flow_tex;
832         } else {
833                 GLuint final_tex = pool.get_texture(GL_RG16F, width, height, num_layers);
834                 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width, height, num_layers);
835                 pool.release_texture(prev_level_flow_tex);
836                 return final_tex;
837         }
838 }
839
840 Splat::Splat(const OperatingPoint &op)
841         : op(op)
842 {
843         splat_vs_obj = compile_shader(read_file("splat.vert"), GL_VERTEX_SHADER);
844         splat_fs_obj = compile_shader(read_file("splat.frag"), GL_FRAGMENT_SHADER);
845         splat_program = link_program(splat_vs_obj, splat_fs_obj);
846
847         uniform_splat_size = glGetUniformLocation(splat_program, "splat_size");
848         uniform_alpha = glGetUniformLocation(splat_program, "alpha");
849         uniform_image_tex = glGetUniformLocation(splat_program, "image_tex");
850         uniform_flow_tex = glGetUniformLocation(splat_program, "flow_tex");
851         uniform_inv_flow_size = glGetUniformLocation(splat_program, "inv_flow_size");
852 }
853
854 void Splat::exec(GLuint image_tex, GLuint bidirectional_flow_tex, GLuint flow_tex, GLuint depth_rb, int width, int height, float alpha)
855 {
856         glUseProgram(splat_program);
857
858         bind_sampler(splat_program, uniform_image_tex, 0, image_tex, linear_sampler);
859         bind_sampler(splat_program, uniform_flow_tex, 1, bidirectional_flow_tex, nearest_sampler);
860
861         glProgramUniform2f(splat_program, uniform_splat_size, op.splat_size / width, op.splat_size / height);
862         glProgramUniform1f(splat_program, uniform_alpha, alpha);
863         glProgramUniform2f(splat_program, uniform_inv_flow_size, 1.0f / width, 1.0f / height);
864
865         glViewport(0, 0, width, height);
866         glDisable(GL_BLEND);
867         glEnable(GL_DEPTH_TEST);
868         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.)
869
870         fbos.render_to(depth_rb, flow_tex);
871
872         // Evidently NVIDIA doesn't use fast clears for glClearTexImage, so clear now that
873         // we've got it bound.
874         glClearColor(1000.0f, 1000.0f, 0.0f, 1.0f);  // Invalid flow.
875         glClearDepth(1.0f);  // Effectively infinity.
876         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
877
878         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width * height * 2);
879
880         glDisable(GL_DEPTH_TEST);
881 }
882
883 HoleFill::HoleFill()
884 {
885         fill_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER);
886         fill_fs_obj = compile_shader(read_file("hole_fill.frag"), GL_FRAGMENT_SHADER);
887         fill_program = link_program(fill_vs_obj, fill_fs_obj);
888
889         uniform_tex = glGetUniformLocation(fill_program, "tex");
890         uniform_z = glGetUniformLocation(fill_program, "z");
891         uniform_sample_offset = glGetUniformLocation(fill_program, "sample_offset");
892 }
893
894 void HoleFill::exec(GLuint flow_tex, GLuint depth_rb, GLuint temp_tex[3], int width, int height)
895 {
896         glUseProgram(fill_program);
897
898         bind_sampler(fill_program, uniform_tex, 0, flow_tex, nearest_sampler);
899
900         glProgramUniform1f(fill_program, uniform_z, 1.0f - 1.0f / 1024.0f);
901
902         glViewport(0, 0, width, height);
903         glDisable(GL_BLEND);
904         glEnable(GL_DEPTH_TEST);
905         glDepthFunc(GL_LESS);  // Only update the values > 0.999f (ie., only invalid pixels).
906
907         fbos.render_to(depth_rb, flow_tex);  // NOTE: Reading and writing to the same texture.
908
909         // Fill holes from the left, by shifting 1, 2, 4, 8, etc. pixels to the right.
910         for (int offs = 1; offs < width; offs *= 2) {
911                 glProgramUniform2f(fill_program, uniform_sample_offset, -offs / float(width), 0.0f);
912                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
913                 glTextureBarrier();
914         }
915         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[0], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
916
917         // Similar to the right; adjust Z a bit down, so that we re-fill the pixels that
918         // were overwritten in the last algorithm.
919         glProgramUniform1f(fill_program, uniform_z, 1.0f - 2.0f / 1024.0f);
920         for (int offs = 1; offs < width; offs *= 2) {
921                 glProgramUniform2f(fill_program, uniform_sample_offset, offs / float(width), 0.0f);
922                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
923                 glTextureBarrier();
924         }
925         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[1], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
926
927         // Up.
928         glProgramUniform1f(fill_program, uniform_z, 1.0f - 3.0f / 1024.0f);
929         for (int offs = 1; offs < height; offs *= 2) {
930                 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, -offs / float(height));
931                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
932                 glTextureBarrier();
933         }
934         glCopyImageSubData(flow_tex, GL_TEXTURE_2D, 0, 0, 0, 0, temp_tex[2], GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1);
935
936         // Down.
937         glProgramUniform1f(fill_program, uniform_z, 1.0f - 4.0f / 1024.0f);
938         for (int offs = 1; offs < height; offs *= 2) {
939                 glProgramUniform2f(fill_program, uniform_sample_offset, 0.0f, offs / float(height));
940                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
941                 glTextureBarrier();
942         }
943
944         glDisable(GL_DEPTH_TEST);
945 }
946
947 HoleBlend::HoleBlend()
948 {
949         blend_vs_obj = compile_shader(read_file("hole_fill.vert"), GL_VERTEX_SHADER);  // Reuse the vertex shader from the fill.
950         blend_fs_obj = compile_shader(read_file("hole_blend.frag"), GL_FRAGMENT_SHADER);
951         blend_program = link_program(blend_vs_obj, blend_fs_obj);
952
953         uniform_left_tex = glGetUniformLocation(blend_program, "left_tex");
954         uniform_right_tex = glGetUniformLocation(blend_program, "right_tex");
955         uniform_up_tex = glGetUniformLocation(blend_program, "up_tex");
956         uniform_down_tex = glGetUniformLocation(blend_program, "down_tex");
957         uniform_z = glGetUniformLocation(blend_program, "z");
958         uniform_sample_offset = glGetUniformLocation(blend_program, "sample_offset");
959 }
960
961 void HoleBlend::exec(GLuint flow_tex, GLuint depth_rb, GLuint temp_tex[3], int width, int height)
962 {
963         glUseProgram(blend_program);
964
965         bind_sampler(blend_program, uniform_left_tex, 0, temp_tex[0], nearest_sampler);
966         bind_sampler(blend_program, uniform_right_tex, 1, temp_tex[1], nearest_sampler);
967         bind_sampler(blend_program, uniform_up_tex, 2, temp_tex[2], nearest_sampler);
968         bind_sampler(blend_program, uniform_down_tex, 3, flow_tex, nearest_sampler);
969
970         glProgramUniform1f(blend_program, uniform_z, 1.0f - 4.0f / 1024.0f);
971         glProgramUniform2f(blend_program, uniform_sample_offset, 0.0f, 0.0f);
972
973         glViewport(0, 0, width, height);
974         glDisable(GL_BLEND);
975         glEnable(GL_DEPTH_TEST);
976         glDepthFunc(GL_LEQUAL);  // Skip over all of the pixels that were never holes to begin with.
977
978         fbos.render_to(depth_rb, flow_tex);  // NOTE: Reading and writing to the same texture.
979
980         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
981
982         glDisable(GL_DEPTH_TEST);
983 }
984
985 Blend::Blend()
986 {
987         blend_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
988         blend_fs_obj = compile_shader(read_file("blend.frag"), GL_FRAGMENT_SHADER);
989         blend_program = link_program(blend_vs_obj, blend_fs_obj);
990
991         uniform_image_tex = glGetUniformLocation(blend_program, "image_tex");
992         uniform_flow_tex = glGetUniformLocation(blend_program, "flow_tex");
993         uniform_alpha = glGetUniformLocation(blend_program, "alpha");
994         uniform_flow_consistency_tolerance = glGetUniformLocation(blend_program, "flow_consistency_tolerance");
995 }
996
997 void Blend::exec(GLuint image_tex, GLuint flow_tex, GLuint output_tex, int level_width, int level_height, float alpha)
998 {
999         glUseProgram(blend_program);
1000         bind_sampler(blend_program, uniform_image_tex, 0, image_tex, linear_sampler);
1001         bind_sampler(blend_program, uniform_flow_tex, 1, flow_tex, linear_sampler);  // May be upsampled.
1002         glProgramUniform1f(blend_program, uniform_alpha, alpha);
1003
1004         glViewport(0, 0, level_width, level_height);
1005         fbos.render_to(output_tex);
1006         glDisable(GL_BLEND);  // A bit ironic, perhaps.
1007         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
1008 }
1009
1010 Interpolate::Interpolate(int width, int height, const OperatingPoint &op)
1011         : width(width), height(height), flow_level(op.finest_level), op(op), splat(op) {
1012         // Set up the vertex data that will be shared between all passes.
1013         float vertices[] = {
1014                 0.0f, 1.0f,
1015                 0.0f, 0.0f,
1016                 1.0f, 1.0f,
1017                 1.0f, 0.0f,
1018         };
1019         glCreateBuffers(1, &vertex_vbo);
1020         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
1021
1022         glCreateVertexArrays(1, &vao);
1023         glBindVertexArray(vao);
1024         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1025
1026         GLint position_attrib = 0;  // Hard-coded in every vertex shader.
1027         glEnableVertexArrayAttrib(vao, position_attrib);
1028         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
1029 }
1030
1031 GLuint Interpolate::exec(GLuint image_tex, GLuint bidirectional_flow_tex, GLuint width, GLuint height, float alpha)
1032 {
1033         GPUTimers timers;
1034
1035         ScopedTimer total_timer("Interpolate", &timers);
1036
1037         glBindVertexArray(vao);
1038
1039         // Pick out the right level to test splatting results on.
1040         GLuint tex_view;
1041         glGenTextures(1, &tex_view);
1042         glTextureView(tex_view, GL_TEXTURE_2D_ARRAY, image_tex, GL_RGBA8, flow_level, 1, 0, 2);
1043
1044         int flow_width = width >> flow_level;
1045         int flow_height = height >> flow_level;
1046
1047         GLuint flow_tex = pool.get_texture(GL_RG16F, flow_width, flow_height);
1048         GLuint depth_rb = pool.get_renderbuffer(GL_DEPTH_COMPONENT16, flow_width, flow_height);  // Used for ranking flows.
1049
1050         {
1051                 ScopedTimer timer("Splat", &total_timer);
1052                 splat.exec(tex_view, bidirectional_flow_tex, flow_tex, depth_rb, flow_width, flow_height, alpha);
1053         }
1054         glDeleteTextures(1, &tex_view);
1055
1056         GLuint temp_tex[3];
1057         temp_tex[0] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1058         temp_tex[1] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1059         temp_tex[2] = pool.get_texture(GL_RG16F, flow_width, flow_height);
1060
1061         {
1062                 ScopedTimer timer("Fill holes", &total_timer);
1063                 hole_fill.exec(flow_tex, depth_rb, temp_tex, flow_width, flow_height);
1064                 hole_blend.exec(flow_tex, depth_rb, temp_tex, flow_width, flow_height);
1065         }
1066
1067         pool.release_texture(temp_tex[0]);
1068         pool.release_texture(temp_tex[1]);
1069         pool.release_texture(temp_tex[2]);
1070         pool.release_renderbuffer(depth_rb);
1071
1072         GLuint output_tex = pool.get_texture(GL_RGBA8, width, height);
1073         {
1074                 ScopedTimer timer("Blend", &total_timer);
1075                 blend.exec(image_tex, flow_tex, output_tex, width, height, alpha);
1076         }
1077         pool.release_texture(flow_tex);
1078         total_timer.end();
1079         if (!in_warmup) {
1080                 timers.print();
1081         }
1082
1083         return output_tex;
1084 }
1085
1086 GLuint TexturePool::get_texture(GLenum format, GLuint width, GLuint height, GLuint num_layers)
1087 {
1088         for (Texture &tex : textures) {
1089                 if (!tex.in_use && !tex.is_renderbuffer && tex.format == format &&
1090                     tex.width == width && tex.height == height && tex.num_layers == num_layers) {
1091                         tex.in_use = true;
1092                         return tex.tex_num;
1093                 }
1094         }
1095
1096         Texture tex;
1097         if (num_layers == 0) {
1098                 glCreateTextures(GL_TEXTURE_2D, 1, &tex.tex_num);
1099                 glTextureStorage2D(tex.tex_num, 1, format, width, height);
1100         } else {
1101                 glCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &tex.tex_num);
1102                 glTextureStorage3D(tex.tex_num, 1, format, width, height, num_layers);
1103         }
1104         tex.format = format;
1105         tex.width = width;
1106         tex.height = height;
1107         tex.num_layers = num_layers;
1108         tex.in_use = true;
1109         tex.is_renderbuffer = false;
1110         textures.push_back(tex);
1111         return tex.tex_num;
1112 }
1113
1114 GLuint TexturePool::get_renderbuffer(GLenum format, GLuint width, GLuint height)
1115 {
1116         for (Texture &tex : textures) {
1117                 if (!tex.in_use && tex.is_renderbuffer && tex.format == format &&
1118                     tex.width == width && tex.height == height) {
1119                         tex.in_use = true;
1120                         return tex.tex_num;
1121                 }
1122         }
1123
1124         Texture tex;
1125         glCreateRenderbuffers(1, &tex.tex_num);
1126         glNamedRenderbufferStorage(tex.tex_num, format, width, height);
1127
1128         tex.format = format;
1129         tex.width = width;
1130         tex.height = height;
1131         tex.in_use = true;
1132         tex.is_renderbuffer = true;
1133         textures.push_back(tex);
1134         return tex.tex_num;
1135 }
1136
1137 void TexturePool::release_texture(GLuint tex_num)
1138 {
1139         for (Texture &tex : textures) {
1140                 if (!tex.is_renderbuffer && tex.tex_num == tex_num) {
1141                         assert(tex.in_use);
1142                         tex.in_use = false;
1143                         return;
1144                 }
1145         }
1146         assert(false);
1147 }
1148
1149 void TexturePool::release_renderbuffer(GLuint tex_num)
1150 {
1151         for (Texture &tex : textures) {
1152                 if (tex.is_renderbuffer && tex.tex_num == tex_num) {
1153                         assert(tex.in_use);
1154                         tex.in_use = false;
1155                         return;
1156                 }
1157         }
1158         //assert(false);
1159 }
1160
1161 // OpenGL uses a bottom-left coordinate system, .flo files use a top-left coordinate system.
1162 void flip_coordinate_system(float *dense_flow, unsigned width, unsigned height)
1163 {
1164         for (unsigned i = 0; i < width * height; ++i) {
1165                 dense_flow[i * 2 + 1] = -dense_flow[i * 2 + 1];
1166         }
1167 }
1168
1169 // Not relevant for RGB.
1170 void flip_coordinate_system(uint8_t *dense_flow, unsigned width, unsigned height)
1171 {
1172 }
1173
1174 void write_flow(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1175 {
1176         FILE *flowfp = fopen(filename, "wb");
1177         fprintf(flowfp, "FEIH");
1178         fwrite(&width, 4, 1, flowfp);
1179         fwrite(&height, 4, 1, flowfp);
1180         for (unsigned y = 0; y < height; ++y) {
1181                 int yy = height - y - 1;
1182                 fwrite(&dense_flow[yy * width * 2], width * 2 * sizeof(float), 1, flowfp);
1183         }
1184         fclose(flowfp);
1185 }
1186
1187 // Not relevant for RGB.
1188 void write_flow(const char *filename, const uint8_t *dense_flow, unsigned width, unsigned height)
1189 {
1190         assert(false);
1191 }
1192
1193 void write_ppm(const char *filename, const float *dense_flow, unsigned width, unsigned height)
1194 {
1195         FILE *fp = fopen(filename, "wb");
1196         fprintf(fp, "P6\n%d %d\n255\n", width, height);
1197         for (unsigned y = 0; y < unsigned(height); ++y) {
1198                 int yy = height - y - 1;
1199                 for (unsigned x = 0; x < unsigned(width); ++x) {
1200                         float du = dense_flow[(yy * width + x) * 2 + 0];
1201                         float dv = dense_flow[(yy * width + x) * 2 + 1];
1202
1203                         uint8_t r, g, b;
1204                         flow2rgb(du, dv, &r, &g, &b);
1205                         putc(r, fp);
1206                         putc(g, fp);
1207                         putc(b, fp);
1208                 }
1209         }
1210         fclose(fp);
1211 }
1212
1213 void write_ppm(const char *filename, const uint8_t *rgba, unsigned width, unsigned height)
1214 {
1215         unique_ptr<uint8_t[]> rgb_line(new uint8_t[width * 3 + 1]);
1216
1217         FILE *fp = fopen(filename, "wb");
1218         fprintf(fp, "P6\n%d %d\n255\n", width, height);
1219         for (unsigned y = 0; y < height; ++y) {
1220                 unsigned y2 = height - 1 - y;
1221                 for (size_t x = 0; x < width; ++x) {
1222                         memcpy(&rgb_line[x * 3], &rgba[(y2 * width + x) * 4], 4);
1223                 }
1224                 fwrite(rgb_line.get(), width * 3, 1, fp);
1225         }
1226         fclose(fp);
1227 }
1228
1229 struct FlowType {
1230         using type = float;
1231         static constexpr GLenum gl_format = GL_RG;
1232         static constexpr GLenum gl_type = GL_FLOAT;
1233         static constexpr int num_channels = 2;
1234 };
1235
1236 struct RGBAType {
1237         using type = uint8_t;
1238         static constexpr GLenum gl_format = GL_RGBA;
1239         static constexpr GLenum gl_type = GL_UNSIGNED_BYTE;
1240         static constexpr int num_channels = 4;
1241 };
1242
1243 template <class Type>
1244 void finish_one_read(GLuint width, GLuint height)
1245 {
1246         using T = typename Type::type;
1247         constexpr int bytes_per_pixel = Type::num_channels * sizeof(T);
1248
1249         assert(!reads_in_progress.empty());
1250         ReadInProgress read = reads_in_progress.front();
1251         reads_in_progress.pop_front();
1252
1253         unique_ptr<T[]> flow(new typename Type::type[width * height * Type::num_channels]);
1254         void *buf = glMapNamedBufferRange(read.pbo, 0, width * height * bytes_per_pixel, GL_MAP_READ_BIT);  // Blocks if the read isn't done yet.
1255         memcpy(flow.get(), buf, width * height * bytes_per_pixel);  // TODO: Unneeded for RGBType, since flip_coordinate_system() does nothing.:
1256         glUnmapNamedBuffer(read.pbo);
1257         spare_pbos.push(read.pbo);
1258
1259         flip_coordinate_system(flow.get(), width, height);
1260         if (!read.flow_filename.empty()) {
1261                 write_flow(read.flow_filename.c_str(), flow.get(), width, height);
1262                 fprintf(stderr, "%s %s -> %s\n", read.filename0.c_str(), read.filename1.c_str(), read.flow_filename.c_str());
1263         }
1264         if (!read.ppm_filename.empty()) {
1265                 write_ppm(read.ppm_filename.c_str(), flow.get(), width, height);
1266         }
1267 }
1268
1269 template <class Type>
1270 void schedule_read(GLuint tex, GLuint width, GLuint height, const char *filename0, const char *filename1, const char *flow_filename, const char *ppm_filename)
1271 {
1272         using T = typename Type::type;
1273         constexpr int bytes_per_pixel = Type::num_channels * sizeof(T);
1274
1275         if (spare_pbos.empty()) {
1276                 finish_one_read<Type>(width, height);
1277         }
1278         assert(!spare_pbos.empty());
1279         reads_in_progress.emplace_back(ReadInProgress{ spare_pbos.top(), filename0, filename1, flow_filename, ppm_filename });
1280         glBindBuffer(GL_PIXEL_PACK_BUFFER, spare_pbos.top());
1281         spare_pbos.pop();
1282         glGetTextureImage(tex, 0, Type::gl_format, Type::gl_type, width * height * bytes_per_pixel, nullptr);
1283         glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
1284 }
1285
1286 void compute_flow_only(int argc, char **argv, int optind)
1287 {
1288         const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1289         const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1290         const char *flow_filename = argc >= (optind + 3) ? argv[optind + 2] : "flow.flo";
1291
1292         // Load pictures.
1293         unsigned width1, height1, width2, height2;
1294         GLuint tex0 = load_texture(filename0, &width1, &height1, WITHOUT_MIPMAPS);
1295         GLuint tex1 = load_texture(filename1, &width2, &height2, WITHOUT_MIPMAPS);
1296
1297         if (width1 != width2 || height1 != height2) {
1298                 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1299                         width1, height1, width2, height2);
1300                 exit(1);
1301         }
1302
1303         // Move them into an array texture, since that's how the rest of the code
1304         // would like them.
1305         GLuint image_tex;
1306         glCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &image_tex);
1307         glTextureStorage3D(image_tex, 1, GL_RGBA8, width1, height1, 2);
1308         glCopyImageSubData(tex0, GL_TEXTURE_2D, 0, 0, 0, 0, image_tex, GL_TEXTURE_2D_ARRAY, 0, 0, 0, 0, width1, height1, 1);
1309         glCopyImageSubData(tex1, GL_TEXTURE_2D, 0, 0, 0, 0, image_tex, GL_TEXTURE_2D_ARRAY, 0, 0, 0, 1, width1, height1, 1);
1310         glDeleteTextures(1, &tex0);
1311         glDeleteTextures(1, &tex1);
1312
1313         // Set up some PBOs to do asynchronous readback.
1314         GLuint pbos[5];
1315         glCreateBuffers(5, pbos);
1316         for (int i = 0; i < 5; ++i) {
1317                 glNamedBufferData(pbos[i], width1 * height1 * 2 * 2 * sizeof(float), nullptr, GL_STREAM_READ);
1318                 spare_pbos.push(pbos[i]);
1319         }
1320
1321         int levels = find_num_levels(width1, height1);
1322
1323         GLuint tex_gray;
1324         glCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &tex_gray);
1325         glTextureStorage3D(tex_gray, levels, GL_R8, width1, height1, 2);
1326
1327         GrayscaleConversion gray;
1328         gray.exec(image_tex, tex_gray, width1, height1, /*num_layers=*/2);
1329         glGenerateTextureMipmap(tex_gray);
1330
1331         OperatingPoint op = operating_point3;
1332         if (!enable_variational_refinement) {
1333                 op.variational_refinement = false;
1334         }
1335         DISComputeFlow compute_flow(width1, height1, op);
1336
1337         if (enable_warmup) {
1338                 in_warmup = true;
1339                 for (int i = 0; i < 10; ++i) {
1340                         GLuint final_tex = compute_flow.exec(tex_gray, DISComputeFlow::FORWARD, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1341                         compute_flow.release_texture(final_tex);
1342                 }
1343                 in_warmup = false;
1344         }
1345
1346         GLuint final_tex = compute_flow.exec(tex_gray, DISComputeFlow::FORWARD, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1347         //GLuint final_tex = compute_flow.exec(tex_gray, DISComputeFlow::FORWARD_AND_BACKWARD, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1348
1349         schedule_read<FlowType>(final_tex, width1, height1, filename0, filename1, flow_filename, "flow.ppm");
1350         compute_flow.release_texture(final_tex);
1351
1352         // See if there are more flows on the command line (ie., more than three arguments),
1353         // and if so, process them.
1354         int num_flows = (argc - optind) / 3;
1355         for (int i = 1; i < num_flows; ++i) {
1356                 const char *filename0 = argv[optind + i * 3 + 0];
1357                 const char *filename1 = argv[optind + i * 3 + 1];
1358                 const char *flow_filename = argv[optind + i * 3 + 2];
1359                 GLuint width, height;
1360                 GLuint tex0 = load_texture(filename0, &width, &height, WITHOUT_MIPMAPS);
1361                 if (width != width1 || height != height1) {
1362                         fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1363                                 filename0, width, height, width1, height1);
1364                         exit(1);
1365                 }
1366                 glCopyImageSubData(tex0, GL_TEXTURE_2D, 0, 0, 0, 0, image_tex, GL_TEXTURE_2D_ARRAY, 0, 0, 0, 0, width1, height1, 1);
1367                 glDeleteTextures(1, &tex0);
1368
1369                 GLuint tex1 = load_texture(filename1, &width, &height, WITHOUT_MIPMAPS);
1370                 if (width != width1 || height != height1) {
1371                         fprintf(stderr, "%s: Image dimensions don't match (%dx%d versus %dx%d)\n",
1372                                 filename1, width, height, width1, height1);
1373                         exit(1);
1374                 }
1375                 glCopyImageSubData(tex1, GL_TEXTURE_2D, 0, 0, 0, 0, image_tex, GL_TEXTURE_2D_ARRAY, 0, 0, 0, 1, width1, height1, 1);
1376                 glDeleteTextures(1, &tex1);
1377
1378                 gray.exec(image_tex, tex_gray, width1, height1, /*num_layers=*/2);
1379                 glGenerateTextureMipmap(tex_gray);
1380
1381                 GLuint final_tex = compute_flow.exec(tex_gray, DISComputeFlow::FORWARD, DISComputeFlow::RESIZE_FLOW_TO_FULL_SIZE);
1382
1383                 schedule_read<FlowType>(final_tex, width1, height1, filename0, filename1, flow_filename, "");
1384                 compute_flow.release_texture(final_tex);
1385         }
1386         glDeleteTextures(1, &tex_gray);
1387
1388         while (!reads_in_progress.empty()) {
1389                 finish_one_read<FlowType>(width1, height1);
1390         }
1391 }
1392
1393 // Interpolate images based on
1394 //
1395 //   Herbst, Seitz, Baker: “Occlusion Reasoning for Temporal Interpolation
1396 //   Using Optical Flow”
1397 //
1398 // or at least a reasonable subset thereof. Unfinished.
1399 void interpolate_image(int argc, char **argv, int optind)
1400 {
1401         const char *filename0 = argc >= (optind + 1) ? argv[optind] : "test1499.png";
1402         const char *filename1 = argc >= (optind + 2) ? argv[optind + 1] : "test1500.png";
1403         //const char *out_filename = argc >= (optind + 3) ? argv[optind + 2] : "interpolated.png";
1404
1405         // Load pictures.
1406         unsigned width1, height1, width2, height2;
1407         GLuint tex0 = load_texture(filename0, &width1, &height1, WITH_MIPMAPS);
1408         GLuint tex1 = load_texture(filename1, &width2, &height2, WITH_MIPMAPS);
1409
1410         if (width1 != width2 || height1 != height2) {
1411                 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1412                         width1, height1, width2, height2);
1413                 exit(1);
1414         }
1415
1416         // Move them into an array texture, since that's how the rest of the code
1417         // would like them.
1418         int levels = find_num_levels(width1, height1);
1419         GLuint image_tex;
1420         glCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &image_tex);
1421         glTextureStorage3D(image_tex, levels, GL_RGBA8, width1, height1, 2);
1422         glCopyImageSubData(tex0, GL_TEXTURE_2D, 0, 0, 0, 0, image_tex, GL_TEXTURE_2D_ARRAY, 0, 0, 0, 0, width1, height1, 1);
1423         glCopyImageSubData(tex1, GL_TEXTURE_2D, 0, 0, 0, 0, image_tex, GL_TEXTURE_2D_ARRAY, 0, 0, 0, 1, width1, height1, 1);
1424         glDeleteTextures(1, &tex0);
1425         glDeleteTextures(1, &tex1);
1426         glGenerateTextureMipmap(image_tex);
1427
1428         // Set up some PBOs to do asynchronous readback.
1429         GLuint pbos[5];
1430         glCreateBuffers(5, pbos);
1431         for (int i = 0; i < 5; ++i) {
1432                 glNamedBufferData(pbos[i], width1 * height1 * 4 * sizeof(uint8_t), nullptr, GL_STREAM_READ);
1433                 spare_pbos.push(pbos[i]);
1434         }
1435
1436         OperatingPoint op = operating_point3;
1437         if (!enable_variational_refinement) {
1438                 op.variational_refinement = false;
1439         }
1440         DISComputeFlow compute_flow(width1, height1, op);
1441         GrayscaleConversion gray;
1442         Interpolate interpolate(width1, height1, op);
1443
1444         GLuint tex_gray;
1445         glCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &tex_gray);
1446         glTextureStorage3D(tex_gray, levels, GL_R8, width1, height1, 2);
1447         gray.exec(image_tex, tex_gray, width1, height1, /*num_layers=*/2);
1448         glGenerateTextureMipmap(tex_gray);
1449
1450         if (enable_warmup) {
1451                 in_warmup = true;
1452                 for (int i = 0; i < 10; ++i) {
1453                         GLuint bidirectional_flow_tex = compute_flow.exec(tex_gray, DISComputeFlow::FORWARD_AND_BACKWARD, DISComputeFlow::DO_NOT_RESIZE_FLOW);
1454                         GLuint interpolated_tex = interpolate.exec(image_tex, bidirectional_flow_tex, width1, height1, 0.5f);
1455                         compute_flow.release_texture(bidirectional_flow_tex);
1456                         interpolate.release_texture(interpolated_tex);
1457                 }
1458                 in_warmup = false;
1459         }
1460
1461         GLuint bidirectional_flow_tex = compute_flow.exec(tex_gray, DISComputeFlow::FORWARD_AND_BACKWARD, DISComputeFlow::DO_NOT_RESIZE_FLOW);
1462
1463         for (int frameno = 1; frameno < 60; ++frameno) {
1464                 char ppm_filename[256];
1465                 snprintf(ppm_filename, sizeof(ppm_filename), "interp%04d.ppm", frameno);
1466
1467                 float alpha = frameno / 60.0f;
1468                 GLuint interpolated_tex = interpolate.exec(image_tex, bidirectional_flow_tex, width1, height1, alpha);
1469
1470                 schedule_read<RGBAType>(interpolated_tex, width1, height1, filename0, filename1, "", ppm_filename);
1471                 interpolate.release_texture(interpolated_tex);
1472         }
1473
1474         while (!reads_in_progress.empty()) {
1475                 finish_one_read<RGBAType>(width1, height1);
1476         }
1477 }
1478
1479 int main(int argc, char **argv)
1480 {
1481         static const option long_options[] = {
1482                 { "smoothness-relative-weight", required_argument, 0, 's' },  // alpha.
1483                 { "intensity-relative-weight", required_argument, 0, 'i' },  // delta.
1484                 { "gradient-relative-weight", required_argument, 0, 'g' },  // gamma.
1485                 { "disable-timing", no_argument, 0, 1000 },
1486                 { "detailed-timing", no_argument, 0, 1003 },
1487                 { "ignore-variational-refinement", no_argument, 0, 1001 },  // Still calculates it, just doesn't apply it.
1488                 { "interpolate", no_argument, 0, 1002 },
1489                 { "warmup", no_argument, 0, 1004 }
1490         };
1491
1492         for ( ;; ) {
1493                 int option_index = 0;
1494                 int c = getopt_long(argc, argv, "s:i:g:", long_options, &option_index);
1495
1496                 if (c == -1) {
1497                         break;
1498                 }
1499                 switch (c) {
1500                 case 's':
1501                         vr_alpha = atof(optarg);
1502                         break;
1503                 case 'i':
1504                         vr_delta = atof(optarg);
1505                         break;
1506                 case 'g':
1507                         vr_gamma = atof(optarg);
1508                         break;
1509                 case 1000:
1510                         enable_timing = false;
1511                         break;
1512                 case 1001:
1513                         enable_variational_refinement = false;
1514                         break;
1515                 case 1002:
1516                         enable_interpolation = true;
1517                         break;
1518                 case 1003:
1519                         detailed_timing = true;
1520                         break;
1521                 case 1004:
1522                         enable_warmup = true;
1523                         break;
1524                 default:
1525                         fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
1526                         exit(1);
1527                 };
1528         }
1529
1530         if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
1531                 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
1532                 exit(1);
1533         }
1534         SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
1535         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
1536         SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
1537         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
1538
1539         SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
1540         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
1541         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
1542         // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
1543         window = SDL_CreateWindow("OpenGL window",
1544                 SDL_WINDOWPOS_UNDEFINED,
1545                 SDL_WINDOWPOS_UNDEFINED,
1546                 64, 64,
1547                 SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
1548         SDL_GLContext context = SDL_GL_CreateContext(window);
1549         assert(context != nullptr);
1550
1551         glDisable(GL_DITHER);
1552
1553         // FIXME: Should be part of DISComputeFlow (but needs to be initialized
1554         // before all the render passes).
1555         float vertices[] = {
1556                 0.0f, 1.0f,
1557                 0.0f, 0.0f,
1558                 1.0f, 1.0f,
1559                 1.0f, 0.0f,
1560         };
1561         glCreateBuffers(1, &vertex_vbo);
1562         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
1563         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1564
1565         if (enable_interpolation) {
1566                 interpolate_image(argc, argv, optind);
1567         } else {
1568                 compute_flow_only(argc, argv, optind);
1569         }
1570 }