]> git.sesse.net Git - nageru/blob - flow.cpp
Add some beginning flow computation code (currently only gradient calculation).
[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 <algorithm>
20 #include <memory>
21
22 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
23
24 using namespace std;
25
26 // Operating point 3 (10 Hz on CPU, excluding preprocessing).
27 constexpr float patch_overlap_ratio = 0.75f;
28 constexpr unsigned coarsest_level = 0;
29 constexpr unsigned finest_level = 0;
30 constexpr unsigned patch_size_pixels = 12;
31
32 string read_file(const string &filename)
33 {
34         FILE *fp = fopen(filename.c_str(), "r");
35         if (fp == nullptr) {
36                 perror(filename.c_str());
37                 exit(1);
38         }
39
40         int ret = fseek(fp, 0, SEEK_END);
41         if (ret == -1) {
42                 perror("fseek(SEEK_END)");
43                 exit(1);
44         }
45
46         int size = ftell(fp);
47
48         ret = fseek(fp, 0, SEEK_SET);
49         if (ret == -1) {
50                 perror("fseek(SEEK_SET)");
51                 exit(1);
52         }
53
54         string str;
55         str.resize(size);
56         ret = fread(&str[0], size, 1, fp);
57         if (ret == -1) {
58                 perror("fread");
59                 exit(1);
60         }
61         if (ret == 0) {
62                 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
63                                 size, filename.c_str());
64                 exit(1);
65         }
66         fclose(fp);
67
68         return str;
69 }
70
71
72 GLuint compile_shader(const string &shader_src, GLenum type)
73 {
74         GLuint obj = glCreateShader(type);
75         const GLchar* source[] = { shader_src.data() };
76         const GLint length[] = { (GLint)shader_src.size() };
77         glShaderSource(obj, 1, source, length);
78         glCompileShader(obj);
79
80         GLchar info_log[4096];
81         GLsizei log_length = sizeof(info_log) - 1;
82         glGetShaderInfoLog(obj, log_length, &log_length, info_log);
83         info_log[log_length] = 0;
84         if (strlen(info_log) > 0) {
85                 fprintf(stderr, "Shader compile log: %s\n", info_log);
86         }
87
88         GLint status;
89         glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
90         if (status == GL_FALSE) {
91                 // Add some line numbers to easier identify compile errors.
92                 string src_with_lines = "/*   1 */ ";
93                 size_t lineno = 1;
94                 for (char ch : shader_src) {
95                         src_with_lines.push_back(ch);
96                         if (ch == '\n') {
97                                 char buf[32];
98                                 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
99                                 src_with_lines += buf;
100                         }
101                 }
102
103                 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
104                 exit(1);
105         }
106
107         return obj;
108 }
109
110
111 GLuint load_texture(const char *filename, unsigned width, unsigned height)
112 {
113         FILE *fp = fopen(filename, "rb");
114         if (fp == nullptr) {
115                 perror(filename);
116                 exit(1);
117         }
118         unique_ptr<uint8_t[]> pix(new uint8_t[width * height]);
119         if (fread(pix.get(), width * height, 1, fp) != 1) {
120                 fprintf(stderr, "Short read from %s\n", filename);
121                 exit(1);
122         }
123         fclose(fp);
124
125         // Convert to bottom-left origin.
126         for (unsigned y = 0; y < height / 2; ++y) {
127                 unsigned y2 = height - 1 - y;
128                 swap_ranges(&pix[y * width], &pix[y * width + width], &pix[y2 * width]);
129         }
130
131         int levels = 1;
132         for (int w = width, h = height; w > 1 || h > 1; ) {
133                 w >>= 1;
134                 h >>= 1;
135                 ++levels;
136         }
137
138         GLuint tex;
139         glCreateTextures(GL_TEXTURE_2D, 1, &tex);
140         glTextureStorage2D(tex, levels, GL_R8, width, height);
141         glTextureSubImage2D(tex, 0, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, pix.get());
142         glGenerateTextureMipmap(tex);
143
144         return tex;
145 }
146
147 GLuint link_program(GLuint vs_obj, GLuint fs_obj)
148 {
149         GLuint program = glCreateProgram();
150         glAttachShader(program, vs_obj);
151         glAttachShader(program, fs_obj);
152         glLinkProgram(program);
153         GLint success;
154         glGetProgramiv(program, GL_LINK_STATUS, &success);
155         if (success == GL_FALSE) {
156                 GLchar error_log[1024] = {0};
157                 glGetProgramInfoLog(program, 1024, nullptr, error_log);
158                 fprintf(stderr, "Error linking program: %s\n", error_log);
159                 exit(1);
160         }
161         return program;
162 }
163
164 GLuint generate_vbo(GLint size, GLsizeiptr data_size, const GLvoid *data)
165 {
166         GLuint vbo;
167         glCreateBuffers(1, &vbo);
168         glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
169         glNamedBufferData(vbo, data_size, data, GL_STATIC_DRAW);
170         return vbo;
171 }
172
173 GLuint fill_vertex_attribute(GLuint vao, GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
174 {
175         int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
176         if (attrib == -1) {
177                 return -1;
178         }
179
180         GLuint vbo = generate_vbo(size, data_size, data);
181
182         glBindBuffer(GL_ARRAY_BUFFER, vbo);
183         glEnableVertexArrayAttrib(vao, attrib);
184         glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
185         glBindBuffer(GL_ARRAY_BUFFER, 0);
186
187         return vbo;
188 }      
189
190 int main(void)
191 {
192         if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
193                 fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
194                 exit(1);
195         }
196         SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
197         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
198         SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
199         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
200
201         SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
202         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
203         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
204         // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
205         SDL_Window *window = SDL_CreateWindow("OpenGL window",
206                         SDL_WINDOWPOS_UNDEFINED,
207                         SDL_WINDOWPOS_UNDEFINED,
208                         64, 64,
209                         SDL_WINDOW_OPENGL);
210         SDL_GLContext context = SDL_GL_CreateContext(window);
211         assert(context != nullptr);
212
213         // Load pictures.
214         GLuint tex0 = load_texture("test1499.pgm", WIDTH, HEIGHT);
215         GLuint tex1 = load_texture("test1500.pgm", WIDTH, HEIGHT);
216
217         // Load shaders.
218         GLuint motion_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
219         GLuint motion_fs_obj = compile_shader(read_file("motion_search.frag"), GL_FRAGMENT_SHADER);
220         GLuint motion_search_program = link_program(motion_vs_obj, motion_fs_obj);
221
222         GLuint sobel_vs_obj = compile_shader(read_file("vs.vert"), GL_VERTEX_SHADER);
223         GLuint sobel_fs_obj = compile_shader(read_file("sobel.frag"), GL_FRAGMENT_SHADER);
224         GLuint sobel_program = link_program(sobel_vs_obj, sobel_fs_obj);
225
226         // Coarsest level.
227         int level_width = WIDTH >> coarsest_level;
228         int level_height = HEIGHT >> coarsest_level;
229         float patch_spacing_pixels = patch_size_pixels * (1.0f - patch_overlap_ratio);
230         int width_patches = 1 + lrintf((level_width - patch_size_pixels) / patch_spacing_pixels);
231         int height_patches = 1 + lrintf((level_height - patch_size_pixels) / patch_spacing_pixels);
232
233         // Compute gradients in every point, used for the motion search.
234         // The DIS paper doesn't actually mention how these are computed,
235         // but seemingly, a 3x3 Sobel operator is used here (at least in
236         // later versions of the code), while a [1 -8 0 8 -1] kernel is
237         // used for all the derivatives in the variational refinement part
238         // (which borrows code from DeepFlow). This is inconsistent,
239         // but I guess we're better off with staying with the original
240         // decisions until we actually know having different ones would be better.
241
242         // Create a new texture; we could be fancy and render use a multi-level
243         // texture, but meh.
244         GLuint grad_tex;
245         glCreateTextures(GL_TEXTURE_2D, 1, &grad_tex);
246         glTextureStorage2D(grad_tex, 1, GL_RG16F, level_width, level_height);
247
248         GLuint grad_fbo;
249         glCreateFramebuffers(1, &grad_fbo);
250         glNamedFramebufferTexture(grad_fbo, GL_COLOR_ATTACHMENT0, grad_tex, 0);
251
252         glUseProgram(sobel_program);
253         glBindTextureUnit(0, tex0);
254         glUniform1i(glGetUniformLocation(sobel_program, "tex"), 0);
255         glUniform1f(glGetUniformLocation(sobel_program, "inv_width"), 1.0f / level_width);
256         glUniform1f(glGetUniformLocation(sobel_program, "inv_height"), 1.0f / level_height);
257
258         // Set up the VAO containing all the required position/texcoord data.
259         GLuint sobel_vao;
260         glCreateVertexArrays(1, &sobel_vao);
261         glBindVertexArray(sobel_vao);
262         float vertices[] = {
263                 0.0f, 1.0f,
264                 0.0f, 0.0f,
265                 1.0f, 1.0f,
266                 1.0f, 0.0f,
267         };
268         GLuint vertex_vbo;
269         glCreateBuffers(1, &vertex_vbo);
270         glNamedBufferData(vertex_vbo, sizeof(vertices), vertices, GL_STATIC_DRAW);
271         glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo);
272
273         int position_attrib = glGetAttribLocation(sobel_program, "position");
274         glEnableVertexArrayAttrib(sobel_vao, position_attrib);
275         glVertexAttribPointer(position_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
276
277         int texcoord_attrib = glGetAttribLocation(sobel_program, "texcoord");
278         glEnableVertexArrayAttrib(sobel_vao, texcoord_attrib);
279         glVertexAttribPointer(texcoord_attrib, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
280
281         glBindBuffer(GL_ARRAY_BUFFER, 0);
282
283         // Now finally draw.
284         glViewport(0, 0, level_width, level_height);
285         glBindFramebuffer(GL_FRAMEBUFFER, grad_fbo);
286         glUseProgram(sobel_program);
287         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
288         glUseProgram(0);
289         glBindFramebuffer(GL_FRAMEBUFFER, 0);
290         glBindVertexArray(0);
291
292         GLuint flow_tex;
293         glCreateTextures(GL_TEXTURE_2D, 1, &flow_tex);
294         glTextureStorage2D(flow_tex, 1, GL_RG16F, width_patches, height_patches);
295
296 //      printf("%d x %d patches on this level\n", width_patches, height_patches);
297 }