]> git.cworth.org Git - apitrace/blob - retrace/glstate_images.cpp
glstate: Better support for integer textures dumps.
[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 GLboolean
416 isIntegerFormat(GLenum internalFormat)
417 {
418    switch (internalFormat) {
419
420    case GL_RG_INTEGER:
421    case GL_RED_INTEGER:
422    case GL_GREEN_INTEGER:
423    case GL_BLUE_INTEGER:
424    case GL_ALPHA_INTEGER:
425    case GL_RGB_INTEGER:
426    case GL_RGBA_INTEGER:
427    case GL_BGR_INTEGER:
428    case GL_BGRA_INTEGER:
429    case GL_LUMINANCE_INTEGER_EXT:
430    case GL_LUMINANCE_ALPHA_INTEGER_EXT:
431
432    case GL_R8I:
433    case GL_R8UI:
434    case GL_R16I:
435    case GL_R16UI:
436    case GL_R32I:
437    case GL_R32UI:
438    case GL_RG8I:
439    case GL_RG8UI:
440    case GL_RG16I:
441    case GL_RG16UI:
442    case GL_RG32I:
443    case GL_RG32UI:
444    case GL_RGB8I:
445    case GL_RGB8UI:
446    case GL_RGB16I:
447    case GL_RGB16UI:
448    case GL_RGB32I:
449    case GL_RGB32UI:
450    case GL_RGBA8I:
451    case GL_RGBA8UI:
452    case GL_RGBA16I:
453    case GL_RGBA16UI:
454    case GL_RGBA32I:
455    case GL_RGBA32UI:
456    case GL_RGB10_A2UI:
457    case GL_LUMINANCE8I_EXT:
458    case GL_LUMINANCE8UI_EXT:
459    case GL_LUMINANCE16I_EXT:
460    case GL_LUMINANCE16UI_EXT:
461    case GL_LUMINANCE32I_EXT:
462    case GL_LUMINANCE32UI_EXT:
463    case GL_ALPHA8I_EXT:
464    case GL_ALPHA8UI_EXT:
465    case GL_ALPHA16I_EXT:
466    case GL_ALPHA16UI_EXT:
467    case GL_ALPHA32I_EXT:
468    case GL_ALPHA32UI_EXT:
469    case GL_LUMINANCE_ALPHA8I_EXT:
470    case GL_LUMINANCE_ALPHA8UI_EXT:
471    case GL_LUMINANCE_ALPHA16I_EXT:
472    case GL_LUMINANCE_ALPHA16UI_EXT:
473    case GL_LUMINANCE_ALPHA32I_EXT:
474    case GL_LUMINANCE_ALPHA32UI_EXT:
475    case GL_INTENSITY8I_EXT:
476    case GL_INTENSITY8UI_EXT:
477    case GL_INTENSITY16I_EXT:
478    case GL_INTENSITY16UI_EXT:
479    case GL_INTENSITY32I_EXT:
480    case GL_INTENSITY32UI_EXT:
481       return GL_TRUE;
482    }
483    return GL_FALSE;
484 }
485
486
487 static inline void
488 dumpActiveTextureLevel(JSONWriter &json, Context &context, GLenum target, GLint level)
489 {
490     ImageDesc desc;
491     if (!getActiveTextureLevelDesc(context, target, level, desc)) {
492         return;
493     }
494
495     char label[512];
496     GLint active_texture = GL_TEXTURE0;
497     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
498     snprintf(label, sizeof label, "%s, %s, level = %d",
499              enumToString(active_texture), enumToString(target), level);
500
501     json.beginMember(label);
502
503     GLuint channels;
504     GLenum format;
505     if (!context.ES && isDepthFormat(desc.internalFormat)) {
506         format = GL_DEPTH_COMPONENT;
507         channels = 1;
508     } else {
509         if (isIntegerFormat(desc.internalFormat)) {
510             format = GL_RGBA_INTEGER;
511         } else {
512             format = GL_RGBA;
513         }
514         channels = 4;
515     }
516
517     image::Image *image = new image::Image(desc.width, desc.height*desc.depth, channels, true);
518
519     context.resetPixelPackState();
520
521     if (context.ES) {
522         getTexImageOES(target, level, desc, image->pixels);
523     } else {
524         glGetTexImage(target, level, format, GL_UNSIGNED_BYTE, image->pixels);
525     }
526
527     context.restorePixelPackState();
528
529     json.writeImage(image, formatToString(desc.internalFormat), desc.depth);
530
531     delete image;
532
533     json.endMember(); // label
534 }
535
536
537 static inline void
538 dumpTexture(JSONWriter &json, Context &context, GLenum target, GLenum binding)
539 {
540     GLint texture_binding = 0;
541     glGetIntegerv(binding, &texture_binding);
542     if (!glIsEnabled(target) && !texture_binding) {
543         return;
544     }
545
546     GLint level = 0;
547     do {
548         ImageDesc desc;
549
550         if (target == GL_TEXTURE_CUBE_MAP) {
551             for (int face = 0; face < 6; ++face) {
552                 if (!getActiveTextureLevelDesc(context, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, desc)) {
553                     return;
554                 }
555                 dumpActiveTextureLevel(json, context, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level);
556             }
557         } else {
558             if (!getActiveTextureLevelDesc(context, target, level, desc)) {
559                 return;
560             }
561             dumpActiveTextureLevel(json, context, target, level);
562         }
563
564         ++level;
565     } while(true);
566 }
567
568
569 void
570 dumpTextures(JSONWriter &json, Context &context)
571 {
572     json.beginMember("textures");
573     json.beginObject();
574     GLint active_texture = GL_TEXTURE0;
575     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
576
577     GLint max_texture_coords = 0;
578     glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);
579     GLint max_combined_texture_image_units = 0;
580     glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);
581     GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);
582
583     /*
584      * At least the Android software GL implementation doesn't return the
585      * proper value for this, but rather returns 0. The GL(ES) specification
586      * mandates a minimum value of 2, so use this as a fall-back value.
587      */
588     max_units = std::max(max_units, 2);
589
590     for (GLint unit = 0; unit < max_units; ++unit) {
591         GLenum texture = GL_TEXTURE0 + unit;
592         glActiveTexture(texture);
593         dumpTexture(json, context, GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D);
594         dumpTexture(json, context, GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D);
595         dumpTexture(json, context, GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D);
596         dumpTexture(json, context, GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE);
597         dumpTexture(json, context, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP);
598     }
599     glActiveTexture(active_texture);
600     json.endObject();
601     json.endMember(); // textures
602 }
603
604
605 static bool
606 getDrawableBounds(GLint *width, GLint *height) {
607 #if defined(__linux__)
608     if (dlsym(RTLD_DEFAULT, "eglGetCurrentContext")) {
609         EGLContext currentContext = eglGetCurrentContext();
610         if (currentContext != EGL_NO_CONTEXT) {
611             EGLSurface currentSurface = eglGetCurrentSurface(EGL_DRAW);
612             if (currentSurface == EGL_NO_SURFACE) {
613                 return false;
614             }
615
616             EGLDisplay currentDisplay = eglGetCurrentDisplay();
617             if (currentDisplay == EGL_NO_DISPLAY) {
618                 return false;
619             }
620
621             if (!eglQuerySurface(currentDisplay, currentSurface, EGL_WIDTH, width) ||
622                 !eglQuerySurface(currentDisplay, currentSurface, EGL_HEIGHT, height)) {
623                 return false;
624             }
625
626             return true;
627         }
628     }
629 #endif
630
631 #if defined(_WIN32)
632
633     HDC hDC = wglGetCurrentDC();
634     if (!hDC) {
635         return false;
636     }
637
638     HWND hWnd = WindowFromDC(hDC);
639     RECT rect;
640
641     if (!GetClientRect(hWnd, &rect)) {
642        return false;
643     }
644
645     *width  = rect.right  - rect.left;
646     *height = rect.bottom - rect.top;
647     return true;
648
649 #elif defined(__APPLE__)
650
651     CGLContextObj ctx = CGLGetCurrentContext();
652     if (ctx == NULL) {
653         return false;
654     }
655
656     CGSConnectionID cid;
657     CGSWindowID wid;
658     CGSSurfaceID sid;
659
660     if (CGLGetSurface(ctx, &cid, &wid, &sid) != kCGLNoError) {
661         return false;
662     }
663
664     CGRect rect;
665
666     if (CGSGetSurfaceBounds(cid, wid, sid, &rect) != 0) {
667         return false;
668     }
669
670     *width = rect.size.width;
671     *height = rect.size.height;
672     return true;
673
674 #elif defined(HAVE_X11)
675
676     Display *display;
677     Drawable drawable;
678     Window root;
679     int x, y;
680     unsigned int w, h, bw, depth;
681
682     display = glXGetCurrentDisplay();
683     if (!display) {
684         return false;
685     }
686
687     drawable = glXGetCurrentDrawable();
688     if (drawable == None) {
689         return false;
690     }
691
692     if (!XGetGeometry(display, drawable, &root, &x, &y, &w, &h, &bw, &depth)) {
693         return false;
694     }
695
696     *width = w;
697     *height = h;
698     return true;
699
700 #else
701
702     return false;
703
704 #endif
705 }
706
707
708 struct TextureTargetBinding
709 {
710     GLenum target;
711     GLenum binding;
712 };
713
714
715 static const GLenum
716 textureTargets[] = {
717     GL_TEXTURE_1D,
718     GL_TEXTURE_2D,
719     GL_TEXTURE_RECTANGLE,
720     GL_TEXTURE_CUBE_MAP,
721     GL_TEXTURE_3D,
722     GL_TEXTURE_2D_MULTISAMPLE,
723     GL_TEXTURE_1D_ARRAY,
724     GL_TEXTURE_2D_ARRAY,
725     GL_TEXTURE_CUBE_MAP_ARRAY,
726 };
727
728
729 static GLenum
730 getTextureTarget(GLint texture)
731 {
732     if (!glIsTexture(texture)) {
733         return GL_NONE;
734     }
735
736     for (unsigned i = 0; i < sizeof(textureTargets)/sizeof(textureTargets[0]); ++i) {
737         GLenum target = textureTargets[i];
738         GLenum binding = getTextureBinding(target);
739
740         while (glGetError() != GL_NO_ERROR)
741             ;
742
743         GLint bound_texture = 0;
744         glGetIntegerv(binding, &bound_texture);
745         glBindTexture(target, texture);
746
747         bool succeeded = glGetError() == GL_NO_ERROR;
748
749         glBindTexture(target, bound_texture);
750
751         if (succeeded) {
752             return target;
753         }
754     }
755
756     return GL_NONE;
757 }
758
759
760 static bool
761 getBoundRenderbufferDesc(Context &context, ImageDesc &desc)
762 {
763     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &desc.width);
764     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &desc.height);
765     desc.depth = 1;
766     
767     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &desc.samples);
768
769     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &desc.internalFormat);
770     
771     return desc.valid();
772 }
773
774
775 static bool
776 getRenderbufferDesc(Context &context, GLint renderbuffer, ImageDesc &desc)
777 {
778     GLint bound_renderbuffer = 0;
779     glGetIntegerv(GL_RENDERBUFFER_BINDING, &bound_renderbuffer);
780     glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
781
782     getBoundRenderbufferDesc(context, desc);
783
784     glBindRenderbuffer(GL_RENDERBUFFER, bound_renderbuffer);
785     
786     return desc.valid();
787 }
788
789
790 static bool
791 getFramebufferAttachmentDesc(Context &context, GLenum target, GLenum attachment, ImageDesc &desc)
792 {
793     GLint object_type = GL_NONE;
794     glGetFramebufferAttachmentParameteriv(target, attachment,
795                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
796                                           &object_type);
797     if (object_type == GL_NONE) {
798         return false;
799     }
800
801     GLint object_name = 0;
802     glGetFramebufferAttachmentParameteriv(target, attachment,
803                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
804                                           &object_name);
805     if (object_name == 0) {
806         return false;
807     }
808
809     if (object_type == GL_RENDERBUFFER) {
810         return getRenderbufferDesc(context, object_name, desc);
811     } else if (object_type == GL_TEXTURE) {
812         GLint texture_face = 0;
813         glGetFramebufferAttachmentParameteriv(target, attachment,
814                                               GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE,
815                                               &texture_face);
816
817         GLint texture_level = 0;
818         glGetFramebufferAttachmentParameteriv(target, attachment,
819                                               GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
820                                               &texture_level);
821
822         GLint bound_texture = 0;
823         if (texture_face != 0) {
824             glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &bound_texture);
825             glBindTexture(GL_TEXTURE_CUBE_MAP, object_name);
826             getActiveTextureLevelDesc(context, texture_face, texture_level, desc);
827             glBindTexture(GL_TEXTURE_CUBE_MAP, bound_texture);
828         } else {
829             GLenum texture_target = getTextureTarget(object_name);
830             GLenum texture_binding = getTextureBinding(texture_target);
831             glGetIntegerv(texture_binding, &bound_texture);
832             glBindTexture(texture_target, object_name);
833             getActiveTextureLevelDesc(context, texture_target, texture_level, desc);
834             glBindTexture(texture_target, bound_texture);
835         }
836
837         return desc.valid();
838     } else {
839         std::cerr << "warning: unexpected GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = " << object_type << "\n";
840         return false;
841     }
842 }
843
844
845
846 image::Image *
847 getDrawBufferImage() {
848     GLenum format = GL_RGB;
849     GLint channels = _gl_format_channels(format);
850     if (channels > 4) {
851         return NULL;
852     }
853
854     Context context;
855
856     GLenum framebuffer_binding;
857     GLenum framebuffer_target;
858     if (context.ES) {
859         framebuffer_binding = GL_FRAMEBUFFER_BINDING;
860         framebuffer_target = GL_FRAMEBUFFER;
861     } else {
862         framebuffer_binding = GL_DRAW_FRAMEBUFFER_BINDING;
863         framebuffer_target = GL_DRAW_FRAMEBUFFER;
864     }
865
866     GLint draw_framebuffer = 0;
867     glGetIntegerv(framebuffer_binding, &draw_framebuffer);
868
869     GLint draw_buffer = GL_NONE;
870     ImageDesc desc;
871     if (draw_framebuffer) {
872         if (context.ARB_draw_buffers) {
873             glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer);
874             if (draw_buffer == GL_NONE) {
875                 return NULL;
876             }
877         } else {
878             // GL_COLOR_ATTACHMENT0 is implied
879             draw_buffer = GL_COLOR_ATTACHMENT0;
880         }
881
882         if (!getFramebufferAttachmentDesc(context, framebuffer_target, draw_buffer, desc)) {
883             return NULL;
884         }
885     } else {
886         if (context.ES) {
887             // XXX: Draw buffer is always FRONT for single buffer context, BACK
888             // for double buffered contexts. There is no way to know which (as
889             // GL_DOUBLEBUFFER state is also unavailable), so always assume
890             // double-buffering.
891             draw_buffer = GL_BACK;
892         } else {
893             glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
894             if (draw_buffer == GL_NONE) {
895                 return NULL;
896             }
897         }
898
899         if (!getDrawableBounds(&desc.width, &desc.height)) {
900             return NULL;
901         }
902
903         desc.depth = 1;
904     }
905
906     GLenum type = GL_UNSIGNED_BYTE;
907
908 #if DEPTH_AS_RGBA
909     if (format == GL_DEPTH_COMPONENT) {
910         type = GL_UNSIGNED_INT;
911         channels = 4;
912     }
913 #endif
914
915     image::Image *image = new image::Image(desc.width, desc.height, channels, true);
916     if (!image) {
917         return NULL;
918     }
919
920     while (glGetError() != GL_NO_ERROR) {}
921
922     GLint read_framebuffer = 0;
923     GLint read_buffer = GL_NONE;
924     if (!context.ES) {
925         glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
926         glBindFramebuffer(GL_READ_FRAMEBUFFER, draw_framebuffer);
927
928         glGetIntegerv(GL_READ_BUFFER, &read_buffer);
929         glReadBuffer(draw_buffer);
930     }
931
932     // TODO: reset imaging state too
933     context.resetPixelPackState();
934
935     glReadPixels(0, 0, desc.width, desc.height, format, type, image->pixels);
936
937     context.restorePixelPackState();
938
939     if (!context.ES) {
940         glReadBuffer(read_buffer);
941         glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
942     }
943
944     GLenum error = glGetError();
945     if (error != GL_NO_ERROR) {
946         do {
947             std::cerr << "warning: " << enumToString(error) << " while getting snapshot\n";
948             error = glGetError();
949         } while(error != GL_NO_ERROR);
950         delete image;
951         return NULL;
952     }
953      
954     return image;
955 }
956
957
958 /**
959  * Dump the image of the currently bound read buffer.
960  */
961 static inline void
962 dumpReadBufferImage(JSONWriter &json, GLint width, GLint height, GLenum format,
963                     GLint internalFormat = GL_NONE)
964 {
965     GLint channels = _gl_format_channels(format);
966
967     if (internalFormat == GL_NONE) {
968         internalFormat = format;
969     }
970
971     Context context;
972
973     GLenum type = GL_UNSIGNED_BYTE;
974
975 #if DEPTH_AS_RGBA
976     if (format == GL_DEPTH_COMPONENT) {
977         type = GL_UNSIGNED_INT;
978         channels = 4;
979     }
980 #endif
981
982     image::Image *image = new image::Image(width, height, channels, true);
983
984     while (glGetError() != GL_NO_ERROR) {}
985
986     // TODO: reset imaging state too
987     context.resetPixelPackState();
988
989     glReadPixels(0, 0, width, height, format, type, image->pixels);
990
991     context.restorePixelPackState();
992
993     GLenum error = glGetError();
994     if (error != GL_NO_ERROR) {
995         do {
996             std::cerr << "warning: " << enumToString(error) << " while reading framebuffer\n";
997             error = glGetError();
998         } while(error != GL_NO_ERROR);
999         json.writeNull();
1000     } else {
1001         json.writeImage(image, formatToString(internalFormat));
1002     }
1003
1004     delete image;
1005 }
1006
1007
1008 static inline GLuint
1009 downsampledFramebuffer(Context &context,
1010                        GLuint oldFbo, GLint drawbuffer,
1011                        const ImageDesc &colorDesc,
1012                        const ImageDesc &depthDesc,
1013                        const ImageDesc &stencilDesc,
1014                        GLuint *rbs, GLint *numRbs)
1015 {
1016     GLuint fbo;
1017
1018
1019     *numRbs = 0;
1020
1021     glGenFramebuffers(1, &fbo);
1022     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1023
1024     {
1025         // color buffer
1026         glGenRenderbuffers(1, &rbs[*numRbs]);
1027         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
1028         glRenderbufferStorage(GL_RENDERBUFFER, colorDesc.internalFormat, colorDesc.width, colorDesc.height);
1029         glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer,
1030                                   GL_RENDERBUFFER, rbs[*numRbs]);
1031
1032         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
1033         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
1034         glDrawBuffer(drawbuffer);
1035         glReadBuffer(drawbuffer);
1036         glBlitFramebuffer(0, 0, colorDesc.width, colorDesc.height, 0, 0, colorDesc.width, colorDesc.height,
1037                           GL_COLOR_BUFFER_BIT, GL_NEAREST);
1038         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1039         ++*numRbs;
1040     }
1041
1042     if (stencilDesc == depthDesc &&
1043         depthDesc.valid()) {
1044         //combined depth and stencil buffer
1045         glGenRenderbuffers(1, &rbs[*numRbs]);
1046         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
1047         glRenderbufferStorage(GL_RENDERBUFFER, depthDesc.internalFormat, depthDesc.width, depthDesc.height);
1048         glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
1049                                   GL_RENDERBUFFER, rbs[*numRbs]);
1050         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
1051         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
1052         glBlitFramebuffer(0, 0, depthDesc.width, depthDesc.height, 0, 0, depthDesc.width, depthDesc.height,
1053                           GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
1054         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1055         ++*numRbs;
1056     } else {
1057         if (depthDesc.valid()) {
1058             glGenRenderbuffers(1, &rbs[*numRbs]);
1059             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
1060             glRenderbufferStorage(GL_RENDERBUFFER, depthDesc.internalFormat, depthDesc.width, depthDesc.height);
1061             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
1062                                       GL_DEPTH_ATTACHMENT,
1063                                       GL_RENDERBUFFER, rbs[*numRbs]);
1064             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
1065             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
1066             glDrawBuffer(GL_DEPTH_ATTACHMENT);
1067             glReadBuffer(GL_DEPTH_ATTACHMENT);
1068             glBlitFramebuffer(0, 0, depthDesc.width, depthDesc.height, 0, 0, depthDesc.width, depthDesc.height,
1069                               GL_DEPTH_BUFFER_BIT, GL_NEAREST);
1070             ++*numRbs;
1071         }
1072         if (stencilDesc.valid()) {
1073             glGenRenderbuffers(1, &rbs[*numRbs]);
1074             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
1075             glRenderbufferStorage(GL_RENDERBUFFER, stencilDesc.internalFormat, stencilDesc.width, stencilDesc.height);
1076             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
1077                                       GL_STENCIL_ATTACHMENT,
1078                                       GL_RENDERBUFFER, rbs[*numRbs]);
1079             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
1080             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
1081             glDrawBuffer(GL_STENCIL_ATTACHMENT);
1082             glReadBuffer(GL_STENCIL_ATTACHMENT);
1083             glBlitFramebuffer(0, 0, stencilDesc.width, stencilDesc.height, 0, 0, stencilDesc.width, stencilDesc.height,
1084                               GL_STENCIL_BUFFER_BIT, GL_NEAREST);
1085             ++*numRbs;
1086         }
1087     }
1088
1089     return fbo;
1090 }
1091
1092
1093 /**
1094  * Dump images of current draw drawable/window.
1095  */
1096 static void
1097 dumpDrawableImages(JSONWriter &json, Context &context)
1098 {
1099     GLint width, height;
1100
1101     if (!getDrawableBounds(&width, &height)) {
1102         return;
1103     }
1104
1105     GLint draw_buffer = GL_NONE;
1106     if (context.ES) {
1107         // XXX: Draw buffer is always FRONT for single buffer context, BACK for
1108         // double buffered contexts. There is no way to know which (as
1109         // GL_DOUBLEBUFFER state is also unavailable), so always assume
1110         // double-buffering.
1111         draw_buffer = GL_BACK;
1112     } else {
1113         glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
1114     }
1115
1116     if (draw_buffer != GL_NONE) {
1117         // Read from current draw buffer
1118         GLint read_buffer = GL_NONE;
1119         if (!context.ES) {
1120             glGetIntegerv(GL_READ_BUFFER, &read_buffer);
1121             glReadBuffer(draw_buffer);
1122         }
1123
1124         GLint alpha_bits = 0;
1125 #if 0
1126         // XXX: Ignore alpha until we are able to match the traced visual
1127         glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
1128 #endif
1129         GLenum format = alpha_bits ? GL_RGBA : GL_RGB;
1130         json.beginMember(enumToString(draw_buffer));
1131         dumpReadBufferImage(json, width, height, format);
1132         json.endMember();
1133
1134         // Restore original read buffer
1135         if (!context.ES) {
1136             glReadBuffer(read_buffer);
1137         }
1138     }
1139
1140     if (!context.ES) {
1141         GLint depth_bits = 0;
1142         glGetIntegerv(GL_DEPTH_BITS, &depth_bits);
1143         if (depth_bits) {
1144             json.beginMember("GL_DEPTH_COMPONENT");
1145             dumpReadBufferImage(json, width, height, GL_DEPTH_COMPONENT);
1146             json.endMember();
1147         }
1148
1149         GLint stencil_bits = 0;
1150         glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);
1151         if (stencil_bits) {
1152             json.beginMember("GL_STENCIL_INDEX");
1153             dumpReadBufferImage(json, width, height, GL_STENCIL_INDEX);
1154             json.endMember();
1155         }
1156     }
1157 }
1158
1159
1160 /**
1161  * Dump the specified framebuffer attachment.
1162  *
1163  * In the case of a color attachment, it assumes it is already bound for read.
1164  */
1165 static void
1166 dumpFramebufferAttachment(JSONWriter &json, Context &context, GLenum target, GLenum attachment, GLenum format)
1167 {
1168     ImageDesc desc;
1169     if (!getFramebufferAttachmentDesc(context, target, attachment, desc)) {
1170         return;
1171     }
1172
1173     assert(desc.samples == 0);
1174
1175     json.beginMember(enumToString(attachment));
1176     dumpReadBufferImage(json, desc.width, desc.height, format, desc.internalFormat);
1177     json.endMember();
1178 }
1179
1180
1181 static void
1182 dumpFramebufferAttachments(JSONWriter &json, Context &context, GLenum target)
1183 {
1184     GLint read_framebuffer = 0;
1185     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
1186
1187     GLint read_buffer = GL_NONE;
1188     glGetIntegerv(GL_READ_BUFFER, &read_buffer);
1189
1190     GLint max_draw_buffers = 1;
1191     glGetIntegerv(GL_MAX_DRAW_BUFFERS, &max_draw_buffers);
1192     GLint max_color_attachments = 0;
1193     glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);
1194
1195     for (GLint i = 0; i < max_draw_buffers; ++i) {
1196         GLint draw_buffer = GL_NONE;
1197         glGetIntegerv(GL_DRAW_BUFFER0 + i, &draw_buffer);
1198         if (draw_buffer != GL_NONE) {
1199             glReadBuffer(draw_buffer);
1200             GLint attachment;
1201             if (draw_buffer >= GL_COLOR_ATTACHMENT0 && draw_buffer < GL_COLOR_ATTACHMENT0 + max_color_attachments) {
1202                 attachment = draw_buffer;
1203             } else {
1204                 std::cerr << "warning: unexpected GL_DRAW_BUFFER" << i << " = " << draw_buffer << "\n";
1205                 attachment = GL_COLOR_ATTACHMENT0;
1206             }
1207             GLint alpha_size = 0;
1208             glGetFramebufferAttachmentParameteriv(target, attachment,
1209                                                   GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE,
1210                                                   &alpha_size);
1211             GLenum format = alpha_size ? GL_RGBA : GL_RGB;
1212             dumpFramebufferAttachment(json, context, target, attachment, format);
1213         }
1214     }
1215
1216     glReadBuffer(read_buffer);
1217
1218     if (!context.ES) {
1219         dumpFramebufferAttachment(json, context, target, GL_DEPTH_ATTACHMENT, GL_DEPTH_COMPONENT);
1220         dumpFramebufferAttachment(json, context, target, GL_STENCIL_ATTACHMENT, GL_STENCIL_INDEX);
1221     }
1222
1223     glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
1224 }
1225
1226
1227 void
1228 dumpFramebuffer(JSONWriter &json, Context &context)
1229 {
1230     json.beginMember("framebuffer");
1231     json.beginObject();
1232
1233     GLint boundDrawFbo = 0, boundReadFbo = 0;
1234     glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo);
1235     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo);
1236     if (!boundDrawFbo) {
1237         dumpDrawableImages(json, context);
1238     } else if (context.ES) {
1239         dumpFramebufferAttachments(json, context, GL_FRAMEBUFFER);
1240     } else {
1241         GLint draw_buffer0 = GL_NONE;
1242         glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer0);
1243         bool multisample = false;
1244
1245         GLint boundRb = 0;
1246         glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb);
1247
1248         ImageDesc colorDesc;
1249         if (getFramebufferAttachmentDesc(context, GL_DRAW_FRAMEBUFFER, draw_buffer0, colorDesc)) {
1250             if (colorDesc.samples) {
1251                 multisample = true;
1252             }
1253         }
1254
1255         ImageDesc depthDesc;
1256         if (getFramebufferAttachmentDesc(context, GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthDesc)) {
1257             if (depthDesc.samples) {
1258                 multisample = true;
1259             }
1260         }
1261
1262         ImageDesc stencilDesc;
1263         if (getFramebufferAttachmentDesc(context, GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, stencilDesc)) {
1264             if (stencilDesc.samples) {
1265                 multisample = true;
1266             }
1267         }
1268
1269         GLuint rbs[3];
1270         GLint numRbs = 0;
1271         GLuint fboCopy = 0;
1272
1273         if (multisample) {
1274             // glReadPixels doesnt support multisampled buffers so we need
1275             // to blit the fbo to a temporary one
1276             fboCopy = downsampledFramebuffer(context,
1277                                              boundDrawFbo, draw_buffer0,
1278                                              colorDesc, depthDesc, stencilDesc,
1279                                              rbs, &numRbs);
1280         } else {
1281             glBindFramebuffer(GL_READ_FRAMEBUFFER, boundDrawFbo);
1282         }
1283
1284         dumpFramebufferAttachments(json, context, GL_READ_FRAMEBUFFER);
1285
1286         if (multisample) {
1287             glBindRenderbuffer(GL_RENDERBUFFER, boundRb);
1288             glDeleteRenderbuffers(numRbs, rbs);
1289             glDeleteFramebuffers(1, &fboCopy);
1290         }
1291
1292         glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo);
1293         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo);
1294     }
1295
1296     json.endObject();
1297     json.endMember(); // framebuffer
1298 }
1299
1300
1301 } /* namespace glstate */