]> git.cworth.org Git - apitrace/blob - glstate_images.cpp
Simplify image size determination.
[apitrace] / 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
32 #include "image.hpp"
33 #include "json.hpp"
34 #include "glproc.hpp"
35 #include "glsize.hpp"
36 #include "glstate.hpp"
37 #include "glstate_internal.hpp"
38
39
40 #ifdef __APPLE__
41
42 #include <Carbon/Carbon.h>
43
44 #ifdef __cplusplus
45 extern "C" {
46 #endif
47
48 OSStatus CGSGetSurfaceBounds(CGSConnectionID, CGWindowID, CGSSurfaceID, CGRect *);
49
50 #ifdef __cplusplus
51 }
52 #endif
53
54 #endif /* __APPLE__ */
55
56
57 /* Change thi to one to force interpreting depth buffers as RGBA, which enables
58  * visualizing full dynamic range, until we can transmit HDR images to the GUI */
59 #define DEPTH_AS_RGBA 0
60
61
62 namespace glstate {
63
64
65 struct ImageDesc
66 {
67     GLint width;
68     GLint height;
69     GLint depth;
70     GLint internalFormat;
71
72     inline
73     ImageDesc() :
74         width(0),
75         height(0),
76         depth(0),
77         internalFormat(GL_NONE)
78     {}
79
80     inline bool
81     valid(void) const {
82         return width > 0 && height > 0 && depth > 0;
83     }
84 };
85
86
87 static inline bool
88 getActiveTextureLevelDesc(Context &context, GLenum target, GLint level, ImageDesc &desc)
89 {
90     if (context.ES) {
91         // XXX: OpenGL ES does not support glGetTexLevelParameteriv
92         return false;
93     }
94
95     glGetTexLevelParameteriv(target, level, GL_TEXTURE_INTERNAL_FORMAT, &desc.internalFormat);
96
97     desc.width = 0;
98     glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &desc.width);
99
100     if (target == GL_TEXTURE_1D) {
101         desc.height = 1;
102         desc.depth = 1;
103     } else {
104         desc.height = 0;
105         glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &desc.height);
106         if (target != GL_TEXTURE_3D) {
107             desc.depth = 1;
108         } else {
109             desc.depth = 0;
110             glGetTexLevelParameteriv(target, level, GL_TEXTURE_DEPTH, &desc.depth);
111         }
112     }
113
114     return desc.valid();
115 }
116
117
118 static inline void
119 dumpActiveTextureLevel(JSONWriter &json, Context &context, GLenum target, GLint level)
120 {
121     ImageDesc desc;
122     if (!getActiveTextureLevelDesc(context, target, level, desc)) {
123         return;
124     }
125
126     char label[512];
127
128     GLint active_texture = GL_TEXTURE0;
129     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
130     snprintf(label, sizeof label, "%s, %s, level = %d",
131              enumToString(active_texture), enumToString(target), level);
132
133     json.beginMember(label);
134
135     json.beginObject();
136
137     // Tell the GUI this is no ordinary object, but an image
138     json.writeStringMember("__class__", "image");
139
140     json.writeNumberMember("__width__", desc.width);
141     json.writeNumberMember("__height__", desc.height);
142     json.writeNumberMember("__depth__", desc.depth);
143
144     json.writeStringMember("__format__", enumToString(desc.internalFormat));
145
146     // Hardcoded for now, but we could chose types more adequate to the
147     // texture internal format
148     json.writeStringMember("__type__", "uint8");
149     json.writeBoolMember("__normalized__", true);
150     json.writeNumberMember("__channels__", 4);
151
152     GLubyte *pixels = new GLubyte[desc.depth*desc.width*desc.height*4];
153
154     context.resetPixelPackState();
155
156     glGetTexImage(target, level, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
157
158     context.restorePixelPackState();
159
160     json.beginMember("__data__");
161     char *pngBuffer;
162     int pngBufferSize;
163     image::writePixelsToBuffer(pixels, desc.width, desc.height, 4, true, &pngBuffer, &pngBufferSize);
164     json.writeBase64(pngBuffer, pngBufferSize);
165     free(pngBuffer);
166     json.endMember(); // __data__
167
168     delete [] pixels;
169     json.endObject();
170 }
171
172
173 static inline void
174 dumpTexture(JSONWriter &json, Context &context, GLenum target, GLenum binding)
175 {
176     GLint texture_binding = 0;
177     glGetIntegerv(binding, &texture_binding);
178     if (!glIsEnabled(target) && !texture_binding) {
179         return;
180     }
181
182     GLint level = 0;
183     do {
184         ImageDesc desc;
185         if (!getActiveTextureLevelDesc(context, target, level, desc)) {
186             break;
187         }
188
189         if (target == GL_TEXTURE_CUBE_MAP) {
190             for (int face = 0; face < 6; ++face) {
191                 dumpActiveTextureLevel(json, context, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level);
192             }
193         } else {
194             dumpActiveTextureLevel(json, context, target, level);
195         }
196
197         ++level;
198     } while(true);
199 }
200
201
202 void
203 dumpTextures(JSONWriter &json, Context &context)
204 {
205     json.beginMember("textures");
206     json.beginObject();
207     GLint active_texture = GL_TEXTURE0;
208     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
209     GLint max_texture_coords = 0;
210     glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);
211     GLint max_combined_texture_image_units = 0;
212     glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);
213     GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);
214     for (GLint unit = 0; unit < max_units; ++unit) {
215         GLenum texture = GL_TEXTURE0 + unit;
216         glActiveTexture(texture);
217         dumpTexture(json, context, GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D);
218         dumpTexture(json, context, GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D);
219         dumpTexture(json, context, GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D);
220         dumpTexture(json, context, GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE);
221         dumpTexture(json, context, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP);
222     }
223     glActiveTexture(active_texture);
224     json.endObject();
225     json.endMember(); // textures
226 }
227
228
229 static bool
230 getDrawableBounds(GLint *width, GLint *height) {
231 #if defined(TRACE_EGL)
232
233     EGLContext currentContext = eglGetCurrentContext();
234     if (currentContext == EGL_NO_CONTEXT) {
235         return false;
236     }
237
238     EGLSurface currentSurface = eglGetCurrentSurface(EGL_DRAW);
239     if (currentSurface == EGL_NO_SURFACE) {
240         return false;
241     }
242
243     EGLDisplay currentDisplay = eglGetCurrentDisplay();
244     if (currentDisplay == EGL_NO_DISPLAY) {
245         return false;
246     }
247
248     if (!eglQuerySurface(currentDisplay, currentSurface, EGL_WIDTH, width) ||
249         !eglQuerySurface(currentDisplay, currentSurface, EGL_HEIGHT, height)) {
250         return false;
251     }
252
253     return true;
254
255 #elif defined(_WIN32)
256
257     HDC hDC = wglGetCurrentDC();
258     if (!hDC) {
259         return false;
260     }
261
262     HWND hWnd = WindowFromDC(hDC);
263     RECT rect;
264
265     if (!GetClientRect(hWnd, &rect)) {
266        return false;
267     }
268
269     *width  = rect.right  - rect.left;
270     *height = rect.bottom - rect.top;
271     return true;
272
273 #elif defined(__APPLE__)
274
275     CGLContextObj ctx = CGLGetCurrentContext();
276     if (ctx == NULL) {
277         return false;
278     }
279
280     CGSConnectionID cid;
281     CGSWindowID wid;
282     CGSSurfaceID sid;
283
284     if (CGLGetSurface(ctx, &cid, &wid, &sid) != kCGLNoError) {
285         return false;
286     }
287
288     CGRect rect;
289
290     if (CGSGetSurfaceBounds(cid, wid, sid, &rect) != 0) {
291         return false;
292     }
293
294     *width = rect.size.width;
295     *height = rect.size.height;
296     return true;
297
298 #elif defined(HAVE_X11)
299
300     Display *display;
301     Drawable drawable;
302     Window root;
303     int x, y;
304     unsigned int w, h, bw, depth;
305
306     display = glXGetCurrentDisplay();
307     if (!display) {
308         return false;
309     }
310
311     drawable = glXGetCurrentDrawable();
312     if (drawable == None) {
313         return false;
314     }
315
316     if (!XGetGeometry(display, drawable, &root, &x, &y, &w, &h, &bw, &depth)) {
317         return false;
318     }
319
320     *width = w;
321     *height = h;
322     return true;
323
324 #else
325
326     return false;
327
328 #endif
329 }
330
331
332 static const GLenum texture_bindings[][2] = {
333     {GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D},
334     {GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D},
335     {GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D},
336     {GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE},
337     {GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP}
338 };
339
340
341 static bool
342 bindTexture(GLint texture, GLenum &target, GLint &bound_texture)
343 {
344
345     for (unsigned i = 0; i < sizeof(texture_bindings)/sizeof(texture_bindings[0]); ++i) {
346         target  = texture_bindings[i][0];
347
348         GLenum binding = texture_bindings[i][1];
349
350         while (glGetError() != GL_NO_ERROR)
351             ;
352
353         glGetIntegerv(binding, &bound_texture);
354         glBindTexture(target, texture);
355
356         if (glGetError() == GL_NO_ERROR) {
357             return true;
358         }
359
360         glBindTexture(target, bound_texture);
361     }
362
363     target = GL_NONE;
364
365     return false;
366 }
367
368
369 static bool
370 getTextureLevelDesc(Context &context, GLint texture, GLint level, ImageDesc &desc)
371 {
372     GLenum target;
373     GLint bound_texture = 0;
374     if (!bindTexture(texture, target, bound_texture)) {
375         return false;
376     }
377
378     getActiveTextureLevelDesc(context, target, level, desc);
379
380     glBindTexture(target, bound_texture);
381
382     return desc.valid();
383 }
384
385
386 static bool
387 getRenderbufferDesc(Context &context, GLint renderbuffer, ImageDesc &desc)
388 {
389     GLint bound_renderbuffer = 0;
390     glGetIntegerv(GL_RENDERBUFFER_BINDING, &bound_renderbuffer);
391     glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
392
393     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &desc.width);
394     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &desc.height);
395     desc.depth = 1;
396     
397     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &desc.internalFormat);
398
399     glBindRenderbuffer(GL_RENDERBUFFER, bound_renderbuffer);
400     
401     return desc.valid();
402 }
403
404
405 static bool
406 getFramebufferAttachmentDesc(Context &context, GLenum target, GLenum attachment, ImageDesc &desc)
407 {
408     GLint object_type = GL_NONE;
409     glGetFramebufferAttachmentParameteriv(target, attachment,
410                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
411                                           &object_type);
412     if (object_type == GL_NONE) {
413         return false;
414     }
415
416     GLint object_name = 0;
417     glGetFramebufferAttachmentParameteriv(target, attachment,
418                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
419                                           &object_name);
420     if (object_name == 0) {
421         return false;
422     }
423
424     if (object_type == GL_RENDERBUFFER) {
425         return getRenderbufferDesc(context, object_name, desc);
426     } else if (object_type == GL_TEXTURE) {
427         GLint texture_level = 0;
428         glGetFramebufferAttachmentParameteriv(target, attachment,
429                                               GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
430                                               &texture_level);
431         return getTextureLevelDesc(context, object_name, texture_level, desc);
432     } else {
433         std::cerr << "warning: unexpected GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = " << object_type << "\n";
434         return false;
435     }
436 }
437
438
439
440 image::Image *
441 getDrawBufferImage() {
442     GLenum format = GL_RGB;
443     GLint channels = __gl_format_channels(format);
444     if (channels > 4) {
445         return NULL;
446     }
447
448     Context context;
449
450     GLenum framebuffer_binding;
451     GLenum framebuffer_target;
452     if (context.ES) {
453         framebuffer_binding = GL_FRAMEBUFFER_BINDING;
454         framebuffer_target = GL_FRAMEBUFFER;
455     } else {
456         framebuffer_binding = GL_DRAW_FRAMEBUFFER_BINDING;
457         framebuffer_target = GL_DRAW_FRAMEBUFFER;
458     }
459
460     GLint draw_framebuffer = 0;
461     glGetIntegerv(framebuffer_binding, &draw_framebuffer);
462
463     GLint draw_buffer = GL_NONE;
464     ImageDesc desc;
465     if (draw_framebuffer) {
466         if (context.ARB_draw_buffers) {
467             glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer);
468             if (draw_buffer == GL_NONE) {
469                 return NULL;
470             }
471         }
472
473         if (!getFramebufferAttachmentDesc(context, framebuffer_target, draw_buffer, desc)) {
474             return NULL;
475         }
476     } else {
477         if (!context.ES) {
478             glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
479             if (draw_buffer == GL_NONE) {
480                 return NULL;
481             }
482         }
483
484         if (!getDrawableBounds(&desc.width, &desc.height)) {
485             return NULL;
486         }
487
488         desc.depth = 1;
489     }
490
491     GLenum type = GL_UNSIGNED_BYTE;
492
493 #if DEPTH_AS_RGBA
494     if (format == GL_DEPTH_COMPONENT) {
495         type = GL_UNSIGNED_INT;
496         channels = 4;
497     }
498 #endif
499
500     image::Image *image = new image::Image(desc.width, desc.height, channels, true);
501     if (!image) {
502         return NULL;
503     }
504
505     while (glGetError() != GL_NO_ERROR) {}
506
507     GLint read_framebuffer = 0;
508     GLint read_buffer = GL_NONE;
509     if (!context.ES) {
510         glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
511         glBindFramebuffer(GL_READ_FRAMEBUFFER, draw_framebuffer);
512
513         glGetIntegerv(GL_READ_BUFFER, &read_buffer);
514         glReadBuffer(draw_buffer);
515     }
516
517     // TODO: reset imaging state too
518     context.resetPixelPackState();
519
520     glReadPixels(0, 0, desc.width, desc.height, format, type, image->pixels);
521
522     context.restorePixelPackState();
523
524     if (!context.ES) {
525         glReadBuffer(read_buffer);
526         glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
527     }
528
529     GLenum error = glGetError();
530     if (error != GL_NO_ERROR) {
531         do {
532             std::cerr << "warning: " << enumToString(error) << " while getting snapshot\n";
533             error = glGetError();
534         } while(error != GL_NO_ERROR);
535         delete image;
536         return NULL;
537     }
538      
539     return image;
540 }
541
542
543 /**
544  * Dump the image of the currently bound read buffer.
545  */
546 static inline void
547 dumpReadBufferImage(JSONWriter &json, GLint width, GLint height, GLenum format,
548                     GLint internalFormat = GL_NONE)
549 {
550     GLint channels = __gl_format_channels(format);
551
552     Context context;
553
554     json.beginObject();
555
556     // Tell the GUI this is no ordinary object, but an image
557     json.writeStringMember("__class__", "image");
558
559     json.writeNumberMember("__width__", width);
560     json.writeNumberMember("__height__", height);
561     json.writeNumberMember("__depth__", 1);
562
563     json.writeStringMember("__format__", enumToString(internalFormat));
564
565     // Hardcoded for now, but we could chose types more adequate to the
566     // texture internal format
567     json.writeStringMember("__type__", "uint8");
568     json.writeBoolMember("__normalized__", true);
569     json.writeNumberMember("__channels__", channels);
570
571     GLenum type = GL_UNSIGNED_BYTE;
572
573 #if DEPTH_AS_RGBA
574     if (format == GL_DEPTH_COMPONENT) {
575         type = GL_UNSIGNED_INT;
576         channels = 4;
577     }
578 #endif
579
580     GLubyte *pixels = new GLubyte[width*height*channels];
581
582     // TODO: reset imaging state too
583     context.resetPixelPackState();
584
585     glReadPixels(0, 0, width, height, format, type, pixels);
586
587     context.restorePixelPackState();
588
589     json.beginMember("__data__");
590     char *pngBuffer;
591     int pngBufferSize;
592     image::writePixelsToBuffer(pixels, width, height, channels, true, &pngBuffer, &pngBufferSize);
593     //std::cerr <<" Before = "<<(width * height * channels * sizeof *pixels)
594     //          <<", after = "<<pngBufferSize << ", ratio = " << double(width * height * channels * sizeof *pixels)/pngBufferSize;
595     json.writeBase64(pngBuffer, pngBufferSize);
596     free(pngBuffer);
597     json.endMember(); // __data__
598
599     delete [] pixels;
600     json.endObject();
601 }
602
603
604 static inline GLuint
605 downsampledFramebuffer(GLuint oldFbo, GLint drawbuffer,
606                        GLint colorRb, GLint depthRb, GLint stencilRb,
607                        GLuint *rbs, GLint *numRbs)
608 {
609     GLuint fbo;
610     GLint format;
611     GLint w, h;
612
613     *numRbs = 0;
614
615     glGenFramebuffers(1, &fbo);
616     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
617
618     glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
619     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
620                                  GL_RENDERBUFFER_WIDTH, &w);
621     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
622                                  GL_RENDERBUFFER_HEIGHT, &h);
623     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
624                                  GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
625
626     glGenRenderbuffers(1, &rbs[*numRbs]);
627     glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
628     glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
629     glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer,
630                               GL_RENDERBUFFER, rbs[*numRbs]);
631
632     glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
633     glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
634     glDrawBuffer(drawbuffer);
635     glReadBuffer(drawbuffer);
636     glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
637                       GL_COLOR_BUFFER_BIT, GL_NEAREST);
638     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
639     ++*numRbs;
640
641     if (stencilRb == depthRb && stencilRb) {
642         //combined depth and stencil buffer
643         glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
644         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
645                                      GL_RENDERBUFFER_WIDTH, &w);
646         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
647                                      GL_RENDERBUFFER_HEIGHT, &h);
648         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
649                                      GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
650
651         glGenRenderbuffers(1, &rbs[*numRbs]);
652         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
653         glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
654         glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
655                                   GL_RENDERBUFFER, rbs[*numRbs]);
656         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
657         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
658         glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
659                           GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
660         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
661         ++*numRbs;
662     } else {
663         if (depthRb) {
664             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
665             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
666                                          GL_RENDERBUFFER_WIDTH, &w);
667             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
668                                          GL_RENDERBUFFER_HEIGHT, &h);
669             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
670                                          GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
671
672             glGenRenderbuffers(1, &rbs[*numRbs]);
673             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
674             glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
675             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
676                                       GL_DEPTH_ATTACHMENT,
677                                       GL_RENDERBUFFER, rbs[*numRbs]);
678             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
679             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
680             glDrawBuffer(GL_DEPTH_ATTACHMENT);
681             glReadBuffer(GL_DEPTH_ATTACHMENT);
682             glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
683                               GL_DEPTH_BUFFER_BIT, GL_NEAREST);
684             ++*numRbs;
685         }
686         if (stencilRb) {
687             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
688             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
689                                          GL_RENDERBUFFER_WIDTH, &w);
690             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
691                                          GL_RENDERBUFFER_HEIGHT, &h);
692             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
693                                      GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
694
695             glGenRenderbuffers(1, &rbs[*numRbs]);
696             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
697             glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
698             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
699                                       GL_STENCIL_ATTACHMENT,
700                                       GL_RENDERBUFFER, rbs[*numRbs]);
701             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
702             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
703             glDrawBuffer(GL_STENCIL_ATTACHMENT);
704             glReadBuffer(GL_STENCIL_ATTACHMENT);
705             glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
706                               GL_STENCIL_BUFFER_BIT, GL_NEAREST);
707             ++*numRbs;
708         }
709     }
710
711     return fbo;
712 }
713
714
715 /**
716  * Dump images of current draw drawable/window.
717  */
718 static void
719 dumpDrawableImages(JSONWriter &json, Context &context)
720 {
721     GLint width, height;
722
723     if (!getDrawableBounds(&width, &height)) {
724         return;
725     }
726
727     GLint draw_buffer = GL_NONE;
728     if (context.ES) {
729         draw_buffer = GL_BACK;
730     } else {
731         glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
732         glReadBuffer(draw_buffer);
733     }
734
735     if (draw_buffer != GL_NONE) {
736         GLint read_buffer = GL_NONE;
737         if (!context.ES) {
738             glGetIntegerv(GL_READ_BUFFER, &read_buffer);
739         }
740
741         GLint alpha_bits = 0;
742 #if 0
743         // XXX: Ignore alpha until we are able to match the traced visual
744         glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
745 #endif
746         GLenum format = alpha_bits ? GL_RGBA : GL_RGB;
747         json.beginMember(enumToString(draw_buffer));
748         dumpReadBufferImage(json, width, height, format);
749         json.endMember();
750
751         if (!context.ES) {
752             glReadBuffer(read_buffer);
753         }
754     }
755
756     if (!context.ES) {
757         GLint depth_bits = 0;
758         glGetIntegerv(GL_DEPTH_BITS, &depth_bits);
759         if (depth_bits) {
760             json.beginMember("GL_DEPTH_COMPONENT");
761             dumpReadBufferImage(json, width, height, GL_DEPTH_COMPONENT);
762             json.endMember();
763         }
764
765         GLint stencil_bits = 0;
766         glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);
767         if (stencil_bits) {
768             json.beginMember("GL_STENCIL_INDEX");
769             dumpReadBufferImage(json, width, height, GL_STENCIL_INDEX);
770             json.endMember();
771         }
772     }
773 }
774
775
776 /**
777  * Dump the specified framebuffer attachment.
778  *
779  * In the case of a color attachment, it assumes it is already bound for read.
780  */
781 static void
782 dumpFramebufferAttachment(JSONWriter &json, Context &context, GLenum target, GLenum attachment, GLenum format)
783 {
784     ImageDesc desc;
785     if (!getFramebufferAttachmentDesc(context, target, attachment, desc)) {
786         return;
787     }
788
789     json.beginMember(enumToString(attachment));
790     dumpReadBufferImage(json, desc.width, desc.height, format, desc.internalFormat);
791     json.endMember();
792 }
793
794
795 static void
796 dumpFramebufferAttachments(JSONWriter &json, Context &context, GLenum target)
797 {
798     GLint read_framebuffer = 0;
799     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
800
801     GLint read_buffer = GL_NONE;
802     glGetIntegerv(GL_READ_BUFFER, &read_buffer);
803
804     GLint max_draw_buffers = 1;
805     glGetIntegerv(GL_MAX_DRAW_BUFFERS, &max_draw_buffers);
806     GLint max_color_attachments = 0;
807     glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);
808
809     for (GLint i = 0; i < max_draw_buffers; ++i) {
810         GLint draw_buffer = GL_NONE;
811         glGetIntegerv(GL_DRAW_BUFFER0 + i, &draw_buffer);
812         if (draw_buffer != GL_NONE) {
813             glReadBuffer(draw_buffer);
814             GLint attachment;
815             if (draw_buffer >= GL_COLOR_ATTACHMENT0 && draw_buffer < GL_COLOR_ATTACHMENT0 + max_color_attachments) {
816                 attachment = draw_buffer;
817             } else {
818                 std::cerr << "warning: unexpected GL_DRAW_BUFFER" << i << " = " << draw_buffer << "\n";
819                 attachment = GL_COLOR_ATTACHMENT0;
820             }
821             GLint alpha_size = 0;
822             glGetFramebufferAttachmentParameteriv(target, attachment,
823                                                   GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE,
824                                                   &alpha_size);
825             GLenum format = alpha_size ? GL_RGBA : GL_RGB;
826             dumpFramebufferAttachment(json, context, target, attachment, format);
827         }
828     }
829
830     glReadBuffer(read_buffer);
831
832     if (!context.ES) {
833         dumpFramebufferAttachment(json, context, target, GL_DEPTH_ATTACHMENT, GL_DEPTH_COMPONENT);
834         dumpFramebufferAttachment(json, context, target, GL_STENCIL_ATTACHMENT, GL_STENCIL_INDEX);
835     }
836
837     glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
838 }
839
840
841 void
842 dumpFramebuffer(JSONWriter &json, Context &context)
843 {
844     json.beginMember("framebuffer");
845     json.beginObject();
846
847     GLint boundDrawFbo = 0, boundReadFbo = 0;
848     glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo);
849     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo);
850     if (!boundDrawFbo) {
851         dumpDrawableImages(json, context);
852     } else if (context.ES) {
853         dumpFramebufferAttachments(json, context, GL_FRAMEBUFFER);
854     } else {
855         GLint colorRb = 0, stencilRb = 0, depthRb = 0;
856         GLint draw_buffer0 = GL_NONE;
857         glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer0);
858         bool multisample = false;
859
860         GLint boundRb = 0;
861         glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb);
862
863         GLint object_type;
864         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
865         if (object_type == GL_RENDERBUFFER) {
866             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &colorRb);
867             glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
868             GLint samples = 0;
869             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
870             if (samples) {
871                 multisample = true;
872             }
873         }
874
875         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
876         if (object_type == GL_RENDERBUFFER) {
877             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &depthRb);
878             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
879             GLint samples = 0;
880             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
881             if (samples) {
882                 multisample = true;
883             }
884         }
885
886         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
887         if (object_type == GL_RENDERBUFFER) {
888             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &stencilRb);
889             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
890             GLint samples = 0;
891             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
892             if (samples) {
893                 multisample = true;
894             }
895         }
896
897         glBindRenderbuffer(GL_RENDERBUFFER, boundRb);
898
899         GLuint rbs[3];
900         GLint numRbs = 0;
901         GLuint fboCopy = 0;
902
903         if (multisample) {
904             // glReadPixels doesnt support multisampled buffers so we need
905             // to blit the fbo to a temporary one
906             fboCopy = downsampledFramebuffer(boundDrawFbo, draw_buffer0,
907                                              colorRb, depthRb, stencilRb,
908                                              rbs, &numRbs);
909         }
910
911         dumpFramebufferAttachments(json, context, GL_DRAW_FRAMEBUFFER);
912
913         if (multisample) {
914             glBindRenderbuffer(GL_RENDERBUFFER_BINDING, boundRb);
915             glDeleteRenderbuffers(numRbs, rbs);
916             glDeleteFramebuffers(1, &fboCopy);
917         }
918
919         glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo);
920         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo);
921     }
922
923     json.endObject();
924     json.endMember(); // framebuffer
925 }
926
927
928 } /* namespace glstate */