]> git.cworth.org Git - apitrace/blob - retrace/glstate_images.cpp
7b0a42473fdf97cbc8c04ad4910247d078d4b2cf
[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         }
749
750         if (!getFramebufferAttachmentDesc(context, framebuffer_target, draw_buffer, desc)) {
751             return NULL;
752         }
753     } else {
754         if (!context.ES) {
755             glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
756             if (draw_buffer == GL_NONE) {
757                 return NULL;
758             }
759         }
760
761         if (!getDrawableBounds(&desc.width, &desc.height)) {
762             return NULL;
763         }
764
765         desc.depth = 1;
766     }
767
768     GLenum type = GL_UNSIGNED_BYTE;
769
770 #if DEPTH_AS_RGBA
771     if (format == GL_DEPTH_COMPONENT) {
772         type = GL_UNSIGNED_INT;
773         channels = 4;
774     }
775 #endif
776
777     image::Image *image = new image::Image(desc.width, desc.height, channels, true);
778     if (!image) {
779         return NULL;
780     }
781
782     while (glGetError() != GL_NO_ERROR) {}
783
784     GLint read_framebuffer = 0;
785     GLint read_buffer = GL_NONE;
786     if (!context.ES) {
787         glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
788         glBindFramebuffer(GL_READ_FRAMEBUFFER, draw_framebuffer);
789
790         glGetIntegerv(GL_READ_BUFFER, &read_buffer);
791         glReadBuffer(draw_buffer);
792     }
793
794     // TODO: reset imaging state too
795     context.resetPixelPackState();
796
797     glReadPixels(0, 0, desc.width, desc.height, format, type, image->pixels);
798
799     context.restorePixelPackState();
800
801     if (!context.ES) {
802         glReadBuffer(read_buffer);
803         glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
804     }
805
806     GLenum error = glGetError();
807     if (error != GL_NO_ERROR) {
808         do {
809             std::cerr << "warning: " << enumToString(error) << " while getting snapshot\n";
810             error = glGetError();
811         } while(error != GL_NO_ERROR);
812         delete image;
813         return NULL;
814     }
815      
816     return image;
817 }
818
819
820 /**
821  * Dump the image of the currently bound read buffer.
822  */
823 static inline void
824 dumpReadBufferImage(JSONWriter &json, GLint width, GLint height, GLenum format,
825                     GLint internalFormat = GL_NONE)
826 {
827     GLint channels = _gl_format_channels(format);
828
829     if (internalFormat == GL_NONE) {
830         internalFormat = format;
831     }
832
833     Context context;
834
835     GLenum type = GL_UNSIGNED_BYTE;
836
837 #if DEPTH_AS_RGBA
838     if (format == GL_DEPTH_COMPONENT) {
839         type = GL_UNSIGNED_INT;
840         channels = 4;
841     }
842 #endif
843
844     image::Image *image = new image::Image(width, height, channels, true);
845
846     // TODO: reset imaging state too
847     context.resetPixelPackState();
848
849     glReadPixels(0, 0, width, height, format, type, image->pixels);
850
851     context.restorePixelPackState();
852
853     json.writeImage(image, formatToString(internalFormat));
854
855     delete image;
856 }
857
858
859 static inline GLuint
860 downsampledFramebuffer(Context &context,
861                        GLuint oldFbo, GLint drawbuffer,
862                        GLint colorRb, GLint depthRb, GLint stencilRb,
863                        GLuint *rbs, GLint *numRbs)
864 {
865     GLuint fbo;
866
867
868     *numRbs = 0;
869
870     glGenFramebuffers(1, &fbo);
871     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
872
873     {
874         // color buffer
875         ImageDesc desc;
876         glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
877         getBoundRenderbufferDesc(context, desc);
878
879         glGenRenderbuffers(1, &rbs[*numRbs]);
880         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
881         glRenderbufferStorage(GL_RENDERBUFFER, desc.internalFormat, desc.width, desc.height);
882         glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer,
883                                   GL_RENDERBUFFER, rbs[*numRbs]);
884
885         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
886         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
887         glDrawBuffer(drawbuffer);
888         glReadBuffer(drawbuffer);
889         glBlitFramebuffer(0, 0, desc.width, desc.height, 0, 0, desc.width, desc.height,
890                           GL_COLOR_BUFFER_BIT, GL_NEAREST);
891         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
892         ++*numRbs;
893     }
894
895     if (stencilRb == depthRb && stencilRb) {
896         //combined depth and stencil buffer
897         ImageDesc desc;
898         glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
899         getBoundRenderbufferDesc(context, desc);
900
901         glGenRenderbuffers(1, &rbs[*numRbs]);
902         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
903         glRenderbufferStorage(GL_RENDERBUFFER, desc.internalFormat, desc.width, desc.height);
904         glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
905                                   GL_RENDERBUFFER, rbs[*numRbs]);
906         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
907         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
908         glBlitFramebuffer(0, 0, desc.width, desc.height, 0, 0, desc.width, desc.height,
909                           GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
910         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
911         ++*numRbs;
912     } else {
913         if (depthRb) {
914             ImageDesc desc;
915             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
916             getBoundRenderbufferDesc(context, desc);
917
918             glGenRenderbuffers(1, &rbs[*numRbs]);
919             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
920             glRenderbufferStorage(GL_RENDERBUFFER, desc.internalFormat, desc.width, desc.height);
921             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
922                                       GL_DEPTH_ATTACHMENT,
923                                       GL_RENDERBUFFER, rbs[*numRbs]);
924             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
925             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
926             glDrawBuffer(GL_DEPTH_ATTACHMENT);
927             glReadBuffer(GL_DEPTH_ATTACHMENT);
928             glBlitFramebuffer(0, 0, desc.width, desc.height, 0, 0, desc.width, desc.height,
929                               GL_DEPTH_BUFFER_BIT, GL_NEAREST);
930             ++*numRbs;
931         }
932         if (stencilRb) {
933             ImageDesc desc;
934             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
935             getBoundRenderbufferDesc(context, desc);
936
937             glGenRenderbuffers(1, &rbs[*numRbs]);
938             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
939             glRenderbufferStorage(GL_RENDERBUFFER, desc.internalFormat, desc.width, desc.height);
940             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
941                                       GL_STENCIL_ATTACHMENT,
942                                       GL_RENDERBUFFER, rbs[*numRbs]);
943             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
944             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
945             glDrawBuffer(GL_STENCIL_ATTACHMENT);
946             glReadBuffer(GL_STENCIL_ATTACHMENT);
947             glBlitFramebuffer(0, 0, desc.width, desc.height, 0, 0, desc.width, desc.height,
948                               GL_STENCIL_BUFFER_BIT, GL_NEAREST);
949             ++*numRbs;
950         }
951     }
952
953     return fbo;
954 }
955
956
957 /**
958  * Dump images of current draw drawable/window.
959  */
960 static void
961 dumpDrawableImages(JSONWriter &json, Context &context)
962 {
963     GLint width, height;
964
965     if (!getDrawableBounds(&width, &height)) {
966         return;
967     }
968
969     GLint draw_buffer = GL_NONE;
970     if (context.ES) {
971         draw_buffer = GL_BACK;
972     } else {
973         glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
974         glReadBuffer(draw_buffer);
975     }
976
977     if (draw_buffer != GL_NONE) {
978         GLint read_buffer = GL_NONE;
979         if (!context.ES) {
980             glGetIntegerv(GL_READ_BUFFER, &read_buffer);
981         }
982
983         GLint alpha_bits = 0;
984 #if 0
985         // XXX: Ignore alpha until we are able to match the traced visual
986         glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
987 #endif
988         GLenum format = alpha_bits ? GL_RGBA : GL_RGB;
989         json.beginMember(enumToString(draw_buffer));
990         dumpReadBufferImage(json, width, height, format);
991         json.endMember();
992
993         if (!context.ES) {
994             glReadBuffer(read_buffer);
995         }
996     }
997
998     if (!context.ES) {
999         GLint depth_bits = 0;
1000         glGetIntegerv(GL_DEPTH_BITS, &depth_bits);
1001         if (depth_bits) {
1002             json.beginMember("GL_DEPTH_COMPONENT");
1003             dumpReadBufferImage(json, width, height, GL_DEPTH_COMPONENT);
1004             json.endMember();
1005         }
1006
1007         GLint stencil_bits = 0;
1008         glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);
1009         if (stencil_bits) {
1010             json.beginMember("GL_STENCIL_INDEX");
1011             dumpReadBufferImage(json, width, height, GL_STENCIL_INDEX);
1012             json.endMember();
1013         }
1014     }
1015 }
1016
1017
1018 /**
1019  * Dump the specified framebuffer attachment.
1020  *
1021  * In the case of a color attachment, it assumes it is already bound for read.
1022  */
1023 static void
1024 dumpFramebufferAttachment(JSONWriter &json, Context &context, GLenum target, GLenum attachment, GLenum format)
1025 {
1026     ImageDesc desc;
1027     if (!getFramebufferAttachmentDesc(context, target, attachment, desc)) {
1028         return;
1029     }
1030
1031     json.beginMember(enumToString(attachment));
1032     dumpReadBufferImage(json, desc.width, desc.height, format, desc.internalFormat);
1033     json.endMember();
1034 }
1035
1036
1037 static void
1038 dumpFramebufferAttachments(JSONWriter &json, Context &context, GLenum target)
1039 {
1040     GLint read_framebuffer = 0;
1041     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
1042
1043     GLint read_buffer = GL_NONE;
1044     glGetIntegerv(GL_READ_BUFFER, &read_buffer);
1045
1046     GLint max_draw_buffers = 1;
1047     glGetIntegerv(GL_MAX_DRAW_BUFFERS, &max_draw_buffers);
1048     GLint max_color_attachments = 0;
1049     glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);
1050
1051     for (GLint i = 0; i < max_draw_buffers; ++i) {
1052         GLint draw_buffer = GL_NONE;
1053         glGetIntegerv(GL_DRAW_BUFFER0 + i, &draw_buffer);
1054         if (draw_buffer != GL_NONE) {
1055             glReadBuffer(draw_buffer);
1056             GLint attachment;
1057             if (draw_buffer >= GL_COLOR_ATTACHMENT0 && draw_buffer < GL_COLOR_ATTACHMENT0 + max_color_attachments) {
1058                 attachment = draw_buffer;
1059             } else {
1060                 std::cerr << "warning: unexpected GL_DRAW_BUFFER" << i << " = " << draw_buffer << "\n";
1061                 attachment = GL_COLOR_ATTACHMENT0;
1062             }
1063             GLint alpha_size = 0;
1064             glGetFramebufferAttachmentParameteriv(target, attachment,
1065                                                   GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE,
1066                                                   &alpha_size);
1067             GLenum format = alpha_size ? GL_RGBA : GL_RGB;
1068             dumpFramebufferAttachment(json, context, target, attachment, format);
1069         }
1070     }
1071
1072     glReadBuffer(read_buffer);
1073
1074     if (!context.ES) {
1075         dumpFramebufferAttachment(json, context, target, GL_DEPTH_ATTACHMENT, GL_DEPTH_COMPONENT);
1076         dumpFramebufferAttachment(json, context, target, GL_STENCIL_ATTACHMENT, GL_STENCIL_INDEX);
1077     }
1078
1079     glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
1080 }
1081
1082
1083 void
1084 dumpFramebuffer(JSONWriter &json, Context &context)
1085 {
1086     json.beginMember("framebuffer");
1087     json.beginObject();
1088
1089     GLint boundDrawFbo = 0, boundReadFbo = 0;
1090     glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo);
1091     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo);
1092     if (!boundDrawFbo) {
1093         dumpDrawableImages(json, context);
1094     } else if (context.ES) {
1095         dumpFramebufferAttachments(json, context, GL_FRAMEBUFFER);
1096     } else {
1097         GLint colorRb = 0, stencilRb = 0, depthRb = 0;
1098         GLint draw_buffer0 = GL_NONE;
1099         glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer0);
1100         bool multisample = false;
1101
1102         GLint boundRb = 0;
1103         glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb);
1104
1105         GLint object_type;
1106         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
1107         if (object_type == GL_RENDERBUFFER) {
1108             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &colorRb);
1109             glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
1110             GLint samples = 0;
1111             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
1112             if (samples) {
1113                 multisample = true;
1114             }
1115         }
1116
1117         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
1118         if (object_type == GL_RENDERBUFFER) {
1119             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &depthRb);
1120             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
1121             GLint samples = 0;
1122             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
1123             if (samples) {
1124                 multisample = true;
1125             }
1126         }
1127
1128         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
1129         if (object_type == GL_RENDERBUFFER) {
1130             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &stencilRb);
1131             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
1132             GLint samples = 0;
1133             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
1134             if (samples) {
1135                 multisample = true;
1136             }
1137         }
1138
1139         glBindRenderbuffer(GL_RENDERBUFFER, boundRb);
1140
1141         GLuint rbs[3];
1142         GLint numRbs = 0;
1143         GLuint fboCopy = 0;
1144
1145         if (multisample) {
1146             // glReadPixels doesnt support multisampled buffers so we need
1147             // to blit the fbo to a temporary one
1148             fboCopy = downsampledFramebuffer(context,
1149                                              boundDrawFbo, draw_buffer0,
1150                                              colorRb, depthRb, stencilRb,
1151                                              rbs, &numRbs);
1152         }
1153
1154         dumpFramebufferAttachments(json, context, GL_DRAW_FRAMEBUFFER);
1155
1156         if (multisample) {
1157             glBindRenderbuffer(GL_RENDERBUFFER_BINDING, boundRb);
1158             glDeleteRenderbuffers(numRbs, rbs);
1159             glDeleteFramebuffers(1, &fboCopy);
1160         }
1161
1162         glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo);
1163         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo);
1164     }
1165
1166     json.endObject();
1167     json.endMember(); // framebuffer
1168 }
1169
1170
1171 } /* namespace glstate */