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