]> git.cworth.org Git - apitrace/blob - glstate.cpp
Put all thirdparty code into a separate subdirectory.
[apitrace] / glstate.cpp
1 /**************************************************************************
2  *
3  * Copyright 2011 Jose Fonseca
4  * All Rights Reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  *
24  **************************************************************************/
25
26
27 #include <string.h>
28 #include <iostream>
29 #include <algorithm>
30
31 #include "image.hpp"
32 #include "json.hpp"
33 #include "glproc.hpp"
34 #include "glsize.hpp"
35 #include "glstate.hpp"
36
37
38 #ifdef __APPLE__
39
40 #include <Carbon/Carbon.h>
41
42 #ifdef __cplusplus
43 extern "C" {
44 #endif
45
46 OSStatus CGSGetSurfaceBounds(CGSConnectionID, CGWindowID, CGSSurfaceID, CGRect *);
47
48 #ifdef __cplusplus
49 }
50 #endif
51
52 #endif /* __APPLE__ */
53
54
55 namespace glstate {
56
57
58 static inline void
59 resetPixelPackState(void) {
60     glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
61     glPixelStorei(GL_PACK_SWAP_BYTES, GL_FALSE);
62     glPixelStorei(GL_PACK_LSB_FIRST, GL_FALSE);
63     glPixelStorei(GL_PACK_ROW_LENGTH, 0);
64     glPixelStorei(GL_PACK_IMAGE_HEIGHT, 0);
65     glPixelStorei(GL_PACK_SKIP_ROWS, 0);
66     glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
67     glPixelStorei(GL_PACK_SKIP_IMAGES, 0);
68     glPixelStorei(GL_PACK_ALIGNMENT, 1);
69     glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
70 }
71
72
73 static inline void
74 restorePixelPackState(void) {
75     glPopClientAttrib();
76 }
77
78
79 static void
80 dumpShader(JSONWriter &json, GLuint shader)
81 {
82     if (!shader) {
83         return;
84     }
85
86     GLint shader_type = 0;
87     glGetShaderiv(shader, GL_SHADER_TYPE, &shader_type);
88     if (!shader_type) {
89         return;
90     }
91
92     GLint source_length = 0;
93     glGetShaderiv(shader, GL_SHADER_SOURCE_LENGTH, &source_length);
94     if (!source_length) {
95         return;
96     }
97
98     GLchar *source = new GLchar[source_length];
99     GLsizei length = 0;
100     source[0] = 0;
101     glGetShaderSource(shader, source_length, &length, source);
102
103     json.beginMember(enumToString(shader_type));
104     json.writeString(source);
105     json.endMember();
106
107     delete [] source;
108 }
109
110
111 static void
112 dumpShaderObj(JSONWriter &json, GLhandleARB shaderObj)
113 {
114     if (!shaderObj) {
115         return;
116     }
117
118     GLint shader_type = 0;
119     glGetObjectParameterivARB(shaderObj, GL_OBJECT_TYPE_ARB, &shader_type);
120     if (!shader_type) {
121         return;
122     }
123
124     GLint source_length = 0;
125     glGetObjectParameterivARB(shaderObj, GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &source_length);
126     if (!source_length) {
127         return;
128     }
129
130     GLcharARB *source = new GLcharARB[source_length];
131     GLsizei length = 0;
132     source[0] = 0;
133     glGetShaderSource(shaderObj, source_length, &length, source);
134
135     json.beginMember(enumToString(shader_type));
136     json.writeString(source);
137     json.endMember();
138
139     delete [] source;
140 }
141
142
143 static inline void
144 dumpCurrentProgram(JSONWriter &json)
145 {
146     GLint program = 0;
147     glGetIntegerv(GL_CURRENT_PROGRAM, &program);
148     if (!program) {
149         return;
150     }
151
152     GLint attached_shaders = 0;
153     glGetProgramiv(program, GL_ATTACHED_SHADERS, &attached_shaders);
154     if (!attached_shaders) {
155         return;
156     }
157
158     GLuint *shaders = new GLuint[attached_shaders];
159     GLsizei count = 0;
160     glGetAttachedShaders(program, attached_shaders, &count, shaders);
161     for (GLsizei i = 0; i < count; ++ i) {
162        dumpShader(json, shaders[i]);
163     }
164     delete [] shaders;
165 }
166
167
168 static inline void
169 dumpCurrentProgramObj(JSONWriter &json)
170 {
171     GLhandleARB programObj = glGetHandleARB(GL_PROGRAM_OBJECT_ARB);
172     if (!programObj) {
173         return;
174     }
175
176     GLint attached_shaders = 0;
177     glGetProgramivARB(programObj, GL_OBJECT_ATTACHED_OBJECTS_ARB, &attached_shaders);
178     if (!attached_shaders) {
179         return;
180     }
181
182     GLhandleARB *shaderObjs = new GLhandleARB[attached_shaders];
183     GLsizei count = 0;
184     glGetAttachedObjectsARB(programObj, attached_shaders, &count, shaderObjs);
185     for (GLsizei i = 0; i < count; ++ i) {
186        dumpShaderObj(json, shaderObjs[i]);
187     }
188     delete [] shaderObjs;
189 }
190
191
192 static inline void
193 dumpArbProgram(JSONWriter &json, GLenum target)
194 {
195     if (!glIsEnabled(target)) {
196         return;
197     }
198
199     GLint program_length = 0;
200     glGetProgramivARB(target, GL_PROGRAM_LENGTH_ARB, &program_length);
201     if (!program_length) {
202         return;
203     }
204
205     GLchar *source = new GLchar[program_length + 1];
206     source[0] = 0;
207     glGetProgramStringARB(target, GL_PROGRAM_STRING_ARB, source);
208     source[program_length] = 0;
209
210     json.beginMember(enumToString(target));
211     json.writeString(source);
212     json.endMember();
213
214     delete [] source;
215 }
216
217
218 static inline void
219 dumpShaders(JSONWriter &json)
220 {
221     json.beginMember("shaders");
222     json.beginObject();
223     dumpCurrentProgram(json);
224     dumpArbProgram(json, GL_FRAGMENT_PROGRAM_ARB);
225     dumpArbProgram(json, GL_VERTEX_PROGRAM_ARB);
226     json.endObject();
227     json.endMember(); //shaders
228 }
229
230
231 static inline void
232 dumpTextureImage(JSONWriter &json, GLenum target, GLint level)
233 {
234     GLint width, height = 1, depth = 1;
235
236     width = 0;
237     glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width);
238
239     if (target != GL_TEXTURE_1D) {
240         height = 0;
241         glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height);
242         if (target == GL_TEXTURE_3D) {
243             depth = 0;
244             glGetTexLevelParameteriv(target, level, GL_TEXTURE_DEPTH, &depth);
245         }
246     }
247
248     if (width <= 0 || height <= 0 || depth <= 0) {
249         return;
250     } else {
251         char label[512];
252
253         GLint active_texture = GL_TEXTURE0;
254         glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
255         snprintf(label, sizeof label, "%s, %s, level = %i", enumToString(active_texture), enumToString(target), level);
256
257         json.beginMember(label);
258
259         json.beginObject();
260
261         // Tell the GUI this is no ordinary object, but an image
262         json.writeStringMember("__class__", "image");
263
264         json.writeNumberMember("__width__", width);
265         json.writeNumberMember("__height__", height);
266         json.writeNumberMember("__depth__", depth);
267
268         // Hardcoded for now, but we could chose types more adequate to the
269         // texture internal format
270         json.writeStringMember("__type__", "uint8");
271         json.writeBoolMember("__normalized__", true);
272         json.writeNumberMember("__channels__", 4);
273
274         GLubyte *pixels = new GLubyte[depth*width*height*4];
275
276         resetPixelPackState();
277
278         glGetTexImage(target, level, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
279
280         restorePixelPackState();
281
282         json.beginMember("__data__");
283         char *pngBuffer;
284         int pngBufferSize;
285         Image::writePixelsToBuffer(pixels, width, height, 4, false, &pngBuffer, &pngBufferSize);
286         json.writeBase64(pngBuffer, pngBufferSize);
287         free(pngBuffer);
288         json.endMember(); // __data__
289
290         delete [] pixels;
291         json.endObject();
292     }
293 }
294
295
296 static inline void
297 dumpTexture(JSONWriter &json, GLenum target, GLenum binding)
298 {
299     GLint texture_binding = 0;
300     glGetIntegerv(binding, &texture_binding);
301     if (!glIsEnabled(target) && !texture_binding) {
302         return;
303     }
304
305     GLint level = 0;
306     do {
307         GLint width = 0, height = 0;
308         glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width);
309         glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height);
310         if (!width || !height) {
311             break;
312         }
313
314         if (target == GL_TEXTURE_CUBE_MAP) {
315             for (int face = 0; face < 6; ++face) {
316                 dumpTextureImage(json, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level);
317             }
318         } else {
319             dumpTextureImage(json, target, level);
320         }
321
322         ++level;
323     } while(true);
324 }
325
326
327 static inline void
328 dumpTextures(JSONWriter &json)
329 {
330     json.beginMember("textures");
331     json.beginObject();
332     GLint active_texture = GL_TEXTURE0;
333     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
334     GLint max_texture_coords = 0;
335     glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);
336     GLint max_combined_texture_image_units = 0;
337     glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);
338     GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);
339     for (GLint unit = 0; unit < max_units; ++unit) {
340         GLenum texture = GL_TEXTURE0 + unit;
341         glActiveTexture(texture);
342         dumpTexture(json, GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D);
343         dumpTexture(json, GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D);
344         dumpTexture(json, GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D);
345         dumpTexture(json, GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE);
346         dumpTexture(json, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP);
347     }
348     glActiveTexture(active_texture);
349     json.endObject();
350     json.endMember(); // textures
351 }
352
353
354 static bool
355 getDrawableBounds(GLint *width, GLint *height) {
356 #if defined(_WIN32)
357
358     HDC hDC = wglGetCurrentDC();
359     if (!hDC) {
360         return false;
361     }
362
363     HWND hWnd = WindowFromDC(hDC);
364     RECT rect;
365
366     if (!GetClientRect(hWnd, &rect)) {
367        return false;
368     }
369
370     *width  = rect.right  - rect.left;
371     *height = rect.bottom - rect.top;
372
373 #elif defined(__APPLE__)
374
375     CGLContextObj ctx = CGLGetCurrentContext();
376     if (ctx == NULL) {
377         return false;
378     }
379
380     CGSConnectionID cid;
381     CGSWindowID wid;
382     CGSSurfaceID sid;
383
384     if (CGLGetSurface(ctx, &cid, &wid, &sid) != kCGLNoError) {
385         return false;
386     }
387
388     CGRect rect;
389
390     if (CGSGetSurfaceBounds(cid, wid, sid, &rect) != 0) {
391         return false;
392     }
393
394     *width = rect.size.width;
395     *height = rect.size.height;
396
397 #else
398
399     Display *display;
400     Drawable drawable;
401     Window root;
402     int x, y;
403     unsigned int w, h, bw, depth;
404
405     display = glXGetCurrentDisplay();
406     if (!display) {
407         return false;
408     }
409
410     drawable = glXGetCurrentDrawable();
411     if (drawable == None) {
412         return false;
413     }
414
415     if (!XGetGeometry(display, drawable, &root, &x, &y, &w, &h, &bw, &depth)) {
416         return false;
417     }
418
419     *width = w;
420     *height = h;
421
422 #endif
423
424     return true;
425 }
426
427
428 static const GLenum texture_bindings[][2] = {
429     {GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D},
430     {GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D},
431     {GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D},
432     {GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE},
433     {GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP}
434 };
435
436
437 static bool
438 bindTexture(GLint texture, GLenum &target, GLint &bound_texture)
439 {
440
441     for (unsigned i = 0; i < sizeof(texture_bindings)/sizeof(texture_bindings[0]); ++i) {
442         target  = texture_bindings[i][0];
443
444         GLenum binding = texture_bindings[i][1];
445
446         while (glGetError() != GL_NO_ERROR)
447             ;
448
449         glGetIntegerv(binding, &bound_texture);
450         glBindTexture(target, texture);
451
452         if (glGetError() == GL_NO_ERROR) {
453             return true;
454         }
455
456         glBindTexture(target, bound_texture);
457     }
458
459     target = GL_NONE;
460
461     return false;
462 }
463
464
465 static bool
466 getTextureLevelSize(GLint texture, GLint level, GLint *width, GLint *height)
467 {
468     *width = 0;
469     *height = 0;
470
471     GLenum target;
472     GLint bound_texture = 0;
473     if (!bindTexture(texture, target, bound_texture)) {
474         return false;
475     }
476
477     glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, width);
478     glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, height);
479
480     glBindTexture(target, bound_texture);
481
482     return *width > 0 && *height > 0;
483 }
484
485
486 static bool
487 getRenderbufferSize(GLint renderbuffer, GLint *width, GLint *height)
488 {
489     GLint bound_renderbuffer = 0;
490     glGetIntegerv(GL_RENDERBUFFER_BINDING, &bound_renderbuffer);
491     glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
492
493     *width = 0;
494     *height = 0;
495     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, width);
496     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, height);
497
498     glBindRenderbuffer(GL_RENDERBUFFER, bound_renderbuffer);
499     
500     return *width > 0 && *height > 0;
501 }
502
503
504 static bool
505 getFramebufferAttachmentSize(GLenum target, GLenum attachment, GLint *width, GLint *height)
506 {
507     GLint object_type = GL_NONE;
508     glGetFramebufferAttachmentParameteriv(target, attachment,
509                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
510                                           &object_type);
511     if (object_type == GL_NONE) {
512         return false;
513     }
514
515     GLint object_name = 0;
516     glGetFramebufferAttachmentParameteriv(target, attachment,
517                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
518                                           &object_name);
519     if (object_name == 0) {
520         return false;
521     }
522
523     if (object_type == GL_RENDERBUFFER) {
524         return getRenderbufferSize(object_name, width, height);
525     } else if (object_type == GL_TEXTURE) {
526         GLint texture_level = 0;
527         glGetFramebufferAttachmentParameteriv(target, attachment,
528                                               GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
529                                               &texture_level);
530         return getTextureLevelSize(object_name, texture_level, width, height);
531     } else {
532         std::cerr << "warning: unexpected GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = " << object_type << "\n";
533         return false;
534     }
535 }
536
537
538 Image::Image *
539 getDrawBufferImage(GLenum format) {
540     GLint channels = __gl_format_channels(format);
541     if (channels > 4) {
542         return NULL;
543     }
544
545     GLint draw_framebuffer = 0;
546     glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &draw_framebuffer);
547
548     GLint draw_buffer = GL_NONE;
549     GLint width, height;
550     if (draw_framebuffer) {
551         glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer);
552         if (draw_buffer == GL_NONE) {
553             return NULL;
554         }
555
556         if (!getFramebufferAttachmentSize(GL_DRAW_FRAMEBUFFER, draw_buffer, &width, &height)) {
557             return NULL;
558         }
559     } else {
560         glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
561         if (draw_buffer == GL_NONE) {
562             return NULL;
563         }
564
565         if (!getDrawableBounds(&width, &height)) {
566             return NULL;
567         }
568     }
569
570     Image::Image *image = new Image::Image(width, height, channels, true);
571     if (!image) {
572         return NULL;
573     }
574
575     while (glGetError() != GL_NO_ERROR) {}
576
577     GLint read_framebuffer = 0;
578     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
579     glBindFramebuffer(GL_READ_FRAMEBUFFER, draw_framebuffer);
580
581     GLint read_buffer = 0;
582     glGetIntegerv(GL_READ_BUFFER, &read_buffer);
583     glReadBuffer(draw_buffer);
584
585     // TODO: reset imaging state too
586     resetPixelPackState();
587
588     glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, image->pixels);
589
590     restorePixelPackState();
591     glReadBuffer(read_buffer);
592     glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
593
594     GLenum error = glGetError();
595     if (error != GL_NO_ERROR) {
596         do {
597             std::cerr << "warning: " << enumToString(error) << " while getting snapshot\n";
598             error = glGetError();
599         } while(error != GL_NO_ERROR);
600         delete image;
601         return NULL;
602     }
603      
604     return image;
605 }
606
607
608 /**
609  * Dump the image of the currently bound read buffer.
610  */
611 static inline void
612 dumpReadBufferImage(JSONWriter &json, GLint width, GLint height, GLenum format)
613 {
614     GLint channels = __gl_format_channels(format);
615
616     json.beginObject();
617
618     // Tell the GUI this is no ordinary object, but an image
619     json.writeStringMember("__class__", "image");
620
621     json.writeNumberMember("__width__", width);
622     json.writeNumberMember("__height__", height);
623     json.writeNumberMember("__depth__", 1);
624
625     // Hardcoded for now, but we could chose types more adequate to the
626     // texture internal format
627     json.writeStringMember("__type__", "uint8");
628     json.writeBoolMember("__normalized__", true);
629     json.writeNumberMember("__channels__", channels);
630
631     GLubyte *pixels = new GLubyte[width*height*channels];
632
633     // TODO: reset imaging state too
634     resetPixelPackState();
635
636     glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, pixels);
637
638     restorePixelPackState();
639
640     json.beginMember("__data__");
641     char *pngBuffer;
642     int pngBufferSize;
643     Image::writePixelsToBuffer(pixels, width, height, channels, false, &pngBuffer, &pngBufferSize);
644     //std::cerr <<" Before = "<<(width * height * channels * sizeof *pixels)
645     //          <<", after = "<<pngBufferSize << ", ratio = " << double(width * height * channels * sizeof *pixels)/pngBufferSize;
646     json.writeBase64(pngBuffer, pngBufferSize);
647     free(pngBuffer);
648     json.endMember(); // __data__
649
650     delete [] pixels;
651     json.endObject();
652 }
653
654
655 static inline GLuint
656 downsampledFramebuffer(GLuint oldFbo, GLint drawbuffer,
657                        GLint colorRb, GLint depthRb, GLint stencilRb,
658                        GLuint *rbs, GLint *numRbs)
659 {
660     GLuint fbo;
661     GLint format;
662     GLint w, h;
663
664     *numRbs = 0;
665
666     glGenFramebuffers(1, &fbo);
667     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
668
669     glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
670     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
671                                  GL_RENDERBUFFER_WIDTH, &w);
672     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
673                                  GL_RENDERBUFFER_HEIGHT, &h);
674     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
675                                  GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
676
677     glGenRenderbuffers(1, &rbs[*numRbs]);
678     glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
679     glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
680     glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer,
681                               GL_RENDERBUFFER, rbs[*numRbs]);
682
683     glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
684     glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
685     glDrawBuffer(drawbuffer);
686     glReadBuffer(drawbuffer);
687     glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
688                       GL_COLOR_BUFFER_BIT, GL_NEAREST);
689     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
690     ++*numRbs;
691
692     if (stencilRb == depthRb && stencilRb) {
693         //combined depth and stencil buffer
694         glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
695         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
696                                      GL_RENDERBUFFER_WIDTH, &w);
697         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
698                                      GL_RENDERBUFFER_HEIGHT, &h);
699         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
700                                      GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
701
702         glGenRenderbuffers(1, &rbs[*numRbs]);
703         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
704         glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
705         glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
706                                   GL_RENDERBUFFER, rbs[*numRbs]);
707         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
708         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
709         glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
710                           GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
711         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
712         ++*numRbs;
713     } else {
714         if (depthRb) {
715             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
716             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
717                                          GL_RENDERBUFFER_WIDTH, &w);
718             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
719                                          GL_RENDERBUFFER_HEIGHT, &h);
720             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
721                                          GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
722
723             glGenRenderbuffers(1, &rbs[*numRbs]);
724             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
725             glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
726             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
727                                       GL_DEPTH_ATTACHMENT,
728                                       GL_RENDERBUFFER, rbs[*numRbs]);
729             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
730             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
731             glDrawBuffer(GL_DEPTH_ATTACHMENT);
732             glReadBuffer(GL_DEPTH_ATTACHMENT);
733             glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
734                               GL_DEPTH_BUFFER_BIT, GL_NEAREST);
735             ++*numRbs;
736         }
737         if (stencilRb) {
738             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
739             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
740                                          GL_RENDERBUFFER_WIDTH, &w);
741             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
742                                          GL_RENDERBUFFER_HEIGHT, &h);
743             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
744                                      GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
745
746             glGenRenderbuffers(1, &rbs[*numRbs]);
747             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
748             glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
749             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
750                                       GL_STENCIL_ATTACHMENT,
751                                       GL_RENDERBUFFER, rbs[*numRbs]);
752             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
753             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
754             glDrawBuffer(GL_STENCIL_ATTACHMENT);
755             glReadBuffer(GL_STENCIL_ATTACHMENT);
756             glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
757                               GL_STENCIL_BUFFER_BIT, GL_NEAREST);
758             ++*numRbs;
759         }
760     }
761
762     return fbo;
763 }
764
765
766 /**
767  * Dump images of current draw drawable/window.
768  */
769 static void
770 dumpDrawableImages(JSONWriter &json)
771 {
772     GLint width, height;
773
774     if (!getDrawableBounds(&width, &height)) {
775         return;
776     }
777
778     GLint draw_buffer = GL_NONE;
779     glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
780     glReadBuffer(draw_buffer);
781
782     if (draw_buffer != GL_NONE) {
783         GLint read_buffer = GL_NONE;
784         glGetIntegerv(GL_READ_BUFFER, &read_buffer);
785
786         GLint alpha_bits = 0;
787         glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
788         GLenum format = alpha_bits ? GL_RGBA : GL_RGB;
789         json.beginMember(enumToString(draw_buffer));
790         dumpReadBufferImage(json, width, height, format);
791         json.endMember();
792
793         glReadBuffer(read_buffer);
794     }
795
796     GLint depth_bits = 0;
797     glGetIntegerv(GL_DEPTH_BITS, &depth_bits);
798     if (depth_bits) {
799         json.beginMember("GL_DEPTH_COMPONENT");
800         dumpReadBufferImage(json, width, height, GL_DEPTH_COMPONENT);
801         json.endMember();
802     }
803
804     GLint stencil_bits = 0;
805     glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);
806     if (stencil_bits) {
807         json.beginMember("GL_STENCIL_INDEX");
808         dumpReadBufferImage(json, width, height, GL_STENCIL_INDEX);
809         json.endMember();
810     }
811 }
812 /**
813  * Dump the specified framebuffer attachment.
814  *
815  * In the case of a color attachment, it assumes it is already bound for read.
816  */
817 static void
818 dumpFramebufferAttachment(JSONWriter &json, GLenum target, GLenum attachment, GLenum format)
819 {
820     GLint width = 0, height = 0;
821     if (!getFramebufferAttachmentSize(target, attachment, &width, &height)) {
822         return;
823     }
824
825     json.beginMember(enumToString(attachment));
826     dumpReadBufferImage(json, width, height, format);
827     json.endMember();
828 }
829
830
831 static void
832 dumpFramebufferAttachments(JSONWriter &json, GLenum target)
833 {
834     GLint read_framebuffer = 0;
835     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
836
837     GLint read_buffer = GL_NONE;
838     glGetIntegerv(GL_READ_BUFFER, &read_buffer);
839
840     GLint max_draw_buffers = 1;
841     glGetIntegerv(GL_MAX_DRAW_BUFFERS, &max_draw_buffers);
842     GLint max_color_attachments = 0;
843     glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);
844
845     for (GLint i = 0; i < max_draw_buffers; ++i) {
846         GLint draw_buffer = GL_NONE;
847         glGetIntegerv(GL_DRAW_BUFFER0 + i, &draw_buffer);
848         if (draw_buffer != GL_NONE) {
849             glReadBuffer(draw_buffer);
850             GLint attachment;
851             if (draw_buffer >= GL_COLOR_ATTACHMENT0 && draw_buffer < GL_COLOR_ATTACHMENT0 + max_color_attachments) {
852                 attachment = draw_buffer;
853             } else {
854                 std::cerr << "warning: unexpected GL_DRAW_BUFFER" << i << " = " << draw_buffer << "\n";
855                 attachment = GL_COLOR_ATTACHMENT0;
856             }
857             GLint alpha_size = 0;
858             glGetFramebufferAttachmentParameteriv(target, attachment,
859                                                   GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE,
860                                                   &alpha_size);
861             GLenum format = alpha_size ? GL_RGBA : GL_RGB;
862             dumpFramebufferAttachment(json, target, attachment, format);
863         }
864     }
865
866     glReadBuffer(read_buffer);
867
868     dumpFramebufferAttachment(json, target, GL_DEPTH_ATTACHMENT, GL_DEPTH_COMPONENT);
869     dumpFramebufferAttachment(json, target, GL_STENCIL_ATTACHMENT, GL_STENCIL_INDEX);
870
871     glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
872 }
873
874
875 static void
876 dumpFramebuffer(JSONWriter &json)
877 {
878     json.beginMember("framebuffer");
879     json.beginObject();
880
881     GLint boundDrawFbo = 0, boundReadFbo = 0;
882     glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo);
883     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo);
884     if (!boundDrawFbo) {
885         dumpDrawableImages(json);
886     } else {
887         GLint colorRb = 0, stencilRb = 0, depthRb = 0;
888         GLint draw_buffer0 = GL_NONE;
889         glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer0);
890         bool multisample = false;
891
892         GLint boundRb = 0;
893         glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb);
894
895         GLint object_type;
896         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
897         if (object_type == GL_RENDERBUFFER) {
898             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &colorRb);
899             glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
900             GLint samples = 0;
901             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
902             if (samples) {
903                 multisample = true;
904             }
905         }
906
907         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
908         if (object_type == GL_RENDERBUFFER) {
909             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &depthRb);
910             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
911             GLint samples = 0;
912             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
913             if (samples) {
914                 multisample = true;
915             }
916         }
917
918         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
919         if (object_type == GL_RENDERBUFFER) {
920             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &stencilRb);
921             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
922             GLint samples = 0;
923             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
924             if (samples) {
925                 multisample = true;
926             }
927         }
928
929         glBindRenderbuffer(GL_RENDERBUFFER, boundRb);
930
931         GLuint rbs[3];
932         GLint numRbs = 0;
933         GLuint fboCopy = 0;
934
935         if (multisample) {
936             // glReadPixels doesnt support multisampled buffers so we need
937             // to blit the fbo to a temporary one
938             fboCopy = downsampledFramebuffer(boundDrawFbo, draw_buffer0,
939                                              colorRb, depthRb, stencilRb,
940                                              rbs, &numRbs);
941         }
942
943         dumpFramebufferAttachments(json, GL_DRAW_FRAMEBUFFER);
944
945         if (multisample) {
946             glBindRenderbuffer(GL_RENDERBUFFER_BINDING, boundRb);
947             glDeleteRenderbuffers(numRbs, rbs);
948             glDeleteFramebuffers(1, &fboCopy);
949         }
950
951         glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo);
952         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo);
953     }
954
955     json.endObject();
956     json.endMember(); // framebuffer
957 }
958
959
960 static const GLenum bindings[] = {
961     GL_DRAW_BUFFER,
962     GL_READ_BUFFER,
963     GL_PIXEL_PACK_BUFFER_BINDING,
964     GL_PIXEL_UNPACK_BUFFER_BINDING,
965     GL_TEXTURE_BINDING_1D,
966     GL_TEXTURE_BINDING_2D,
967     GL_TEXTURE_BINDING_3D,
968     GL_TEXTURE_BINDING_RECTANGLE,
969     GL_TEXTURE_BINDING_CUBE_MAP,
970     GL_DRAW_FRAMEBUFFER_BINDING,
971     GL_READ_FRAMEBUFFER_BINDING,
972     GL_RENDERBUFFER_BINDING,
973     GL_DRAW_BUFFER0,
974     GL_DRAW_BUFFER1,
975     GL_DRAW_BUFFER2,
976     GL_DRAW_BUFFER3,
977     GL_DRAW_BUFFER4,
978     GL_DRAW_BUFFER5,
979     GL_DRAW_BUFFER6,
980     GL_DRAW_BUFFER7,
981 };
982
983
984 #define NUM_BINDINGS sizeof(bindings)/sizeof(bindings[0])
985
986
987 void dumpCurrentContext(std::ostream &os)
988 {
989     JSONWriter json(os);
990
991 #ifndef NDEBUG
992     GLint old_bindings[NUM_BINDINGS];
993     for (unsigned i = 0; i < NUM_BINDINGS; ++i) {
994         old_bindings[i] = 0;
995         glGetIntegerv(bindings[i], &old_bindings[i]);
996     }
997 #endif
998
999     dumpParameters(json);
1000     dumpShaders(json);
1001     dumpTextures(json);
1002     dumpFramebuffer(json);
1003
1004 #ifndef NDEBUG
1005     for (unsigned i = 0; i < NUM_BINDINGS; ++i) {
1006         GLint new_binding = 0;
1007         glGetIntegerv(bindings[i], &new_binding);
1008         if (new_binding != old_bindings[i]) {
1009             std::cerr << "warning: " << enumToString(bindings[i]) << " was clobbered\n";
1010         }
1011     }
1012 #endif
1013
1014 }
1015
1016
1017 } /* namespace glstate */