6 #include <SDL2/SDL_error.h>
7 #include <SDL2/SDL_events.h>
8 #include <SDL2/SDL_image.h>
9 #include <SDL2/SDL_keyboard.h>
10 #include <SDL2/SDL_mouse.h>
11 #include <SDL2/SDL_video.h>
24 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
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;
34 // Weighting constants for the different parts of the variational refinement.
35 // These don't correspond 1:1 to the values given in the DIS paper,
36 // since we have different normalizations and ranges in some cases.
37 float vr_gamma = 10.0f, vr_delta = 5.0f, vr_alpha = 10.0f;
39 // Some global OpenGL objects.
40 GLuint nearest_sampler, linear_sampler, smoothness_sampler;
43 string read_file(const string &filename)
45 FILE *fp = fopen(filename.c_str(), "r");
47 perror(filename.c_str());
51 int ret = fseek(fp, 0, SEEK_END);
53 perror("fseek(SEEK_END)");
59 ret = fseek(fp, 0, SEEK_SET);
61 perror("fseek(SEEK_SET)");
67 ret = fread(&str[0], size, 1, fp);
73 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
74 size, filename.c_str());
83 GLuint compile_shader(const string &shader_src, GLenum type)
85 GLuint obj = glCreateShader(type);
86 const GLchar* source[] = { shader_src.data() };
87 const GLint length[] = { (GLint)shader_src.size() };
88 glShaderSource(obj, 1, source, length);
91 GLchar info_log[4096];
92 GLsizei log_length = sizeof(info_log) - 1;
93 glGetShaderInfoLog(obj, log_length, &log_length, info_log);
94 info_log[log_length] = 0;
95 if (strlen(info_log) > 0) {
96 fprintf(stderr, "Shader compile log: %s\n", info_log);
100 glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
101 if (status == GL_FALSE) {
102 // Add some line numbers to easier identify compile errors.
103 string src_with_lines = "/* 1 */ ";
105 for (char ch : shader_src) {
106 src_with_lines.push_back(ch);
109 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
110 src_with_lines += buf;
114 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
121 GLuint load_texture(const char *filename, unsigned *width_ret, unsigned *height_ret)
123 SDL_Surface *surf = IMG_Load(filename);
124 if (surf == nullptr) {
125 fprintf(stderr, "IMG_Load(%s): %s\n", filename, IMG_GetError());
129 // For whatever reason, SDL doesn't support converting to YUV surfaces
130 // nor grayscale, so we'll do it (slowly) ourselves.
131 SDL_Surface *rgb_surf = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_RGBA8888, /*flags=*/0);
132 if (rgb_surf == nullptr) {
133 fprintf(stderr, "SDL_ConvertSurfaceFormat(%s): %s\n", filename, SDL_GetError());
137 SDL_FreeSurface(surf);
139 unsigned width = rgb_surf->w, height = rgb_surf->h;
140 const uint8_t *sptr = (uint8_t *)rgb_surf->pixels;
141 unique_ptr<uint8_t[]> pix(new uint8_t[width * height]);
143 // Extract the Y component, and convert to bottom-left origin.
144 for (unsigned y = 0; y < height; ++y) {
145 unsigned y2 = height - 1 - y;
146 for (unsigned x = 0; x < width; ++x) {
147 uint8_t r = sptr[(y2 * width + x) * 4 + 3];
148 uint8_t g = sptr[(y2 * width + x) * 4 + 2];
149 uint8_t b = sptr[(y2 * width + x) * 4 + 1];
152 pix[y * width + x] = lrintf(r * 0.2126f + g * 0.7152f + b * 0.0722f);
155 SDL_FreeSurface(rgb_surf);
158 for (int w = width, h = height; w > 1 || h > 1; ) {
165 glCreateTextures(GL_TEXTURE_2D, 1, &tex);
166 glTextureStorage2D(tex, levels, GL_R8, width, height);
167 glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, pix.get());
168 glGenerateTextureMipmap(tex);
171 *height_ret = height;
176 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
178 GLuint program = glCreateProgram();
179 glAttachShader(program, vs_obj);
180 glAttachShader(program, fs_obj);
181 glLinkProgram(program);
183 glGetProgramiv(program, GL_LINK_STATUS, &success);
184 if (success == GL_FALSE) {
185 GLchar error_log[1024] = {0};
186 glGetProgramInfoLog(program, 1024, nullptr, error_log);
187 fprintf(stderr, "Error linking program: %s\n", error_log);
193 GLuint generate_vbo(GLint size, GLsizeiptr data_size, const GLvoid *data)
196 glCreateBuffers(1, &vbo);
197 glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
198 glNamedBufferData(vbo, data_size, data, GL_STATIC_DRAW);
202 GLuint fill_vertex_attribute(GLuint vao, GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
204 int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
209 GLuint vbo = generate_vbo(size, data_size, data);
211 glBindBuffer(GL_ARRAY_BUFFER, vbo);
212 glEnableVertexArrayAttrib(vao, attrib);
213 glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
214 glBindBuffer(GL_ARRAY_BUFFER, 0);
219 void bind_sampler(GLuint program, GLint location, GLuint texture_unit, GLuint tex, GLuint sampler)
221 if (location == -1) {
225 glBindTextureUnit(texture_unit, tex);
226 glBindSampler(texture_unit, sampler);
227 glProgramUniform1i(program, location, texture_unit);
230 // Compute gradients in every point, used for the motion search.
231 // The DIS paper doesn't actually mention how these are computed,
232 // but seemingly, a 3x3 Sobel operator is used here (at least in
233 // later versions of the code), while a [1 -8 0 8 -1] kernel is
234 // used for all the derivatives in the variational refinement part
235 // (which borrows code from DeepFlow). This is inconsistent,
236 // but I guess we're better off with staying with the original
237 // decisions until we actually know having different ones would be better.
241 void exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height);
246 GLuint sobel_program;
249 GLuint uniform_tex, uniform_image_size;
254 sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
255 sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
256 sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
258 // Set up the VAO containing all the required position/texcoord data.
259 glCreateVertexArrays(1, &sobel_vao);
260 glBindVertexArray(sobel_vao);
262 GLint position_attrib = glGetAttribLocation(sobel_program, "position");
263 glEnableVertexArrayAttrib(sobel_vao, position_attrib);
264 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
266 uniform_tex = glGetUniformLocation(sobel_program, "tex");
269 void Sobel::exec(GLint tex0_view, GLint grad0_tex, int level_width, int level_height)
271 glUseProgram(sobel_program);
272 glBindTextureUnit(0, tex0_view);
273 glBindSampler(0, nearest_sampler);
274 glProgramUniform1i(sobel_program, uniform_tex, 0);
276 GLuint grad0_fbo; // TODO: cleanup
277 glCreateFramebuffers(1, &grad0_fbo);
278 glNamedFramebufferTexture(grad0_fbo, GL_COLOR_ATTACHMENT0, grad0_tex, 0);
280 glViewport(0, 0, level_width, level_height);
281 glBindFramebuffer(GL_FRAMEBUFFER, grad0_fbo);
282 glBindVertexArray(sobel_vao);
283 glUseProgram(sobel_program);
285 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
288 // Motion search to find the initial flow. See motion_search.frag for documentation.
292 void exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int prev_level_width, int prev_level_height, int width_patches, int height_patches);
295 GLuint motion_vs_obj;
296 GLuint motion_fs_obj;
297 GLuint motion_search_program;
298 GLuint motion_search_vao;
300 GLuint uniform_image_size, uniform_inv_image_size, uniform_inv_prev_level_size;
301 GLuint uniform_image0_tex, uniform_image1_tex, uniform_grad0_tex, uniform_flow_tex;
304 MotionSearch::MotionSearch()
306 motion_vs_obj = compile_shader(read_file("motion_search.vert"), GL_VERTEX_SHADER);
307 motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
308 motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
310 // Set up the VAO containing all the required position/texcoord data.
311 glCreateVertexArrays(1, &motion_search_vao);
312 glBindVertexArray(motion_search_vao);
313 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
315 GLint position_attrib = glGetAttribLocation(motion_search_program, "position");
316 glEnableVertexArrayAttrib(motion_search_vao, position_attrib);
317 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
319 uniform_image_size = glGetUniformLocation(motion_search_program, "image_size");
320 uniform_inv_image_size = glGetUniformLocation(motion_search_program, "inv_image_size");
321 uniform_inv_prev_level_size = glGetUniformLocation(motion_search_program, "inv_prev_level_size");
322 uniform_image0_tex = glGetUniformLocation(motion_search_program, "image0_tex");
323 uniform_image1_tex = glGetUniformLocation(motion_search_program, "image1_tex");
324 uniform_grad0_tex = glGetUniformLocation(motion_search_program, "grad0_tex");
325 uniform_flow_tex = glGetUniformLocation(motion_search_program, "flow_tex");
328 void MotionSearch::exec(GLuint tex0_view, GLuint tex1_view, GLuint grad0_tex, GLuint flow_tex, GLuint flow_out_tex, int level_width, int level_height, int prev_level_width, int prev_level_height, int width_patches, int height_patches)
330 glUseProgram(motion_search_program);
332 bind_sampler(motion_search_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
333 bind_sampler(motion_search_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
334 bind_sampler(motion_search_program, uniform_grad0_tex, 2, grad0_tex, nearest_sampler);
335 bind_sampler(motion_search_program, uniform_flow_tex, 3, flow_tex, linear_sampler);
337 glProgramUniform2f(motion_search_program, uniform_image_size, level_width, level_height);
338 glProgramUniform2f(motion_search_program, uniform_inv_image_size, 1.0f / level_width, 1.0f / level_height);
339 glProgramUniform2f(motion_search_program, uniform_inv_prev_level_size, 1.0f / prev_level_width, 1.0f / prev_level_height);
341 GLuint flow_fbo; // TODO: cleanup
342 glCreateFramebuffers(1, &flow_fbo);
343 glNamedFramebufferTexture(flow_fbo, GL_COLOR_ATTACHMENT0, flow_out_tex, 0);
345 glViewport(0, 0, width_patches, height_patches);
346 glBindFramebuffer(GL_FRAMEBUFFER, flow_fbo);
347 glBindVertexArray(motion_search_vao);
348 glUseProgram(motion_search_program);
349 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
352 // Do “densification”, ie., upsampling of the flow patches to the flow field
353 // (the same size as the image at this level). We draw one quad per patch
354 // over its entire covered area (using instancing in the vertex shader),
355 // and then weight the contributions in the pixel shader by post-warp difference.
356 // This is equation (3) in the paper.
358 // We accumulate the flow vectors in the R/G channels (for u/v) and the total
359 // weight in the B channel. Dividing R and G by B gives the normalized values.
363 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);
366 GLuint densify_vs_obj;
367 GLuint densify_fs_obj;
368 GLuint densify_program;
371 GLuint uniform_width_patches, uniform_patch_size, uniform_patch_spacing;
372 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
377 densify_vs_obj = compile_shader(read_file("densify.vert"), GL_VERTEX_SHADER);
378 densify_fs_obj = compile_shader(read_file("densify.frag"), GL_FRAGMENT_SHADER);
379 densify_program = link_program(densify_vs_obj, densify_fs_obj);
381 // Set up the VAO containing all the required position/texcoord data.
382 glCreateVertexArrays(1, &densify_vao);
383 glBindVertexArray(densify_vao);
384 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
386 GLint position_attrib = glGetAttribLocation(densify_program, "position");
387 glEnableVertexArrayAttrib(densify_vao, position_attrib);
388 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
390 uniform_width_patches = glGetUniformLocation(densify_program, "width_patches");
391 uniform_patch_size = glGetUniformLocation(densify_program, "patch_size");
392 uniform_patch_spacing = glGetUniformLocation(densify_program, "patch_spacing");
393 uniform_image0_tex = glGetUniformLocation(densify_program, "image0_tex");
394 uniform_image1_tex = glGetUniformLocation(densify_program, "image1_tex");
395 uniform_flow_tex = glGetUniformLocation(densify_program, "flow_tex");
398 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)
400 glUseProgram(densify_program);
402 bind_sampler(densify_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
403 bind_sampler(densify_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
404 bind_sampler(densify_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
406 glProgramUniform1i(densify_program, uniform_width_patches, width_patches);
407 glProgramUniform2f(densify_program, uniform_patch_size,
408 float(patch_size_pixels) / level_width,
409 float(patch_size_pixels) / level_height);
411 float patch_spacing_x = float(level_width - patch_size_pixels) / (width_patches - 1);
412 float patch_spacing_y = float(level_height - patch_size_pixels) / (height_patches - 1);
413 if (width_patches == 1) patch_spacing_x = 0.0f; // Avoid infinities.
414 if (height_patches == 1) patch_spacing_y = 0.0f;
415 glProgramUniform2f(densify_program, uniform_patch_spacing,
416 patch_spacing_x / level_width,
417 patch_spacing_y / level_height);
419 GLuint dense_flow_fbo; // TODO: cleanup
420 glCreateFramebuffers(1, &dense_flow_fbo);
421 glNamedFramebufferTexture(dense_flow_fbo, GL_COLOR_ATTACHMENT0, dense_flow_tex, 0);
423 glViewport(0, 0, level_width, level_height);
425 glBlendFunc(GL_ONE, GL_ONE);
426 glBindVertexArray(densify_vao);
427 glBindFramebuffer(GL_FRAMEBUFFER, dense_flow_fbo);
428 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, width_patches * height_patches);
431 // Warp I_1 to I_w, and then compute the mean (I) and difference (I_t) of
432 // I_0 and I_w. The prewarping is what enables us to solve the variational
433 // flow for du,dv instead of u,v.
435 // Also calculates the normalized flow, ie. divides by z (this is needed because
436 // Densify works by additive blending) and multiplies by the image size.
438 // See variational_refinement.txt for more information.
442 void exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint normalized_flow_tex, GLuint I_tex, GLuint I_t_tex, int level_width, int level_height);
445 GLuint prewarp_vs_obj;
446 GLuint prewarp_fs_obj;
447 GLuint prewarp_program;
450 GLuint uniform_image0_tex, uniform_image1_tex, uniform_flow_tex;
451 GLuint uniform_image_size;
456 prewarp_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
457 prewarp_fs_obj = compile_shader(read_file("prewarp.frag"), GL_FRAGMENT_SHADER);
458 prewarp_program = link_program(prewarp_vs_obj, prewarp_fs_obj);
460 // Set up the VAO containing all the required position/texcoord data.
461 glCreateVertexArrays(1, &prewarp_vao);
462 glBindVertexArray(prewarp_vao);
463 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
465 GLint position_attrib = glGetAttribLocation(prewarp_program, "position");
466 glEnableVertexArrayAttrib(prewarp_vao, position_attrib);
467 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
469 uniform_image0_tex = glGetUniformLocation(prewarp_program, "image0_tex");
470 uniform_image1_tex = glGetUniformLocation(prewarp_program, "image1_tex");
471 uniform_flow_tex = glGetUniformLocation(prewarp_program, "flow_tex");
473 uniform_image_size = glGetUniformLocation(prewarp_program, "image_size");
476 void Prewarp::exec(GLuint tex0_view, GLuint tex1_view, GLuint flow_tex, GLuint I_tex, GLuint I_t_tex, GLuint normalized_flow_tex, int level_width, int level_height)
478 glUseProgram(prewarp_program);
480 bind_sampler(prewarp_program, uniform_image0_tex, 0, tex0_view, nearest_sampler);
481 bind_sampler(prewarp_program, uniform_image1_tex, 1, tex1_view, linear_sampler);
482 bind_sampler(prewarp_program, uniform_flow_tex, 2, flow_tex, nearest_sampler);
484 glProgramUniform2f(prewarp_program, uniform_image_size, level_width, level_height);
486 GLuint prewarp_fbo; // TODO: cleanup
487 glCreateFramebuffers(1, &prewarp_fbo);
488 GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
489 glNamedFramebufferDrawBuffers(prewarp_fbo, 3, bufs);
490 glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT0, I_tex, 0);
491 glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT1, I_t_tex, 0);
492 glNamedFramebufferTexture(prewarp_fbo, GL_COLOR_ATTACHMENT2, normalized_flow_tex, 0);
494 glViewport(0, 0, level_width, level_height);
496 glBindVertexArray(prewarp_vao);
497 glBindFramebuffer(GL_FRAMEBUFFER, prewarp_fbo);
498 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
501 // From I, calculate the partial derivatives I_x and I_y. We use a four-tap
502 // central difference filter, since apparently, that's tradition (I haven't
503 // measured quality versus a more normal 0.5 (I[x+1] - I[x-1]).)
504 // The coefficients come from
506 // https://en.wikipedia.org/wiki/Finite_difference_coefficient
508 // Also computes β_0, since it depends only on I_x and I_y.
512 void exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height);
515 GLuint derivatives_vs_obj;
516 GLuint derivatives_fs_obj;
517 GLuint derivatives_program;
518 GLuint derivatives_vao;
523 Derivatives::Derivatives()
525 derivatives_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
526 derivatives_fs_obj = compile_shader(read_file("derivatives.frag"), GL_FRAGMENT_SHADER);
527 derivatives_program = link_program(derivatives_vs_obj, derivatives_fs_obj);
529 // Set up the VAO containing all the required position/texcoord data.
530 glCreateVertexArrays(1, &derivatives_vao);
531 glBindVertexArray(derivatives_vao);
532 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
534 GLint position_attrib = glGetAttribLocation(derivatives_program, "position");
535 glEnableVertexArrayAttrib(derivatives_vao, position_attrib);
536 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
538 uniform_tex = glGetUniformLocation(derivatives_program, "tex");
541 void Derivatives::exec(GLuint input_tex, GLuint I_x_y_tex, GLuint beta_0_tex, int level_width, int level_height)
543 glUseProgram(derivatives_program);
545 bind_sampler(derivatives_program, uniform_tex, 0, input_tex, nearest_sampler);
547 GLuint derivatives_fbo; // TODO: cleanup
548 glCreateFramebuffers(1, &derivatives_fbo);
549 GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
550 glNamedFramebufferDrawBuffers(derivatives_fbo, 2, bufs);
551 glNamedFramebufferTexture(derivatives_fbo, GL_COLOR_ATTACHMENT0, I_x_y_tex, 0);
552 glNamedFramebufferTexture(derivatives_fbo, GL_COLOR_ATTACHMENT1, beta_0_tex, 0);
554 glViewport(0, 0, level_width, level_height);
556 glBindVertexArray(derivatives_vao);
557 glBindFramebuffer(GL_FRAMEBUFFER, derivatives_fbo);
558 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
561 // Calculate the smoothness constraints between neighboring pixels;
562 // s_x(x,y) stores smoothness between pixel (x,y) and (x+1,y),
563 // and s_y(x,y) stores between (x,y) and (x,y+1). We'll sample with
564 // border color (0,0) later, so that there's zero diffusion out of
567 // See variational_refinement.txt for more information.
568 class ComputeSmoothness {
571 void exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height);
574 GLuint smoothness_vs_obj;
575 GLuint smoothness_fs_obj;
576 GLuint smoothness_program;
577 GLuint smoothness_vao;
579 GLuint uniform_flow_tex, uniform_diff_flow_tex;
580 GLuint uniform_alpha;
583 ComputeSmoothness::ComputeSmoothness()
585 smoothness_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
586 smoothness_fs_obj = compile_shader(read_file("smoothness.frag"), GL_FRAGMENT_SHADER);
587 smoothness_program = link_program(smoothness_vs_obj, smoothness_fs_obj);
589 // Set up the VAO containing all the required position/texcoord data.
590 glCreateVertexArrays(1, &smoothness_vao);
591 glBindVertexArray(smoothness_vao);
592 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
594 GLint position_attrib = glGetAttribLocation(smoothness_program, "position");
595 glEnableVertexArrayAttrib(smoothness_vao, position_attrib);
596 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
598 uniform_flow_tex = glGetUniformLocation(smoothness_program, "flow_tex");
599 uniform_diff_flow_tex = glGetUniformLocation(smoothness_program, "diff_flow_tex");
600 uniform_alpha = glGetUniformLocation(smoothness_program, "alpha");
603 void ComputeSmoothness::exec(GLuint flow_tex, GLuint diff_flow_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, int level_width, int level_height)
605 glUseProgram(smoothness_program);
607 bind_sampler(smoothness_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
608 bind_sampler(smoothness_program, uniform_diff_flow_tex, 1, diff_flow_tex, nearest_sampler);
609 glProgramUniform1f(smoothness_program, uniform_alpha, vr_alpha);
611 GLuint smoothness_fbo; // TODO: cleanup
612 glCreateFramebuffers(1, &smoothness_fbo);
613 GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
614 glNamedFramebufferDrawBuffers(smoothness_fbo, 2, bufs);
615 glNamedFramebufferTexture(smoothness_fbo, GL_COLOR_ATTACHMENT0, smoothness_x_tex, 0);
616 glNamedFramebufferTexture(smoothness_fbo, GL_COLOR_ATTACHMENT1, smoothness_y_tex, 0);
618 glViewport(0, 0, level_width, level_height);
621 glBindVertexArray(smoothness_vao);
622 glBindFramebuffer(GL_FRAMEBUFFER, smoothness_fbo);
623 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
625 // Make sure the smoothness on the right and upper borders is zero.
626 // We could have done this by making (W-1)xH and Wx(H-1) textures instead
627 // (we're sampling smoothness with all-zero border color), but we'd
628 // have to adjust the sampling coordinates, which is annoying.
629 glClearTexSubImage(smoothness_x_tex, 0, level_width - 1, 0, 0, 1, level_height, 1, GL_RED, GL_FLOAT, nullptr);
630 glClearTexSubImage(smoothness_y_tex, 0, 0, level_height - 1, 0, level_width, 1, 1, GL_RED, GL_FLOAT, nullptr);
633 // Set up the equations set (two equations in two unknowns, per pixel).
634 // We store five floats; the three non-redundant elements of the 2x2 matrix (A)
635 // as 32-bit floats, and the two elements on the right-hand side (b) as 16-bit
636 // floats. (Actually, we store the inverse of the diagonal elements, because
637 // we only ever need to divide by them.) This fits into four u32 values;
638 // R, G, B for the matrix (the last element is symmetric) and A for the two b values.
639 // All the values of the energy term (E_I, E_G, E_S), except the smoothness
640 // terms that depend on other pixels, are calculated in one pass.
642 // See variational_refinement.txt for more information.
643 class SetupEquations {
646 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);
649 GLuint equations_vs_obj;
650 GLuint equations_fs_obj;
651 GLuint equations_program;
652 GLuint equations_vao;
654 GLuint uniform_I_x_y_tex, uniform_I_t_tex;
655 GLuint uniform_diff_flow_tex, uniform_base_flow_tex;
656 GLuint uniform_beta_0_tex;
657 GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
658 GLuint uniform_gamma, uniform_delta;
661 SetupEquations::SetupEquations()
663 equations_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
664 equations_fs_obj = compile_shader(read_file("equations.frag"), GL_FRAGMENT_SHADER);
665 equations_program = link_program(equations_vs_obj, equations_fs_obj);
667 // Set up the VAO containing all the required position/texcoord data.
668 glCreateVertexArrays(1, &equations_vao);
669 glBindVertexArray(equations_vao);
670 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
672 GLint position_attrib = glGetAttribLocation(equations_program, "position");
673 glEnableVertexArrayAttrib(equations_vao, position_attrib);
674 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
676 uniform_I_x_y_tex = glGetUniformLocation(equations_program, "I_x_y_tex");
677 uniform_I_t_tex = glGetUniformLocation(equations_program, "I_t_tex");
678 uniform_diff_flow_tex = glGetUniformLocation(equations_program, "diff_flow_tex");
679 uniform_base_flow_tex = glGetUniformLocation(equations_program, "base_flow_tex");
680 uniform_beta_0_tex = glGetUniformLocation(equations_program, "beta_0_tex");
681 uniform_smoothness_x_tex = glGetUniformLocation(equations_program, "smoothness_x_tex");
682 uniform_smoothness_y_tex = glGetUniformLocation(equations_program, "smoothness_y_tex");
683 uniform_gamma = glGetUniformLocation(equations_program, "gamma");
684 uniform_delta = glGetUniformLocation(equations_program, "delta");
687 void SetupEquations::exec(GLuint I_x_y_tex, GLuint I_t_tex, GLuint diff_flow_tex, GLuint base_flow_tex, GLuint beta_0_tex, GLuint smoothness_x_tex, GLuint smoothness_y_tex, GLuint equation_tex, int level_width, int level_height)
689 glUseProgram(equations_program);
691 bind_sampler(equations_program, uniform_I_x_y_tex, 0, I_x_y_tex, nearest_sampler);
692 bind_sampler(equations_program, uniform_I_t_tex, 1, I_t_tex, nearest_sampler);
693 bind_sampler(equations_program, uniform_diff_flow_tex, 2, diff_flow_tex, nearest_sampler);
694 bind_sampler(equations_program, uniform_base_flow_tex, 3, base_flow_tex, nearest_sampler);
695 bind_sampler(equations_program, uniform_beta_0_tex, 4, beta_0_tex, nearest_sampler);
696 bind_sampler(equations_program, uniform_smoothness_x_tex, 5, smoothness_x_tex, smoothness_sampler);
697 bind_sampler(equations_program, uniform_smoothness_y_tex, 6, smoothness_y_tex, smoothness_sampler);
698 glProgramUniform1f(equations_program, uniform_delta, vr_delta);
699 glProgramUniform1f(equations_program, uniform_gamma, vr_gamma);
701 GLuint equations_fbo; // TODO: cleanup
702 glCreateFramebuffers(1, &equations_fbo);
703 glNamedFramebufferTexture(equations_fbo, GL_COLOR_ATTACHMENT0, equation_tex, 0);
705 glViewport(0, 0, level_width, level_height);
707 glBindVertexArray(equations_vao);
708 glBindFramebuffer(GL_FRAMEBUFFER, equations_fbo);
709 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
712 // Actually solve the equation sets made by SetupEquations, by means of
713 // successive over-relaxation (SOR).
715 // See variational_refinement.txt for more information.
719 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);
727 GLuint uniform_diff_flow_tex;
728 GLuint uniform_equation_tex;
729 GLuint uniform_smoothness_x_tex, uniform_smoothness_y_tex;
734 sor_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
735 sor_fs_obj = compile_shader(read_file("sor.frag"), GL_FRAGMENT_SHADER);
736 sor_program = link_program(sor_vs_obj, sor_fs_obj);
738 // Set up the VAO containing all the required position/texcoord data.
739 glCreateVertexArrays(1, &sor_vao);
740 glBindVertexArray(sor_vao);
741 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
743 GLint position_attrib = glGetAttribLocation(sor_program, "position");
744 glEnableVertexArrayAttrib(sor_vao, position_attrib);
745 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
747 uniform_diff_flow_tex = glGetUniformLocation(sor_program, "diff_flow_tex");
748 uniform_equation_tex = glGetUniformLocation(sor_program, "equation_tex");
749 uniform_smoothness_x_tex = glGetUniformLocation(sor_program, "smoothness_x_tex");
750 uniform_smoothness_y_tex = glGetUniformLocation(sor_program, "smoothness_y_tex");
753 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)
755 glUseProgram(sor_program);
757 bind_sampler(sor_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
758 bind_sampler(sor_program, uniform_smoothness_x_tex, 1, smoothness_x_tex, smoothness_sampler);
759 bind_sampler(sor_program, uniform_smoothness_y_tex, 2, smoothness_y_tex, smoothness_sampler);
760 bind_sampler(sor_program, uniform_equation_tex, 3, equation_tex, nearest_sampler);
762 GLuint sor_fbo; // TODO: cleanup
763 glCreateFramebuffers(1, &sor_fbo);
764 glNamedFramebufferTexture(sor_fbo, GL_COLOR_ATTACHMENT0, diff_flow_tex, 0); // NOTE: Bind to same as we render from!
766 glViewport(0, 0, level_width, level_height);
768 glBindVertexArray(sor_vao);
769 glBindFramebuffer(GL_FRAMEBUFFER, sor_fbo);
771 for (int i = 0; i < num_iterations; ++i) {
772 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
773 if (i != num_iterations - 1) {
779 // Simply add the differential flow found by the variational refinement to the base flow.
780 // The output is in base_flow_tex; we don't need to make a new texture.
784 void exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height);
787 GLuint add_flow_vs_obj;
788 GLuint add_flow_fs_obj;
789 GLuint add_flow_program;
792 GLuint uniform_diff_flow_tex;
795 AddBaseFlow::AddBaseFlow()
797 add_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
798 add_flow_fs_obj = compile_shader(read_file("add_base_flow.frag"), GL_FRAGMENT_SHADER);
799 add_flow_program = link_program(add_flow_vs_obj, add_flow_fs_obj);
801 // Set up the VAO containing all the required position/texcoord data.
802 glCreateVertexArrays(1, &add_flow_vao);
803 glBindVertexArray(add_flow_vao);
804 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
806 GLint position_attrib = glGetAttribLocation(add_flow_program, "position");
807 glEnableVertexArrayAttrib(add_flow_vao, position_attrib);
808 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
810 uniform_diff_flow_tex = glGetUniformLocation(add_flow_program, "diff_flow_tex");
813 void AddBaseFlow::exec(GLuint base_flow_tex, GLuint diff_flow_tex, int level_width, int level_height)
815 glUseProgram(add_flow_program);
817 bind_sampler(add_flow_program, uniform_diff_flow_tex, 0, diff_flow_tex, nearest_sampler);
819 GLuint add_flow_fbo; // TODO: cleanup
820 glCreateFramebuffers(1, &add_flow_fbo);
821 glNamedFramebufferTexture(add_flow_fbo, GL_COLOR_ATTACHMENT0, base_flow_tex, 0);
823 glViewport(0, 0, level_width, level_height);
825 glBlendFunc(GL_ONE, GL_ONE);
826 glBindVertexArray(add_flow_vao);
827 glBindFramebuffer(GL_FRAMEBUFFER, add_flow_fbo);
829 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
832 // Take a copy of the flow, bilinearly interpolated and scaled up.
836 void exec(GLuint in_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height);
839 GLuint resize_flow_vs_obj;
840 GLuint resize_flow_fs_obj;
841 GLuint resize_flow_program;
842 GLuint resize_flow_vao;
844 GLuint uniform_flow_tex;
845 GLuint uniform_scale_factor;
848 ResizeFlow::ResizeFlow()
850 resize_flow_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
851 resize_flow_fs_obj = compile_shader(read_file("resize_flow.frag"), GL_FRAGMENT_SHADER);
852 resize_flow_program = link_program(resize_flow_vs_obj, resize_flow_fs_obj);
854 // Set up the VAO containing all the required position/texcoord data.
855 glCreateVertexArrays(1, &resize_flow_vao);
856 glBindVertexArray(resize_flow_vao);
857 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
859 GLint position_attrib = glGetAttribLocation(resize_flow_program, "position");
860 glEnableVertexArrayAttrib(resize_flow_vao, position_attrib);
861 glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
863 uniform_flow_tex = glGetUniformLocation(resize_flow_program, "flow_tex");
864 uniform_scale_factor = glGetUniformLocation(resize_flow_program, "scale_factor");
867 void ResizeFlow::exec(GLuint flow_tex, GLuint out_tex, int input_width, int input_height, int output_width, int output_height)
869 glUseProgram(resize_flow_program);
871 bind_sampler(resize_flow_program, uniform_flow_tex, 0, flow_tex, nearest_sampler);
873 glProgramUniform2f(resize_flow_program, uniform_scale_factor, float(output_width) / input_width, float(output_height) / input_height);
875 GLuint resize_flow_fbo; // TODO: cleanup
876 glCreateFramebuffers(1, &resize_flow_fbo);
877 glNamedFramebufferTexture(resize_flow_fbo, GL_COLOR_ATTACHMENT0, out_tex, 0);
879 glViewport(0, 0, output_width, output_height);
881 glBindVertexArray(resize_flow_vao);
882 glBindFramebuffer(GL_FRAMEBUFFER, resize_flow_fbo);
884 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
890 pair<GLuint, GLuint> begin_timer(const string &name, int level);
896 pair<GLuint, GLuint> query;
898 vector<Timer> timers;
901 pair<GLuint, GLuint> GPUTimers::begin_timer(const string &name, int level)
904 glGenQueries(2, queries);
905 glQueryCounter(queries[0], GL_TIMESTAMP);
910 timer.query.first = queries[0];
911 timer.query.second = queries[1];
912 timers.push_back(timer);
916 void GPUTimers::print()
918 for (const Timer &timer : timers) {
919 // NOTE: This makes the CPU wait for the GPU.
920 GLuint64 time_start, time_end;
921 glGetQueryObjectui64v(timer.query.first, GL_QUERY_RESULT, &time_start);
922 glGetQueryObjectui64v(timer.query.second, GL_QUERY_RESULT, &time_end);
923 //fprintf(stderr, "GPU time used = %.1f ms\n", time_elapsed / 1e6);
924 for (int i = 0; i < timer.level * 2; ++i) {
925 fprintf(stderr, " ");
927 fprintf(stderr, "%-30s %4.1f ms\n", timer.name.c_str(), GLint64(time_end - time_start) / 1e6);
931 // A simple RAII class for timing until the end of the scope.
934 ScopedTimer(const string &name, GPUTimers *timers)
935 : timers(timers), level(0)
937 query = timers->begin_timer(name, level);
940 ScopedTimer(const string &name, ScopedTimer *parent_timer)
941 : timers(parent_timer->timers),
942 level(parent_timer->level + 1)
944 query = timers->begin_timer(name, level);
955 glQueryCounter(query.second, GL_TIMESTAMP);
963 pair<GLuint, GLuint> query;
967 int main(int argc, char **argv)
969 static const option long_options[] = {
970 { "alpha", required_argument, 0, 'a' },
971 { "delta", required_argument, 0, 'd' },
972 { "gamma", required_argument, 0, 'g' }
976 int option_index = 0;
977 int c = getopt_long(argc, argv, "a:d:g:", long_options, &option_index);
984 vr_alpha = atof(optarg);
987 vr_delta = atof(optarg);
990 vr_gamma = atof(optarg);
993 fprintf(stderr, "Unknown option '%s'\n", argv[option_index]);
998 if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
999 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
1002 SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
1003 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
1004 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
1005 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
1007 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
1008 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
1009 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
1010 // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
1011 SDL_Window *window = SDL_CreateWindow("OpenGL window",
1012 SDL_WINDOWPOS_UNDEFINED,
1013 SDL_WINDOWPOS_UNDEFINED,
1016 SDL_GLContext context = SDL_GL_CreateContext(window);
1017 assert(context != nullptr);
1020 unsigned width1, height1, width2, height2;
1021 GLuint tex0 = load_texture(argc >= (optind + 1) ? argv[optind] : "test1499.png", &width1, &height1);
1022 GLuint tex1 = load_texture(argc >= (optind + 2) ? argv[optind + 1] : "test1500.png", &width2, &height2);
1024 if (width1 != width2 || height1 != height2) {
1025 fprintf(stderr, "Image dimensions don't match (%dx%d versus %dx%d)\n",
1026 width1, height1, width2, height2);
1030 // Make some samplers.
1031 glCreateSamplers(1, &nearest_sampler);
1032 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1033 glSamplerParameteri(nearest_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1034 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1035 glSamplerParameteri(nearest_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1037 glCreateSamplers(1, &linear_sampler);
1038 glSamplerParameteri(linear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1039 glSamplerParameteri(linear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1040 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
1041 glSamplerParameteri(linear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
1043 // The smoothness is sampled so that once we get to a smoothness involving
1044 // a value outside the border, the diffusivity between the two becomes zero.
1045 glCreateSamplers(1, &smoothness_sampler);
1046 glSamplerParameteri(smoothness_sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1047 glSamplerParameteri(smoothness_sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1048 glSamplerParameteri(smoothness_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
1049 glSamplerParameteri(smoothness_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
1050 float zero[] = { 0.0f, 0.0f, 0.0f, 0.0f };
1051 glSamplerParameterfv(smoothness_sampler, GL_TEXTURE_BORDER_COLOR, zero);
1053 float vertices[] = {
1059 glCreateBuffers(1, &vertex_vbo);
1060 glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
1061 glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
1063 // Initial flow is zero, 1x1.
1064 GLuint initial_flow_tex;
1065 glCreateTextures(GL_TEXTURE_2D, 1, &initial_flow_tex);
1066 glTextureStorage2D(initial_flow_tex, 1, GL_RG16F, 1, 1);
1067 glClearTexImage(initial_flow_tex, 0, GL_RG, GL_FLOAT, nullptr);
1068 int prev_level_width = 1, prev_level_height = 1;
1070 GLuint prev_level_flow_tex = initial_flow_tex;
1073 MotionSearch motion_search;
1076 Derivatives derivatives;
1077 ComputeSmoothness compute_smoothness;
1078 SetupEquations setup_equations;
1080 AddBaseFlow add_base_flow;
1081 ResizeFlow resize_flow;
1084 glGenQueries(1, &query);
1085 glBeginQuery(GL_TIME_ELAPSED, query);
1089 ScopedTimer total_timer("Total", &timers);
1090 for (int level = coarsest_level; level >= int(finest_level); --level) {
1091 char timer_name[256];
1092 snprintf(timer_name, sizeof(timer_name), "Level %d", level);
1093 ScopedTimer level_timer(timer_name, &total_timer);
1095 int level_width = width1 >> level;
1096 int level_height = height1 >> level;
1097 float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
1098 int width_patches = 1 + lrintf((level_width - patch_size_pixels) / patch_spacing_pixels);
1099 int height_patches = 1 + lrintf((level_height - patch_size_pixels) / patch_spacing_pixels);
1101 // Make sure we always read from the correct level; the chosen
1102 // mipmapping could otherwise be rather unpredictable, especially
1103 // during motion search.
1104 // TODO: create these beforehand, and stop leaking them.
1105 GLuint tex0_view, tex1_view;
1106 glGenTextures(1, &tex0_view);
1107 glTextureView(tex0_view, GL_TEXTURE_2D, tex0, GL_R8, level, 1, 0, 1);
1108 glGenTextures(1, &tex1_view);
1109 glTextureView(tex1_view, GL_TEXTURE_2D, tex1, GL_R8, level, 1, 0, 1);
1111 // Create a new texture; we could be fancy and render use a multi-level
1112 // texture, but meh.
1114 glCreateTextures(GL_TEXTURE_2D, 1, &grad0_tex);
1115 glTextureStorage2D(grad0_tex, 1, GL_RG16F, level_width, level_height);
1117 // Find the derivative.
1119 ScopedTimer timer("Sobel", &level_timer);
1120 sobel.exec(tex0_view, grad0_tex, level_width, level_height);
1123 // Motion search to find the initial flow. We use the flow from the previous
1124 // level (sampled bilinearly; no fancy tricks) as a guide, then search from there.
1126 // Create an output flow texture.
1127 GLuint flow_out_tex;
1128 glCreateTextures(GL_TEXTURE_2D, 1, &flow_out_tex);
1129 glTextureStorage2D(flow_out_tex, 1, GL_RGB16F, width_patches, height_patches);
1133 ScopedTimer timer("Motion search", &level_timer);
1134 motion_search.exec(tex0_view, tex1_view, grad0_tex, prev_level_flow_tex, flow_out_tex, level_width, level_height, prev_level_width, prev_level_height, width_patches, height_patches);
1139 // Set up an output texture (initially zero).
1140 GLuint dense_flow_tex;
1141 glCreateTextures(GL_TEXTURE_2D, 1, &dense_flow_tex);
1142 glTextureStorage2D(dense_flow_tex, 1, GL_RGB16F, level_width, level_height);
1143 glClearTexImage(dense_flow_tex, 0, GL_RGB, GL_FLOAT, nullptr);
1147 ScopedTimer timer("Densification", &level_timer);
1148 densify.exec(tex0_view, tex1_view, flow_out_tex, dense_flow_tex, level_width, level_height, width_patches, height_patches);
1151 // Everything below here in the loop belongs to variational refinement.
1152 ScopedTimer varref_timer("Variational refinement", &level_timer);
1154 // Prewarping; create I and I_t, and a normalized base flow (so we don't
1155 // have to normalize it over and over again, and also save some bandwidth).
1157 // During the entire rest of the variational refinement, flow will be measured
1158 // in pixels, not 0..1 normalized OpenGL texture coordinates.
1159 // This is because variational refinement depends so heavily on derivatives,
1160 // which are measured in intensity levels per pixel.
1161 GLuint I_tex, I_t_tex, base_flow_tex;
1162 glCreateTextures(GL_TEXTURE_2D, 1, &I_tex);
1163 glCreateTextures(GL_TEXTURE_2D, 1, &I_t_tex);
1164 glCreateTextures(GL_TEXTURE_2D, 1, &base_flow_tex);
1165 glTextureStorage2D(I_tex, 1, GL_R16F, level_width, level_height);
1166 glTextureStorage2D(I_t_tex, 1, GL_R16F, level_width, level_height);
1167 glTextureStorage2D(base_flow_tex, 1, GL_RG16F, level_width, level_height);
1169 ScopedTimer timer("Prewarping", &varref_timer);
1170 prewarp.exec(tex0_view, tex1_view, dense_flow_tex, I_tex, I_t_tex, base_flow_tex, level_width, level_height);
1173 // Calculate I_x and I_y. We're only calculating first derivatives;
1174 // the others will be taken on-the-fly in order to sample from fewer
1175 // textures overall, since sampling from the L1 cache is cheap.
1176 // (TODO: Verify that this is indeed faster than making separate
1177 // double-derivative textures.)
1178 GLuint I_x_y_tex, beta_0_tex;
1179 glCreateTextures(GL_TEXTURE_2D, 1, &I_x_y_tex);
1180 glCreateTextures(GL_TEXTURE_2D, 1, &beta_0_tex);
1181 glTextureStorage2D(I_x_y_tex, 1, GL_RG16F, level_width, level_height);
1182 glTextureStorage2D(beta_0_tex, 1, GL_R16F, level_width, level_height);
1184 ScopedTimer timer("First derivatives", &varref_timer);
1185 derivatives.exec(I_tex, I_x_y_tex, beta_0_tex, level_width, level_height);
1188 // We need somewhere to store du and dv (the flow increment, relative
1189 // to the non-refined base flow u0 and v0). It starts at zero.
1191 glCreateTextures(GL_TEXTURE_2D, 1, &du_dv_tex);
1192 glTextureStorage2D(du_dv_tex, 1, GL_RG16F, level_width, level_height);
1193 glClearTexImage(du_dv_tex, 0, GL_RG, GL_FLOAT, nullptr);
1195 // And for smoothness.
1196 GLuint smoothness_x_tex, smoothness_y_tex;
1197 glCreateTextures(GL_TEXTURE_2D, 1, &smoothness_x_tex);
1198 glCreateTextures(GL_TEXTURE_2D, 1, &smoothness_y_tex);
1199 glTextureStorage2D(smoothness_x_tex, 1, GL_R16F, level_width, level_height);
1200 glTextureStorage2D(smoothness_y_tex, 1, GL_R16F, level_width, level_height);
1202 // And finally for the equation set. See SetupEquations for
1203 // the storage format.
1204 GLuint equation_tex;
1205 glCreateTextures(GL_TEXTURE_2D, 1, &equation_tex);
1206 glTextureStorage2D(equation_tex, 1, GL_RGBA32UI, level_width, level_height);
1208 for (int outer_idx = 0; outer_idx < level + 1; ++outer_idx) {
1209 // Calculate the smoothness terms between the neighboring pixels,
1210 // both in x and y direction.
1212 ScopedTimer timer("Compute smoothness", &varref_timer);
1213 compute_smoothness.exec(base_flow_tex, du_dv_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height);
1216 // Set up the 2x2 equation system for each pixel.
1218 ScopedTimer timer("Set up equations", &varref_timer);
1219 setup_equations.exec(I_x_y_tex, I_t_tex, du_dv_tex, base_flow_tex, beta_0_tex, smoothness_x_tex, smoothness_y_tex, equation_tex, level_width, level_height);
1222 // Run a few SOR (or quasi-SOR, since we're not really Jacobi) iterations.
1223 // Note that these are to/from the same texture.
1225 ScopedTimer timer("SOR", &varref_timer);
1226 sor.exec(du_dv_tex, equation_tex, smoothness_x_tex, smoothness_y_tex, level_width, level_height, 5);
1230 // Add the differential flow found by the variational refinement to the base flow,
1231 // giving the final flow estimate for this level.
1232 // The output is in diff_flow_tex; we don't need to make a new texture.
1233 // You can comment out this part if you wish to test disabling of the variational refinement.
1235 ScopedTimer timer("Add differential flow", &varref_timer);
1236 add_base_flow.exec(base_flow_tex, du_dv_tex, level_width, level_height);
1239 prev_level_flow_tex = base_flow_tex;
1240 prev_level_width = level_width;
1241 prev_level_height = level_height;
1247 // Scale up the flow to the final size (if needed).
1249 if (finest_level == 0) {
1250 final_tex = prev_level_flow_tex;
1252 glCreateTextures(GL_TEXTURE_2D, 1, &final_tex);
1253 glTextureStorage2D(final_tex, 1, GL_RG16F, width1, height1);
1254 resize_flow.exec(prev_level_flow_tex, final_tex, prev_level_width, prev_level_height, width1, height1);
1257 unique_ptr<float[]> dense_flow(new float[width1 * height1 * 2]);
1258 glGetTextureImage(final_tex, 0, GL_RG, GL_FLOAT, width1 * height1 * 2 * sizeof(float), dense_flow.get());
1260 FILE *fp = fopen("flow.ppm", "wb");
1261 FILE *flowfp = fopen("flow.flo", "wb");
1262 fprintf(fp, "P6\n%d %d\n255\n", width1, height1);
1263 fprintf(flowfp, "FEIH");
1264 fwrite(&width1, 4, 1, flowfp);
1265 fwrite(&height1, 4, 1, flowfp);
1266 for (unsigned y = 0; y < unsigned(height1); ++y) {
1267 int yy = height1 - y - 1;
1268 for (unsigned x = 0; x < unsigned(width1); ++x) {
1269 float du = dense_flow[(yy * width1 + x) * 2 + 0];
1270 float dv = dense_flow[(yy * width1 + x) * 2 + 1];
1274 fwrite(&du, 4, 1, flowfp);
1275 fwrite(&dv, 4, 1, flowfp);
1278 flow2rgb(du, dv, &r, &g, &b);
1287 fprintf(stderr, "err = %d\n", glGetError());