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