]> git.sesse.net Git - movit/blob - util.cpp
Fix a C++11-related warning.
[movit] / util.cpp
1 #include <epoxy/gl.h>
2 #include <assert.h>
3 #include <math.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <locale>
8 #include <sstream>
9 #include <string>
10 #include <Eigen/Core>
11
12 #include "fp16.h"
13 #include "init.h"
14 #include "util.h"
15
16 #if defined(__APPLE__)
17 #include <OpenGL/OpenGL.h>
18 #elif defined(WIN32)
19 #include <epoxy/wgl.h>
20 #else
21 #include <epoxy/glx.h>
22 #endif
23
24 using namespace std;
25
26 namespace movit {
27
28 extern string *movit_data_directory;
29
30 void hsv2rgb(float h, float s, float v, float *r, float *g, float *b)
31 {
32         if (h < 0.0f) {
33                 h += 2.0f * M_PI;
34         }
35         float c = v * s;
36         float hp = (h * 180.0 / M_PI) / 60.0;
37         float x = c * (1 - fabs(fmod(hp, 2.0f) - 1.0f));
38
39         if (hp >= 0 && hp < 1) {
40                 *r = c;
41                 *g = x;
42                 *b = 0.0f;
43         } else if (hp >= 1 && hp < 2) {
44                 *r = x;
45                 *g = c;
46                 *b = 0.0f;
47         } else if (hp >= 2 && hp < 3) {
48                 *r = 0.0f;
49                 *g = c;
50                 *b = x;
51         } else if (hp >= 3 && hp < 4) {
52                 *r = 0.0f;
53                 *g = x;
54                 *b = c;
55         } else if (hp >= 4 && hp < 5) {
56                 *r = x;
57                 *g = 0.0f;
58                 *b = c;
59         } else {
60                 *r = c;
61                 *g = 0.0f;
62                 *b = x;
63         }
64
65         float m = v - c;
66         *r += m;
67         *g += m;
68         *b += m;
69 }
70
71 void hsv2rgb_normalized(float h, float s, float v, float *r, float *g, float *b)
72 {
73         float ref_r, ref_g, ref_b;
74         hsv2rgb(h, s, v, r, g, b);
75         hsv2rgb(h, 0.0f, v, &ref_r, &ref_g, &ref_b);
76         float lum = 0.2126 * *r + 0.7152 * *g + 0.0722 * *b;
77         float ref_lum = 0.2126 * ref_r + 0.7152 * ref_g + 0.0722 * ref_b;
78         if (lum > 1e-3) {
79                 float fac = ref_lum / lum;
80                 *r *= fac;
81                 *g *= fac;
82                 *b *= fac;
83         }
84 }
85
86 string read_file(const string &filename)
87 {
88         const string full_pathname = *movit_data_directory + "/" + filename;
89
90         FILE *fp = fopen(full_pathname.c_str(), "r");
91         if (fp == NULL) {
92                 perror(full_pathname.c_str());
93                 exit(1);
94         }
95
96         int ret = fseek(fp, 0, SEEK_END);
97         if (ret == -1) {
98                 perror("fseek(SEEK_END)");
99                 exit(1);
100         }
101
102         int size = ftell(fp);
103
104         ret = fseek(fp, 0, SEEK_SET);
105         if (ret == -1) {
106                 perror("fseek(SEEK_SET)");
107                 exit(1);
108         }
109
110         string str;
111         str.resize(size);
112         ret = fread(&str[0], size, 1, fp);
113         if (ret == -1) {
114                 perror("fread");
115                 exit(1);
116         }
117         if (ret == 0) {
118                 fprintf(stderr, "Short read when trying to read %d bytes from %s\n",
119                         size, full_pathname.c_str());
120                 exit(1);
121         }
122         fclose(fp);
123
124         return str;
125 }
126
127 string read_version_dependent_file(const string &base, const string &extension)
128 {
129         if (movit_shader_model == MOVIT_GLSL_110) {
130                 return read_file(base + "." + extension);
131         } else if (movit_shader_model == MOVIT_GLSL_130) {
132                 return read_file(base + ".130." + extension);
133         } else if (movit_shader_model == MOVIT_ESSL_300) {
134                 return read_file(base + ".300es." + extension);
135         } else {
136                 assert(false);
137         }
138 }
139
140 GLuint compile_shader(const string &shader_src, GLenum type)
141 {
142         GLuint obj = glCreateShader(type);
143         const GLchar* source[] = { shader_src.data() };
144         const GLint length[] = { (GLint)shader_src.size() };
145         glShaderSource(obj, 1, source, length);
146         glCompileShader(obj);
147
148         GLchar info_log[4096];
149         GLsizei log_length = sizeof(info_log) - 1;
150         glGetShaderInfoLog(obj, log_length, &log_length, info_log);
151         info_log[log_length] = 0; 
152         if (strlen(info_log) > 0) {
153                 fprintf(stderr, "Shader compile log: %s\n", info_log);
154         }
155
156         GLint status;
157         glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
158         if (status == GL_FALSE) {
159                 exit(1);
160         }
161
162         return obj;
163 }
164
165 void print_3x3_matrix(const Eigen::Matrix3d& m)
166 {
167         printf("%6.4f %6.4f %6.4f\n", m(0,0), m(0,1), m(0,2));
168         printf("%6.4f %6.4f %6.4f\n", m(1,0), m(1,1), m(1,2));
169         printf("%6.4f %6.4f %6.4f\n", m(2,0), m(2,1), m(2,2));
170         printf("\n");
171 }
172
173 string output_glsl_mat3(const string &name, const Eigen::Matrix3d &m)
174 {
175         // Use stringstream to be independent of the current locale in a thread-safe manner.
176         stringstream ss;
177         ss.imbue(locale("C"));
178         ss.precision(8);
179         ss << "const mat3 " << name << " = mat3(\n";
180         ss << "    " << m(0,0) << ", " << m(1,0) << ", " << m(2,0) << ",\n";
181         ss << "    " << m(0,1) << ", " << m(1,1) << ", " << m(2,1) << ",\n";
182         ss << "    " << m(0,2) << ", " << m(1,2) << ", " << m(2,2) << ");\n\n";
183         return ss.str();
184 }
185
186 string output_glsl_vec2(const string &name, float x, float y)
187 {
188         // Use stringstream to be independent of the current locale in a thread-safe manner.
189         stringstream ss;
190         ss.imbue(locale("C"));
191         ss.precision(8);
192         ss << "const vec2 " << name << " = vec2(" << x << ", " << y << ");\n";
193         return ss.str();
194 }
195
196 string output_glsl_vec3(const string &name, float x, float y, float z)
197 {
198         // Use stringstream to be independent of the current locale in a thread-safe manner.
199         stringstream ss;
200         ss.imbue(locale("C"));
201         ss.precision(8);
202         ss << "const vec3 " << name << " = vec3(" << x << ", " << y << ", " << z << ");\n";
203         return ss.str();
204 }
205
206 template<class DestFloat>
207 void combine_two_samples(float w1, float w2, float pos1, float pos2, unsigned size,
208                          DestFloat *offset, DestFloat *total_weight, float *sum_sq_error)
209 {
210         assert(movit_initialized);
211         assert(w1 * w2 >= 0.0f);  // Should not have differing signs.
212         float z;  // Normalized 0..1 between pos1 and pos2.
213         if (fabs(w1 + w2) < 1e-6) {
214                 z = 0.5f;
215         } else {
216                 z = w2 / (w1 + w2);
217         }
218
219         // Round to the desired precision. Note that this might take z outside the 0..1 range.
220         *offset = from_fp64<DestFloat>(pos1 + z * (pos2 - pos1));
221         z = (to_fp64(*offset) - pos1) / (pos2 - pos1);
222
223         // Round to the minimum number of bits we have measured earlier.
224         // The card will do this for us anyway, but if we know what the real z
225         // is, we can pick a better total_weight below.
226         z *= size;  // Move to pixel coordinates,
227         z = lrintf(z / movit_texel_subpixel_precision) * movit_texel_subpixel_precision;  // Round.
228         z /= size;  // Move back to normalized coordinates.
229         
230         // Choose total weight w so that we minimize total squared error
231         // for the effective weights:
232         //
233         //   e = (w(1-z) - a)² + (wz - b)²
234         //
235         // Differentiating by w and setting equal to zero:
236         //
237         //   2(w(1-z) - a)(1-z) + 2(wz - b)z = 0
238         //   w(1-z)² - a(1-z) + wz² - bz = 0
239         //   w((1-z)² + z²) = a(1-z) + bz
240         //   w = (a(1-z) + bz) / ((1-z)² + z²)
241         //
242         // If z had infinite precision, this would simply reduce to w = w1 + w2.
243         *total_weight = (w1 * (1 - z) + w2 * z) / (z * z + (1 - z) * (1 - z));
244
245         if (sum_sq_error != NULL) {
246                 float err1 = *total_weight * (1 - z) - w1;
247                 float err2 = *total_weight * z - w2;
248                 *sum_sq_error = err1 * err1 + err2 * err2;
249         }
250 }
251
252 // Explicit instantiations.
253 template
254 void combine_two_samples<float>(float w1, float w2, float pos1, float pos2, unsigned size,
255                                 float *offset, float *total_weight, float *sum_sq_error);
256
257 template
258 void combine_two_samples<fp16_int_t>(float w1, float w2, float pos1, float pos2, unsigned size,
259                                      fp16_int_t *offset, fp16_int_t *total_weight, float *sum_sq_error);
260
261 GLuint fill_vertex_attribute(GLuint glsl_program_num, const string &attribute_name, GLint size, GLenum type, GLsizeiptr data_size, const GLvoid *data)
262 {
263         int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
264         if (attrib == -1) {
265                 return -1;
266         }
267
268         GLuint vbo;
269         glGenBuffers(1, &vbo);
270         check_error();
271         glBindBuffer(GL_ARRAY_BUFFER, vbo);
272         check_error();
273         glBufferData(GL_ARRAY_BUFFER, data_size, data, GL_STATIC_DRAW);
274         check_error();
275         glEnableVertexAttribArray(attrib);
276         check_error();
277         glVertexAttribPointer(attrib, size, type, GL_FALSE, 0, BUFFER_OFFSET(0));
278         check_error();
279         glBindBuffer(GL_ARRAY_BUFFER, 0);
280         check_error();
281
282         return vbo;
283 }
284
285 void cleanup_vertex_attribute(GLuint glsl_program_num, const string &attribute_name, GLuint vbo)
286 {
287         int attrib = glGetAttribLocation(glsl_program_num, attribute_name.c_str());
288         if (attrib == -1) {
289                 return;
290         }
291
292         glDisableVertexAttribArray(attrib);
293         check_error();
294         glDeleteBuffers(1, &vbo);
295         check_error();
296 }
297
298 unsigned div_round_up(unsigned a, unsigned b)
299 {
300         return (a + b - 1) / b;
301 }
302
303 // Algorithm from http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2.
304 unsigned next_power_of_two(unsigned v)
305 {
306         v--;
307         v |= v >> 1;
308         v |= v >> 2;
309         v |= v >> 4;
310         v |= v >> 8;
311         v |= v >> 16;
312         v++;
313         return v;
314 }
315
316 void *get_gl_context_identifier()
317 {
318 #if defined(__APPLE__)
319         return (void *)CGLGetCurrentContext();
320 #elif defined(WIN32)
321         return (void *)wglGetCurrentContext();
322 #else
323         return (void *)glXGetCurrentContext();
324 #endif
325 }
326
327 }  // namespace movit