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