]> git.sesse.net Git - nageru/blob - flow.cpp
Add in the relative weighting of the variational refinement terms.
[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 <stdio.h>
15 #include <unistd.h>
16
17 #include "util.h"
18
19 #include <algorithm>
20 #include <memory>
21 #include <vector>
22
23 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
24
25 using namespace std;
26
27 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
28 constexpr float patch_overlap_ratio = 0.75f;
29 constexpr unsigned coarsest_level = 5;
30 constexpr unsigned finest_level = 1;
31 constexpr unsigned patch_size_pixels = 12;
32
33 // Weighting constants for the different parts of the variational refinement.
34 // These don't correspond 1:1 to the values given in the DIS paper,
35 // since we have different normalizations and ranges in some cases.
36 float vr_gamma = 10.0f, vr_delta = 5.0f, vr_alpha = 10.0f;
37
38 // Some global OpenGL objects.
39 GLuint nearest_sampler, linear_sampler, smoothness_sampler;
40 GLuint vertex_vbo;
41
42 string read_file(const string &filename)
43 {
44         FILE *fp = fopen(filename.c_str(), "r");
45         if (fp == nullptr) {
46                 perror(filename.c_str());
47                 exit(1);
48         }
49
50         int ret = fseek(fp, 0, SEEK_END);
51         if (ret == -1) {
52                 perror("fseek(SEEK_END)");
53                 exit(1);
54         }
55
56         int size = ftell(fp);
57
58         ret = fseek(fp, 0, SEEK_SET);
59         if (ret == -1) {
60                 perror("fseek(SEEK_SET)");
61                 exit(1);
62         }
63
64         string str;
65         str.resize(size);
66         ret = fread(&str[0], size, 1, fp);
67         if (ret == -1) {
68                 perror("fread");
69                 exit(1);
70         }
71         if (ret == 0) {
72                 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
73                                 size, filename.c_str());
74                 exit(1);
75         }
76         fclose(fp);
77
78         return str;
79 }
80
81
82 GLuint compile_shader(const string &shader_src, GLenum type)
83 {
84         GLuint obj = glCreateShader(type);
85         const GLchar* source[] = { shader_src.data() };
86         const GLint length[] = { (GLint)shader_src.size() };
87         glShaderSource(obj, 1, source, length);
88         glCompileShader(obj);
89
90         GLchar info_log[4096];
91         GLsizei log_length = sizeof(info_log) - 1;
92         glGetShaderInfoLog(obj, log_length, &log_length, info_log);
93         info_log[log_length] = 0;
94         if (strlen(info_log) > 0) {
95                 fprintf(stderr, "Shader compile log: %s\n", info_log);
96         }
97
98         GLint status;
99         glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
100         if (status == GL_FALSE) {
101                 // Add some line numbers to easier identify compile errors.
102                 string src_with_lines = "/*   1 */ ";
103                 size_t lineno = 1;
104                 for (char ch : shader_src) {
105                         src_with_lines.push_back(ch);
106                         if (ch == '\n') {
107                                 char buf[32];
108                                 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
109                                 src_with_lines += buf;
110                         }
111                 }
112
113                 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
114                 exit(1);
115         }
116
117         return obj;
118 }
119
120 GLuint load_texture(const char *filename, unsigned *width_ret, unsigned *height_ret)
121 {
122         SDL_Surface *surf = IMG_Load(filename);
123         if (surf == nullptr) {
124                 fprintf(stderr, "IMG_Load(%s): %s\n", filename, IMG_GetError());
125                 exit(1);
126         }
127
128         // For whatever reason, SDL doesn't support converting to YUV surfaces
129         // nor grayscale, so we'll do it (slowly) ourselves.
130         SDL_Surface *rgb_surf = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_RGBA8888, /*flags=*/0);
131         if (rgb_surf == nullptr) {
132                 fprintf(stderr, "SDL_ConvertSurfaceFormat(%s): %s\n", filename, SDL_GetError());
133                 exit(1);
134         }
135
136         SDL_FreeSurface(surf);
137
138         unsigned width = rgb_surf->w, height = rgb_surf->h;
139         const uint8_t *sptr = (uint8_t *)rgb_surf->pixels;
140         unique_ptr<uint8_t[]> pix(new uint8_t[width * height]);
141
142         // Extract the Y component, and convert to bottom-left origin.
143         for (unsigned y = 0; y < height; ++y) {
144                 unsigned y2 = height - 1 - y;
145                 for (unsigned x = 0; x < width; ++x) {
146                         uint8_t r = sptr[(y2 * width + x) * 4 + 3];
147                         uint8_t g = sptr[(y2 * width + x) * 4 + 2];
148                         uint8_t b = sptr[(y2 * width + x) * 4 + 1];
149
150                         // Rec. 709.
151                         pix[y * width + x] = lrintf(r * 0.2126f + g * 0.7152f + b * 0.0722f);
152                 }
153         }
154         SDL_FreeSurface(rgb_surf);
155
156         int levels = 1;
157         for (int w = width, h = height; w > 1 || h > 1; ) {
158                 w >>= 1;
159                 h >>= 1;
160                 ++levels;
161         }
162
163         GLuint tex;
164         glCreateTextures(GL_TEXTURE_2D, 1, &tex);
165         glTextureStorage2D(tex, levels, GL_R8, width, height);
166         glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, pix.get());
167         glGenerateTextureMipmap(tex);
168
169         *width_ret = width;
170         *height_ret = height;
171
172         return tex;
173 }
174
175 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
176 {
177         GLuint program = glCreateProgram();
178         glAttachShader(program, vs_obj);
179         glAttachShader(program, fs_obj);
180         glLinkProgram(program);
181         GLint success;
182         glGetProgramiv(program, GL_LINK_STATUS, &success);
183         if (success == GL_FALSE) {
184                 GLchar error_log[1024] = {0};
185                 glGetProgramInfoLog(program, 1024, nullptr, error_log);
186                 fprintf(stderr, "Error linking program: %s\n", error_log);
187                 exit(1);
188         }
189         return program;
190 }
191
192 GLuint generate_vbo(GLint size, GLsizeiptr data_size, const GLvoid *data)
193 {
194         GLuint vbo;
195         glCreateBuffers(1, &vbo);
196         glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
197         glNamedBufferData(vbo, data_size, data, GL_STATIC_DRAW);
198         return vbo;
199 }
200
201 GLuint fill_vertex_attribute(GLuint vao, GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
202 {
203         int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
204         if (attrib == -1) {
205                 return -1;
206         }
207
208         GLuint vbo = generate_vbo(size, data_size, data);
209
210         glBindBuffer(GL_ARRAY_BUFFER, vbo);
211         glEnableVertexArrayAttrib(vao, attrib);
212         glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
213         glBindBuffer(GL_ARRAY_BUFFER, 0);
214
215         return vbo;
216 }
217
218 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
219 {
220         if (location == -1) {
221                 return;
222         }
223
224         glBindTextureUnit(texture_unit, tex);
225         glBindSampler(texture_unit, sampler);
226         glProgramUniform1i(program, location, texture_unit);
227 }
228
229 // Compute gradients in every point, used for the motion search.
230 // The DIS paper doesn't actually mention how these are computed,
231 // but seemingly, a 3x3 Sobel operator is used here (at least in
232 // later versions of the code), while a [1 -8 0 8 -1] kernel is
233 // used for all the derivatives in the variational refinement part
234 // (which borrows code from DeepFlow). This is inconsistent,
235 // but I guess we're better off with staying with the original
236 // decisions until we actually know having different ones would be better.
237 class Sobel {
238 public:
239         Sobel();
240         void exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height);
241
242 private:
243         GLuint sobel_vs_obj;
244         GLuint sobel_fs_obj;
245         GLuint sobel_program;
246         GLuint sobel_vao;
247
248         GLuint uniform_tex, uniform_image_size;
249 };
250
251 Sobel::Sobel()
252 {
253         sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
254         sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
255         sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
256
257         // Set up the VAO containing all the required position/texcoord data.
258         glCreateVertexArrays(1, &sobel_vao);
259         glBindVertexArray(sobel_vao);
260
261         GLint position_attrib = glGetAttribLocation(sobel_program, "position");
262         glEnableVertexArrayAttrib(sobel_vao, position_attrib);
263         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
264
265         uniform_tex = glGetUniformLocation(sobel_program, "tex");
266 }
267
268 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
269 {
270         glUseProgram(sobel_program);
271         glBindTextureUnit(0, tex0_view);
272         glBindSampler(0, nearest_sampler);
273         glProgramUniform1i(sobel_program, uniform_tex, 0);
274
275         GLuint grad0_fbo;  // TODO: cleanup
276         glCreateFramebuffers(1, &grad0_fbo);
277         glNamedFramebufferTexture(grad0_fbo, GL_COLOR_ATTACHMENT0, grad0_tex, 0);
278
279         glViewport(0, 0, level_width, level_height);
280         glBindFramebuffer(GL_FRAMEBUFFER, grad0_fbo);
281         glBindVertexArray(sobel_vao);
282         glUseProgram(sobel_program);
283         glDisable(GL_BLEND);
284         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
285 }
286
287 // Motion search to find the initial flow. See motion_search.frag for documentation.
288 class MotionSearch {
289 public:
290         MotionSearch();
291         void exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int prev_level_width, int prev_level_height, int width_patches, int height_patches);
292
293 private:
294         GLuint motion_vs_obj;
295         GLuint motion_fs_obj;
296         GLuint motion_search_program;
297         GLuint motion_search_vao;
298
299         GLuint uniform_image_size, uniform_inv_image_size, uniform_inv_prev_level_size;
300         GLuint uniform_image0_tex, uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
301 };
302
303 MotionSearch::MotionSearch()
304 {
305         motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
306         motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
307         motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
308
309         // Set up the VAO containing all the required position/texcoord data.
310         glCreateVertexArrays(1, &motion_search_vao);
311         glBindVertexArray(motion_search_vao);
312         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
313
314         GLint position_attrib = glGetAttribLocation(motion_search_program, "position");
315         glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
316         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
317
318         uniform_image_size = glGetUniformLocation(motion_search_program, "image_size");
319         uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
320         uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
321         uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
322         uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
323         uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
324         uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
325 }
326
327 void MotionSearch::exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int prev_level_width, int prev_level_height, int width_patches, int height_patches)
328 {
329         glUseProgram(motion_search_program);
330
331         bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
332         bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
333         bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, nearest_sampler);
334         bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
335
336         glProgramUniform2f(motion_search_program, uniform_image_size, level_width, level_height);
337         glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
338         glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
339
340         GLuint flow_fbo;  // TODO: cleanup
341         glCreateFramebuffers(1, &flow_fbo);
342         glNamedFramebufferTexture(flow_fbo, GL_COLOR_ATTACHMENT0, flow_out_tex, 0);
343
344         glViewport(0, 0, width_patches, height_patches);
345         glBindFramebuffer(GL_FRAMEBUFFER, flow_fbo);
346         glBindVertexArray(motion_search_vao);
347         glUseProgram(motion_search_program);
348         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
349 }
350
351 // Do “densification”, ie., upsampling of the flow patches to the flow field
352 // (the same size as the image at this level). We draw one quad per patch
353 // over its entire covered area (using instancing in the vertex shader),
354 // and then weight the contributions in the pixel shader by post-warp difference.
355 // This is equation (3) in the paper.
356 //
357 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
358 // weight in the B channel. Dividing R and G by B gives the normalized values.
359 class Densify {
360 public:
361         Densify();
362         void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches);
363
364 private:
365         GLuint densify_vs_obj;
366         GLuint densify_fs_obj;
367         GLuint densify_program;
368         GLuint densify_vao;
369
370         GLuint uniform_width_patches, uniform_patch_size, uniform_patch_spacing;
371         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
372 };
373
374 Densify::Densify()
375 {
376         densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
377         densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
378         densify_program = link_program(densify_vs_obj, densify_fs_obj);
379
380         // Set up the VAO containing all the required position/texcoord data.
381         glCreateVertexArrays(1, &densify_vao);
382         glBindVertexArray(densify_vao);
383         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
384
385         GLint position_attrib = glGetAttribLocation(densify_program, "position");
386         glEnableVertexArrayAttrib(densify_vao, position_attrib);
387         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
388
389         uniform_width_patches = glGetUniformLocation(densify_program, "width_patches");
390         uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
391         uniform_patch_spacing = glGetUniformLocation(densify_program, "patch_spacing");
392         uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
393         uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
394         uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
395 }
396
397 void Densify::exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint dense_flow_tex, int level_width, int level_height, int width_patches, int height_patches)
398 {
399         glUseProgram(densify_program);
400
401         bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
402         bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
403         bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
404
405         glProgramUniform1i(densify_program, uniform_width_patches, width_patches);
406         glProgramUniform2f(densify_program, uniform_patch_size,
407                 float(patch_size_pixels) / level_width,
408                 float(patch_size_pixels) / level_height);
409
410         float patch_spacing_x = float(level_width - patch_size_pixels) / (width_patches - 1);
411         float patch_spacing_y = float(level_height - patch_size_pixels) / (height_patches - 1);
412         if (width_patches == 1) patch_spacing_x = 0.0f;  // Avoid infinities.
413         if (height_patches == 1) patch_spacing_y = 0.0f;
414         glProgramUniform2f(densify_program, uniform_patch_spacing,
415                 patch_spacing_x / level_width,
416                 patch_spacing_y / level_height);
417
418         GLuint dense_flow_fbo;  // TODO: cleanup
419         glCreateFramebuffers(1, &dense_flow_fbo);
420         glNamedFramebufferTexture(dense_flow_fbo, GL_COLOR_ATTACHMENT0, dense_flow_tex, 0);
421
422         glViewport(0, 0, level_width, level_height);
423         glEnable(GL_BLEND);
424         glBlendFunc(GL_ONE, GL_ONE);
425         glBindVertexArray(densify_vao);
426         glBindFramebuffer(GL_FRAMEBUFFER, dense_flow_fbo);
427         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
428 }
429
430 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
431 // I_0 and I_w. The prewarping is what enables us to solve the variational
432 // flow for du,dv instead of u,v.
433 //
434 // Also calculates the normalized flow, ie. divides by z (this is needed because
435 // Densify works by additive blending) and multiplies by the image size.
436 //
437 // See variational_refinement.txt for more information.
438 class Prewarp {
439 public:
440         Prewarp();
441         void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint normalized_flow_tex, GLuint I_tex, GLuint I_t_tex, int level_width, int level_height);
442
443 private:
444         GLuint prewarp_vs_obj;
445         GLuint prewarp_fs_obj;
446         GLuint prewarp_program;
447         GLuint prewarp_vao;
448
449         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
450         GLuint uniform_image_size;
451 };
452
453 Prewarp::Prewarp()
454 {
455         prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
456         prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
457         prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
458
459         // Set up the VAO containing all the required position/texcoord data.
460         glCreateVertexArrays(1, &prewarp_vao);
461         glBindVertexArray(prewarp_vao);
462         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
463
464         GLint position_attrib = glGetAttribLocation(prewarp_program, "position");
465         glEnableVertexArrayAttrib(prewarp_vao, position_attrib);
466         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
467
468         uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
469         uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
470         uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
471
472         uniform_image_size = glGetUniformLocation(prewarp_program, "image_size");
473 }
474
475 void Prewarp::exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint I_tex, GLuint I_t_tex, GLuint normalized_flow_tex, int level_width, int level_height)
476 {
477         glUseProgram(prewarp_program);
478
479         bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
480         bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
481         bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
482
483         glProgramUniform2f(prewarp_program, uniform_image_size, level_width, level_height);
484
485         GLuint prewarp_fbo;  // TODO: cleanup
486         glCreateFramebuffers(1, &prewarp_fbo);
487         GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
488         glNamedFramebufferDrawBuffers(prewarp_fbo, 3, bufs);
489         glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT0, I_tex, 0);
490         glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT1, I_t_tex, 0);
491         glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT2, normalized_flow_tex, 0);
492
493         glViewport(0, 0, level_width, level_height);
494         glDisable(GL_BLEND);
495         glBindVertexArray(prewarp_vao);
496         glBindFramebuffer(GL_FRAMEBUFFER, prewarp_fbo);
497         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
498 }
499
500 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
501 // central difference filter, since apparently, that's tradition (I haven't
502 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
503 // The coefficients come from
504 //
505 //   https://en.wikipedia.org/wiki/Finite_difference_coefficient
506 //
507 // Also computes β_0, since it depends only on I_x and I_y.
508 class Derivatives {
509 public:
510         Derivatives();
511         void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
512
513 private:
514         GLuint derivatives_vs_obj;
515         GLuint derivatives_fs_obj;
516         GLuint derivatives_program;
517         GLuint derivatives_vao;
518
519         GLuint uniform_tex;
520 };
521
522 Derivatives::Derivatives()
523 {
524         derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
525         derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
526         derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
527
528         // Set up the VAO containing all the required position/texcoord data.
529         glCreateVertexArrays(1, &derivatives_vao);
530         glBindVertexArray(derivatives_vao);
531         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
532
533         GLint position_attrib = glGetAttribLocation(derivatives_program, "position");
534         glEnableVertexArrayAttrib(derivatives_vao, position_attrib);
535         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
536
537         uniform_tex = glGetUniformLocation(derivatives_program, "tex");
538 }
539
540 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
541 {
542         glUseProgram(derivatives_program);
543
544         bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
545
546         GLuint derivatives_fbo;  // TODO: cleanup
547         glCreateFramebuffers(1, &derivatives_fbo);
548         GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
549         glNamedFramebufferDrawBuffers(derivatives_fbo, 2, bufs);
550         glNamedFramebufferTexture(derivatives_fbo, GL_COLOR_ATTACHMENT0, I_x_y_tex, 0);
551         glNamedFramebufferTexture(derivatives_fbo, GL_COLOR_ATTACHMENT1, beta_0_tex, 0);
552
553         glViewport(0, 0, level_width, level_height);
554         glDisable(GL_BLEND);
555         glBindVertexArray(derivatives_vao);
556         glBindFramebuffer(GL_FRAMEBUFFER, derivatives_fbo);
557         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
558 }
559
560 // Calculate the smoothness constraints between neighboring pixels;
561 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
562 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
563 // border color (0,0) later, so that there's zero diffusion out of
564 // the border.
565 //
566 // See variational_refinement.txt for more information.
567 class ComputeSmoothness {
568 public:
569         ComputeSmoothness();
570         void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height);
571
572 private:
573         GLuint smoothness_vs_obj;
574         GLuint smoothness_fs_obj;
575         GLuint smoothness_program;
576         GLuint smoothness_vao;
577
578         GLuint uniform_flow_tex, uniform_diff_flow_tex;
579         GLuint uniform_alpha;
580 };
581
582 ComputeSmoothness::ComputeSmoothness()
583 {
584         smoothness_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
585         smoothness_fs_obj = compile_shader(read_file("smoothness.frag"), GL_FRAGMENT_SHADER);
586         smoothness_program = link_program(smoothness_vs_obj, smoothness_fs_obj);
587
588         // Set up the VAO containing all the required position/texcoord data.
589         glCreateVertexArrays(1, &smoothness_vao);
590         glBindVertexArray(smoothness_vao);
591         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
592
593         GLint position_attrib = glGetAttribLocation(smoothness_program, "position");
594         glEnableVertexArrayAttrib(smoothness_vao, position_attrib);
595         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
596
597         uniform_flow_tex = glGetUniformLocation(smoothness_program, "flow_tex");
598         uniform_diff_flow_tex = glGetUniformLocation(smoothness_program, "diff_flow_tex");
599         uniform_alpha = glGetUniformLocation(smoothness_program, "alpha");
600 }
601
602 void ComputeSmoothness::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height)
603 {
604         glUseProgram(smoothness_program);
605
606         bind_sampler(smoothness_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
607         bind_sampler(smoothness_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
608         glProgramUniform1f(smoothness_program, uniform_alpha, vr_alpha);
609
610         GLuint smoothness_fbo;  // TODO: cleanup
611         glCreateFramebuffers(1, &smoothness_fbo);
612         GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
613         glNamedFramebufferDrawBuffers(smoothness_fbo, 2, bufs);
614         glNamedFramebufferTexture(smoothness_fbo, GL_COLOR_ATTACHMENT0, smoothness_x_tex, 0);
615         glNamedFramebufferTexture(smoothness_fbo, GL_COLOR_ATTACHMENT1, smoothness_y_tex, 0);
616
617         glViewport(0, 0, level_width, level_height);
618
619         glDisable(GL_BLEND);
620         glBindVertexArray(smoothness_vao);
621         glBindFramebuffer(GL_FRAMEBUFFER, smoothness_fbo);
622         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
623
624         // Make sure the smoothness on the right and upper borders is zero.
625         // We could have done this by making (W-1)xH and Wx(H-1) textures instead
626         // (we're sampling smoothness with all-zero border color), but we'd
627         // have to adjust the sampling coordinates, which is annoying.
628         glClearTexSubImage(smoothness_x_tex, 0,  level_width - 1, 0, 0,   1, level_height, 1,  GL_RED, GL_FLOAT, nullptr);
629         glClearTexSubImage(smoothness_y_tex, 0,  0, level_height - 1, 0,  level_width, 1, 1,   GL_RED, GL_FLOAT, nullptr);
630 }
631
632 // Set up the equations set (two equations in two unknowns, per pixel).
633 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
634 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
635 // floats. (Actually, we store the inverse of the diagonal elements, because
636 // we only ever need to divide by them.) This fits into four u32 values;
637 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
638 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
639 // terms that depend on other pixels, are calculated in one pass.
640 //
641 // See variational_refinement.txt for more information.
642 class SetupEquations {
643 public:
644         SetupEquations();
645         void exec(GLuint I_x_y_tex, GLuint I_t_tex, GLuint diff_flow_tex, GLuint flow_tex, GLuint beta_0_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, GLuint equation_tex, int level_width, int level_height);
646
647 private:
648         GLuint equations_vs_obj;
649         GLuint equations_fs_obj;
650         GLuint equations_program;
651         GLuint equations_vao;
652
653         GLuint uniform_I_x_y_tex, uniform_I_t_tex;
654         GLuint uniform_diff_flow_tex, uniform_base_flow_tex;
655         GLuint uniform_beta_0_tex;
656         GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
657         GLuint uniform_gamma, uniform_delta;
658 };
659
660 SetupEquations::SetupEquations()
661 {
662         equations_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
663         equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
664         equations_program = link_program(equations_vs_obj, equations_fs_obj);
665
666         // Set up the VAO containing all the required position/texcoord data.
667         glCreateVertexArrays(1, &equations_vao);
668         glBindVertexArray(equations_vao);
669         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
670
671         GLint position_attrib = glGetAttribLocation(equations_program, "position");
672         glEnableVertexArrayAttrib(equations_vao, position_attrib);
673         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
674
675         uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
676         uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
677         uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
678         uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
679         uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
680         uniform_smoothness_x_tex = glGetUniformLocation(equations_program, "smoothness_x_tex");
681         uniform_smoothness_y_tex = glGetUniformLocation(equations_program, "smoothness_y_tex");
682         uniform_gamma = glGetUniformLocation(equations_program, "gamma");
683         uniform_delta = glGetUniformLocation(equations_program, "delta");
684 }
685
686 void SetupEquations::exec(GLuint I_x_y_tex, GLuint I_t_tex, GLuint diff_flow_tex, GLuint base_flow_tex, GLuint beta_0_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, GLuint equation_tex, int level_width, int level_height)
687 {
688         glUseProgram(equations_program);
689
690         bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
691         bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
692         bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
693         bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
694         bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
695         bind_sampler(equations_program, uniform_smoothness_x_tex, 5, smoothness_x_tex, smoothness_sampler);
696         bind_sampler(equations_program, uniform_smoothness_y_tex, 6, smoothness_y_tex, smoothness_sampler);
697         glProgramUniform1f(equations_program, uniform_delta, vr_delta);
698         glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
699
700         GLuint equations_fbo;  // TODO: cleanup
701         glCreateFramebuffers(1, &equations_fbo);
702         glNamedFramebufferTexture(equations_fbo, GL_COLOR_ATTACHMENT0, equation_tex, 0);
703
704         glViewport(0, 0, level_width, level_height);
705         glDisable(GL_BLEND);
706         glBindVertexArray(equations_vao);
707         glBindFramebuffer(GL_FRAMEBUFFER, equations_fbo);
708         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
709 }
710
711 // Actually solve the equation sets made by SetupEquations, by means of
712 // successive over-relaxation (SOR).
713 //
714 // See variational_refinement.txt for more information.
715 class SOR {
716 public:
717         SOR();
718         void exec(GLuint diff_flow_tex, GLuint equation_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height, int num_iterations);
719
720 private:
721         GLuint sor_vs_obj;
722         GLuint sor_fs_obj;
723         GLuint sor_program;
724         GLuint sor_vao;
725
726         GLuint uniform_diff_flow_tex;
727         GLuint uniform_equation_tex;
728         GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
729 };
730
731 SOR::SOR()
732 {
733         sor_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
734         sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
735         sor_program = link_program(sor_vs_obj, sor_fs_obj);
736
737         // Set up the VAO containing all the required position/texcoord data.
738         glCreateVertexArrays(1, &sor_vao);
739         glBindVertexArray(sor_vao);
740         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
741
742         GLint position_attrib = glGetAttribLocation(sor_program, "position");
743         glEnableVertexArrayAttrib(sor_vao, position_attrib);
744         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
745
746         uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
747         uniform_equation_tex = glGetUniformLocation(sor_program, "equation_tex");
748         uniform_smoothness_x_tex = glGetUniformLocation(sor_program, "smoothness_x_tex");
749         uniform_smoothness_y_tex = glGetUniformLocation(sor_program, "smoothness_y_tex");
750 }
751
752 void SOR::exec(GLuint diff_flow_tex, GLuint equation_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height, int num_iterations)
753 {
754         glUseProgram(sor_program);
755
756         bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
757         bind_sampler(sor_program, uniform_smoothness_x_tex, 1, smoothness_x_tex, smoothness_sampler);
758         bind_sampler(sor_program, uniform_smoothness_y_tex, 2, smoothness_y_tex, smoothness_sampler);
759         bind_sampler(sor_program, uniform_equation_tex, 3, equation_tex, nearest_sampler);
760
761         GLuint sor_fbo;  // TODO: cleanup
762         glCreateFramebuffers(1, &sor_fbo);
763         glNamedFramebufferTexture(sor_fbo, GL_COLOR_ATTACHMENT0, diff_flow_tex, 0);  // NOTE: Bind to same as we render from!
764
765         glViewport(0, 0, level_width, level_height);
766         glDisable(GL_BLEND);
767         glBindVertexArray(sor_vao);
768         glBindFramebuffer(GL_FRAMEBUFFER, sor_fbo);
769
770         for (int i = 0; i < num_iterations; ++i) {
771                 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
772                 if (i != num_iterations - 1) {
773                         glTextureBarrier();
774                 }
775         }
776 }
777
778 // Simply add the differential flow found by the variational refinement to the base flow.
779 // The output is in base_flow_tex; we don't need to make a new texture.
780 class AddBaseFlow {
781 public:
782         AddBaseFlow();
783         void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
784
785 private:
786         GLuint add_flow_vs_obj;
787         GLuint add_flow_fs_obj;
788         GLuint add_flow_program;
789         GLuint add_flow_vao;
790
791         GLuint uniform_diff_flow_tex;
792 };
793
794 AddBaseFlow::AddBaseFlow()
795 {
796         add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
797         add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
798         add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
799
800         // Set up the VAO containing all the required position/texcoord data.
801         glCreateVertexArrays(1, &add_flow_vao);
802         glBindVertexArray(add_flow_vao);
803         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
804
805         GLint position_attrib = glGetAttribLocation(add_flow_program, "position");
806         glEnableVertexArrayAttrib(add_flow_vao, position_attrib);
807         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
808
809         uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
810 }
811
812 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
813 {
814         glUseProgram(add_flow_program);
815
816         bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
817
818         GLuint add_flow_fbo;  // TODO: cleanup
819         glCreateFramebuffers(1, &add_flow_fbo);
820         glNamedFramebufferTexture(add_flow_fbo, GL_COLOR_ATTACHMENT0, base_flow_tex, 0);
821
822         glViewport(0, 0, level_width, level_height);
823         glEnable(GL_BLEND);
824         glBlendFunc(GL_ONE, GL_ONE);
825         glBindVertexArray(add_flow_vao);
826         glBindFramebuffer(GL_FRAMEBUFFER, add_flow_fbo);
827
828         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
829 }
830
831 class GPUTimers {
832 public:
833         void print();
834         pair<GLuint, GLuint> begin_timer(const string &name, int level);
835
836 private:
837         struct Timer {
838                 string name;
839                 int level;
840                 pair<GLuint, GLuint> query;
841         };
842         vector<Timer> timers;
843 };
844
845 pair<GLuint, GLuint> GPUTimers::begin_timer(const string &name, int level)
846 {
847         GLuint queries[2];
848         glGenQueries(2, queries);
849         glQueryCounter(queries[0], GL_TIMESTAMP);
850
851         Timer timer;
852         timer.name = name;
853         timer.level = level;
854         timer.query.first = queries[0];
855         timer.query.second = queries[1];
856         timers.push_back(timer);
857         return timer.query;
858 }
859
860 // Take a copy of the flow, bilinearly interpolated and scaled up.
861 class ResizeFlow {
862 public:
863         ResizeFlow();
864         void exec(GLuint in_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height);
865
866 private:
867         GLuint resize_flow_vs_obj;
868         GLuint resize_flow_fs_obj;
869         GLuint resize_flow_program;
870         GLuint resize_flow_vao;
871
872         GLuint uniform_flow_tex;
873         GLuint uniform_scale_factor;
874 };
875
876 ResizeFlow::ResizeFlow()
877 {
878         resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
879         resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
880         resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
881
882         // Set up the VAO containing all the required position/texcoord data.
883         glCreateVertexArrays(1, &resize_flow_vao);
884         glBindVertexArray(resize_flow_vao);
885         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
886
887         GLint position_attrib = glGetAttribLocation(resize_flow_program, "position");
888         glEnableVertexArrayAttrib(resize_flow_vao, position_attrib);
889         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
890
891         uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
892         uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
893 }
894
895 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height)
896 {
897         glUseProgram(resize_flow_program);
898
899         bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
900
901         glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
902
903         GLuint resize_flow_fbo;  // TODO: cleanup
904         glCreateFramebuffers(1, &resize_flow_fbo);
905         glNamedFramebufferTexture(resize_flow_fbo, GL_COLOR_ATTACHMENT0, out_tex, 0);
906
907         glViewport(0, 0, output_width, output_height);
908         glDisable(GL_BLEND);
909         glBindVertexArray(resize_flow_vao);
910         glBindFramebuffer(GL_FRAMEBUFFER, resize_flow_fbo);
911
912         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
913 }
914
915 void GPUTimers::print()
916 {
917         for (const Timer &timer : timers) {
918                 // NOTE: This makes the CPU wait for the GPU.
919                 GLuint64 time_start, time_end;
920                 glGetQueryObjectui64v(timer.query.first, GL_QUERY_RESULT, &time_start);
921                 glGetQueryObjectui64v(timer.query.second, GL_QUERY_RESULT, &time_end);
922                 //fprintf(stderr, "GPU time used = %.1f ms\n", time_elapsed / 1e6);
923                 for (int i = 0; i < timer.level * 2; ++i) {
924                         fprintf(stderr, " ");
925                 }
926                 fprintf(stderr, "%-30s %4.1f ms\n", timer.name.c_str(), GLint64(time_end - time_start) / 1e6);
927         }
928 }
929
930 // A simple RAII class for timing until the end of the scope.
931 class ScopedTimer {
932 public:
933         ScopedTimer(const string &name, GPUTimers *timers)
934                 : timers(timers), level(0)
935         {
936                 query = timers->begin_timer(name, level);
937         }
938
939         ScopedTimer(const string &name, ScopedTimer *parent_timer)
940                 : timers(parent_timer->timers),
941                   level(parent_timer->level + 1)
942         {
943                 query = timers->begin_timer(name, level);
944         }
945
946         ~ScopedTimer()
947         {
948                 end();
949         }
950
951         void end()
952         {
953                 if (!ended) {
954                         glQueryCounter(query.second, GL_TIMESTAMP);
955                         ended = true;
956                 }
957         }
958
959 private:
960         GPUTimers *timers;
961         int level;
962         pair<GLuint, GLuint> query;
963         bool ended = false;
964 };
965
966 int main(int argc, char **argv)
967 {
968         if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
969                 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
970                 exit(1);
971         }
972         SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
973         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
974         SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
975         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
976
977         SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
978         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
979         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
980         // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
981         SDL_Window *window = SDL_CreateWindow("OpenGL window",
982                         SDL_WINDOWPOS_UNDEFINED,
983                         SDL_WINDOWPOS_UNDEFINED,
984                         64, 64,
985                         SDL_WINDOW_OPENGL);
986         SDL_GLContext context = SDL_GL_CreateContext(window);
987         assert(context != nullptr);
988
989         // Load pictures.
990         unsigned width1, height1, width2, height2;
991         GLuint tex0 = load_texture(argc >= 2 ? argv[1] : "test1499.png", &width1, &height1);
992         GLuint tex1 = load_texture(argc >= 3 ? argv[2] : "test1500.png", &width2, &height2);
993
994         if (width1 != width2 || height1 != height2) {
995                 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
996                         width1, height1, width2, height2);
997                 exit(1);
998         }
999
1000         // Make some samplers.
1001         glCreateSamplers(1, &nearest_sampler);
1002         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1003         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1004         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1005         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1006
1007         glCreateSamplers(1, &linear_sampler);
1008         glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1009         glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1010         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1011         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1012
1013         // The smoothness is sampled so that once we get to a smoothness involving
1014         // a value outside the border, the diffusivity between the two becomes zero.
1015         glCreateSamplers(1, &smoothness_sampler);
1016         glSamplerParameteri(smoothness_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1017         glSamplerParameteri(smoothness_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1018         glSamplerParameteri(smoothness_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
1019         glSamplerParameteri(smoothness_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
1020         float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f };
1021         glSamplerParameterfv(smoothness_sampler, GL_TEXTURE_BORDER_COLOR, zero);
1022
1023         float vertices[] = {
1024                 0.0f, 1.0f,
1025                 0.0f, 0.0f,
1026                 1.0f, 1.0f,
1027                 1.0f, 0.0f,
1028         };
1029         glCreateBuffers(1, &vertex_vbo);
1030         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
1031         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1032
1033         // Initial flow is zero, 1x1.
1034         GLuint initial_flow_tex;
1035         glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
1036         glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
1037         glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
1038         int prev_level_width = 1, prev_level_height = 1;
1039
1040         GLuint prev_level_flow_tex = initial_flow_tex;
1041
1042         Sobel sobel;
1043         MotionSearch motion_search;
1044         Densify densify;
1045         Prewarp prewarp;
1046         Derivatives derivatives;
1047         ComputeSmoothness compute_smoothness;
1048         SetupEquations setup_equations;
1049         SOR sor;
1050         AddBaseFlow add_base_flow;
1051         ResizeFlow resize_flow;
1052
1053         GLuint query;
1054         glGenQueries(1, &query);
1055         glBeginQuery(GL_TIME_ELAPSED, query);
1056
1057         GPUTimers timers;
1058
1059         ScopedTimer total_timer("Total", &timers);
1060         for (int level = coarsest_level; level >= int(finest_level); --level) {
1061                 char timer_name[256];
1062                 snprintf(timer_name, sizeof(timer_name), "Level %d", level);
1063                 ScopedTimer level_timer(timer_name, &total_timer);
1064
1065                 int level_width = width1 >> level;
1066                 int level_height = height1 >> level;
1067                 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
1068                 int width_patches = 1 + lrintf((level_width - patch_size_pixels) / patch_spacing_pixels);
1069                 int height_patches = 1 + lrintf((level_height - patch_size_pixels) / patch_spacing_pixels);
1070
1071                 // Make sure we always read from the correct level; the chosen
1072                 // mipmapping could otherwise be rather unpredictable, especially
1073                 // during motion search.
1074                 // TODO: create these beforehand, and stop leaking them.
1075                 GLuint tex0_view, tex1_view;
1076                 glGenTextures(1, &tex0_view);
1077                 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
1078                 glGenTextures(1, &tex1_view);
1079                 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
1080
1081                 // Create a new texture; we could be fancy and render use a multi-level
1082                 // texture, but meh.
1083                 GLuint grad0_tex;
1084                 glCreateTextures(GL_TEXTURE_2D, 1, &grad0_tex);
1085                 glTextureStorage2D(grad0_tex, 1, GL_RG16F, level_width, level_height);
1086
1087                 // Find the derivative.
1088                 {
1089                         ScopedTimer timer("Sobel", &level_timer);
1090                         sobel.exec(tex0_view, grad0_tex, level_width, level_height);
1091                 }
1092
1093                 // Motion search to find the initial flow. We use the flow from the previous
1094                 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
1095
1096                 // Create an output flow texture.
1097                 GLuint flow_out_tex;
1098                 glCreateTextures(GL_TEXTURE_2D, 1, &flow_out_tex);
1099                 glTextureStorage2D(flow_out_tex, 1, GL_RGB16F, width_patches, height_patches);
1100
1101                 // And draw.
1102                 {
1103                         ScopedTimer timer("Motion search", &level_timer);
1104                         motion_search.exec(tex0_view, tex1_view, grad0_tex, prev_level_flow_tex, flow_out_tex, level_width, level_height, prev_level_width, prev_level_height, width_patches, height_patches);
1105                 }
1106
1107                 // Densification.
1108
1109                 // Set up an output texture (initially zero).
1110                 GLuint dense_flow_tex;
1111                 glCreateTextures(GL_TEXTURE_2D, 1, &dense_flow_tex);
1112                 glTextureStorage2D(dense_flow_tex, 1, GL_RGB16F, level_width, level_height);
1113                 glClearTexImage(dense_flow_tex, 0, GL_RGB, GL_FLOAT, nullptr);
1114
1115                 // And draw.
1116                 {
1117                         ScopedTimer timer("Densification", &level_timer);
1118                         densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
1119                 }
1120
1121                 // Everything below here in the loop belongs to variational refinement.
1122                 ScopedTimer varref_timer("Variational refinement", &level_timer);
1123
1124                 // Prewarping; create I and I_t, and a normalized base flow (so we don't
1125                 // have to normalize it over and over again, and also save some bandwidth).
1126                 //
1127                 // During the entire rest of the variational refinement, flow will be measured
1128                 // in pixels, not 0..1 normalized OpenGL texture coordinates.
1129                 // This is because variational refinement depends so heavily on derivatives,
1130                 // which are measured in intensity levels per pixel.
1131                 GLuint I_tex, I_t_tex, base_flow_tex;
1132                 glCreateTextures(GL_TEXTURE_2D, 1, &I_tex);
1133                 glCreateTextures(GL_TEXTURE_2D, 1, &I_t_tex);
1134                 glCreateTextures(GL_TEXTURE_2D, 1, &base_flow_tex);
1135                 glTextureStorage2D(I_tex, 1, GL_R16F, level_width, level_height);
1136                 glTextureStorage2D(I_t_tex, 1, GL_R16F, level_width, level_height);
1137                 glTextureStorage2D(base_flow_tex, 1, GL_RG16F, level_width, level_height);
1138                 {
1139                         ScopedTimer timer("Prewarping", &varref_timer);
1140                         prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height);
1141                 }
1142
1143                 // Calculate I_x and I_y. We're only calculating first derivatives;
1144                 // the others will be taken on-the-fly in order to sample from fewer
1145                 // textures overall, since sampling from the L1 cache is cheap.
1146                 // (TODO: Verify that this is indeed faster than making separate
1147                 // double-derivative textures.)
1148                 GLuint I_x_y_tex, beta_0_tex;
1149                 glCreateTextures(GL_TEXTURE_2D, 1, &I_x_y_tex);
1150                 glCreateTextures(GL_TEXTURE_2D, 1, &beta_0_tex);
1151                 glTextureStorage2D(I_x_y_tex, 1, GL_RG16F, level_width, level_height);
1152                 glTextureStorage2D(beta_0_tex, 1, GL_R16F, level_width, level_height);
1153                 {
1154                         ScopedTimer timer("First derivatives", &varref_timer);
1155                         derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
1156                 }
1157
1158                 // We need somewhere to store du and dv (the flow increment, relative
1159                 // to the non-refined base flow u0 and v0). It starts at zero.
1160                 GLuint du_dv_tex;
1161                 glCreateTextures(GL_TEXTURE_2D, 1, &du_dv_tex);
1162                 glTextureStorage2D(du_dv_tex, 1, GL_RG16F, level_width, level_height);
1163                 glClearTexImage(du_dv_tex, 0, GL_RG, GL_FLOAT, nullptr);
1164
1165                 // And for smoothness.
1166                 GLuint smoothness_x_tex, smoothness_y_tex;
1167                 glCreateTextures(GL_TEXTURE_2D, 1, &smoothness_x_tex);
1168                 glCreateTextures(GL_TEXTURE_2D, 1, &smoothness_y_tex);
1169                 glTextureStorage2D(smoothness_x_tex, 1, GL_R16F, level_width, level_height);
1170                 glTextureStorage2D(smoothness_y_tex, 1, GL_R16F, level_width, level_height);
1171
1172                 // And finally for the equation set. See SetupEquations for
1173                 // the storage format.
1174                 GLuint equation_tex;
1175                 glCreateTextures(GL_TEXTURE_2D, 1, &equation_tex);
1176                 glTextureStorage2D(equation_tex, 1, GL_RGBA32UI, level_width, level_height);
1177
1178                 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
1179                         // Calculate the smoothness terms between the neighboring pixels,
1180                         // both in x and y direction.
1181                         {
1182                                 ScopedTimer timer("Compute smoothness", &varref_timer);
1183                                 compute_smoothness.exec(base_flow_tex, du_dv_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height);
1184                         }
1185
1186                         // Set up the 2x2 equation system for each pixel.
1187                         {
1188                                 ScopedTimer timer("Set up equations", &varref_timer);
1189                                 setup_equations.exec(I_x_y_tex, I_t_tex, du_dv_tex, base_flow_tex, beta_0_tex, smoothness_x_tex, smoothness_y_tex, equation_tex, level_width, level_height);
1190                         }
1191
1192                         // Run a few SOR (or quasi-SOR, since we're not really Jacobi) iterations.
1193                         // Note that these are to/from the same texture.
1194                         {
1195                                 ScopedTimer timer("SOR", &varref_timer);
1196                                 sor.exec(du_dv_tex, equation_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height, 5);
1197                         }
1198                 }
1199
1200                 // Add the differential flow found by the variational refinement to the base flow,
1201                 // giving the final flow estimate for this level.
1202                 // The output is in diff_flow_tex; we don't need to make a new texture.
1203                 // You can comment out this part if you wish to test disabling of the variational refinement.
1204                 {
1205                         ScopedTimer timer("Add differential flow", &varref_timer);
1206                         add_base_flow.exec(base_flow_tex, du_dv_tex, level_width, level_height);
1207                 }
1208
1209                 prev_level_flow_tex = base_flow_tex;
1210                 prev_level_width = level_width;
1211                 prev_level_height = level_height;
1212         }
1213         total_timer.end();
1214
1215         timers.print();
1216
1217         // Scale up the flow to the final size (if needed).
1218         GLuint final_tex;
1219         if (finest_level == 0) {
1220                 final_tex = prev_level_flow_tex;
1221         } else {
1222                 glCreateTextures(GL_TEXTURE_2D, 1, &final_tex);
1223                 glTextureStorage2D(final_tex, 1, GL_RG16F, width1, height1);
1224                 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width1, height1);
1225         }
1226
1227         unique_ptr<float[]> dense_flow(new float[width1 * height1 * 2]);
1228         glGetTextureImage(final_tex, 0, GL_RG, GL_FLOAT, width1 * height1 * 2 * sizeof(float), dense_flow.get());
1229
1230         FILE *fp = fopen("flow.ppm", "wb");
1231         FILE *flowfp = fopen("flow.flo", "wb");
1232         fprintf(fp, "P6\n%d %d\n255\n", width1, height1);
1233         fprintf(flowfp, "FEIH");
1234         fwrite(&width1, 4, 1, flowfp);
1235         fwrite(&height1, 4, 1, flowfp);
1236         for (unsigned y = 0; y < unsigned(height1); ++y) {
1237                 int yy = height1 - y - 1;
1238                 for (unsigned x = 0; x < unsigned(width1); ++x) {
1239                         float du = dense_flow[(yy * width1 + x) * 2 + 0];
1240                         float dv = dense_flow[(yy * width1 + x) * 2 + 1];
1241
1242                         dv = -dv;
1243
1244                         fwrite(&du, 4, 1, flowfp);
1245                         fwrite(&dv, 4, 1, flowfp);
1246
1247                         uint8_t r, g, b;
1248                         flow2rgb(du, dv, &r, &g, &b);
1249                         putc(r, fp);
1250                         putc(g, fp);
1251                         putc(b, fp);
1252                 }
1253         }
1254         fclose(fp);
1255         fclose(flowfp);
1256
1257         fprintf(stderr, "err = %d\n", glGetError());
1258 }