12 #include "resource_pool.h"
19 ResourcePool::ResourcePool(size_t program_freelist_max_length,
20 size_t texture_freelist_max_bytes,
21 size_t fbo_freelist_max_length,
22 size_t vao_freelist_max_length)
23 : program_freelist_max_length(program_freelist_max_length),
24 texture_freelist_max_bytes(texture_freelist_max_bytes),
25 fbo_freelist_max_length(fbo_freelist_max_length),
26 vao_freelist_max_length(vao_freelist_max_length),
27 texture_freelist_bytes(0)
29 pthread_mutex_init(&lock, nullptr);
32 ResourcePool::~ResourcePool()
34 assert(program_refcount.empty());
36 for (list<GLuint>::const_iterator freelist_it = program_freelist.begin();
37 freelist_it != program_freelist.end();
39 delete_program(*freelist_it);
41 assert(programs.empty());
42 assert(program_shaders.empty());
44 for (list<GLuint>::const_iterator freelist_it = texture_freelist.begin();
45 freelist_it != texture_freelist.end();
47 GLuint free_texture_num = *freelist_it;
48 assert(texture_formats.count(free_texture_num) != 0);
49 texture_freelist_bytes -= estimate_texture_size(texture_formats[free_texture_num]);
50 texture_formats.erase(free_texture_num);
51 glDeleteTextures(1, &free_texture_num);
54 assert(texture_formats.empty());
55 assert(texture_freelist_bytes == 0);
57 void *context = get_gl_context_identifier();
58 cleanup_unlinked_fbos(context);
60 for (map<void *, std::list<FBOFormatIterator> >::iterator context_it = fbo_freelist.begin();
61 context_it != fbo_freelist.end();
63 if (context_it->first != context) {
64 // If this does not hold, the client should have called clean_context() earlier.
65 assert(context_it->second.empty());
68 for (list<FBOFormatIterator>::const_iterator freelist_it = context_it->second.begin();
69 freelist_it != context_it->second.end();
71 FBOFormatIterator fbo_it = *freelist_it;
72 glDeleteFramebuffers(1, &fbo_it->second.fbo_num);
74 fbo_formats.erase(fbo_it);
78 assert(fbo_formats.empty());
81 void ResourcePool::delete_program(GLuint glsl_program_num)
83 bool found_program = false;
84 for (map<pair<string, string>, GLuint>::iterator program_it = programs.begin();
85 program_it != programs.end();
87 if (program_it->second == glsl_program_num) {
88 programs.erase(program_it);
93 assert(found_program);
95 map<GLuint, stack<GLuint> >::iterator instance_list_it = program_instances.find(glsl_program_num);
96 assert(instance_list_it != program_instances.end());
98 while (!instance_list_it->second.empty()) {
99 GLuint instance_program_num = instance_list_it->second.top();
100 instance_list_it->second.pop();
101 glDeleteProgram(instance_program_num);
102 program_masters.erase(instance_program_num);
104 program_instances.erase(instance_list_it);
106 map<GLuint, ShaderSpec>::iterator shader_it =
107 program_shaders.find(glsl_program_num);
108 assert(shader_it != program_shaders.end());
110 glDeleteShader(shader_it->second.vs_obj);
111 glDeleteShader(shader_it->second.fs_obj);
112 program_shaders.erase(shader_it);
115 GLuint ResourcePool::compile_glsl_program(const string& vertex_shader,
116 const string& fragment_shader,
117 const vector<string>& fragment_shader_outputs)
119 GLuint glsl_program_num;
120 pthread_mutex_lock(&lock);
122 // Augment the fragment shader program text with the outputs, so that they become
123 // part of the key. Also potentially useful for debugging.
124 string fragment_shader_processed = fragment_shader;
125 for (unsigned output_index = 0; output_index < fragment_shader_outputs.size(); ++output_index) {
127 snprintf(buf, sizeof(buf), "// Bound output: %s\n", fragment_shader_outputs[output_index].c_str());
128 fragment_shader_processed += buf;
131 const pair<string, string> key(vertex_shader, fragment_shader_processed);
132 if (programs.count(key)) {
133 // Already in the cache.
134 glsl_program_num = programs[key];
135 increment_program_refcount(glsl_program_num);
137 // Not in the cache. Compile the shaders.
138 GLuint vs_obj = compile_shader(vertex_shader, GL_VERTEX_SHADER);
140 GLuint fs_obj = compile_shader(fragment_shader_processed, GL_FRAGMENT_SHADER);
142 glsl_program_num = link_program(vs_obj, fs_obj, fragment_shader_outputs);
144 output_debug_shader(fragment_shader_processed, "frag");
146 programs.insert(make_pair(key, glsl_program_num));
147 add_master_program(glsl_program_num);
150 spec.vs_obj = vs_obj;
151 spec.fs_obj = fs_obj;
152 spec.fragment_shader_outputs = fragment_shader_outputs;
153 program_shaders.insert(make_pair(glsl_program_num, spec));
155 pthread_mutex_unlock(&lock);
156 return glsl_program_num;
159 GLuint ResourcePool::link_program(GLuint vs_obj,
161 const vector<string>& fragment_shader_outputs)
163 GLuint glsl_program_num = glCreateProgram();
165 glAttachShader(glsl_program_num, vs_obj);
167 glAttachShader(glsl_program_num, fs_obj);
170 // Bind the outputs, if we have multiple ones.
171 if (fragment_shader_outputs.size() > 1) {
172 for (unsigned output_index = 0; output_index < fragment_shader_outputs.size(); ++output_index) {
173 glBindFragDataLocation(glsl_program_num, output_index,
174 fragment_shader_outputs[output_index].c_str());
178 glLinkProgram(glsl_program_num);
182 glGetProgramiv(glsl_program_num, GL_LINK_STATUS, &success);
183 if (success == GL_FALSE) {
184 GLchar error_log[1024] = {0};
185 glGetProgramInfoLog(glsl_program_num, 1024, nullptr, error_log);
186 fprintf(stderr, "Error linking program: %s\n", error_log);
190 return glsl_program_num;
193 void ResourcePool::release_glsl_program(GLuint glsl_program_num)
195 pthread_mutex_lock(&lock);
196 map<GLuint, int>::iterator refcount_it = program_refcount.find(glsl_program_num);
197 assert(refcount_it != program_refcount.end());
199 if (--refcount_it->second == 0) {
200 program_refcount.erase(refcount_it);
201 assert(find(program_freelist.begin(), program_freelist.end(), glsl_program_num)
202 == program_freelist.end());
203 program_freelist.push_front(glsl_program_num);
204 if (program_freelist.size() > program_freelist_max_length) {
205 delete_program(program_freelist.back());
206 program_freelist.pop_back();
210 pthread_mutex_unlock(&lock);
213 GLuint ResourcePool::compile_glsl_compute_program(const string& compute_shader)
215 GLuint glsl_program_num;
216 pthread_mutex_lock(&lock);
218 const string &key = compute_shader;
219 if (compute_programs.count(key)) {
220 // Already in the cache.
221 glsl_program_num = compute_programs[key];
222 increment_program_refcount(glsl_program_num);
224 // Not in the cache. Compile the shader.
225 GLuint cs_obj = compile_shader(compute_shader, GL_COMPUTE_SHADER);
227 glsl_program_num = link_compute_program(cs_obj);
229 output_debug_shader(compute_shader, "compute");
231 compute_programs.insert(make_pair(key, glsl_program_num));
232 add_master_program(glsl_program_num);
234 ComputeShaderSpec spec;
235 spec.cs_obj = cs_obj;
236 compute_program_shaders.insert(make_pair(glsl_program_num, spec));
238 pthread_mutex_unlock(&lock);
239 return glsl_program_num;
242 GLuint ResourcePool::link_compute_program(GLuint cs_obj)
244 GLuint glsl_program_num = glCreateProgram();
246 glAttachShader(glsl_program_num, cs_obj);
248 glLinkProgram(glsl_program_num);
252 glGetProgramiv(glsl_program_num, GL_LINK_STATUS, &success);
253 if (success == GL_FALSE) {
254 GLchar error_log[1024] = {0};
255 glGetProgramInfoLog(glsl_program_num, 1024, nullptr, error_log);
256 fprintf(stderr, "Error linking program: %s\n", error_log);
260 return glsl_program_num;
263 GLuint ResourcePool::use_glsl_program(GLuint glsl_program_num)
265 pthread_mutex_lock(&lock);
266 assert(program_instances.count(glsl_program_num));
267 stack<GLuint> &instances = program_instances[glsl_program_num];
269 GLuint instance_program_num;
270 if (!instances.empty()) {
271 // There's an unused instance of this program; just return it.
272 instance_program_num = instances.top();
275 // We need to clone this program. (unuse_glsl_program()
276 // will later put it onto the list.)
277 map<GLuint, ShaderSpec>::iterator shader_it =
278 program_shaders.find(glsl_program_num);
279 if (shader_it == program_shaders.end()) {
280 // Should be a compute shader.
281 map<GLuint, ComputeShaderSpec>::iterator compute_shader_it =
282 compute_program_shaders.find(glsl_program_num);
283 instance_program_num = link_compute_program(
284 compute_shader_it->second.cs_obj);
286 // A regular fragment shader.
287 instance_program_num = link_program(
288 shader_it->second.vs_obj,
289 shader_it->second.fs_obj,
290 shader_it->second.fragment_shader_outputs);
292 program_masters.insert(make_pair(instance_program_num, glsl_program_num));
294 pthread_mutex_unlock(&lock);
296 glUseProgram(instance_program_num);
297 return instance_program_num;
300 void ResourcePool::unuse_glsl_program(GLuint instance_program_num)
302 pthread_mutex_lock(&lock);
304 map<GLuint, GLuint>::const_iterator master_it = program_masters.find(instance_program_num);
305 assert(master_it != program_masters.end());
307 assert(program_instances.count(master_it->second));
308 stack<GLuint> &instances = program_instances[master_it->second];
310 instances.push(instance_program_num);
312 pthread_mutex_unlock(&lock);
315 GLuint ResourcePool::create_2d_texture(GLint internal_format, GLsizei width, GLsizei height)
320 pthread_mutex_lock(&lock);
321 // See if there's a texture on the freelist we can use.
322 for (list<GLuint>::iterator freelist_it = texture_freelist.begin();
323 freelist_it != texture_freelist.end();
325 GLuint texture_num = *freelist_it;
326 map<GLuint, Texture2D>::const_iterator format_it = texture_formats.find(texture_num);
327 assert(format_it != texture_formats.end());
328 if (format_it->second.internal_format == internal_format &&
329 format_it->second.width == width &&
330 format_it->second.height == height) {
331 texture_freelist_bytes -= estimate_texture_size(format_it->second);
332 texture_freelist.erase(freelist_it);
333 pthread_mutex_unlock(&lock);
338 // Find any reasonable format given the internal format; OpenGL validates it
339 // even though we give nullptr as pointer.
341 switch (internal_format) {
347 case GL_SRGB8_ALPHA8:
353 case GL_R11F_G11F_B10F:
374 // TODO: Add more here as needed.
378 // Same with type; GLES is stricter than desktop OpenGL here.
380 switch (internal_format) {
385 case GL_R11F_G11F_B10F:
397 type = GL_UNSIGNED_SHORT;
399 case GL_SRGB8_ALPHA8:
407 type = GL_UNSIGNED_BYTE;
410 type = GL_UNSIGNED_SHORT_5_6_5;
413 // TODO: Add more here as needed.
419 glGenTextures(1, &texture_num);
421 glBindTexture(GL_TEXTURE_2D, texture_num);
423 glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0, format, type, nullptr);
425 glBindTexture(GL_TEXTURE_2D, 0);
428 Texture2D texture_format;
429 texture_format.internal_format = internal_format;
430 texture_format.width = width;
431 texture_format.height = height;
432 assert(texture_formats.count(texture_num) == 0);
433 texture_formats.insert(make_pair(texture_num, texture_format));
435 pthread_mutex_unlock(&lock);
439 void ResourcePool::release_2d_texture(GLuint texture_num)
441 pthread_mutex_lock(&lock);
442 texture_freelist.push_front(texture_num);
443 assert(texture_formats.count(texture_num) != 0);
444 texture_freelist_bytes += estimate_texture_size(texture_formats[texture_num]);
446 while (texture_freelist_bytes > texture_freelist_max_bytes) {
447 GLuint free_texture_num = texture_freelist.back();
448 texture_freelist.pop_back();
449 assert(texture_formats.count(free_texture_num) != 0);
450 texture_freelist_bytes -= estimate_texture_size(texture_formats[free_texture_num]);
451 texture_formats.erase(free_texture_num);
452 glDeleteTextures(1, &free_texture_num);
455 // Unlink any lingering FBO related to this texture. We might
456 // not be in the right context, so don't delete it right away;
457 // the cleanup in release_fbo() (which calls cleanup_unlinked_fbos())
458 // will take care of actually doing that later.
459 for (map<pair<void *, GLuint>, FBO>::iterator format_it = fbo_formats.begin();
460 format_it != fbo_formats.end();
462 for (unsigned i = 0; i < num_fbo_attachments; ++i) {
463 if (format_it->second.texture_num[i] == free_texture_num) {
464 format_it->second.texture_num[i] = GL_INVALID_INDEX;
469 pthread_mutex_unlock(&lock);
472 GLuint ResourcePool::create_fbo(GLuint texture0_num, GLuint texture1_num, GLuint texture2_num, GLuint texture3_num)
474 void *context = get_gl_context_identifier();
476 // Make sure we are filled from the bottom.
477 assert(texture0_num != 0);
478 if (texture1_num == 0) {
479 assert(texture2_num == 0);
481 if (texture2_num == 0) {
482 assert(texture3_num == 0);
485 pthread_mutex_lock(&lock);
486 if (fbo_freelist.count(context) != 0) {
487 // See if there's an FBO on the freelist we can use.
488 list<FBOFormatIterator>::iterator end = fbo_freelist[context].end();
489 for (list<FBOFormatIterator>::iterator freelist_it = fbo_freelist[context].begin();
490 freelist_it != end; ++freelist_it) {
491 FBOFormatIterator fbo_it = *freelist_it;
492 if (fbo_it->second.texture_num[0] == texture0_num &&
493 fbo_it->second.texture_num[1] == texture1_num &&
494 fbo_it->second.texture_num[2] == texture2_num &&
495 fbo_it->second.texture_num[3] == texture3_num) {
496 fbo_freelist[context].erase(freelist_it);
497 pthread_mutex_unlock(&lock);
498 return fbo_it->second.fbo_num;
505 fbo_format.texture_num[0] = texture0_num;
506 fbo_format.texture_num[1] = texture1_num;
507 fbo_format.texture_num[2] = texture2_num;
508 fbo_format.texture_num[3] = texture3_num;
510 glGenFramebuffers(1, &fbo_format.fbo_num);
512 glBindFramebuffer(GL_FRAMEBUFFER, fbo_format.fbo_num);
515 GLenum bufs[num_fbo_attachments];
516 unsigned num_active_attachments = 0;
517 for (unsigned i = 0; i < num_fbo_attachments; ++i, ++num_active_attachments) {
518 if (fbo_format.texture_num[i] == 0) {
521 glFramebufferTexture2D(
523 GL_COLOR_ATTACHMENT0 + i,
525 fbo_format.texture_num[i],
528 bufs[i] = GL_COLOR_ATTACHMENT0 + i;
531 glDrawBuffers(num_active_attachments, bufs);
534 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
535 assert(status == GL_FRAMEBUFFER_COMPLETE);
536 glBindFramebuffer(GL_FRAMEBUFFER, 0);
539 pair<void *, GLuint> key(context, fbo_format.fbo_num);
540 assert(fbo_formats.count(key) == 0);
541 fbo_formats.insert(make_pair(key, fbo_format));
543 pthread_mutex_unlock(&lock);
544 return fbo_format.fbo_num;
547 void ResourcePool::release_fbo(GLuint fbo_num)
549 void *context = get_gl_context_identifier();
551 pthread_mutex_lock(&lock);
552 FBOFormatIterator fbo_it = fbo_formats.find(make_pair(context, fbo_num));
553 assert(fbo_it != fbo_formats.end());
554 fbo_freelist[context].push_front(fbo_it);
556 // Now that we're in this context, free up any FBOs that are connected
557 // to deleted textures (in release_2d_texture).
558 cleanup_unlinked_fbos(context);
560 shrink_fbo_freelist(context, fbo_freelist_max_length);
561 pthread_mutex_unlock(&lock);
564 GLuint ResourcePool::create_vec2_vao(const set<GLint> &attribute_indices, GLuint vbo_num)
566 void *context = get_gl_context_identifier();
568 pthread_mutex_lock(&lock);
569 if (vao_freelist.count(context) != 0) {
570 // See if there's a VAO the freelist we can use.
571 list<VAOFormatIterator>::iterator end = vao_freelist[context].end();
572 for (list<VAOFormatIterator>::iterator freelist_it = vao_freelist[context].begin();
573 freelist_it != end; ++freelist_it) {
574 VAOFormatIterator vao_it = *freelist_it;
575 if (vao_it->second.vbo_num == vbo_num &&
576 vao_it->second.attribute_indices == attribute_indices) {
577 vao_freelist[context].erase(freelist_it);
578 pthread_mutex_unlock(&lock);
579 return vao_it->second.vao_num;
586 vao_format.attribute_indices = attribute_indices;
587 vao_format.vbo_num = vbo_num;
589 glGenVertexArrays(1, &vao_format.vao_num);
591 glBindVertexArray(vao_format.vao_num);
593 glBindBuffer(GL_ARRAY_BUFFER, vbo_num);
596 for (set<GLint>::const_iterator attr_it = attribute_indices.begin(); attr_it != attribute_indices.end(); ++attr_it) {
597 glEnableVertexAttribArray(*attr_it);
599 glVertexAttribPointer(*attr_it, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
603 glBindVertexArray(0);
605 glBindBuffer(GL_ARRAY_BUFFER, 0);
608 pair<void *, GLuint> key(context, vao_format.vao_num);
609 assert(vao_formats.count(key) == 0);
610 vao_formats.insert(make_pair(key, vao_format));
612 pthread_mutex_unlock(&lock);
613 return vao_format.vao_num;
616 void ResourcePool::release_vec2_vao(GLuint vao_num)
618 void *context = get_gl_context_identifier();
620 pthread_mutex_lock(&lock);
621 VAOFormatIterator vao_it = vao_formats.find(make_pair(context, vao_num));
622 assert(vao_it != vao_formats.end());
623 vao_freelist[context].push_front(vao_it);
625 shrink_vao_freelist(context, vao_freelist_max_length);
626 pthread_mutex_unlock(&lock);
629 void ResourcePool::clean_context()
631 void *context = get_gl_context_identifier();
633 // Currently, we only need to worry about FBOs and VAOs, as they are the only
634 // non-shareable resources we hold.
635 shrink_fbo_freelist(context, 0);
636 fbo_freelist.erase(context);
638 shrink_vao_freelist(context, 0);
639 vao_freelist.erase(context);
642 void ResourcePool::cleanup_unlinked_fbos(void *context)
644 list<FBOFormatIterator>::iterator end = fbo_freelist[context].end();
645 for (list<FBOFormatIterator>::iterator freelist_it = fbo_freelist[context].begin(); freelist_it != end; ) {
646 FBOFormatIterator fbo_it = *freelist_it;
648 bool all_unlinked = true;
649 for (unsigned i = 0; i < num_fbo_attachments; ++i) {
650 if (fbo_it->second.texture_num[i] != 0 &&
651 fbo_it->second.texture_num[i] != GL_INVALID_INDEX) {
652 all_unlinked = false;
657 glDeleteFramebuffers(1, &fbo_it->second.fbo_num);
659 fbo_formats.erase(fbo_it);
660 fbo_freelist[context].erase(freelist_it++);
667 void ResourcePool::shrink_fbo_freelist(void *context, size_t max_length)
669 list<FBOFormatIterator> &freelist = fbo_freelist[context];
670 while (freelist.size() > max_length) {
671 FBOFormatIterator free_fbo_it = freelist.back();
672 glDeleteFramebuffers(1, &free_fbo_it->second.fbo_num);
674 fbo_formats.erase(free_fbo_it);
679 void ResourcePool::shrink_vao_freelist(void *context, size_t max_length)
681 list<VAOFormatIterator> &freelist = vao_freelist[context];
682 while (freelist.size() > max_length) {
683 VAOFormatIterator free_vao_it = freelist.back();
684 glDeleteVertexArrays(1, &free_vao_it->second.vao_num);
686 vao_formats.erase(free_vao_it);
691 void ResourcePool::increment_program_refcount(GLuint program_num)
693 map<GLuint, int>::iterator refcount_it = program_refcount.find(program_num);
694 if (refcount_it != program_refcount.end()) {
695 ++refcount_it->second;
697 list<GLuint>::iterator freelist_it =
698 find(program_freelist.begin(), program_freelist.end(), program_num);
699 assert(freelist_it != program_freelist.end());
700 program_freelist.erase(freelist_it);
701 program_refcount.insert(make_pair(program_num, 1));
705 void ResourcePool::output_debug_shader(const string &shader_src, const string &suffix)
707 if (movit_debug_level == MOVIT_DEBUG_ON) {
708 // Output shader to a temporary file, for easier debugging.
709 static int compiled_shader_num = 0;
711 sprintf(filename, "chain-%03d.%s", compiled_shader_num++, suffix.c_str());
712 FILE *fp = fopen(filename, "w");
717 fprintf(fp, "%s\n", shader_src.c_str());
722 void ResourcePool::add_master_program(GLuint program_num)
724 program_refcount.insert(make_pair(program_num, 1));
725 stack<GLuint> instances;
726 instances.push(program_num);
727 program_instances.insert(make_pair(program_num, instances));
728 program_masters.insert(make_pair(program_num, program_num));
731 size_t ResourcePool::estimate_texture_size(const Texture2D &texture_format)
733 size_t bytes_per_pixel;
735 switch (texture_format.internal_format) {
737 bytes_per_pixel = 16;
743 bytes_per_pixel = 12;
748 case GL_R11F_G11F_B10F:
755 case GL_SRGB8_ALPHA8:
798 // TODO: Add more here as needed.
802 return texture_format.width * texture_format.height * bytes_per_pixel;