]> git.cworth.org Git - apitrace/blob - glstate.cpp
Add some sanity checks to catch state clobering.
[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     resetPixelPackState();
586
587     glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, image->pixels);
588
589     restorePixelPackState();
590     glReadBuffer(read_buffer);
591     glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
592
593     GLenum error = glGetError();
594     if (error != GL_NO_ERROR) {
595         do {
596             std::cerr << "warning: " << enumToString(error) << " while getting snapshot\n";
597             error = glGetError();
598         } while(error != GL_NO_ERROR);
599         delete image;
600         return NULL;
601     }
602      
603     return image;
604 }
605
606
607 /**
608  * Dump the image of the currently bound read buffer.
609  */
610 static inline void
611 dumpReadBufferImage(JSONWriter &json, GLint width, GLint height, GLenum format)
612 {
613     GLint channels = __gl_format_channels(format);
614
615     json.beginObject();
616
617     // Tell the GUI this is no ordinary object, but an image
618     json.writeStringMember("__class__", "image");
619
620     json.writeNumberMember("__width__", width);
621     json.writeNumberMember("__height__", height);
622     json.writeNumberMember("__depth__", 1);
623
624     // Hardcoded for now, but we could chose types more adequate to the
625     // texture internal format
626     json.writeStringMember("__type__", "uint8");
627     json.writeBoolMember("__normalized__", true);
628     json.writeNumberMember("__channels__", channels);
629
630     GLubyte *pixels = new GLubyte[width*height*channels];
631
632     resetPixelPackState();
633
634     glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, pixels);
635
636     restorePixelPackState();
637
638     json.beginMember("__data__");
639     char *pngBuffer;
640     int pngBufferSize;
641     Image::writePixelsToBuffer(pixels, width, height, channels, false, &pngBuffer, &pngBufferSize);
642     //std::cerr <<" Before = "<<(width * height * channels * sizeof *pixels)
643     //          <<", after = "<<pngBufferSize << ", ratio = " << double(width * height * channels * sizeof *pixels)/pngBufferSize;
644     json.writeBase64(pngBuffer, pngBufferSize);
645     free(pngBuffer);
646     json.endMember(); // __data__
647
648     delete [] pixels;
649     json.endObject();
650 }
651
652
653 static inline GLuint
654 downsampledFramebuffer(GLuint oldFbo, GLint drawbuffer,
655                        GLint colorRb, GLint depthRb, GLint stencilRb,
656                        GLuint *rbs, GLint *numRbs)
657 {
658     GLuint fbo;
659     GLint format;
660     GLint w, h;
661
662     *numRbs = 0;
663
664     glGenFramebuffers(1, &fbo);
665     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
666
667     glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
668     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
669                                  GL_RENDERBUFFER_WIDTH, &w);
670     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
671                                  GL_RENDERBUFFER_HEIGHT, &h);
672     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
673                                  GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
674
675     glGenRenderbuffers(1, &rbs[*numRbs]);
676     glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
677     glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
678     glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer,
679                               GL_RENDERBUFFER, rbs[*numRbs]);
680
681     glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
682     glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
683     glDrawBuffer(drawbuffer);
684     glReadBuffer(drawbuffer);
685     glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
686                       GL_COLOR_BUFFER_BIT, GL_NEAREST);
687     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
688     ++*numRbs;
689
690     if (stencilRb == depthRb && stencilRb) {
691         //combined depth and stencil buffer
692         glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
693         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
694                                      GL_RENDERBUFFER_WIDTH, &w);
695         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
696                                      GL_RENDERBUFFER_HEIGHT, &h);
697         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
698                                      GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
699
700         glGenRenderbuffers(1, &rbs[*numRbs]);
701         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
702         glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
703         glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
704                                   GL_RENDERBUFFER, rbs[*numRbs]);
705         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
706         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
707         glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
708                           GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
709         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
710         ++*numRbs;
711     } else {
712         if (depthRb) {
713             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
714             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
715                                          GL_RENDERBUFFER_WIDTH, &w);
716             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
717                                          GL_RENDERBUFFER_HEIGHT, &h);
718             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
719                                          GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
720
721             glGenRenderbuffers(1, &rbs[*numRbs]);
722             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
723             glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
724             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
725                                       GL_DEPTH_ATTACHMENT,
726                                       GL_RENDERBUFFER, rbs[*numRbs]);
727             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
728             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
729             glDrawBuffer(GL_DEPTH_ATTACHMENT);
730             glReadBuffer(GL_DEPTH_ATTACHMENT);
731             glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
732                               GL_DEPTH_BUFFER_BIT, GL_NEAREST);
733             ++*numRbs;
734         }
735         if (stencilRb) {
736             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
737             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
738                                          GL_RENDERBUFFER_WIDTH, &w);
739             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
740                                          GL_RENDERBUFFER_HEIGHT, &h);
741             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
742                                      GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
743
744             glGenRenderbuffers(1, &rbs[*numRbs]);
745             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
746             glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
747             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
748                                       GL_STENCIL_ATTACHMENT,
749                                       GL_RENDERBUFFER, rbs[*numRbs]);
750             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
751             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
752             glDrawBuffer(GL_STENCIL_ATTACHMENT);
753             glReadBuffer(GL_STENCIL_ATTACHMENT);
754             glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
755                               GL_STENCIL_BUFFER_BIT, GL_NEAREST);
756             ++*numRbs;
757         }
758     }
759
760     return fbo;
761 }
762
763
764 /**
765  * Dump images of current draw drawable/window.
766  */
767 static void
768 dumpDrawableImages(JSONWriter &json)
769 {
770     GLint width, height;
771
772     if (!getDrawableBounds(&width, &height)) {
773         return;
774     }
775
776     GLint draw_buffer = GL_NONE;
777     glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
778     glReadBuffer(draw_buffer);
779
780     if (draw_buffer != GL_NONE) {
781         GLint read_buffer = GL_NONE;
782         glGetIntegerv(GL_READ_BUFFER, &read_buffer);
783
784         GLint alpha_bits = 0;
785         glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
786         GLenum format = alpha_bits ? GL_RGBA : GL_RGB;
787         json.beginMember(enumToString(draw_buffer));
788         dumpReadBufferImage(json, width, height, format);
789         json.endMember();
790
791         glReadBuffer(read_buffer);
792     }
793
794     GLint depth_bits = 0;
795     glGetIntegerv(GL_DEPTH_BITS, &depth_bits);
796     if (depth_bits) {
797         json.beginMember("GL_DEPTH_COMPONENT");
798         dumpReadBufferImage(json, width, height, GL_DEPTH_COMPONENT);
799         json.endMember();
800     }
801
802     GLint stencil_bits = 0;
803     glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);
804     if (stencil_bits) {
805         json.beginMember("GL_STENCIL_INDEX");
806         dumpReadBufferImage(json, width, height, GL_STENCIL_INDEX);
807         json.endMember();
808     }
809 }
810 /**
811  * Dump the specified framebuffer attachment.
812  *
813  * In the case of a color attachment, it assumes it is already bound for read.
814  */
815 static void
816 dumpFramebufferAttachment(JSONWriter &json, GLenum target, GLenum attachment, GLenum format)
817 {
818     GLint width = 0, height = 0;
819     if (!getFramebufferAttachmentSize(target, attachment, &width, &height)) {
820         return;
821     }
822
823     json.beginMember(enumToString(attachment));
824     dumpReadBufferImage(json, width, height, format);
825     json.endMember();
826 }
827
828
829 static void
830 dumpFramebufferAttachments(JSONWriter &json, GLenum target)
831 {
832     GLint read_framebuffer = 0;
833     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
834
835     GLint read_buffer = GL_NONE;
836     glGetIntegerv(GL_READ_BUFFER, &read_buffer);
837
838     GLint max_draw_buffers = 1;
839     glGetIntegerv(GL_MAX_DRAW_BUFFERS, &max_draw_buffers);
840     GLint max_color_attachments = 0;
841     glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);
842
843     for (GLint i = 0; i < max_draw_buffers; ++i) {
844         GLint draw_buffer = GL_NONE;
845         glGetIntegerv(GL_DRAW_BUFFER0 + i, &draw_buffer);
846         if (draw_buffer != GL_NONE) {
847             glReadBuffer(draw_buffer);
848             GLint attachment;
849             if (draw_buffer >= GL_COLOR_ATTACHMENT0 && draw_buffer < GL_COLOR_ATTACHMENT0 + max_color_attachments) {
850                 attachment = draw_buffer;
851             } else {
852                 std::cerr << "warning: unexpected GL_DRAW_BUFFER" << i << " = " << draw_buffer << "\n";
853                 attachment = GL_COLOR_ATTACHMENT0;
854             }
855             GLint alpha_size = 0;
856             glGetFramebufferAttachmentParameteriv(target, attachment,
857                                                   GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE,
858                                                   &alpha_size);
859             GLenum format = alpha_size ? GL_RGBA : GL_RGB;
860             dumpFramebufferAttachment(json, target, attachment, format);
861         }
862     }
863
864     glReadBuffer(read_buffer);
865
866     dumpFramebufferAttachment(json, target, GL_DEPTH_ATTACHMENT, GL_DEPTH_COMPONENT);
867     dumpFramebufferAttachment(json, target, GL_STENCIL_ATTACHMENT, GL_STENCIL_INDEX);
868
869     glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
870 }
871
872
873 static void
874 dumpFramebuffer(JSONWriter &json)
875 {
876     json.beginMember("framebuffer");
877     json.beginObject();
878
879     GLint boundDrawFbo = 0, boundReadFbo = 0;
880     glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo);
881     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo);
882     if (!boundDrawFbo) {
883         dumpDrawableImages(json);
884     } else {
885         GLint colorRb = 0, stencilRb = 0, depthRb = 0;
886         GLint draw_buffer0 = GL_NONE;
887         glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer0);
888         bool multisample = false;
889
890         GLint boundRb = 0;
891         glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb);
892
893         GLint object_type;
894         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
895         if (object_type == GL_RENDERBUFFER) {
896             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &colorRb);
897             glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
898             GLint samples = 0;
899             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
900             if (samples) {
901                 multisample = true;
902             }
903         }
904
905         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
906         if (object_type == GL_RENDERBUFFER) {
907             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &depthRb);
908             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
909             GLint samples = 0;
910             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
911             if (samples) {
912                 multisample = true;
913             }
914         }
915
916         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
917         if (object_type == GL_RENDERBUFFER) {
918             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &stencilRb);
919             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
920             GLint samples = 0;
921             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
922             if (samples) {
923                 multisample = true;
924             }
925         }
926
927         glBindRenderbuffer(GL_RENDERBUFFER, boundRb);
928
929         GLuint rbs[3];
930         GLint numRbs = 0;
931         GLuint fboCopy = 0;
932
933         if (multisample) {
934             // glReadPixels doesnt support multisampled buffers so we need
935             // to blit the fbo to a temporary one
936             fboCopy = downsampledFramebuffer(boundDrawFbo, draw_buffer0,
937                                              colorRb, depthRb, stencilRb,
938                                              rbs, &numRbs);
939         }
940
941         dumpFramebufferAttachments(json, GL_DRAW_FRAMEBUFFER);
942
943         if (multisample) {
944             glBindRenderbuffer(GL_RENDERBUFFER_BINDING, boundRb);
945             glDeleteRenderbuffers(numRbs, rbs);
946             glDeleteFramebuffers(1, &fboCopy);
947         }
948
949         glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo);
950         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo);
951     }
952
953     json.endObject();
954     json.endMember(); // framebuffer
955 }
956
957
958 static const GLenum bindings[] = {
959     GL_DRAW_BUFFER,
960     GL_READ_BUFFER,
961     GL_PIXEL_PACK_BUFFER_BINDING,
962     GL_PIXEL_UNPACK_BUFFER_BINDING,
963     GL_TEXTURE_BINDING_1D,
964     GL_TEXTURE_BINDING_2D,
965     GL_TEXTURE_BINDING_3D,
966     GL_TEXTURE_BINDING_RECTANGLE,
967     GL_TEXTURE_BINDING_CUBE_MAP,
968     GL_DRAW_FRAMEBUFFER_BINDING,
969     GL_READ_FRAMEBUFFER_BINDING,
970     GL_RENDERBUFFER_BINDING,
971     GL_DRAW_BUFFER0,
972     GL_DRAW_BUFFER1,
973     GL_DRAW_BUFFER2,
974     GL_DRAW_BUFFER3,
975     GL_DRAW_BUFFER4,
976     GL_DRAW_BUFFER5,
977     GL_DRAW_BUFFER6,
978     GL_DRAW_BUFFER7,
979 };
980
981
982 #define NUM_BINDINGS sizeof(bindings)/sizeof(bindings[0])
983
984
985 void dumpCurrentContext(std::ostream &os)
986 {
987     JSONWriter json(os);
988
989 #ifndef NDEBUG
990     GLint old_bindings[NUM_BINDINGS];
991     for (unsigned i = 0; i < NUM_BINDINGS; ++i) {
992         old_bindings[i] = 0;
993         glGetIntegerv(bindings[i], &old_bindings[i]);
994     }
995 #endif
996
997     dumpParameters(json);
998     dumpShaders(json);
999     dumpTextures(json);
1000     dumpFramebuffer(json);
1001
1002 #ifndef NDEBUG
1003     for (unsigned i = 0; i < NUM_BINDINGS; ++i) {
1004         GLint new_binding = 0;
1005         glGetIntegerv(bindings[i], &new_binding);
1006         if (new_binding != old_bindings[i]) {
1007             std::cerr << "warning: " << enumToString(bindings[i]) << " was clobbered\n";
1008         }
1009     }
1010 #endif
1011
1012 }
1013
1014
1015 } /* namespace glstate */