]> git.sesse.net Git - nageru/blob - flow.cpp
Check uniform locations ahead-of-time, for slightly reduced GL overhead.
[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
19 #include "util.h"
20
21 #include <algorithm>
22 #include <memory>
23
24 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
25
26 using namespace std;
27
28 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
29 constexpr float patch_overlap_ratio = 0.75f;
30 constexpr unsigned coarsest_level = 5;
31 constexpr unsigned finest_level = 1;
32 constexpr unsigned patch_size_pixels = 12;
33
34 // Some global OpenGL objects.
35 GLuint nearest_sampler, linear_sampler, mipmap_sampler;
36 GLuint vertex_vbo;
37
38 string read_file(const string &filename)
39 {
40         FILE *fp = fopen(filename.c_str(), "r");
41         if (fp == nullptr) {
42                 perror(filename.c_str());
43                 exit(1);
44         }
45
46         int ret = fseek(fp, 0, SEEK_END);
47         if (ret == -1) {
48                 perror("fseek(SEEK_END)");
49                 exit(1);
50         }
51
52         int size = ftell(fp);
53
54         ret = fseek(fp, 0, SEEK_SET);
55         if (ret == -1) {
56                 perror("fseek(SEEK_SET)");
57                 exit(1);
58         }
59
60         string str;
61         str.resize(size);
62         ret = fread(&str[0], size, 1, fp);
63         if (ret == -1) {
64                 perror("fread");
65                 exit(1);
66         }
67         if (ret == 0) {
68                 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
69                                 size, filename.c_str());
70                 exit(1);
71         }
72         fclose(fp);
73
74         return str;
75 }
76
77
78 GLuint compile_shader(const string &shader_src, GLenum type)
79 {
80         GLuint obj = glCreateShader(type);
81         const GLchar* source[] = { shader_src.data() };
82         const GLint length[] = { (GLint)shader_src.size() };
83         glShaderSource(obj, 1, source, length);
84         glCompileShader(obj);
85
86         GLchar info_log[4096];
87         GLsizei log_length = sizeof(info_log) - 1;
88         glGetShaderInfoLog(obj, log_length, &log_length, info_log);
89         info_log[log_length] = 0;
90         if (strlen(info_log) > 0) {
91                 fprintf(stderr, "Shader compile log: %s\n", info_log);
92         }
93
94         GLint status;
95         glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
96         if (status == GL_FALSE) {
97                 // Add some line numbers to easier identify compile errors.
98                 string src_with_lines = "/*   1 */ ";
99                 size_t lineno = 1;
100                 for (char ch : shader_src) {
101                         src_with_lines.push_back(ch);
102                         if (ch == '\n') {
103                                 char buf[32];
104                                 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
105                                 src_with_lines += buf;
106                         }
107                 }
108
109                 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
110                 exit(1);
111         }
112
113         return obj;
114 }
115
116
117 GLuint load_texture(const char *filename, unsigned width, unsigned height)
118 {
119         FILE *fp = fopen(filename, "rb");
120         if (fp == nullptr) {
121                 perror(filename);
122                 exit(1);
123         }
124         unique_ptr<uint8_t[]> pix(new uint8_t[width * height]);
125         if (fread(pix.get(), width * height, 1, fp) != 1) {
126                 fprintf(stderr, "Short read from %s\n", filename);
127                 exit(1);
128         }
129         fclose(fp);
130
131         // Convert to bottom-left origin.
132         for (unsigned y = 0; y < height / 2; ++y) {
133                 unsigned y2 = height - 1 - y;
134                 swap_ranges(&pix[y * width], &pix[y * width + width], &pix[y2 * width]);
135         }
136
137         int levels = 1;
138         for (int w = width, h = height; w > 1 || h > 1; ) {
139                 w >>= 1;
140                 h >>= 1;
141                 ++levels;
142         }
143
144         GLuint tex;
145         glCreateTextures(GL_TEXTURE_2D, 1, &tex);
146         glTextureStorage2D(tex, levels, GL_R8, width, height);
147         glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, pix.get());
148         glGenerateTextureMipmap(tex);
149
150         return tex;
151 }
152
153 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
154 {
155         GLuint program = glCreateProgram();
156         glAttachShader(program, vs_obj);
157         glAttachShader(program, fs_obj);
158         glLinkProgram(program);
159         GLint success;
160         glGetProgramiv(program, GL_LINK_STATUS, &success);
161         if (success == GL_FALSE) {
162                 GLchar error_log[1024] = {0};
163                 glGetProgramInfoLog(program, 1024, nullptr, error_log);
164                 fprintf(stderr, "Error linking program: %s\n", error_log);
165                 exit(1);
166         }
167         return program;
168 }
169
170 GLuint generate_vbo(GLint size, GLsizeiptr data_size, const GLvoid *data)
171 {
172         GLuint vbo;
173         glCreateBuffers(1, &vbo);
174         glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
175         glNamedBufferData(vbo, data_size, data, GL_STATIC_DRAW);
176         return vbo;
177 }
178
179 GLuint fill_vertex_attribute(GLuint vao, GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
180 {
181         int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
182         if (attrib == -1) {
183                 return -1;
184         }
185
186         GLuint vbo = generate_vbo(size, data_size, data);
187
188         glBindBuffer(GL_ARRAY_BUFFER, vbo);
189         glEnableVertexArrayAttrib(vao, attrib);
190         glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
191         glBindBuffer(GL_ARRAY_BUFFER, 0);
192
193         return vbo;
194 }
195
196 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
197 {
198         if (location == -1) {
199                 return;
200         }
201
202         glBindTextureUnit(texture_unit, tex);
203         glBindSampler(texture_unit, sampler);
204         glProgramUniform1i(program, location, texture_unit);
205 }
206
207 // Compute gradients in every point, used for the motion search.
208 // The DIS paper doesn't actually mention how these are computed,
209 // but seemingly, a 3x3 Sobel operator is used here (at least in
210 // later versions of the code), while a [1 -8 0 8 -1] kernel is
211 // used for all the derivatives in the variational refinement part
212 // (which borrows code from DeepFlow). This is inconsistent,
213 // but I guess we're better off with staying with the original
214 // decisions until we actually know having different ones would be better.
215 class Sobel {
216 public:
217         Sobel();
218         void exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height);
219
220 private:
221         GLuint sobel_vs_obj;
222         GLuint sobel_fs_obj;
223         GLuint sobel_program;
224         GLuint sobel_vao;
225
226         GLuint uniform_tex, uniform_image_size, uniform_inv_image_size;
227 };
228
229 Sobel::Sobel()
230 {
231         sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
232         sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
233         sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
234
235         // Set up the VAO containing all the required position/texcoord data.
236         glCreateVertexArrays(1, &sobel_vao);
237         glBindVertexArray(sobel_vao);
238
239         GLint position_attrib = glGetAttribLocation(sobel_program, "position");
240         glEnableVertexArrayAttrib(sobel_vao, position_attrib);
241         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
242
243         GLint texcoord_attrib = glGetAttribLocation(sobel_program, "texcoord");
244         glEnableVertexArrayAttrib(sobel_vao, texcoord_attrib);
245         glVertexAttribPointer(texcoord_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
246
247         uniform_tex = glGetUniformLocation(sobel_program, "tex");
248         uniform_image_size = glGetUniformLocation(sobel_program, "image_size");
249         uniform_inv_image_size = glGetUniformLocation(sobel_program, "inv_image_size");
250 }
251
252 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
253 {
254         glUseProgram(sobel_program);
255         glBindTextureUnit(0, tex0_view);
256         glBindSampler(0, nearest_sampler);
257         glProgramUniform1i(sobel_program, uniform_tex, 0);
258         glProgramUniform2f(sobel_program, uniform_image_size, level_width, level_height);
259         glProgramUniform2f(sobel_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
260
261         GLuint grad0_fbo;  // TODO: cleanup
262         glCreateFramebuffers(1, &grad0_fbo);
263         glNamedFramebufferTexture(grad0_fbo, GL_COLOR_ATTACHMENT0, grad0_tex, 0);
264
265         glViewport(0, 0, level_width, level_height);
266         glBindFramebuffer(GL_FRAMEBUFFER, grad0_fbo);
267         glBindVertexArray(sobel_vao);
268         glUseProgram(sobel_program);
269         glDisable(GL_BLEND);
270         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
271 }
272
273 // Motion search to find the initial flow. See motion_search.frag for documentation.
274 class MotionSearch {
275 public:
276         MotionSearch();
277         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);
278
279 private:
280         GLuint motion_vs_obj;
281         GLuint motion_fs_obj;
282         GLuint motion_search_program;
283         GLuint motion_search_vao;
284
285         GLuint uniform_image_size, uniform_inv_image_size;
286         GLuint uniform_image0_tex, uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
287 };
288
289 MotionSearch::MotionSearch()
290 {
291         motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
292         motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
293         motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
294
295         // Set up the VAO containing all the required position/texcoord data.
296         glCreateVertexArrays(1, &motion_search_vao);
297         glBindVertexArray(motion_search_vao);
298         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
299
300         GLint position_attrib = glGetAttribLocation(motion_search_program, "position");
301         glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
302         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
303
304         GLint texcoord_attrib = glGetAttribLocation(motion_search_program, "texcoord");
305         glEnableVertexArrayAttrib(motion_search_vao, texcoord_attrib);
306         glVertexAttribPointer(texcoord_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
307
308         uniform_image_size = glGetUniformLocation(motion_search_program, "image_size");
309         uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
310         uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
311         uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
312         uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
313         uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
314 }
315
316 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)
317 {
318         glUseProgram(motion_search_program);
319
320         bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
321         bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
322         bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, nearest_sampler);
323         bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
324
325         glProgramUniform2f(motion_search_program, uniform_image_size, level_width, level_height);
326         glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
327
328         GLuint flow_fbo;  // TODO: cleanup
329         glCreateFramebuffers(1, &flow_fbo);
330         glNamedFramebufferTexture(flow_fbo, GL_COLOR_ATTACHMENT0, flow_out_tex, 0);
331
332         glViewport(0, 0, width_patches, height_patches);
333         glBindFramebuffer(GL_FRAMEBUFFER, flow_fbo);
334         glBindVertexArray(motion_search_vao);
335         glUseProgram(motion_search_program);
336         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
337 }
338
339 // Do “densification”, ie., upsampling of the flow patches to the flow field
340 // (the same size as the image at this level). We draw one quad per patch
341 // over its entire covered area (using instancing in the vertex shader),
342 // and then weight the contributions in the pixel shader by post-warp difference.
343 // This is equation (3) in the paper.
344 //
345 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
346 // weight in the B channel. Dividing R and G by B gives the normalized values.
347 class Densify {
348 public:
349         Densify();
350         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);
351
352 private:
353         GLuint densify_vs_obj;
354         GLuint densify_fs_obj;
355         GLuint densify_program;
356         GLuint densify_vao;
357
358         GLuint uniform_width_patches, uniform_patch_size, uniform_patch_spacing;
359         GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
360 };
361
362 Densify::Densify()
363 {
364         densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
365         densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
366         densify_program = link_program(densify_vs_obj, densify_fs_obj);
367
368         // Set up the VAO containing all the required position/texcoord data.
369         glCreateVertexArrays(1, &densify_vao);
370         glBindVertexArray(densify_vao);
371         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
372
373         GLint position_attrib = glGetAttribLocation(densify_program, "position");
374         glEnableVertexArrayAttrib(densify_vao, position_attrib);
375         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
376
377         uniform_width_patches = glGetUniformLocation(densify_program, "width_patches");
378         uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
379         uniform_patch_spacing = glGetUniformLocation(densify_program, "patch_spacing");
380         uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
381         uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
382         uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
383 }
384
385 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)
386 {
387         glUseProgram(densify_program);
388
389         bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
390         bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
391         bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
392
393         glProgramUniform1i(densify_program, uniform_width_patches, width_patches);
394         glProgramUniform2f(densify_program, uniform_patch_size,
395                 float(patch_size_pixels) / level_width,
396                 float(patch_size_pixels) / level_height);
397
398         float patch_spacing_x = float(level_width - patch_size_pixels) / (width_patches - 1);
399         float patch_spacing_y = float(level_height - patch_size_pixels) / (height_patches - 1);
400         glProgramUniform2f(densify_program, uniform_patch_spacing,
401                 patch_spacing_x / level_width,
402                 patch_spacing_y / level_height);
403
404         GLuint dense_flow_fbo;  // TODO: cleanup
405         glCreateFramebuffers(1, &dense_flow_fbo);
406         glNamedFramebufferTexture(dense_flow_fbo, GL_COLOR_ATTACHMENT0, dense_flow_tex, 0);
407
408         glViewport(0, 0, level_width, level_height);
409         glEnable(GL_BLEND);
410         glBlendFunc(GL_ONE, GL_ONE);
411         glBindVertexArray(densify_vao);
412         glBindFramebuffer(GL_FRAMEBUFFER, dense_flow_fbo);
413         glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
414 }
415
416 int main(void)
417 {
418         if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
419                 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
420                 exit(1);
421         }
422         SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
423         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
424         SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
425         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
426
427         SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
428         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
429         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
430         // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
431         SDL_Window *window = SDL_CreateWindow("OpenGL window",
432                         SDL_WINDOWPOS_UNDEFINED,
433                         SDL_WINDOWPOS_UNDEFINED,
434                         64, 64,
435                         SDL_WINDOW_OPENGL);
436         SDL_GLContext context = SDL_GL_CreateContext(window);
437         assert(context != nullptr);
438
439         // Load pictures.
440         GLuint tex0 = load_texture("test1499.pgm", WIDTH, HEIGHT);
441         GLuint tex1 = load_texture("test1500.pgm", WIDTH, HEIGHT);
442
443         // Make some samplers.
444         glCreateSamplers(1, &nearest_sampler);
445         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
446         glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
447         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
448         glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
449
450         glCreateSamplers(1, &linear_sampler);
451         glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
452         glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
453         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
454         glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
455
456         glCreateSamplers(1, &mipmap_sampler);
457         glSamplerParameteri(mipmap_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
458         glSamplerParameteri(mipmap_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
459         glSamplerParameteri(mipmap_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
460         glSamplerParameteri(mipmap_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
461
462         float vertices[] = {
463                 0.0f, 1.0f,
464                 0.0f, 0.0f,
465                 1.0f, 1.0f,
466                 1.0f, 0.0f,
467         };
468         glCreateBuffers(1, &vertex_vbo);
469         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
470         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
471
472         // Initial flow is zero, 1x1.
473         GLuint initial_flow_tex;
474         glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
475         glTextureStorage2D(initial_flow_tex, 1, GL_RGB32F, 1, 1);
476
477         GLuint prev_level_flow_tex = initial_flow_tex;
478
479         Sobel sobel;
480         MotionSearch motion_search;
481         Densify densify;
482
483         GLuint query;
484         glGenQueries(1, &query);
485         glBeginQuery(GL_TIME_ELAPSED, query);
486
487         for (int level = coarsest_level; level >= int(finest_level); --level) {
488                 int level_width = WIDTH >> level;
489                 int level_height = HEIGHT >> level;
490                 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
491                 int width_patches = 1 + lrintf((level_width - patch_size_pixels) / patch_spacing_pixels);
492                 int height_patches = 1 + lrintf((level_height - patch_size_pixels) / patch_spacing_pixels);
493
494                 // Make sure we always read from the correct level; the chosen
495                 // mipmapping could otherwise be rather unpredictable, especially
496                 // during motion search.
497                 // TODO: create these beforehand, and stop leaking them.
498                 GLuint tex0_view, tex1_view;
499                 glGenTextures(1, &tex0_view);
500                 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
501                 glGenTextures(1, &tex1_view);
502                 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
503
504                 // Create a new texture; we could be fancy and render use a multi-level
505                 // texture, but meh.
506                 GLuint grad0_tex;
507                 glCreateTextures(GL_TEXTURE_2D, 1, &grad0_tex);
508                 glTextureStorage2D(grad0_tex, 1, GL_RG16F, level_width, level_height);
509
510                 // Find the derivative.
511                 sobel.exec(tex0_view, grad0_tex, level_width, level_height);
512
513                 // Motion search to find the initial flow. We use the flow from the previous
514                 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
515
516                 // Create an output flow texture.
517                 GLuint flow_out_tex;
518                 glCreateTextures(GL_TEXTURE_2D, 1, &flow_out_tex);
519                 glTextureStorage2D(flow_out_tex, 1, GL_RG16F, width_patches, height_patches);
520
521                 // And draw.
522                 motion_search.exec(tex0_view, tex1_view, grad0_tex, prev_level_flow_tex, flow_out_tex, level_width, level_height, width_patches, height_patches);
523
524                 // Densification.
525
526                 // Set up an output texture (initially zero).
527                 GLuint dense_flow_tex;
528                 glCreateTextures(GL_TEXTURE_2D, 1, &dense_flow_tex);
529                 //glTextureStorage2D(dense_flow_tex, 1, GL_RGB16F, level_width, level_height);
530                 glTextureStorage2D(dense_flow_tex, 1, GL_RGBA32F, level_width, level_height);
531
532                 // And draw.
533                 densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
534
535                 // TODO: Variational refinement.
536
537                 prev_level_flow_tex = dense_flow_tex;
538         }
539         glEndQuery(GL_TIME_ELAPSED);
540
541         GLint available;
542         do {
543                 glGetQueryObjectiv(query, GL_QUERY_RESULT_AVAILABLE, &available);
544         } while (!available);
545         GLuint64 time_elapsed;
546         glGetQueryObjectui64v(query, GL_QUERY_RESULT, &time_elapsed);
547         fprintf(stderr, "GPU time used = %.1f ms\n", time_elapsed / 1e6);
548
549         int level_width = WIDTH >> finest_level;
550         int level_height = HEIGHT >> finest_level;
551         unique_ptr<float[]> dense_flow(new float[level_width * level_height * 3]);
552         glGetTextureImage(prev_level_flow_tex, 0, GL_RGB, GL_FLOAT, level_width * level_height * 3 * sizeof(float), dense_flow.get());
553
554         FILE *fp = fopen("flow.ppm", "wb");
555         FILE *flowfp = fopen("flow.flo", "wb");
556         fprintf(fp, "P6\n%d %d\n255\n", level_width, level_height);
557         fprintf(flowfp, "FEIH");
558         fwrite(&level_width, 4, 1, flowfp);
559         fwrite(&level_height, 4, 1, flowfp);
560         for (unsigned y = 0; y < unsigned(level_height); ++y) {
561                 int yy = level_height - y - 1;
562                 for (unsigned x = 0; x < unsigned(level_width); ++x) {
563                         float du = dense_flow[(yy * level_width + x) * 3 + 0];
564                         float dv = dense_flow[(yy * level_width + x) * 3 + 1];
565                         float w = dense_flow[(yy * level_width + x) * 3 + 2];
566
567                         du = (du / w) * level_width;
568                         dv = (-dv / w) * level_height;
569
570                         fwrite(&du, 4, 1, flowfp);
571                         fwrite(&dv, 4, 1, flowfp);
572
573                         uint8_t r, g, b;
574                         flow2rgb(du, dv, &r, &g, &b);
575                         putc(r, fp);
576                         putc(g, fp);
577                         putc(b, fp);
578                 }
579         }
580         fclose(fp);
581         fclose(flowfp);
582
583         fprintf(stderr, "err = %d\n", glGetError());
584 }