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