]> git.sesse.net Git - nageru/blob - flow.cpp
Start working on variational refinement.
[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;
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, uniform_inv_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         uniform_inv_image_size = glGetUniformLocation(sobel_program, "inv_image_size");
246 }
247
248 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
249 {
250         glUseProgram(sobel_program);
251         glBindTextureUnit(0, tex0_view);
252         glBindSampler(0, nearest_sampler);
253         glProgramUniform1i(sobel_program, uniform_tex, 0);
254         glProgramUniform2f(sobel_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
255
256         GLuint grad0_fbo;  // TODO: cleanup
257         glCreateFramebuffers(1, &grad0_fbo);
258         glNamedFramebufferTexture(grad0_fbo, GL_COLOR_ATTACHMENT0, grad0_tex, 0);
259
260         glViewport(0, 0, level_width, level_height);
261         glBindFramebuffer(GL_FRAMEBUFFER, grad0_fbo);
262         glBindVertexArray(sobel_vao);
263         glUseProgram(sobel_program);
264         glDisable(GL_BLEND);
265         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
266 }
267
268 // Motion search to find the initial flow. See motion_search.frag for documentation.
269 class MotionSearch {
270 public:
271         MotionSearch();
272         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);
273
274 private:
275         GLuint motion_vs_obj;
276         GLuint motion_fs_obj;
277         GLuint motion_search_program;
278         GLuint motion_search_vao;
279
280         GLuint uniform_image_size, uniform_inv_image_size;
281         GLuint uniform_image0_tex, uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
282 };
283
284 MotionSearch::MotionSearch()
285 {
286         motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
287         motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
288         motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
289
290         // Set up the VAO containing all the required position/texcoord data.
291         glCreateVertexArrays(1, &motion_search_vao);
292         glBindVertexArray(motion_search_vao);
293         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
294
295         GLint position_attrib = glGetAttribLocation(motion_search_program, "position");
296         glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
297         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
298
299         uniform_image_size = glGetUniformLocation(motion_search_program, "image_size");
300         uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
301         uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
302         uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
303         uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
304         uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
305 }
306
307 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)
308 {
309         glUseProgram(motion_search_program);
310
311         bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
312         bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
313         bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, nearest_sampler);
314         bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
315
316         glProgramUniform2f(motion_search_program, uniform_image_size, level_width, level_height);
317         glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
318
319         GLuint flow_fbo;  // TODO: cleanup
320         glCreateFramebuffers(1, &flow_fbo);
321         glNamedFramebufferTexture(flow_fbo, GL_COLOR_ATTACHMENT0, flow_out_tex, 0);
322
323         glViewport(0, 0, width_patches, height_patches);
324         glBindFramebuffer(GL_FRAMEBUFFER, flow_fbo);
325         glBindVertexArray(motion_search_vao);
326         glUseProgram(motion_search_program);
327         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
328 }
329
330 // Do “densification”, ie., upsampling of the flow patches to the flow field
331 // (the same size as the image at this level). We draw one quad per patch
332 // over its entire covered area (using instancing in the vertex shader),
333 // and then weight the contributions in the pixel shader by post-warp difference.
334 // This is equation (3) in the paper.
335 //
336 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
337 // weight in the B channel. Dividing R and G by B gives the normalized values.
338 class Densify {
339 public:
340         Densify();
341         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);
342
343 private:
344         GLuint densify_vs_obj;
345         GLuint densify_fs_obj;
346         GLuint densify_program;
347         GLuint densify_vao;
348
349         GLuint uniform_width_patches, uniform_patch_size, uniform_patch_spacing;
350         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
351 };
352
353 Densify::Densify()
354 {
355         densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
356         densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
357         densify_program = link_program(densify_vs_obj, densify_fs_obj);
358
359         // Set up the VAO containing all the required position/texcoord data.
360         glCreateVertexArrays(1, &densify_vao);
361         glBindVertexArray(densify_vao);
362         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
363
364         GLint position_attrib = glGetAttribLocation(densify_program, "position");
365         glEnableVertexArrayAttrib(densify_vao, position_attrib);
366         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
367
368         uniform_width_patches = glGetUniformLocation(densify_program, "width_patches");
369         uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
370         uniform_patch_spacing = glGetUniformLocation(densify_program, "patch_spacing");
371         uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
372         uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
373         uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
374 }
375
376 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)
377 {
378         glUseProgram(densify_program);
379
380         bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
381         bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
382         bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
383
384         glProgramUniform1i(densify_program, uniform_width_patches, width_patches);
385         glProgramUniform2f(densify_program, uniform_patch_size,
386                 float(patch_size_pixels) / level_width,
387                 float(patch_size_pixels) / level_height);
388
389         float patch_spacing_x = float(level_width - patch_size_pixels) / (width_patches - 1);
390         float patch_spacing_y = float(level_height - patch_size_pixels) / (height_patches - 1);
391         glProgramUniform2f(densify_program, uniform_patch_spacing,
392                 patch_spacing_x / level_width,
393                 patch_spacing_y / level_height);
394
395         GLuint dense_flow_fbo;  // TODO: cleanup
396         glCreateFramebuffers(1, &dense_flow_fbo);
397         glNamedFramebufferTexture(dense_flow_fbo, GL_COLOR_ATTACHMENT0, dense_flow_tex, 0);
398
399         glViewport(0, 0, level_width, level_height);
400         glEnable(GL_BLEND);
401         glBlendFunc(GL_ONE, GL_ONE);
402         glBindVertexArray(densify_vao);
403         glBindFramebuffer(GL_FRAMEBUFFER, dense_flow_fbo);
404         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
405 }
406
407 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
408 // I_0 and I_w. The prewarping is what enables us to solve the variational
409 // flow for du,dv instead of u,v.
410 //
411 // See variational_refinement.txt for more information.
412 class Prewarp {
413 public:
414         Prewarp();
415         void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint I_tex, GLuint I_t_tex, int level_width, int level_height);
416
417 private:
418         GLuint prewarp_vs_obj;
419         GLuint prewarp_fs_obj;
420         GLuint prewarp_program;
421         GLuint prewarp_vao;
422
423         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
424 };
425
426 Prewarp::Prewarp()
427 {
428         prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
429         prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
430         prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
431
432         // Set up the VAO containing all the required position/texcoord data.
433         glCreateVertexArrays(1, &prewarp_vao);
434         glBindVertexArray(prewarp_vao);
435         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
436
437         GLint position_attrib = glGetAttribLocation(prewarp_program, "position");
438         glEnableVertexArrayAttrib(prewarp_vao, position_attrib);
439         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
440
441         uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
442         uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
443         uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
444 }
445
446 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)
447 {
448         glUseProgram(prewarp_program);
449
450         bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
451         bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
452         bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
453
454         GLuint prewarp_fbo;  // TODO: cleanup
455         glCreateFramebuffers(1, &prewarp_fbo);
456         GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
457         glNamedFramebufferDrawBuffers(prewarp_fbo, 2, bufs);
458         glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT0, I_tex, 0);
459         glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT1, I_t_tex, 0);
460
461         glViewport(0, 0, level_width, level_height);
462         glDisable(GL_BLEND);
463         glBindVertexArray(prewarp_vao);
464         glBindFramebuffer(GL_FRAMEBUFFER, prewarp_fbo);
465         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
466 }
467
468 int main(void)
469 {
470         if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
471                 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
472                 exit(1);
473         }
474         SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
475         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
476         SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
477         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
478
479         SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
480         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
481         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
482         // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
483         SDL_Window *window = SDL_CreateWindow("OpenGL window",
484                         SDL_WINDOWPOS_UNDEFINED,
485                         SDL_WINDOWPOS_UNDEFINED,
486                         64, 64,
487                         SDL_WINDOW_OPENGL);
488         SDL_GLContext context = SDL_GL_CreateContext(window);
489         assert(context != nullptr);
490
491         // Load pictures.
492         GLuint tex0 = load_texture("test1499.pgm", WIDTH, HEIGHT);
493         GLuint tex1 = load_texture("test1500.pgm", WIDTH, HEIGHT);
494
495         // Make some samplers.
496         glCreateSamplers(1, &nearest_sampler);
497         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
498         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
499         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
500         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
501
502         glCreateSamplers(1, &linear_sampler);
503         glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
504         glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
505         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
506         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
507
508         float vertices[] = {
509                 0.0f, 1.0f,
510                 0.0f, 0.0f,
511                 1.0f, 1.0f,
512                 1.0f, 0.0f,
513         };
514         glCreateBuffers(1, &vertex_vbo);
515         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
516         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
517
518         // Initial flow is zero, 1x1.
519         GLuint initial_flow_tex;
520         glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
521         glTextureStorage2D(initial_flow_tex, 1, GL_RGB32F, 1, 1);
522
523         GLuint prev_level_flow_tex = initial_flow_tex;
524
525         Sobel sobel;
526         MotionSearch motion_search;
527         Densify densify;
528         Prewarp prewarp;
529
530         GLuint query;
531         glGenQueries(1, &query);
532         glBeginQuery(GL_TIME_ELAPSED, query);
533
534         for (int level = coarsest_level; level >= int(finest_level); --level) {
535                 int level_width = WIDTH >> level;
536                 int level_height = HEIGHT >> level;
537                 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
538                 int width_patches = 1 + lrintf((level_width - patch_size_pixels) / patch_spacing_pixels);
539                 int height_patches = 1 + lrintf((level_height - patch_size_pixels) / patch_spacing_pixels);
540
541                 // Make sure we always read from the correct level; the chosen
542                 // mipmapping could otherwise be rather unpredictable, especially
543                 // during motion search.
544                 // TODO: create these beforehand, and stop leaking them.
545                 GLuint tex0_view, tex1_view;
546                 glGenTextures(1, &tex0_view);
547                 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
548                 glGenTextures(1, &tex1_view);
549                 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
550
551                 // Create a new texture; we could be fancy and render use a multi-level
552                 // texture, but meh.
553                 GLuint grad0_tex;
554                 glCreateTextures(GL_TEXTURE_2D, 1, &grad0_tex);
555                 glTextureStorage2D(grad0_tex, 1, GL_RG16F, level_width, level_height);
556
557                 // Find the derivative.
558                 sobel.exec(tex0_view, grad0_tex, level_width, level_height);
559
560                 // Motion search to find the initial flow. We use the flow from the previous
561                 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
562
563                 // Create an output flow texture.
564                 GLuint flow_out_tex;
565                 glCreateTextures(GL_TEXTURE_2D, 1, &flow_out_tex);
566                 glTextureStorage2D(flow_out_tex, 1, GL_RGB16F, width_patches, height_patches);
567
568                 // And draw.
569                 motion_search.exec(tex0_view, tex1_view, grad0_tex, prev_level_flow_tex, flow_out_tex, level_width, level_height, width_patches, height_patches);
570
571                 // Densification.
572
573                 // Set up an output texture (initially zero).
574                 GLuint dense_flow_tex;
575                 glCreateTextures(GL_TEXTURE_2D, 1, &dense_flow_tex);
576                 glTextureStorage2D(dense_flow_tex, 1, GL_RGB16F, level_width, level_height);
577
578                 // And draw.
579                 densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
580
581                 // Everything below here in the loop belongs to variational refinement.
582                 // It is not done yet.
583
584                 // Prewarping; create I and I_t.
585                 GLuint I_tex, I_t_tex;
586                 glCreateTextures(GL_TEXTURE_2D, 1, &I_tex);
587                 glCreateTextures(GL_TEXTURE_2D, 1, &I_t_tex);
588                 glTextureStorage2D(I_tex, 1, GL_R16F, level_width, level_height);
589                 glTextureStorage2D(I_t_tex, 1, GL_R16F, level_width, level_height);
590                 prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, level_width, level_height);
591
592                 prev_level_flow_tex = dense_flow_tex;
593         }
594         glEndQuery(GL_TIME_ELAPSED);
595
596         GLint available;
597         do {
598                 glGetQueryObjectiv(query, GL_QUERY_RESULT_AVAILABLE, &available);
599                 usleep(1000);
600         } while (!available);
601         GLuint64 time_elapsed;
602         glGetQueryObjectui64v(query, GL_QUERY_RESULT, &time_elapsed);
603         fprintf(stderr, "GPU time used = %.1f ms\n", time_elapsed / 1e6);
604
605         int level_width = WIDTH >> finest_level;
606         int level_height = HEIGHT >> finest_level;
607         unique_ptr<float[]> dense_flow(new float[level_width * level_height * 3]);
608         glGetTextureImage(prev_level_flow_tex, 0, GL_RGB, GL_FLOAT, level_width * level_height * 3 * sizeof(float), dense_flow.get());
609
610         FILE *fp = fopen("flow.ppm", "wb");
611         FILE *flowfp = fopen("flow.flo", "wb");
612         fprintf(fp, "P6\n%d %d\n255\n", level_width, level_height);
613         fprintf(flowfp, "FEIH");
614         fwrite(&level_width, 4, 1, flowfp);
615         fwrite(&level_height, 4, 1, flowfp);
616         for (unsigned y = 0; y < unsigned(level_height); ++y) {
617                 int yy = level_height - y - 1;
618                 for (unsigned x = 0; x < unsigned(level_width); ++x) {
619                         float du = dense_flow[(yy * level_width + x) * 3 + 0];
620                         float dv = dense_flow[(yy * level_width + x) * 3 + 1];
621                         float w = dense_flow[(yy * level_width + x) * 3 + 2];
622
623                         du = (du / w) * level_width;
624                         dv = (-dv / w) * level_height;
625
626                         fwrite(&du, 4, 1, flowfp);
627                         fwrite(&dv, 4, 1, flowfp);
628
629                         uint8_t r, g, b;
630                         flow2rgb(du, dv, &r, &g, &b);
631                         putc(r, fp);
632                         putc(g, fp);
633                         putc(b, fp);
634                 }
635         }
636         fclose(fp);
637         fclose(flowfp);
638
639         fprintf(stderr, "err = %d\n", glGetError());
640 }