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