]> git.cworth.org Git - apitrace/blob - retrace/glstate_params.py
c5cddb9cd725fbfc95a7d1b752664afc6cebcb25
[apitrace] / retrace / glstate_params.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 import retrace # to adjust sys.path
31
32 from specs.stdapi import *
33
34 from specs.gltypes import *
35 from specs.glparams import *
36
37
38 texture_targets = [
39     ('GL_TEXTURE_1D', 'GL_TEXTURE_BINDING_1D'),
40     ('GL_TEXTURE_1D_ARRAY', 'GL_TEXTURE_BINDING_1D_ARRAY'),
41     ('GL_TEXTURE_2D', 'GL_TEXTURE_BINDING_2D'),
42     ('GL_TEXTURE_2D_ARRAY', 'GL_TEXTURE_BINDING_2D_ARRAY'),
43     ('GL_TEXTURE_2D_MULTISAMPLE', 'GL_TEXTURE_BINDING_2D_MULTISAMPLE'),
44     ('GL_TEXTURE_2D_MULTISAMPLE_ARRAY', 'GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY'),
45     ('GL_TEXTURE_3D', 'GL_TEXTURE_BINDING_3D'),
46     ('GL_TEXTURE_RECTANGLE', 'GL_TEXTURE_BINDING_RECTANGLE'),
47     ('GL_TEXTURE_CUBE_MAP', 'GL_TEXTURE_BINDING_CUBE_MAP'),
48     ('GL_TEXTURE_CUBE_MAP_ARRAY', 'GL_TEXTURE_BINDING_CUBE_MAP_ARRAY'),
49 ]
50
51 framebuffer_targets = [
52     ('GL_DRAW_FRAMEBUFFER', 'GL_DRAW_FRAMEBUFFER_BINDING'),
53     ('GL_READ_FRAMEBUFFER', 'GL_READ_FRAMEBUFFER_BINDING'),
54 ]
55
56 class GetInflector:
57     '''Objects that describes how to inflect.'''
58
59     reduced_types = {
60         B: I,
61         E: I,
62         I: F,
63     }
64
65     def __init__(self, radical, inflections, suffix = ''):
66         self.radical = radical
67         self.inflections = inflections
68         self.suffix = suffix
69
70     def reduced_type(self, type):
71         if type in self.inflections:
72             return type
73         if type in self.reduced_types:
74             return self.reduced_type(self.reduced_types[type])
75         raise NotImplementedError
76
77     def inflect(self, type):
78         return self.radical + self.inflection(type) + self.suffix
79
80     def inflection(self, type):
81         type = self.reduced_type(type)
82         assert type in self.inflections
83         return self.inflections[type]
84
85     def __str__(self):
86         return self.radical + self.suffix
87
88
89 class StateGetter(Visitor):
90     '''Type visitor that is able to extract the state via one of the glGet*
91     functions.
92
93     It will declare any temporary variable
94     '''
95
96     def __init__(self, radical, inflections, suffix=''):
97         self.inflector = GetInflector(radical, inflections)
98         self.suffix = suffix
99
100     def iter(self):
101         for function, type, count, name in parameters:
102             inflection = self.inflector.radical + self.suffix
103             if inflection not in function.split(','):
104                 continue
105             if type is X:
106                 continue
107             yield type, count, name
108
109     def __call__(self, *args):
110         pname = args[-1]
111
112         for type, count, name in self.iter():
113             if name == pname:
114                 if count != 1:
115                     type = Array(type, str(count))
116
117                 return type, self.visit(type, args)
118
119         raise NotImplementedError
120
121     def temp_name(self, args):
122         '''Return the name of a temporary variable to hold the state.'''
123         pname = args[-1]
124
125         return pname[3:].lower()
126
127     def visitConst(self, const, args):
128         return self.visit(const.type, args)
129
130     def visitScalar(self, type, args):
131         temp_name = self.temp_name(args)
132         elem_type = self.inflector.reduced_type(type)
133         inflection = self.inflector.inflect(type)
134         if inflection.endswith('v'):
135             print '    %s %s = 0;' % (elem_type, temp_name)
136             print '    %s(%s, &%s);' % (inflection + self.suffix, ', '.join(args), temp_name)
137         else:
138             print '    %s %s = %s(%s);' % (elem_type, temp_name, inflection + self.suffix, ', '.join(args))
139         return temp_name
140
141     def visitString(self, string, args):
142         temp_name = self.temp_name(args)
143         inflection = self.inflector.inflect(string)
144         assert not inflection.endswith('v')
145         print '    %s %s = (%s)%s(%s);' % (string, temp_name, string, inflection + self.suffix, ', '.join(args))
146         return temp_name
147
148     def visitAlias(self, alias, args):
149         return self.visitScalar(alias, args)
150
151     def visitEnum(self, enum, args):
152         return self.visitScalar(enum, args)
153
154     def visitBitmask(self, bitmask, args):
155         return self.visit(GLint, args)
156
157     def visitArray(self, array, args):
158         temp_name = self.temp_name(args)
159         if array.length == '1':
160             return self.visit(array.type)
161         elem_type = self.inflector.reduced_type(array.type)
162         inflection = self.inflector.inflect(array.type)
163         assert inflection.endswith('v')
164         array_length = array.length
165         if array_length.isdigit():
166             # Static integer length
167             print '    %s %s[%s + 1];' % (elem_type, temp_name, array_length)
168         else:
169             # Put the length in a variable to avoid recomputing it every time
170             print '    size_t _%s_length = %s;' % (temp_name, array_length)
171             array_length = '_%s_length' % temp_name
172             # Allocate a dynamic sized array
173             print '    %s *%s = _allocator.alloc<%s>(%s + 1);' % (elem_type, temp_name, elem_type, array_length)
174         print '    memset(%s, 0, %s * sizeof *%s);' % (temp_name, array_length, temp_name)
175         print '    %s[%s] = (%s)0xdeadc0de;' % (temp_name, array_length, elem_type)
176         print '    if (%s) {' % array_length
177         print '        %s(%s, %s);' % (inflection + self.suffix, ', '.join(args), temp_name)
178         print '    }'
179         # Simple buffer overflow detection
180         print '    assert(%s[%s] == (%s)0xdeadc0de);' % (temp_name, array_length, elem_type)
181         return temp_name
182
183     def visitOpaque(self, pointer, args):
184         temp_name = self.temp_name(args)
185         inflection = self.inflector.inflect(pointer)
186         assert inflection.endswith('v')
187         print '    GLvoid *%s;' % temp_name
188         print '    %s(%s, &%s);' % (inflection + self.suffix, ', '.join(args), temp_name)
189         return temp_name
190
191
192 glGet = StateGetter('glGet', {
193     B: 'Booleanv',
194     I: 'Integerv',
195     F: 'Floatv',
196     D: 'Doublev',
197     S: 'String',
198     P: 'Pointerv',
199 })
200
201 glGetMaterial = StateGetter('glGetMaterial', {I: 'iv', F: 'fv'})
202 glGetLight = StateGetter('glGetLight', {I: 'iv', F: 'fv'})
203 glGetVertexAttrib = StateGetter('glGetVertexAttrib', {I: 'iv', F: 'fv', D: 'dv', P: 'Pointerv'})
204 glGetTexParameter = StateGetter('glGetTexParameter', {I: 'iv', F: 'fv'})
205 glGetTexEnv = StateGetter('glGetTexEnv', {I: 'iv', F: 'fv'})
206 glGetTexLevelParameter = StateGetter('glGetTexLevelParameter', {I: 'iv', F: 'fv'})
207 glGetShader = StateGetter('glGetShaderiv', {I: 'iv'})
208 glGetProgram = StateGetter('glGetProgram', {I: 'iv'})
209 glGetProgramARB = StateGetter('glGetProgram', {I: 'iv', F: 'fv', S: 'Stringv'}, 'ARB')
210 glGetFramebufferAttachmentParameter = StateGetter('glGetFramebufferAttachmentParameter', {I: 'iv'})
211
212
213 class JsonWriter(Visitor):
214     '''Type visitor that will dump a value of the specified type through the
215     JSON writer.
216     
217     It expects a previously declared JSONWriter instance named "json".'''
218
219     def visitLiteral(self, literal, instance):
220         if literal.kind == 'Bool':
221             print '    json.writeBool(%s);' % instance
222         elif literal.kind in ('SInt', 'Uint'):
223             print '    json.writeInt(%s);' % instance
224         elif literal.kind in ('Float', 'Double'):
225             print '    json.writeFloat(%s);' % instance
226         else:
227             raise NotImplementedError
228
229     def visitString(self, string, instance):
230         assert string.length is None
231         print '    json.writeString((const char *)%s);' % instance
232
233     def visitEnum(self, enum, instance):
234         if enum is GLboolean:
235             print '    dumpBoolean(json, %s);' % instance
236         elif enum is GLenum:
237             print '    dumpEnum(json, %s);' % instance
238         else:
239             assert False
240             print '    json.writeInt(%s);' % instance
241
242     def visitBitmask(self, bitmask, instance):
243         raise NotImplementedError
244
245     def visitAlias(self, alias, instance):
246         self.visit(alias.type, instance)
247
248     def visitOpaque(self, opaque, instance):
249         print '    json.writeInt((size_t)%s);' % instance
250
251     __index = 0
252
253     def visitArray(self, array, instance):
254         index = '_i%u' % JsonWriter.__index
255         JsonWriter.__index += 1
256         print '    json.beginArray();'
257         print '    for (unsigned %s = 0; %s < %s; ++%s) {' % (index, index, array.length, index)
258         self.visit(array.type, '%s[%s]' % (instance, index))
259         print '    }'
260         print '    json.endArray();'
261
262
263
264 class StateDumper:
265     '''Class to generate code to dump all GL state in JSON format via
266     stdout.'''
267
268     def __init__(self):
269         pass
270
271     def dump(self):
272         print '#include <assert.h>'
273         print '#include <string.h>'
274         print
275         print '#include "json.hpp"'
276         print '#include "scoped_allocator.hpp"'
277         print '#include "glproc.hpp"'
278         print '#include "glsize.hpp"'
279         print '#include "glstate.hpp"'
280         print '#include "glstate_internal.hpp"'
281         print
282         print 'namespace glstate {'
283         print
284
285         print 'static void'
286         print 'flushErrors(void) {'
287         print '    while (glGetError() != GL_NO_ERROR) {}'
288         print '}'
289         print
290
291         print 'void'
292         print 'dumpBoolean(JSONWriter &json, GLboolean value)'
293         print '{'
294         print '    switch (value) {'
295         print '    case GL_FALSE:'
296         print '        json.writeString("GL_FALSE");'
297         print '        break;'
298         print '    case GL_TRUE:'
299         print '        json.writeString("GL_TRUE");'
300         print '        break;'
301         print '    default:'
302         print '        json.writeInt(static_cast<GLint>(value));'
303         print '        break;'
304         print '    }'
305         print '}'
306         print
307
308         print 'const char *'
309         print 'enumToString(GLenum pname)'
310         print '{'
311         print '    switch (pname) {'
312         for name in GLenum.values:
313             print '    case %s:' % name
314             print '        return "%s";' % name
315         print '    default:'
316         print '        return NULL;'
317         print '    }'
318         print '}'
319         print
320
321         print 'void'
322         print 'dumpEnum(JSONWriter &json, GLenum pname)'
323         print '{'
324         print '    const char *s = enumToString(pname);'
325         print '    if (s) {'
326         print '        json.writeString(s);'
327         print '    } else {'
328         print '        json.writeInt(pname);'
329         print '    }'
330         print '}'
331         print
332
333         print 'static void'
334         print 'dumpTextureTargetParameters(JSONWriter &json, Context &context, GLenum target, GLenum binding_param)'
335         print '{'
336         print '    GLboolean enabled = GL_FALSE;'
337         print '    GLint binding = 0;'
338         print '    glGetBooleanv(target, &enabled);'
339         print '    json.beginMember(enumToString(target));'
340         print '    dumpBoolean(json, enabled);'
341         print '    json.endMember();'
342         print '    glGetIntegerv(binding_param, &binding);'
343         print '    json.writeIntMember(enumToString(binding_param), binding);'
344         print '    if (enabled || binding) {'
345         print '        json.beginMember(enumToString(target));'
346         print '        json.beginObject();'
347         self.dump_atoms(glGetTexParameter, 'target')
348         print '        if (!context.ES) {'
349         print '            GLenum levelTarget;'
350         print '            if (target == GL_TEXTURE_CUBE_MAP ||'
351         print '                target == GL_TEXTURE_CUBE_MAP_ARRAY) {'
352         print '                // Must pick a face'
353         print '                levelTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X;'
354         print '            } else {'
355         print '                levelTarget = target;'
356         print '            }'
357         self.dump_atoms(glGetTexLevelParameter, 'levelTarget', '0')
358         print '        }'
359         print '        json.endObject();'
360         print '        json.endMember(); // target'
361         print '    }'
362         print '}'
363         print
364
365         print 'static void'
366         print 'dumpFramebufferAttachementParameters(JSONWriter &json, GLenum target, GLenum attachment)'
367         print '{'
368         self.dump_attachment_parameters('target', 'attachment')
369         print '}'
370         print
371
372         print 'void dumpParameters(JSONWriter &json, Context &context)'
373         print '{'
374         print '    ScopedAllocator _allocator;'
375         print '    (void)_allocator;'
376         print
377         print '    json.beginMember("parameters");'
378         print '    json.beginObject();'
379         
380         self.dump_atoms(glGet)
381         
382         self.dump_material_params()
383         self.dump_light_params()
384         self.dump_vertex_attribs()
385         self.dump_program_params()
386         self.dump_texture_parameters()
387         self.dump_framebuffer_parameters()
388
389         print '    json.endObject();'
390         print '    json.endMember(); // parameters'
391         print '}'
392         print
393         
394         print '} /*namespace glstate */'
395
396     def dump_material_params(self):
397         print '    if (!context.ES) {'
398         for face in ['GL_FRONT', 'GL_BACK']:
399             print '    json.beginMember("%s");' % face
400             print '    json.beginObject();'
401             self.dump_atoms(glGetMaterial, face)
402             print '    json.endObject();'
403         print '    }'
404         print
405
406     def dump_light_params(self):
407         print '    GLint max_lights = 0;'
408         print '    _glGetIntegerv(GL_MAX_LIGHTS, &max_lights);'
409         print '    for (GLint index = 0; index < max_lights; ++index) {'
410         print '        GLenum light = GL_LIGHT0 + index;'
411         print '        if (glIsEnabled(light)) {'
412         print '            char name[32];'
413         print '            snprintf(name, sizeof name, "GL_LIGHT%i", index);'
414         print '            json.beginMember(name);'
415         print '            json.beginObject();'
416         self.dump_atoms(glGetLight, '    GL_LIGHT0 + index')
417         print '            json.endObject();'
418         print '            json.endMember(); // GL_LIGHTi'
419         print '        }'
420         print '    }'
421         print
422
423     def texenv_param_target(self, name):
424         if name == 'GL_TEXTURE_LOD_BIAS':
425            return 'GL_TEXTURE_FILTER_CONTROL'
426         elif name == 'GL_COORD_REPLACE':
427            return 'GL_POINT_SPRITE'
428         else:
429            return 'GL_TEXTURE_ENV'
430
431     def dump_texenv_params(self):
432         for target in ['GL_TEXTURE_ENV', 'GL_TEXTURE_FILTER_CONTROL', 'GL_POINT_SPRITE']:
433             print '    if (!context.ES) {'
434             print '        json.beginMember("%s");' % target
435             print '        json.beginObject();'
436             for _, _, name in glGetTexEnv.iter():
437                 if self.texenv_param_target(name) == target:
438                     self.dump_atom(glGetTexEnv, target, name) 
439             print '        json.endObject();'
440             print '    }'
441
442     def dump_vertex_attribs(self):
443         print '    GLint max_vertex_attribs = 0;'
444         print '    _glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attribs);'
445         print '    for (GLint index = 0; index < max_vertex_attribs; ++index) {'
446         print '        char name[32];'
447         print '        snprintf(name, sizeof name, "GL_VERTEX_ATTRIB_ARRAY%i", index);'
448         print '        json.beginMember(name);'
449         print '        json.beginObject();'
450         self.dump_atoms(glGetVertexAttrib, 'index')
451         print '        json.endObject();'
452         print '        json.endMember(); // GL_VERTEX_ATTRIB_ARRAYi'
453         print '    }'
454         print
455
456     program_targets = [
457         'GL_FRAGMENT_PROGRAM_ARB',
458         'GL_VERTEX_PROGRAM_ARB',
459     ]
460
461     def dump_program_params(self):
462         for target in self.program_targets:
463             print '    if (glIsEnabled(%s)) {' % target
464             print '        json.beginMember("%s");' % target
465             print '        json.beginObject();'
466             self.dump_atoms(glGetProgramARB, target)
467             print '        json.endObject();'
468             print '    }'
469
470     def dump_texture_parameters(self):
471         print '    {'
472         print '        GLint active_texture = GL_TEXTURE0;'
473         print '        glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);'
474         print '        GLint max_texture_coords = 0;'
475         print '        glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);'
476         print '        GLint max_combined_texture_image_units = 0;'
477         print '        glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);'
478         print '        GLint max_units = std::max(std::max(max_combined_texture_image_units, max_texture_coords), 2);'
479         print '        for (GLint unit = 0; unit < max_units; ++unit) {'
480         print '            char name[32];'
481         print '            snprintf(name, sizeof name, "GL_TEXTURE%i", unit);'
482         print '            json.beginMember(name);'
483         print '            glActiveTexture(GL_TEXTURE0 + unit);'
484         print '            json.beginObject();'
485         print
486         for target, binding in texture_targets:
487             print '            dumpTextureTargetParameters(json, context, %s, %s);' % (target, binding)
488         print '            if (unit < max_texture_coords) {'
489         self.dump_texenv_params()
490         print '            }'
491         print '            json.endObject();'
492         print '            json.endMember(); // GL_TEXTUREi'
493         print '        }'
494         print '        glActiveTexture(active_texture);'
495         print '    }'
496         print
497
498     def dump_framebuffer_parameters(self):
499         print '    {'
500         print '        GLint max_color_attachments = 0;'
501         print '        glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);'
502         print '        GLint framebuffer;'
503         for target, binding in framebuffer_targets:
504             print '            // %s' % target
505             print '            framebuffer = 0;'
506             print '            glGetIntegerv(%s, &framebuffer);' % binding
507             print '            if (framebuffer) {'
508             print '                json.beginMember("%s");' % target
509             print '                json.beginObject();'
510             print '                for (GLint i = 0; i < max_color_attachments; ++i) {'
511             print '                    GLint color_attachment = GL_COLOR_ATTACHMENT0 + i;'
512             print '                    dumpFramebufferAttachementParameters(json, %s, color_attachment);' % target
513             print '                }'
514             print '                dumpFramebufferAttachementParameters(json, %s, GL_DEPTH_ATTACHMENT);' % target
515             print '                dumpFramebufferAttachementParameters(json, %s, GL_STENCIL_ATTACHMENT);' % target
516             print '                json.endObject();'
517             print '                json.endMember(); // %s' % target
518             print '            }'
519             print
520         print '    }'
521         print
522
523     def dump_attachment_parameters(self, target, attachment):
524         print '            {'
525         print '                GLint object_type = GL_NONE;'
526         print '                glGetFramebufferAttachmentParameteriv(%s, %s, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);' % (target, attachment)
527         print '                if (object_type != GL_NONE) {'
528         print '                    json.beginMember(enumToString(%s));' % attachment
529         print '                    json.beginObject();'
530         self.dump_atoms(glGetFramebufferAttachmentParameter, target, attachment)
531         print '                    json.endObject();'
532         print '                    json.endMember(); // GL_x_ATTACHMENT'
533         print '                }'
534         print '            }'
535
536     def dump_atoms(self, getter, *args):
537         for _, _, name in getter.iter():
538             self.dump_atom(getter, *(args + (name,))) 
539
540     def dump_atom(self, getter, *args):
541         name = args[-1]
542
543         # Avoid crash on MacOSX
544         # XXX: The right fix would be to look at the support extensions..
545         import platform
546         if name == 'GL_SAMPLER_BINDING' and platform.system() == 'Darwin':
547             return
548
549         print '        // %s' % name
550         print '        {'
551         print '            flushErrors();'
552         type, value = getter(*args)
553         print '            if (glGetError() != GL_NO_ERROR) {'
554         #print '                std::cerr << "warning: %s(%s) failed\\n";' % (inflection, name)
555         print '                flushErrors();'
556         print '            } else {'
557         print '                json.beginMember("%s");' % name
558         JsonWriter().visit(type, value)
559         print '                json.endMember();'
560         print '            }'
561         print '        }'
562         print
563
564
565 if __name__ == '__main__':
566     StateDumper().dump()