]> git.cworth.org Git - apitrace/blob - retrace/glstate_images.cpp
45d77eb940d903f5ff9add982e92dd781556cfa9
[apitrace] / retrace / glstate_images.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 <assert.h>
28 #include <string.h>
29
30 #include <algorithm>
31 #include <iostream>
32
33 #include "image.hpp"
34 #include "json.hpp"
35 #include "glproc.hpp"
36 #include "glsize.hpp"
37 #include "glstate.hpp"
38 #include "glstate_internal.hpp"
39
40
41 #ifdef __linux__
42 #include <dlfcn.h>
43 #endif
44
45 #ifdef __APPLE__
46
47 #include <Carbon/Carbon.h>
48
49 #ifdef __cplusplus
50 extern "C" {
51 #endif
52
53 OSStatus CGSGetSurfaceBounds(CGSConnectionID, CGWindowID, CGSSurfaceID, CGRect *);
54
55 #ifdef __cplusplus
56 }
57 #endif
58
59 #endif /* __APPLE__ */
60
61
62 /* Change thi to one to force interpreting depth buffers as RGBA, which enables
63  * visualizing full dynamic range, until we can transmit HDR images to the GUI */
64 #define DEPTH_AS_RGBA 0
65
66
67 namespace glstate {
68
69
70 struct ImageDesc
71 {
72     GLint width;
73     GLint height;
74     GLint depth;
75     GLint samples;
76     GLint internalFormat;
77
78     inline
79     ImageDesc() :
80         width(0),
81         height(0),
82         depth(0),
83         samples(0),
84         internalFormat(GL_NONE)
85     {}
86
87     inline bool
88     operator == (const ImageDesc &other) const {
89         return width == other.width &&
90                height == other.height &&
91                depth == other.depth &&
92                samples == other.samples &&
93                internalFormat == other.internalFormat;
94     }
95
96     inline bool
97     valid(void) const {
98         return width > 0 && height > 0 && depth > 0;
99     }
100 };
101
102
103 /**
104  * Sames as enumToString, but with special provision to handle formatsLUMINANCE_ALPHA.
105  *
106  * OpenGL 2.1 specification states that "internalFormat may (for backwards
107  * compatibility with the 1.0 version of the GL) also take on the integer
108  * values 1, 2, 3, and 4, which are equivalent to symbolic constants LUMINANCE,
109  * LUMINANCE ALPHA, RGB, and RGBA respectively". 
110  */
111 const char *
112 formatToString(GLenum internalFormat) {
113     switch (internalFormat) {
114     case 1:
115         return "GL_LUMINANCE";
116     case 2:
117         return "GL_LUMINANCE_ALPHA";
118     case 3:
119         return "GL_RGB";
120     case 4:
121         return "GL_RGBA";
122     default:
123         return enumToString(internalFormat);
124     }
125 }
126
127
128 /**
129  * OpenGL ES does not support glGetTexLevelParameteriv, but it is possible to
130  * probe whether a texture has a given size by crafting a dummy glTexSubImage()
131  * call.
132  */
133 static bool
134 probeTextureLevelSizeOES(GLenum target, GLint level, const GLint size[3]) {
135     while (glGetError() != GL_NO_ERROR)
136         ;
137
138     GLenum internalFormat = GL_RGBA;
139     GLenum type = GL_UNSIGNED_BYTE;
140     GLint dummy = 0;
141
142     switch (target) {
143     case GL_TEXTURE_2D:
144     case GL_TEXTURE_CUBE_MAP:
145     case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
146     case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
147     case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
148     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
149     case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
150     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
151         glTexSubImage2D(target, level, size[0], size[1], 0, 0, internalFormat, type, &dummy);
152         break;
153     case GL_TEXTURE_3D_OES:
154         glTexSubImage3DOES(target, level, size[0], size[1], size[2], 0, 0, 0, internalFormat, type, &dummy);
155     default:
156         assert(0);
157         return false;
158     }
159
160     GLenum error = glGetError();
161
162     if (0) {
163         std::cerr << "(" << size[0] << ", " << size[1] << ", " << size[2] << ") = " << enumToString(error) << "\n";
164     }
165
166     if (error == GL_NO_ERROR) {
167         return true;
168     }
169
170     while (glGetError() != GL_NO_ERROR)
171         ;
172
173     return false;
174 }
175
176
177 /**
178  * Bisect the texture size along an axis.
179  *
180  * It is assumed that the texture exists.
181  */
182 static GLint
183 bisectTextureLevelSizeOES(GLenum target, GLint level, GLint axis, GLint max) {
184     GLint size[3] = {0, 0, 0};
185
186     assert(axis < 3);
187     assert(max >= 0);
188
189     GLint min = 0;
190     while (true) {
191         GLint test = (min + max) / 2;
192         if (test == min) {
193             return min;
194         }
195
196         size[axis] = test;
197
198         if (probeTextureLevelSizeOES(target, level, size)) {
199             min = test;
200         } else {
201             max = test;
202         }
203     }
204 }
205
206
207 /**
208  * Special path to obtain texture size on OpenGL ES, that does not rely on
209  * glGetTexLevelParameteriv
210  */
211 static bool
212 getActiveTextureLevelDescOES(Context &context, GLenum target, GLint level, ImageDesc &desc)
213 {
214     if (target == GL_TEXTURE_1D) {
215         // OpenGL ES does not support 1D textures
216         return false;
217     }
218
219     const GLint size[3] = {1, 1, 1}; 
220     if (!probeTextureLevelSizeOES(target, level, size)) {
221         return false;
222     }
223
224     // XXX: mere guess
225     desc.internalFormat = GL_RGBA;
226
227     GLint maxSize = 0;
228     switch (target) {
229     case GL_TEXTURE_2D:
230         glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxSize);
231         desc.width = bisectTextureLevelSizeOES(target, level, 0, maxSize);
232         desc.height = bisectTextureLevelSizeOES(target, level, 1, maxSize);
233         desc.depth = 1;
234         break;
235     case GL_TEXTURE_CUBE_MAP:
236     case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
237     case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
238     case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
239     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
240     case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
241     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
242         glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &maxSize);
243         desc.width = bisectTextureLevelSizeOES(target, level, 0, maxSize);
244         desc.height = desc.width;
245         desc.depth = 1;
246         break;
247     case GL_TEXTURE_3D_OES:
248         glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE_OES, &maxSize);
249         desc.width = bisectTextureLevelSizeOES(target, level, 0, maxSize);
250         desc.width = bisectTextureLevelSizeOES(target, level, 1, maxSize);
251         desc.depth = bisectTextureLevelSizeOES(target, level, 2, maxSize);
252         break;
253     default:
254         return false;
255     }
256
257     if (0) {
258         std::cerr
259             << enumToString(target) << " "
260             << level << " "
261             << desc.width << "x" << desc.height << "x" << desc.depth
262             << "\n";
263     }
264
265     return desc.valid();
266 }
267
268
269 static inline bool
270 getActiveTextureLevelDesc(Context &context, GLenum target, GLint level, ImageDesc &desc)
271 {
272     assert(target != GL_TEXTURE_CUBE_MAP);
273
274     if (context.ES) {
275         return getActiveTextureLevelDescOES(context, target, level, desc);
276     }
277
278     glGetTexLevelParameteriv(target, level, GL_TEXTURE_INTERNAL_FORMAT, &desc.internalFormat);
279
280     desc.width = 0;
281     glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &desc.width);
282
283     if (target == GL_TEXTURE_1D) {
284         desc.height = 1;
285         desc.depth = 1;
286     } else {
287         desc.height = 0;
288         glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &desc.height);
289         if (target != GL_TEXTURE_3D) {
290             desc.depth = 1;
291         } else {
292             desc.depth = 0;
293             glGetTexLevelParameteriv(target, level, GL_TEXTURE_DEPTH, &desc.depth);
294         }
295     }
296
297     glGetTexLevelParameteriv(target, level, GL_TEXTURE_SAMPLES, &desc.samples);
298
299     return desc.valid();
300 }
301
302
303 static GLenum
304 getTextureBinding(GLenum target)
305 {
306     switch (target) {
307     case GL_TEXTURE_1D:
308         return GL_TEXTURE_BINDING_1D;
309     case GL_TEXTURE_1D_ARRAY:
310         return GL_TEXTURE_BINDING_1D_ARRAY;
311     case GL_TEXTURE_2D:
312         return GL_TEXTURE_BINDING_2D;
313     case GL_TEXTURE_2D_MULTISAMPLE:
314         return GL_TEXTURE_BINDING_2D_MULTISAMPLE;
315     case GL_TEXTURE_2D_ARRAY:
316         return GL_TEXTURE_BINDING_2D_ARRAY;
317     case GL_TEXTURE_RECTANGLE:
318         return GL_TEXTURE_BINDING_RECTANGLE;
319     case GL_TEXTURE_CUBE_MAP:
320     case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
321     case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
322     case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
323     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
324     case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
325     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
326         return GL_TEXTURE_BINDING_CUBE_MAP;
327     case GL_TEXTURE_CUBE_MAP_ARRAY:
328         return GL_TEXTURE_BINDING_CUBE_MAP_ARRAY;
329     case GL_TEXTURE_3D:
330         return GL_TEXTURE_BINDING_3D;
331     default:
332         assert(false);
333         return GL_NONE;
334     }
335 }
336
337
338 /**
339  * OpenGL ES does not support glGetTexImage. Obtain the pixels by attaching the
340  * texture to a framebuffer.
341  */
342 static inline void
343 getTexImageOES(GLenum target, GLint level, ImageDesc &desc, GLubyte *pixels)
344 {
345     memset(pixels, 0x80, desc.height * desc.width * 4);
346
347     GLenum texture_binding = getTextureBinding(target);
348     if (texture_binding == GL_NONE) {
349         return;
350     }
351
352     GLint texture = 0;
353     glGetIntegerv(texture_binding, &texture);
354     if (!texture) {
355         return;
356     }
357
358     GLint prev_fbo = 0;
359     GLuint fbo = 0;
360     glGetIntegerv(GL_FRAMEBUFFER_BINDING, &prev_fbo);
361     glGenFramebuffers(1, &fbo);
362     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
363
364     GLenum status;
365
366     switch (target) {
367     case GL_TEXTURE_2D:
368     case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
369     case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
370     case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
371     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
372     case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
373     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
374         glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, level);
375         status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
376         if (status != GL_FRAMEBUFFER_COMPLETE) {
377             std::cerr << __FUNCTION__ << ": " << enumToString(status) << "\n";
378         }
379         glReadPixels(0, 0, desc.width, desc.height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
380         break;
381     case GL_TEXTURE_3D_OES:
382         for (int i = 0; i < desc.depth; i++) {
383             glFramebufferTexture3D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_3D, texture, level, i);
384             glReadPixels(0, 0, desc.width, desc.height, GL_RGBA, GL_UNSIGNED_BYTE, pixels + 4 * i * desc.width * desc.height);
385         }
386         break;
387     }
388
389     glBindFramebuffer(GL_FRAMEBUFFER, prev_fbo);
390
391     glDeleteFramebuffers(1, &fbo);
392 }
393
394
395 static inline GLboolean
396 isDepthFormat(GLenum internalFormat)
397 {
398    switch (internalFormat) {
399    case GL_DEPTH_COMPONENT:
400    case GL_DEPTH_COMPONENT16:
401    case GL_DEPTH_COMPONENT24:
402    case GL_DEPTH_COMPONENT32:
403    case GL_DEPTH_COMPONENT32F:
404    case GL_DEPTH_COMPONENT32F_NV:
405    case GL_DEPTH_STENCIL:
406    case GL_DEPTH24_STENCIL8:
407    case GL_DEPTH32F_STENCIL8:
408    case GL_DEPTH32F_STENCIL8_NV:
409       return GL_TRUE;
410    }
411    return GL_FALSE;
412 }
413
414
415 static inline void
416 dumpActiveTextureLevel(JSONWriter &json, Context &context, GLenum target, GLint level)
417 {
418     ImageDesc desc;
419     if (!getActiveTextureLevelDesc(context, target, level, desc)) {
420         return;
421     }
422
423     char label[512];
424     GLint active_texture = GL_TEXTURE0;
425     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
426     snprintf(label, sizeof label, "%s, %s, level = %d",
427              enumToString(active_texture), enumToString(target), level);
428
429     json.beginMember(label);
430
431     GLuint channels;
432     GLenum format;
433     if (!context.ES && isDepthFormat(desc.internalFormat)) {
434        format = GL_DEPTH_COMPONENT;
435        channels = 1;
436     } else {
437        format = GL_RGBA;
438        channels = 4;
439     }
440
441     image::Image *image = new image::Image(desc.width, desc.height*desc.depth, channels, true);
442
443     context.resetPixelPackState();
444
445     if (context.ES) {
446         getTexImageOES(target, level, desc, image->pixels);
447     } else {
448         glGetTexImage(target, level, format, GL_UNSIGNED_BYTE, image->pixels);
449     }
450
451     context.restorePixelPackState();
452
453     json.writeImage(image, formatToString(desc.internalFormat), desc.depth);
454
455     delete image;
456
457     json.endMember(); // label
458 }
459
460
461 static inline void
462 dumpTexture(JSONWriter &json, Context &context, GLenum target, GLenum binding)
463 {
464     GLint texture_binding = 0;
465     glGetIntegerv(binding, &texture_binding);
466     if (!glIsEnabled(target) && !texture_binding) {
467         return;
468     }
469
470     GLint level = 0;
471     do {
472         ImageDesc desc;
473
474         if (target == GL_TEXTURE_CUBE_MAP) {
475             for (int face = 0; face < 6; ++face) {
476                 if (!getActiveTextureLevelDesc(context, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, desc)) {
477                     return;
478                 }
479                 dumpActiveTextureLevel(json, context, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level);
480             }
481         } else {
482             if (!getActiveTextureLevelDesc(context, target, level, desc)) {
483                 return;
484             }
485             dumpActiveTextureLevel(json, context, target, level);
486         }
487
488         ++level;
489     } while(true);
490 }
491
492
493 void
494 dumpTextures(JSONWriter &json, Context &context)
495 {
496     json.beginMember("textures");
497     json.beginObject();
498     GLint active_texture = GL_TEXTURE0;
499     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
500
501     GLint max_texture_coords = 0;
502     glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);
503     GLint max_combined_texture_image_units = 0;
504     glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);
505     GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);
506
507     /*
508      * At least the Android software GL implementation doesn't return the
509      * proper value for this, but rather returns 0. The GL(ES) specification
510      * mandates a minimum value of 2, so use this as a fall-back value.
511      */
512     max_units = std::max(max_units, 2);
513
514     for (GLint unit = 0; unit < max_units; ++unit) {
515         GLenum texture = GL_TEXTURE0 + unit;
516         glActiveTexture(texture);
517         dumpTexture(json, context, GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D);
518         dumpTexture(json, context, GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D);
519         dumpTexture(json, context, GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D);
520         dumpTexture(json, context, GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE);
521         dumpTexture(json, context, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP);
522     }
523     glActiveTexture(active_texture);
524     json.endObject();
525     json.endMember(); // textures
526 }
527
528
529 static bool
530 getDrawableBounds(GLint *width, GLint *height) {
531 #if defined(__linux__)
532     if (dlsym(RTLD_DEFAULT, "eglGetCurrentContext")) {
533         EGLContext currentContext = eglGetCurrentContext();
534         if (currentContext != EGL_NO_CONTEXT) {
535             EGLSurface currentSurface = eglGetCurrentSurface(EGL_DRAW);
536             if (currentSurface == EGL_NO_SURFACE) {
537                 return false;
538             }
539
540             EGLDisplay currentDisplay = eglGetCurrentDisplay();
541             if (currentDisplay == EGL_NO_DISPLAY) {
542                 return false;
543             }
544
545             if (!eglQuerySurface(currentDisplay, currentSurface, EGL_WIDTH, width) ||
546                 !eglQuerySurface(currentDisplay, currentSurface, EGL_HEIGHT, height)) {
547                 return false;
548             }
549
550             return true;
551         }
552     }
553 #endif
554
555 #if defined(_WIN32)
556
557     HDC hDC = wglGetCurrentDC();
558     if (!hDC) {
559         return false;
560     }
561
562     HWND hWnd = WindowFromDC(hDC);
563     RECT rect;
564
565     if (!GetClientRect(hWnd, &rect)) {
566        return false;
567     }
568
569     *width  = rect.right  - rect.left;
570     *height = rect.bottom - rect.top;
571     return true;
572
573 #elif defined(__APPLE__)
574
575     CGLContextObj ctx = CGLGetCurrentContext();
576     if (ctx == NULL) {
577         return false;
578     }
579
580     CGSConnectionID cid;
581     CGSWindowID wid;
582     CGSSurfaceID sid;
583
584     if (CGLGetSurface(ctx, &cid, &wid, &sid) != kCGLNoError) {
585         return false;
586     }
587
588     CGRect rect;
589
590     if (CGSGetSurfaceBounds(cid, wid, sid, &rect) != 0) {
591         return false;
592     }
593
594     *width = rect.size.width;
595     *height = rect.size.height;
596     return true;
597
598 #elif defined(HAVE_X11)
599
600     Display *display;
601     Drawable drawable;
602     Window root;
603     int x, y;
604     unsigned int w, h, bw, depth;
605
606     display = glXGetCurrentDisplay();
607     if (!display) {
608         return false;
609     }
610
611     drawable = glXGetCurrentDrawable();
612     if (drawable == None) {
613         return false;
614     }
615
616     if (!XGetGeometry(display, drawable, &root, &x, &y, &w, &h, &bw, &depth)) {
617         return false;
618     }
619
620     *width = w;
621     *height = h;
622     return true;
623
624 #else
625
626     return false;
627
628 #endif
629 }
630
631
632 struct TextureTargetBinding
633 {
634     GLenum target;
635     GLenum binding;
636 };
637
638
639 static const GLenum
640 textureTargets[] = {
641     GL_TEXTURE_1D,
642     GL_TEXTURE_2D,
643     GL_TEXTURE_RECTANGLE,
644     GL_TEXTURE_CUBE_MAP,
645     GL_TEXTURE_3D,
646     GL_TEXTURE_2D_MULTISAMPLE,
647     GL_TEXTURE_1D_ARRAY,
648     GL_TEXTURE_2D_ARRAY,
649     GL_TEXTURE_CUBE_MAP_ARRAY,
650 };
651
652
653 static GLenum
654 getTextureTarget(GLint texture)
655 {
656     if (!glIsTexture(texture)) {
657         return GL_NONE;
658     }
659
660     for (unsigned i = 0; i < sizeof(textureTargets)/sizeof(textureTargets[0]); ++i) {
661         GLenum target = textureTargets[i];
662         GLenum binding = getTextureBinding(target);
663
664         while (glGetError() != GL_NO_ERROR)
665             ;
666
667         GLint bound_texture = 0;
668         glGetIntegerv(binding, &bound_texture);
669         glBindTexture(target, texture);
670
671         bool succeeded = glGetError() == GL_NO_ERROR;
672
673         glBindTexture(target, bound_texture);
674
675         if (succeeded) {
676             return target;
677         }
678     }
679
680     return GL_NONE;
681 }
682
683
684 static bool
685 getBoundRenderbufferDesc(Context &context, ImageDesc &desc)
686 {
687     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &desc.width);
688     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &desc.height);
689     desc.depth = 1;
690     
691     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &desc.samples);
692
693     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &desc.internalFormat);
694     
695     return desc.valid();
696 }
697
698
699 static bool
700 getRenderbufferDesc(Context &context, GLint renderbuffer, ImageDesc &desc)
701 {
702     GLint bound_renderbuffer = 0;
703     glGetIntegerv(GL_RENDERBUFFER_BINDING, &bound_renderbuffer);
704     glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
705
706     getBoundRenderbufferDesc(context, desc);
707
708     glBindRenderbuffer(GL_RENDERBUFFER, bound_renderbuffer);
709     
710     return desc.valid();
711 }
712
713
714 static bool
715 getFramebufferAttachmentDesc(Context &context, GLenum target, GLenum attachment, ImageDesc &desc)
716 {
717     GLint object_type = GL_NONE;
718     glGetFramebufferAttachmentParameteriv(target, attachment,
719                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
720                                           &object_type);
721     if (object_type == GL_NONE) {
722         return false;
723     }
724
725     GLint object_name = 0;
726     glGetFramebufferAttachmentParameteriv(target, attachment,
727                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
728                                           &object_name);
729     if (object_name == 0) {
730         return false;
731     }
732
733     if (object_type == GL_RENDERBUFFER) {
734         return getRenderbufferDesc(context, object_name, desc);
735     } else if (object_type == GL_TEXTURE) {
736         GLint texture_face = 0;
737         glGetFramebufferAttachmentParameteriv(target, attachment,
738                                               GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE,
739                                               &texture_face);
740
741         GLint texture_level = 0;
742         glGetFramebufferAttachmentParameteriv(target, attachment,
743                                               GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
744                                               &texture_level);
745
746         GLint bound_texture = 0;
747         if (texture_face != 0) {
748             glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &bound_texture);
749             glBindTexture(GL_TEXTURE_CUBE_MAP, object_name);
750             getActiveTextureLevelDesc(context, texture_face, texture_level, desc);
751             glBindTexture(GL_TEXTURE_CUBE_MAP, bound_texture);
752         } else {
753             GLenum texture_target = getTextureTarget(object_name);
754             GLenum texture_binding = getTextureBinding(texture_target);
755             glGetIntegerv(texture_binding, &bound_texture);
756             glBindTexture(texture_target, object_name);
757             getActiveTextureLevelDesc(context, texture_target, texture_level, desc);
758             glBindTexture(texture_target, bound_texture);
759         }
760
761         return desc.valid();
762     } else {
763         std::cerr << "warning: unexpected GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = " << object_type << "\n";
764         return false;
765     }
766 }
767
768
769
770 image::Image *
771 getDrawBufferImage() {
772     GLenum format = GL_RGB;
773     GLint channels = _gl_format_channels(format);
774     if (channels > 4) {
775         return NULL;
776     }
777
778     Context context;
779
780     GLenum framebuffer_binding;
781     GLenum framebuffer_target;
782     if (context.ES) {
783         framebuffer_binding = GL_FRAMEBUFFER_BINDING;
784         framebuffer_target = GL_FRAMEBUFFER;
785     } else {
786         framebuffer_binding = GL_DRAW_FRAMEBUFFER_BINDING;
787         framebuffer_target = GL_DRAW_FRAMEBUFFER;
788     }
789
790     GLint draw_framebuffer = 0;
791     glGetIntegerv(framebuffer_binding, &draw_framebuffer);
792
793     GLint draw_buffer = GL_NONE;
794     ImageDesc desc;
795     if (draw_framebuffer) {
796         if (context.ARB_draw_buffers) {
797             glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer);
798             if (draw_buffer == GL_NONE) {
799                 return NULL;
800             }
801         } else {
802             // GL_COLOR_ATTACHMENT0 is implied
803             draw_buffer = GL_COLOR_ATTACHMENT0;
804         }
805
806         if (!getFramebufferAttachmentDesc(context, framebuffer_target, draw_buffer, desc)) {
807             return NULL;
808         }
809     } else {
810         if (context.ES) {
811             // XXX: Draw buffer is always FRONT for single buffer context, BACK
812             // for double buffered contexts. There is no way to know which (as
813             // GL_DOUBLEBUFFER state is also unavailable), so always assume
814             // double-buffering.
815             draw_buffer = GL_BACK;
816         } else {
817             glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
818             if (draw_buffer == GL_NONE) {
819                 return NULL;
820             }
821         }
822
823         if (!getDrawableBounds(&desc.width, &desc.height)) {
824             return NULL;
825         }
826
827         desc.depth = 1;
828     }
829
830     GLenum type = GL_UNSIGNED_BYTE;
831
832 #if DEPTH_AS_RGBA
833     if (format == GL_DEPTH_COMPONENT) {
834         type = GL_UNSIGNED_INT;
835         channels = 4;
836     }
837 #endif
838
839     image::Image *image = new image::Image(desc.width, desc.height, channels, true);
840     if (!image) {
841         return NULL;
842     }
843
844     while (glGetError() != GL_NO_ERROR) {}
845
846     GLint read_framebuffer = 0;
847     GLint read_buffer = GL_NONE;
848     if (!context.ES) {
849         glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
850         glBindFramebuffer(GL_READ_FRAMEBUFFER, draw_framebuffer);
851
852         glGetIntegerv(GL_READ_BUFFER, &read_buffer);
853         glReadBuffer(draw_buffer);
854     }
855
856     // TODO: reset imaging state too
857     context.resetPixelPackState();
858
859     glReadPixels(0, 0, desc.width, desc.height, format, type, image->pixels);
860
861     context.restorePixelPackState();
862
863     if (!context.ES) {
864         glReadBuffer(read_buffer);
865         glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
866     }
867
868     GLenum error = glGetError();
869     if (error != GL_NO_ERROR) {
870         do {
871             std::cerr << "warning: " << enumToString(error) << " while getting snapshot\n";
872             error = glGetError();
873         } while(error != GL_NO_ERROR);
874         delete image;
875         return NULL;
876     }
877      
878     return image;
879 }
880
881
882 /**
883  * Dump the image of the currently bound read buffer.
884  */
885 static inline void
886 dumpReadBufferImage(JSONWriter &json, GLint width, GLint height, GLenum format,
887                     GLint internalFormat = GL_NONE)
888 {
889     GLint channels = _gl_format_channels(format);
890
891     if (internalFormat == GL_NONE) {
892         internalFormat = format;
893     }
894
895     Context context;
896
897     GLenum type = GL_UNSIGNED_BYTE;
898
899 #if DEPTH_AS_RGBA
900     if (format == GL_DEPTH_COMPONENT) {
901         type = GL_UNSIGNED_INT;
902         channels = 4;
903     }
904 #endif
905
906     image::Image *image = new image::Image(width, height, channels, true);
907
908     while (glGetError() != GL_NO_ERROR) {}
909
910     // TODO: reset imaging state too
911     context.resetPixelPackState();
912
913     glReadPixels(0, 0, width, height, format, type, image->pixels);
914
915     context.restorePixelPackState();
916
917     GLenum error = glGetError();
918     if (error != GL_NO_ERROR) {
919         do {
920             std::cerr << "warning: " << enumToString(error) << " while reading framebuffer\n";
921             error = glGetError();
922         } while(error != GL_NO_ERROR);
923         json.writeNull();
924     } else {
925         json.writeImage(image, formatToString(internalFormat));
926     }
927
928     delete image;
929 }
930
931
932 static inline GLuint
933 downsampledFramebuffer(Context &context,
934                        GLuint oldFbo, GLint drawbuffer,
935                        const ImageDesc &colorDesc,
936                        const ImageDesc &depthDesc,
937                        const ImageDesc &stencilDesc,
938                        GLuint *rbs, GLint *numRbs)
939 {
940     GLuint fbo;
941
942
943     *numRbs = 0;
944
945     glGenFramebuffers(1, &fbo);
946     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
947
948     {
949         // color buffer
950         glGenRenderbuffers(1, &rbs[*numRbs]);
951         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
952         glRenderbufferStorage(GL_RENDERBUFFER, colorDesc.internalFormat, colorDesc.width, colorDesc.height);
953         glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer,
954                                   GL_RENDERBUFFER, rbs[*numRbs]);
955
956         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
957         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
958         glDrawBuffer(drawbuffer);
959         glReadBuffer(drawbuffer);
960         glBlitFramebuffer(0, 0, colorDesc.width, colorDesc.height, 0, 0, colorDesc.width, colorDesc.height,
961                           GL_COLOR_BUFFER_BIT, GL_NEAREST);
962         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
963         ++*numRbs;
964     }
965
966     if (stencilDesc == depthDesc &&
967         depthDesc.valid()) {
968         //combined depth and stencil buffer
969         glGenRenderbuffers(1, &rbs[*numRbs]);
970         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
971         glRenderbufferStorage(GL_RENDERBUFFER, depthDesc.internalFormat, depthDesc.width, depthDesc.height);
972         glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
973                                   GL_RENDERBUFFER, rbs[*numRbs]);
974         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
975         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
976         glBlitFramebuffer(0, 0, depthDesc.width, depthDesc.height, 0, 0, depthDesc.width, depthDesc.height,
977                           GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
978         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
979         ++*numRbs;
980     } else {
981         if (depthDesc.valid()) {
982             glGenRenderbuffers(1, &rbs[*numRbs]);
983             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
984             glRenderbufferStorage(GL_RENDERBUFFER, depthDesc.internalFormat, depthDesc.width, depthDesc.height);
985             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
986                                       GL_DEPTH_ATTACHMENT,
987                                       GL_RENDERBUFFER, rbs[*numRbs]);
988             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
989             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
990             glDrawBuffer(GL_DEPTH_ATTACHMENT);
991             glReadBuffer(GL_DEPTH_ATTACHMENT);
992             glBlitFramebuffer(0, 0, depthDesc.width, depthDesc.height, 0, 0, depthDesc.width, depthDesc.height,
993                               GL_DEPTH_BUFFER_BIT, GL_NEAREST);
994             ++*numRbs;
995         }
996         if (stencilDesc.valid()) {
997             glGenRenderbuffers(1, &rbs[*numRbs]);
998             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
999             glRenderbufferStorage(GL_RENDERBUFFER, stencilDesc.internalFormat, stencilDesc.width, stencilDesc.height);
1000             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
1001                                       GL_STENCIL_ATTACHMENT,
1002                                       GL_RENDERBUFFER, rbs[*numRbs]);
1003             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
1004             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
1005             glDrawBuffer(GL_STENCIL_ATTACHMENT);
1006             glReadBuffer(GL_STENCIL_ATTACHMENT);
1007             glBlitFramebuffer(0, 0, stencilDesc.width, stencilDesc.height, 0, 0, stencilDesc.width, stencilDesc.height,
1008                               GL_STENCIL_BUFFER_BIT, GL_NEAREST);
1009             ++*numRbs;
1010         }
1011     }
1012
1013     return fbo;
1014 }
1015
1016
1017 /**
1018  * Dump images of current draw drawable/window.
1019  */
1020 static void
1021 dumpDrawableImages(JSONWriter &json, Context &context)
1022 {
1023     GLint width, height;
1024
1025     if (!getDrawableBounds(&width, &height)) {
1026         return;
1027     }
1028
1029     GLint draw_buffer = GL_NONE;
1030     if (context.ES) {
1031         // XXX: Draw buffer is always FRONT for single buffer context, BACK for
1032         // double buffered contexts. There is no way to know which (as
1033         // GL_DOUBLEBUFFER state is also unavailable), so always assume
1034         // double-buffering.
1035         draw_buffer = GL_BACK;
1036     } else {
1037         glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
1038     }
1039
1040     if (draw_buffer != GL_NONE) {
1041         // Read from current draw buffer
1042         GLint read_buffer = GL_NONE;
1043         if (!context.ES) {
1044             glGetIntegerv(GL_READ_BUFFER, &read_buffer);
1045             glReadBuffer(draw_buffer);
1046         }
1047
1048         GLint alpha_bits = 0;
1049 #if 0
1050         // XXX: Ignore alpha until we are able to match the traced visual
1051         glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
1052 #endif
1053         GLenum format = alpha_bits ? GL_RGBA : GL_RGB;
1054         json.beginMember(enumToString(draw_buffer));
1055         dumpReadBufferImage(json, width, height, format);
1056         json.endMember();
1057
1058         // Restore original read buffer
1059         if (!context.ES) {
1060             glReadBuffer(read_buffer);
1061         }
1062     }
1063
1064     if (!context.ES) {
1065         GLint depth_bits = 0;
1066         glGetIntegerv(GL_DEPTH_BITS, &depth_bits);
1067         if (depth_bits) {
1068             json.beginMember("GL_DEPTH_COMPONENT");
1069             dumpReadBufferImage(json, width, height, GL_DEPTH_COMPONENT);
1070             json.endMember();
1071         }
1072
1073         GLint stencil_bits = 0;
1074         glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);
1075         if (stencil_bits) {
1076             json.beginMember("GL_STENCIL_INDEX");
1077             dumpReadBufferImage(json, width, height, GL_STENCIL_INDEX);
1078             json.endMember();
1079         }
1080     }
1081 }
1082
1083
1084 /**
1085  * Dump the specified framebuffer attachment.
1086  *
1087  * In the case of a color attachment, it assumes it is already bound for read.
1088  */
1089 static void
1090 dumpFramebufferAttachment(JSONWriter &json, Context &context, GLenum target, GLenum attachment, GLenum format)
1091 {
1092     ImageDesc desc;
1093     if (!getFramebufferAttachmentDesc(context, target, attachment, desc)) {
1094         return;
1095     }
1096
1097     assert(desc.samples == 0);
1098
1099     json.beginMember(enumToString(attachment));
1100     dumpReadBufferImage(json, desc.width, desc.height, format, desc.internalFormat);
1101     json.endMember();
1102 }
1103
1104
1105 static void
1106 dumpFramebufferAttachments(JSONWriter &json, Context &context, GLenum target)
1107 {
1108     GLint read_framebuffer = 0;
1109     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
1110
1111     GLint read_buffer = GL_NONE;
1112     glGetIntegerv(GL_READ_BUFFER, &read_buffer);
1113
1114     GLint max_draw_buffers = 1;
1115     glGetIntegerv(GL_MAX_DRAW_BUFFERS, &max_draw_buffers);
1116     GLint max_color_attachments = 0;
1117     glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);
1118
1119     for (GLint i = 0; i < max_draw_buffers; ++i) {
1120         GLint draw_buffer = GL_NONE;
1121         glGetIntegerv(GL_DRAW_BUFFER0 + i, &draw_buffer);
1122         if (draw_buffer != GL_NONE) {
1123             glReadBuffer(draw_buffer);
1124             GLint attachment;
1125             if (draw_buffer >= GL_COLOR_ATTACHMENT0 && draw_buffer < GL_COLOR_ATTACHMENT0 + max_color_attachments) {
1126                 attachment = draw_buffer;
1127             } else {
1128                 std::cerr << "warning: unexpected GL_DRAW_BUFFER" << i << " = " << draw_buffer << "\n";
1129                 attachment = GL_COLOR_ATTACHMENT0;
1130             }
1131             GLint alpha_size = 0;
1132             glGetFramebufferAttachmentParameteriv(target, attachment,
1133                                                   GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE,
1134                                                   &alpha_size);
1135             GLenum format = alpha_size ? GL_RGBA : GL_RGB;
1136             dumpFramebufferAttachment(json, context, target, attachment, format);
1137         }
1138     }
1139
1140     glReadBuffer(read_buffer);
1141
1142     if (!context.ES) {
1143         dumpFramebufferAttachment(json, context, target, GL_DEPTH_ATTACHMENT, GL_DEPTH_COMPONENT);
1144         dumpFramebufferAttachment(json, context, target, GL_STENCIL_ATTACHMENT, GL_STENCIL_INDEX);
1145     }
1146
1147     glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
1148 }
1149
1150
1151 void
1152 dumpFramebuffer(JSONWriter &json, Context &context)
1153 {
1154     json.beginMember("framebuffer");
1155     json.beginObject();
1156
1157     GLint boundDrawFbo = 0, boundReadFbo = 0;
1158     glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo);
1159     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo);
1160     if (!boundDrawFbo) {
1161         dumpDrawableImages(json, context);
1162     } else if (context.ES) {
1163         dumpFramebufferAttachments(json, context, GL_FRAMEBUFFER);
1164     } else {
1165         GLint draw_buffer0 = GL_NONE;
1166         glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer0);
1167         bool multisample = false;
1168
1169         GLint boundRb = 0;
1170         glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb);
1171
1172         ImageDesc colorDesc;
1173         if (getFramebufferAttachmentDesc(context, GL_DRAW_FRAMEBUFFER, draw_buffer0, colorDesc)) {
1174             if (colorDesc.samples) {
1175                 multisample = true;
1176             }
1177         }
1178
1179         ImageDesc depthDesc;
1180         if (getFramebufferAttachmentDesc(context, GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthDesc)) {
1181             if (depthDesc.samples) {
1182                 multisample = true;
1183             }
1184         }
1185
1186         ImageDesc stencilDesc;
1187         if (getFramebufferAttachmentDesc(context, GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, stencilDesc)) {
1188             if (stencilDesc.samples) {
1189                 multisample = true;
1190             }
1191         }
1192
1193         GLuint rbs[3];
1194         GLint numRbs = 0;
1195         GLuint fboCopy = 0;
1196
1197         if (multisample) {
1198             // glReadPixels doesnt support multisampled buffers so we need
1199             // to blit the fbo to a temporary one
1200             fboCopy = downsampledFramebuffer(context,
1201                                              boundDrawFbo, draw_buffer0,
1202                                              colorDesc, depthDesc, stencilDesc,
1203                                              rbs, &numRbs);
1204         } else {
1205             glBindFramebuffer(GL_READ_FRAMEBUFFER, boundDrawFbo);
1206         }
1207
1208         dumpFramebufferAttachments(json, context, GL_READ_FRAMEBUFFER);
1209
1210         if (multisample) {
1211             glBindRenderbuffer(GL_RENDERBUFFER, boundRb);
1212             glDeleteRenderbuffers(numRbs, rbs);
1213             glDeleteFramebuffers(1, &fboCopy);
1214         }
1215
1216         glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo);
1217         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo);
1218     }
1219
1220     json.endObject();
1221     json.endMember(); // framebuffer
1222 }
1223
1224
1225 } /* namespace glstate */