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