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