]> git.cworth.org Git - apitrace/blob - glstate.py
Dump rectangle textures too.
[apitrace] / glstate.py
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 '''Generate code to dump most GL state into JSON.'''
28
29
30 from stdapi import *
31
32 from gltypes import *
33 from glparams import *
34
35
36 texture_targets = [
37     ('GL_TEXTURE_1D', 'GL_TEXTURE_BINDING_1D'),
38     ('GL_TEXTURE_2D', 'GL_TEXTURE_BINDING_2D'),
39     ('GL_TEXTURE_3D', 'GL_TEXTURE_BINDING_3D'),
40     ('GL_TEXTURE_RECTANGLE', 'GL_TEXTURE_BINDING_RECTANGLE'),
41     #(GL_TEXTURE_CUBE_MAP, 'GL_TEXTURE_BINDING_CUBE_MAP')
42 ]
43
44
45 class GetInflector:
46     '''Objects that describes how to inflect.'''
47
48     reduced_types = {
49         B: I,
50         E: I,
51         I: F,
52     }
53
54     def __init__(self, radical, inflections, suffix = ''):
55         self.radical = radical
56         self.inflections = inflections
57         self.suffix = suffix
58
59     def reduced_type(self, type):
60         if type in self.inflections:
61             return type
62         if type in self.reduced_types:
63             return self.reduced_type(self.reduced_types[type])
64         raise NotImplementedError
65
66     def inflect(self, type):
67         return self.radical + self.inflection(type) + self.suffix
68
69     def inflection(self, type):
70         type = self.reduced_type(type)
71         assert type in self.inflections
72         return self.inflections[type]
73
74     def __str__(self):
75         return self.radical + self.suffix
76
77
78 class StateGetter(Visitor):
79     '''Type visitor that is able to extract the state via one of the glGet*
80     functions.
81
82     It will declare any temporary variable
83     '''
84
85     def __init__(self, radical, inflections, suffix=''):
86         self.inflector = GetInflector(radical, inflections)
87         self.suffix = suffix
88
89     def __call__(self, *args):
90         pname = args[-1]
91
92         for function, type, count, name in parameters:
93             if type is X:
94                 continue
95             if name == pname:
96                 if count != 1:
97                     type = Array(type, str(count))
98
99                 return type, self.visit(type, args)
100
101         raise NotImplementedError
102
103     def temp_name(self, args):
104         '''Return the name of a temporary variable to hold the state.'''
105         pname = args[-1]
106
107         return pname[3:].lower()
108
109     def visit_const(self, const, args):
110         return self.visit(const.type, args)
111
112     def visit_scalar(self, type, args):
113         temp_name = self.temp_name(args)
114         elem_type = self.inflector.reduced_type(type)
115         inflection = self.inflector.inflect(type)
116         if inflection.endswith('v'):
117             print '    %s %s = 0;' % (elem_type, temp_name)
118             print '    %s(%s, &%s);' % (inflection + self.suffix, ', '.join(args), temp_name)
119         else:
120             print '    %s %s = %s(%s);' % (elem_type, temp_name, inflection + self.suffix, ', '.join(args))
121         return temp_name
122
123     def visit_string(self, string, args):
124         temp_name = self.temp_name(args)
125         inflection = self.inflector.inflect(string)
126         assert not inflection.endswith('v')
127         print '    %s %s = (%s)%s(%s);' % (string, temp_name, string, inflection + self.suffix, ', '.join(args))
128         return temp_name
129
130     def visit_alias(self, alias, args):
131         return self.visit_scalar(alias, args)
132
133     def visit_enum(self, enum, args):
134         return self.visit(GLint, args)
135
136     def visit_bitmask(self, bitmask, args):
137         return self.visit(GLint, args)
138
139     def visit_array(self, array, args):
140         temp_name = self.temp_name(args)
141         if array.length == '1':
142             return self.visit(array.type)
143         elem_type = self.inflector.reduced_type(array.type)
144         inflection = self.inflector.inflect(array.type)
145         assert inflection.endswith('v')
146         print '    %s %s[%s];' % (elem_type, temp_name, array.length)
147         print '    memset(%s, 0, %s * sizeof *%s);' % (temp_name, array.length, temp_name)
148         print '    %s(%s, %s);' % (inflection + self.suffix, ', '.join(args), temp_name)
149         return temp_name
150
151     def visit_opaque(self, pointer, args):
152         temp_name = self.temp_name(args)
153         inflection = self.inflector.inflect(pointer)
154         assert inflection.endswith('v')
155         print '    GLvoid *%s;' % temp_name
156         print '    %s(%s, &%s);' % (inflection + self.suffix, ', '.join(args), temp_name)
157         return temp_name
158
159
160 glGet = StateGetter('glGet', {
161     B: 'Booleanv',
162     I: 'Integerv',
163     F: 'Floatv',
164     D: 'Doublev',
165     S: 'String',
166     P: 'Pointerv',
167 })
168
169 glGetMaterial = StateGetter('glGetMaterial', {I: 'iv', F: 'fv'})
170 glGetLight = StateGetter('glGetLight', {I: 'iv', F: 'fv'})
171 glGetVertexAttrib = StateGetter('glGetVertexAttrib', {I: 'iv', F: 'fv', D: 'dv', P: 'Pointerv'})
172 glGetTexParameter = StateGetter('glGetTexParameter', {I: 'iv', F: 'fv'})
173 glGetTexEnv = StateGetter('glGetTexEnv', {I: 'iv', F: 'fv'})
174 glGetTexLevelParameter = StateGetter('glGetTexLevelParameter', {I: 'iv', F: 'fv'})
175 glGetProgramARB = StateGetter('glGetProgram', {I: 'iv', F: 'fv', S: 'Stringv'}, 'ARB')
176
177
178 class JsonWriter(Visitor):
179     '''Type visitor that will dump a value of the specified type through the
180     JSON writer.
181     
182     It expects a previously declared JSONWriter instance named "json".'''
183
184     def visit_literal(self, literal, instance):
185         if literal.format == 'Bool':
186             print '    json.writeBool(%s);' % instance
187         elif literal.format in ('SInt', 'Uint', 'Float', 'Double'):
188             print '    json.writeNumber(%s);' % instance
189         else:
190             raise NotImplementedError
191
192     def visit_string(self, string, instance):
193         assert string.length is None
194         print '    json.writeString((const char *)%s);' % instance
195
196     def visit_enum(self, enum, instance):
197         if enum.expr == 'GLenum':
198             print '    writeEnum(json, %s);' % instance
199         else:
200             print '    json.writeNumber(%s);' % instance
201
202     def visit_bitmask(self, bitmask, instance):
203         raise NotImplementedError
204
205     def visit_alias(self, alias, instance):
206         self.visit(alias.type, instance)
207
208     def visit_opaque(self, opaque, instance):
209         print '    json.writeNumber((size_t)%s);' % instance
210
211     __index = 0
212
213     def visit_array(self, array, instance):
214         index = '__i%u' % JsonWriter.__index
215         JsonWriter.__index += 1
216         print '    json.beginArray();'
217         print '    for (unsigned %s = 0; %s < %s; ++%s) {' % (index, index, array.length, index)
218         self.visit(array.type, '%s[%s]' % (instance, index))
219         print '    }'
220         print '    json.endArray();'
221
222
223
224 class StateDumper:
225     '''Class to generate code to dump all GL state in JSON format via
226     stdout.'''
227
228     def __init__(self):
229         pass
230
231     def dump(self):
232         print '#include <string.h>'
233         print '#include <iostream>'
234         print '#include <algorithm>'
235         print
236         print '#include "image.hpp"'
237         print '#include "json.hpp"'
238         print '#include "glimports.hpp"'
239         print '#include "glproc.hpp"'
240         print '#include "glsize.hpp"'
241         print '#include "glretrace.hpp"'
242         print
243
244         print 'static const char *'
245         print '_enum_string(GLenum pname)'
246         print '{'
247         print '    switch(pname) {'
248         for name in GLenum.values:
249             print '    case %s:' % name
250             print '        return "%s";' % name
251         print '    default:'
252         print '        return NULL;'
253         print '    }'
254         print '}'
255         print
256
257         print 'static const char *'
258         print 'enum_string(GLenum pname)'
259         print '{'
260         print '    const char *s = _enum_string(pname);'
261         print '    if (s) {'
262         print '        return s;'
263         print '    } else {'
264         print '        static char buf[16];'
265         print '        snprintf(buf, sizeof buf, "0x%04x", pname);'
266         print '        return buf;'
267         print '    }'
268         print '}'
269         print
270
271         print 'static inline void'
272         print 'writeEnum(JSONWriter &json, GLenum pname)'
273         print '{'
274         print '    const char *s = _enum_string(pname);'
275         print '    if (s) {'
276         print '        json.writeString(s);'
277         print '    } else {'
278         print '        json.writeNumber(pname);'
279         print '    }'
280         print '}'
281         print
282
283         # shaders
284         print '''
285 static void
286 writeShader(JSONWriter &json, GLuint shader)
287 {
288     if (!shader) {
289         return;
290     }
291
292     GLint shader_type = 0;
293     glGetShaderiv(shader, GL_SHADER_TYPE, &shader_type);
294     if (!shader_type) {
295         return;
296     }
297
298     GLint source_length = 0;
299     glGetShaderiv(shader, GL_SHADER_SOURCE_LENGTH, &source_length);
300     if (!source_length) {
301         return;
302     }
303
304     GLchar *source = new GLchar[source_length];
305     GLsizei length = 0;
306     source[0] = 0;
307     glGetShaderSource(shader, source_length, &length, source);
308
309     json.beginMember(enum_string(shader_type));
310     json.writeString(source);
311     json.endMember();
312
313     delete [] source;
314 }
315
316 static inline void
317 writeCurrentProgram(JSONWriter &json)
318 {
319     GLint program = 0;
320     glGetIntegerv(GL_CURRENT_PROGRAM, &program);
321     if (!program) {
322         return;
323     }
324
325     GLint attached_shaders = 0;
326     glGetProgramiv(program, GL_ATTACHED_SHADERS, &attached_shaders);
327     if (!attached_shaders) {
328         return;
329     }
330
331     GLuint *shaders = new GLuint[attached_shaders];
332     GLsizei count = 0;
333     glGetAttachedShaders(program, attached_shaders, &count, shaders);
334     for (GLsizei i = 0; i < count; ++ i) {
335        writeShader(json, shaders[i]);
336     }
337     delete [] shaders;
338 }
339
340 static inline void
341 writeArbProgram(JSONWriter &json, GLenum target)
342 {
343     if (!glIsEnabled(target)) {
344         return;
345     }
346
347     GLint program_length = 0;
348     glGetProgramivARB(target, GL_PROGRAM_LENGTH_ARB, &program_length);
349     if (!program_length) {
350         return;
351     }
352
353     GLchar *source = new GLchar[program_length + 1];
354     source[0] = 0;
355     glGetProgramStringARB(target, GL_PROGRAM_STRING_ARB, source);
356     source[program_length] = 0;
357
358     json.beginMember(enum_string(target));
359     json.writeString(source);
360     json.endMember();
361
362     delete [] source;
363 }
364 '''
365
366         # texture image
367         print '''
368 static inline void
369 writeTextureImage(JSONWriter &json, GLenum target, GLint level)
370 {
371     GLint width, height = 1, depth = 1;
372
373     width = 0;
374     glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width);
375
376     if (target != GL_TEXTURE_1D) {
377         height = 0;
378         glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height);
379         if (target == GL_TEXTURE_3D) {
380             depth = 0;
381             glGetTexLevelParameteriv(target, level, GL_TEXTURE_DEPTH, &depth);
382         }
383     }
384
385     if (width <= 0 || height <= 0 || depth <= 0) {
386         json.writeNull();
387     } else {
388         json.beginObject();
389
390         // Tell the GUI this is no ordinary object, but an image
391         json.writeStringMember("__class__", "image");
392
393         json.writeNumberMember("__width__", width);
394         json.writeNumberMember("__height__", height);
395         json.writeNumberMember("__depth__", depth);
396
397         // Hardcoded for now, but we could chose types more adequate to the
398         // texture internal format
399         json.writeStringMember("__type__", "uint8");
400         json.writeBoolMember("__normalized__", true);
401         json.writeNumberMember("__channels__", 4);
402         
403         GLubyte *pixels = new GLubyte[depth*width*height*4];
404         
405         glGetTexImage(target, level, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
406
407         json.beginMember("__data__");
408         char *pngBuffer;
409         int pngBufferSize;
410         Image::writePixelsToBuffer(pixels, width, height, 4, false, &pngBuffer, &pngBufferSize);
411         json.writeBase64(pngBuffer, pngBufferSize);
412         free(pngBuffer);
413         json.endMember(); // __data__
414
415         delete [] pixels;
416         json.endObject();
417     }
418 }
419
420 static inline void
421 writeDrawBufferImage(JSONWriter &json, GLenum format)
422 {
423     GLint width  = glretrace::window_width;
424     GLint height = glretrace::window_height;
425
426     GLint channels = __gl_format_channels(format);
427
428     if (!width || !height) {
429         json.writeNull();
430     } else {
431         json.beginObject();
432
433         // Tell the GUI this is no ordinary object, but an image
434         json.writeStringMember("__class__", "image");
435
436         json.writeNumberMember("__width__", width);
437         json.writeNumberMember("__height__", height);
438         json.writeNumberMember("__depth__", 1);
439
440         // Hardcoded for now, but we could chose types more adequate to the
441         // texture internal format
442         json.writeStringMember("__type__", "uint8");
443         json.writeBoolMember("__normalized__", true);
444         json.writeNumberMember("__channels__", channels);
445
446         GLubyte *pixels = new GLubyte[width*height*channels];
447         
448         GLint drawbuffer = glretrace::double_buffer ? GL_BACK : GL_FRONT;
449         GLint readbuffer = glretrace::double_buffer ? GL_BACK : GL_FRONT;
450         glGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);
451         glGetIntegerv(GL_READ_BUFFER, &readbuffer);
452         glReadBuffer(drawbuffer);
453
454         glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
455         glPixelStorei(GL_PACK_ALIGNMENT, 1);
456
457         glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, pixels);
458
459         glPopClientAttrib();
460         glReadBuffer(readbuffer);
461
462         json.beginMember("__data__");
463         char *pngBuffer;
464         int pngBufferSize;
465         Image::writePixelsToBuffer(pixels, width, height, channels, false, &pngBuffer, &pngBufferSize);
466         //std::cerr <<" Before = "<<(width * height * channels * sizeof *pixels)
467         //          <<", after = "<<pngBufferSize << ", ratio = " << double(width * height * channels * sizeof *pixels)/pngBufferSize;
468         json.writeBase64(pngBuffer, pngBufferSize);
469         free(pngBuffer);
470         json.endMember(); // __data__
471
472         delete [] pixels;
473         json.endObject();
474     }
475 }
476
477 static inline GLuint
478 downsampledFramebuffer(GLuint oldFbo, GLint drawbuffer,
479                        GLint colorRb, GLint depthRb, GLint stencilRb,
480                        GLuint *rbs, GLint *numRbs)
481 {
482     GLuint fbo;
483     GLint format;
484     GLint w, h;
485
486     *numRbs = 0;
487
488     glGenFramebuffers(1, &fbo);
489     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
490
491     glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
492     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
493                                  GL_RENDERBUFFER_WIDTH, &w);
494     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
495                                  GL_RENDERBUFFER_HEIGHT, &h);
496     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
497                                  GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
498
499     glGenRenderbuffers(1, &rbs[*numRbs]);
500     glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
501     glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
502     glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer,
503                               GL_RENDERBUFFER, rbs[*numRbs]);
504
505     glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
506     glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
507     glDrawBuffer(drawbuffer);
508     glReadBuffer(drawbuffer);
509     glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
510                       GL_COLOR_BUFFER_BIT, GL_NEAREST);
511     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
512     ++*numRbs;
513
514     if (stencilRb == depthRb && stencilRb) {
515         //combined depth and stencil buffer
516         glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
517         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
518                                      GL_RENDERBUFFER_WIDTH, &w);
519         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
520                                      GL_RENDERBUFFER_HEIGHT, &h);
521         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
522                                      GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
523
524         glGenRenderbuffers(1, &rbs[*numRbs]);
525         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
526         glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
527         glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
528                                   GL_RENDERBUFFER, rbs[*numRbs]);
529         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
530         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
531         glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
532                           GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
533         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
534         ++*numRbs;
535     } else {
536         if (depthRb) {
537             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
538             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
539                                          GL_RENDERBUFFER_WIDTH, &w);
540             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
541                                          GL_RENDERBUFFER_HEIGHT, &h);
542             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
543                                          GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
544
545             glGenRenderbuffers(1, &rbs[*numRbs]);
546             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
547             glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
548             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
549                                       GL_DEPTH_ATTACHMENT,
550                                       GL_RENDERBUFFER, rbs[*numRbs]);
551             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
552             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
553             glDrawBuffer(GL_DEPTH_ATTACHMENT);
554             glReadBuffer(GL_DEPTH_ATTACHMENT);
555             glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
556                               GL_DEPTH_BUFFER_BIT, GL_NEAREST);
557             ++*numRbs;
558         }
559         if (stencilRb) {
560             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
561             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
562                                          GL_RENDERBUFFER_WIDTH, &w);
563             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
564                                          GL_RENDERBUFFER_HEIGHT, &h);
565             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
566                                      GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
567
568             glGenRenderbuffers(1, &rbs[*numRbs]);
569             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
570             glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
571             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
572                                       GL_STENCIL_ATTACHMENT,
573                                       GL_RENDERBUFFER, rbs[*numRbs]);
574             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
575             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
576             glDrawBuffer(GL_STENCIL_ATTACHMENT);
577             glReadBuffer(GL_STENCIL_ATTACHMENT);
578             glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
579                               GL_STENCIL_BUFFER_BIT, GL_NEAREST);
580             ++*numRbs;
581         }
582     }
583
584     return fbo;
585 }
586
587 static void
588 writeDrawBuffers(JSONWriter &json, GLboolean writeDepth, GLboolean writeStencil)
589 {
590     json.beginMember("GL_RGBA");
591     writeDrawBufferImage(json, GL_RGBA);
592     json.endMember();
593
594     if (writeDepth) {
595         json.beginMember("GL_DEPTH_COMPONENT");
596         writeDrawBufferImage(json, GL_DEPTH_COMPONENT);
597         json.endMember();
598     }
599
600     if (writeStencil) {
601         json.beginMember("GL_STENCIL_INDEX");
602         writeDrawBufferImage(json, GL_STENCIL_INDEX);
603         json.endMember();
604     }
605 }
606
607 '''
608
609         # textures
610         print 'static inline void'
611         print 'writeTexture(JSONWriter &json, GLenum target, GLenum binding)'
612         print '{'
613         print '    GLint texture = 0;'
614         print '    glGetIntegerv(binding, &texture);'
615         print '    if (!glIsEnabled(target) && !texture) {'
616         print '        json.writeNull();'
617         print '        return;'
618         print '    }'
619         print
620         print '    json.beginObject();'
621         print '    json.beginMember("levels");'
622         print '    json.beginArray();'
623         print '    GLint level = 0;'
624         print '    do {'
625         print '        GLint width = 0, height = 0;'
626         print '        glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width);'
627         print '        glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height);'
628         print '        if (!width || !height) {'
629         print '            break;'
630         print '        }'
631         print '        json.beginObject();'
632         print
633         # FIXME: This is not the original texture name in the trace -- we need
634         # to do a reverse lookup of the texture mappings to find the original one
635         print '        json.beginMember("binding");'
636         print '        json.writeNumber(texture);'
637         print '        json.endMember();'
638         print
639         print '        json.beginMember("image");'
640         print '        writeTextureImage(json, target, level);'
641         print '        json.endMember();'
642         print
643         print '        json.endObject();'
644         print '        ++level;'
645         print '    } while(true);'
646         print '    json.endArray();'
647         print '    json.endMember(); // levels'
648         print
649         print '    json.endObject();'
650         print '}'
651         print
652
653         print 'void glretrace::state_dump(std::ostream &os)'
654         print '{'
655         print '    JSONWriter json(os);'
656         self.dump_parameters()
657         self.dump_current_program()
658         self.dump_textures()
659         self.dump_framebuffer()
660         print '}'
661         print
662
663     def dump_parameters(self):
664         print '    json.beginMember("parameters");'
665         print '    json.beginObject();'
666         
667         self.dump_atoms(glGet)
668         
669         self.dump_material_params()
670         self.dump_light_params()
671         self.dump_vertex_attribs()
672         self.dump_texenv_params()
673         self.dump_program_params()
674         self.dump_texture_parameters()
675
676         print '    json.endObject();'
677         print '    json.endMember(); // parameters'
678         print
679
680     def dump_material_params(self):
681         for face in ['GL_FRONT', 'GL_BACK']:
682             print '    json.beginMember("%s");' % face
683             print '    json.beginObject();'
684             self.dump_atoms(glGetMaterial, face)
685             print '    json.endObject();'
686         print
687
688     def dump_light_params(self):
689         print '    GLint max_lights = 0;'
690         print '    __glGetIntegerv(GL_MAX_LIGHTS, &max_lights);'
691         print '    for (GLint index = 0; index < max_lights; ++index) {'
692         print '        GLenum light = GL_LIGHT0 + index;'
693         print '        if (glIsEnabled(light)) {'
694         print '            char name[32];'
695         print '            snprintf(name, sizeof name, "GL_LIGHT%i", index);'
696         print '            json.beginMember(name);'
697         print '            json.beginObject();'
698         self.dump_atoms(glGetLight, '    GL_LIGHT0 + index')
699         print '            json.endObject();'
700         print '            json.endMember(); // GL_LIGHTi'
701         print '        }'
702         print '    }'
703         print
704
705     def dump_texenv_params(self):
706         for target in ['GL_TEXTURE_ENV', 'GL_TEXTURE_FILTER_CONTROL', 'GL_POINT_SPRITE']:
707             if target != 'GL_TEXTURE_FILTER_CONTROL':
708                 print '    if (glIsEnabled(%s)) {' % target
709             else:
710                 print '    {'
711             print '        json.beginMember("%s");' % target
712             print '        json.beginObject();'
713             self.dump_atoms(glGetTexEnv, target)
714             print '        json.endObject();'
715             print '    }'
716
717     def dump_vertex_attribs(self):
718         print '    GLint max_vertex_attribs = 0;'
719         print '    __glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attribs);'
720         print '    for (GLint index = 0; index < max_vertex_attribs; ++index) {'
721         print '        char name[32];'
722         print '        snprintf(name, sizeof name, "GL_VERTEX_ATTRIB_ARRAY%i", index);'
723         print '        json.beginMember(name);'
724         print '        json.beginObject();'
725         self.dump_atoms(glGetVertexAttrib, 'index')
726         print '        json.endObject();'
727         print '        json.endMember(); // GL_VERTEX_ATTRIB_ARRAYi'
728         print '    }'
729         print
730
731     program_targets = [
732         'GL_FRAGMENT_PROGRAM_ARB',
733         'GL_VERTEX_PROGRAM_ARB',
734     ]
735
736     def dump_program_params(self):
737         for target in self.program_targets:
738             print '    if (glIsEnabled(%s)) {' % target
739             print '        json.beginMember("%s");' % target
740             print '        json.beginObject();'
741             self.dump_atoms(glGetProgramARB, target)
742             print '        json.endObject();'
743             print '    }'
744
745     def dump_texture_parameters(self):
746         print '    {'
747         print '        GLint active_texture = GL_TEXTURE0;'
748         print '        glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);'
749         print '        GLint max_texture_coords = 0;'
750         print '        glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);'
751         print '        GLint max_combined_texture_image_units = 0;'
752         print '        glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);'
753         print '        GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);'
754         print '        for (GLint unit = 0; unit < max_units; ++unit) {'
755         print '            char name[32];'
756         print '            snprintf(name, sizeof name, "GL_TEXTURE%i", unit);'
757         print '            json.beginMember(name);'
758         print '            glActiveTexture(GL_TEXTURE0 + unit);'
759         print '            json.beginObject();'
760         print '            GLint texture;'
761         print
762         for target, binding in texture_targets:
763             print '            // %s' % target
764             print '            texture = 0;'
765             print '            glGetIntegerv(%s, &texture);' % binding
766             print '            if (glIsEnabled(%s) || texture) {' % target
767             print '                json.beginMember("%s");' % target
768             print '                json.beginObject();'
769             self.dump_atoms(glGetTexParameter, target)
770             # We only dump the first level parameters
771             self.dump_atoms(glGetTexLevelParameter, target, "0")
772             print '                json.endObject();'
773             print '                json.endMember(); // %s' % target
774             print '            }'
775             print
776         print '            json.endObject();'
777         print '            json.endMember(); // GL_TEXTUREi'
778         print '        }'
779         print '        glActiveTexture(active_texture);'
780         print '    }'
781         print
782
783     def dump_current_program(self):
784         print '    json.beginMember("shaders");'
785         print '    json.beginObject();'
786         print '    writeCurrentProgram(json);'
787         for target in self.program_targets:
788             print '    writeArbProgram(json, %s);' % target
789         print '    json.endObject();'
790         print '    json.endMember(); //shaders'
791         print
792
793     def dump_textures(self):
794         print '    {'
795         print '        json.beginMember("textures");'
796         print '        json.beginArray();'
797         print '        GLint active_texture = GL_TEXTURE0;'
798         print '        glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);'
799         print '        GLint max_texture_coords = 0;'
800         print '        glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);'
801         print '        GLint max_combined_texture_image_units = 0;'
802         print '        glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);'
803         print '        GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);'
804         print '        for (GLint unit = 0; unit < max_units; ++unit) {'
805         print '            glActiveTexture(GL_TEXTURE0 + unit);'
806         print '            json.beginObject();'
807         for target, binding in texture_targets:
808             print '            json.beginMember("%s");' % target
809             print '            writeTexture(json, %s, %s);' % (target, binding)
810             print '            json.endMember();'
811         print '            json.endObject();'
812         print '        }'
813         print '        glActiveTexture(active_texture);'
814         print '        json.endArray();'
815         print '        json.endMember(); // texture'
816         print '    }'
817         print
818
819     def dump_framebuffer(self):
820         print '    json.beginMember("framebuffer");'
821         print '    json.beginObject();'
822         # TODO: Handle real FBOs
823         print
824         print '    GLint boundDrawFbo = 0, boundReadFbo = 0;'
825         print '    glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo);'
826         print '    glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo);'
827         print '    if (!boundDrawFbo) {'
828         print '        GLint depth_bits = 0;'
829         print '        glGetIntegerv(GL_DEPTH_BITS, &depth_bits);'
830         print '        GLint stencil_bits = 0;'
831         print '        glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);'
832         print '        writeDrawBuffers(json, depth_bits, stencil_bits);'
833         print '    } else {'
834         print '        GLint colorRb, stencilRb, depthRb;'
835         print '        GLint boundRb;'
836         print '        glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb);'
837         print '        GLint drawbuffer = glretrace::double_buffer ? GL_BACK : GL_FRONT;'
838         print '        glGetIntegerv(GL_DRAW_BUFFER, &drawbuffer);'
839         print
840         print '        glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,'
841         print '                                              drawbuffer,'
842         print '                                              GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,'
843         print '                                              &colorRb);'
844         print '        glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,'
845         print '                                              GL_DEPTH_ATTACHMENT,'
846         print '                                              GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,'
847         print '                                              &depthRb);'
848         print '        glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER,'
849         print '                                              GL_STENCIL_ATTACHMENT,'
850         print '                                              GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,'
851         print '                                              &stencilRb);'
852         print
853         print '        GLint colorSamples, depthSamples, stencilSamples;'
854         print '        GLuint rbs[3];'
855         print '        GLint numRbs = 0;'
856         print '        GLuint fboCopy = 0;'
857         print '        glBindRenderbuffer(GL_RENDERBUFFER, colorRb);'
858         print '        glGetRenderbufferParameteriv(GL_RENDERBUFFER,'
859         print '                                     GL_RENDERBUFFER_SAMPLES, &colorSamples);'
860         print '        glBindRenderbuffer(GL_RENDERBUFFER, depthRb);'
861         print '        glGetRenderbufferParameteriv(GL_RENDERBUFFER,'
862         print '                                     GL_RENDERBUFFER_SAMPLES, &depthSamples);'
863         print '        glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);'
864         print '        glGetRenderbufferParameteriv(GL_RENDERBUFFER,'
865         print '                                     GL_RENDERBUFFER_SAMPLES, &stencilSamples);'
866         print '        glBindRenderbuffer(GL_RENDERBUFFER, boundRb);'
867         print
868         print '        if (colorSamples || depthSamples || stencilSamples) {'
869         print '            //glReadPixels doesnt support multisampled buffers so we need'
870         print '            // to blit the fbo to a temporary one'
871         print '            fboCopy = downsampledFramebuffer(boundDrawFbo, drawbuffer,'
872         print '                                             colorRb, depthRb, stencilRb,'
873         print '                                             rbs, &numRbs);'
874         print '        }'
875         print '        glDrawBuffer(drawbuffer);'
876         print '        glReadBuffer(drawbuffer);'
877         print
878         print '        writeDrawBuffers(json, depthRb, stencilRb);'
879         print
880         print '        if (fboCopy) {'
881         print '            glBindFramebuffer(GL_FRAMEBUFFER, boundDrawFbo);'
882         print '            glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo);'
883         print '            glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo);'
884         print '            glBindRenderbuffer(GL_RENDERBUFFER_BINDING, boundRb);'
885         print '            glDeleteRenderbuffers(numRbs, rbs);'
886         print '            glDeleteFramebuffers(1, &fboCopy);'
887         print '        }'
888         print '    }'
889         print
890         print '    json.endObject();'
891         print '    json.endMember(); // framebuffer'
892         pass
893
894     def dump_atoms(self, getter, *args):
895         for function, type, count, name in parameters:
896             inflection = getter.inflector.radical + getter.suffix
897             if inflection not in function.split(','):
898                 continue
899             if type is X:
900                 continue
901             print '        // %s' % name
902             print '        {'
903             type, value = getter(*(args + (name,)))
904             print '            if (glGetError() != GL_NO_ERROR) {'
905             #print '                std::cerr << "warning: %s(%s) failed\\n";' % (inflection, name)
906             print '            } else {'
907             print '                json.beginMember("%s");' % name
908             JsonWriter().visit(type, value)
909             print '                json.endMember();'
910             print '            }'
911             print '        }'
912             print
913
914
915 if __name__ == '__main__':
916     StateDumper().dump()