1 ##########################################################################
3 # Copyright 2011 Jose Fonseca
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:
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
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
24 ##########################################################################/
27 '''Generate code to dump most GL state into JSON.'''
30 import retrace # to adjust sys.path
32 from specs.stdapi import *
34 from specs.gltypes import *
35 from specs.glparams import *
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'),
51 framebuffer_targets = [
52 ('GL_DRAW_FRAMEBUFFER', 'GL_DRAW_FRAMEBUFFER_BINDING'),
53 ('GL_READ_FRAMEBUFFER', 'GL_READ_FRAMEBUFFER_BINDING'),
57 '''Objects that describes how to inflect.'''
65 def __init__(self, radical, inflections, suffix = ''):
66 self.radical = radical
67 self.inflections = inflections
70 def reduced_type(self, type):
71 if type in self.inflections:
73 if type in self.reduced_types:
74 return self.reduced_type(self.reduced_types[type])
75 raise NotImplementedError
77 def inflect(self, type):
78 return self.radical + self.inflection(type) + self.suffix
80 def inflection(self, type):
81 type = self.reduced_type(type)
82 assert type in self.inflections
83 return self.inflections[type]
86 return self.radical + self.suffix
89 class StateGetter(Visitor):
90 '''Type visitor that is able to extract the state via one of the glGet*
93 It will declare any temporary variable
96 def __init__(self, radical, inflections, suffix=''):
97 self.inflector = GetInflector(radical, inflections)
101 for function, type, count, name in parameters:
102 inflection = self.inflector.radical + self.suffix
103 if inflection not in function.split(','):
107 yield type, count, name
109 def __call__(self, *args):
112 for type, count, name in self.iter():
115 type = Array(type, str(count))
117 return type, self.visit(type, args)
119 raise NotImplementedError
121 def temp_name(self, args):
122 '''Return the name of a temporary variable to hold the state.'''
125 return pname[3:].lower()
127 def visitConst(self, const, args):
128 return self.visit(const.type, args)
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)
138 print ' %s %s = %s(%s);' % (elem_type, temp_name, inflection + self.suffix, ', '.join(args))
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))
148 def visitAlias(self, alias, args):
149 return self.visitScalar(alias, args)
151 def visitEnum(self, enum, args):
152 return self.visitScalar(enum, args)
154 def visitBitmask(self, bitmask, args):
155 return self.visit(GLint, args)
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)
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 ' %s(%s, %s);' % (inflection + self.suffix, ', '.join(args), temp_name)
177 # Simple buffer overflow detection
178 print ' assert(%s[%s] == (%s)0xdeadc0de);' % (temp_name, array_length, elem_type)
181 def visitOpaque(self, pointer, args):
182 temp_name = self.temp_name(args)
183 inflection = self.inflector.inflect(pointer)
184 assert inflection.endswith('v')
185 print ' GLvoid *%s;' % temp_name
186 print ' %s(%s, &%s);' % (inflection + self.suffix, ', '.join(args), temp_name)
190 glGet = StateGetter('glGet', {
199 glGetMaterial = StateGetter('glGetMaterial', {I: 'iv', F: 'fv'})
200 glGetLight = StateGetter('glGetLight', {I: 'iv', F: 'fv'})
201 glGetVertexAttrib = StateGetter('glGetVertexAttrib', {I: 'iv', F: 'fv', D: 'dv', P: 'Pointerv'})
202 glGetTexParameter = StateGetter('glGetTexParameter', {I: 'iv', F: 'fv'})
203 glGetTexEnv = StateGetter('glGetTexEnv', {I: 'iv', F: 'fv'})
204 glGetTexLevelParameter = StateGetter('glGetTexLevelParameter', {I: 'iv', F: 'fv'})
205 glGetShader = StateGetter('glGetShaderiv', {I: 'iv'})
206 glGetProgram = StateGetter('glGetProgram', {I: 'iv'})
207 glGetProgramARB = StateGetter('glGetProgram', {I: 'iv', F: 'fv', S: 'Stringv'}, 'ARB')
208 glGetFramebufferAttachmentParameter = StateGetter('glGetFramebufferAttachmentParameter', {I: 'iv'})
211 class JsonWriter(Visitor):
212 '''Type visitor that will dump a value of the specified type through the
215 It expects a previously declared JSONWriter instance named "json".'''
217 def visitLiteral(self, literal, instance):
218 if literal.kind == 'Bool':
219 print ' json.writeBool(%s);' % instance
220 elif literal.kind in ('SInt', 'Uint'):
221 print ' json.writeInt(%s);' % instance
222 elif literal.kind in ('Float', 'Double'):
223 print ' json.writeFloat(%s);' % instance
225 raise NotImplementedError
227 def visitString(self, string, instance):
228 assert string.length is None
229 print ' json.writeString((const char *)%s);' % instance
231 def visitEnum(self, enum, instance):
232 if enum is GLboolean:
233 print ' dumpBoolean(json, %s);' % instance
235 print ' dumpEnum(json, %s);' % instance
238 print ' json.writeInt(%s);' % instance
240 def visitBitmask(self, bitmask, instance):
241 raise NotImplementedError
243 def visitAlias(self, alias, instance):
244 self.visit(alias.type, instance)
246 def visitOpaque(self, opaque, instance):
247 print ' json.writeInt((size_t)%s);' % instance
251 def visitArray(self, array, instance):
252 index = '_i%u' % JsonWriter.__index
253 JsonWriter.__index += 1
254 print ' json.beginArray();'
255 print ' for (unsigned %s = 0; %s < %s; ++%s) {' % (index, index, array.length, index)
256 self.visit(array.type, '%s[%s]' % (instance, index))
258 print ' json.endArray();'
263 '''Class to generate code to dump all GL state in JSON format via
270 print '#include <assert.h>'
271 print '#include <string.h>'
273 print '#include "json.hpp"'
274 print '#include "scoped_allocator.hpp"'
275 print '#include "glproc.hpp"'
276 print '#include "glsize.hpp"'
277 print '#include "glstate.hpp"'
278 print '#include "glstate_internal.hpp"'
280 print 'namespace glstate {'
284 print 'flushErrors(void) {'
285 print ' while (glGetError() != GL_NO_ERROR) {}'
290 print 'dumpBoolean(JSONWriter &json, GLboolean value)'
292 print ' switch (value) {'
293 print ' case GL_FALSE:'
294 print ' json.writeString("GL_FALSE");'
296 print ' case GL_TRUE:'
297 print ' json.writeString("GL_TRUE");'
300 print ' json.writeInt(static_cast<GLint>(value));'
307 print 'enumToString(GLenum pname)'
309 print ' switch (pname) {'
310 for name in GLenum.values:
311 print ' case %s:' % name
312 print ' return "%s";' % name
314 print ' return NULL;'
320 print 'dumpEnum(JSONWriter &json, GLenum pname)'
322 print ' const char *s = enumToString(pname);'
324 print ' json.writeString(s);'
326 print ' json.writeInt(pname);'
332 print 'dumpTextureTargetParameters(JSONWriter &json, Context &context, GLenum target, GLenum binding_param)'
334 print ' GLboolean enabled = GL_FALSE;'
335 print ' GLint binding = 0;'
336 print ' glGetBooleanv(target, &enabled);'
337 print ' json.beginMember(enumToString(target));'
338 print ' dumpBoolean(json, enabled);'
339 print ' json.endMember();'
340 print ' glGetIntegerv(binding_param, &binding);'
341 print ' json.writeIntMember(enumToString(binding_param), binding);'
342 print ' if (enabled || binding) {'
343 print ' json.beginMember(enumToString(target));'
344 print ' json.beginObject();'
345 self.dump_atoms(glGetTexParameter, 'target')
346 print ' if (!context.ES) {'
347 print ' GLenum levelTarget;'
348 print ' if (target == GL_TEXTURE_CUBE_MAP ||'
349 print ' target == GL_TEXTURE_CUBE_MAP_ARRAY) {'
350 print ' // Must pick a face'
351 print ' levelTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X;'
353 print ' levelTarget = target;'
355 self.dump_atoms(glGetTexLevelParameter, 'levelTarget', '0')
357 print ' json.endObject();'
358 print ' json.endMember(); // target'
364 print 'dumpFramebufferAttachementParameters(JSONWriter &json, GLenum target, GLenum attachment)'
366 self.dump_attachment_parameters('target', 'attachment')
370 print 'void dumpParameters(JSONWriter &json, Context &context)'
372 print ' ScopedAllocator _allocator;'
373 print ' (void)_allocator;'
375 print ' json.beginMember("parameters");'
376 print ' json.beginObject();'
378 self.dump_atoms(glGet)
380 self.dump_material_params()
381 self.dump_light_params()
382 self.dump_vertex_attribs()
383 self.dump_program_params()
384 self.dump_texture_parameters()
385 self.dump_framebuffer_parameters()
387 print ' json.endObject();'
388 print ' json.endMember(); // parameters'
392 print '} /*namespace glstate */'
394 def dump_material_params(self):
395 print ' if (!context.ES) {'
396 for face in ['GL_FRONT', 'GL_BACK']:
397 print ' json.beginMember("%s");' % face
398 print ' json.beginObject();'
399 self.dump_atoms(glGetMaterial, face)
400 print ' json.endObject();'
404 def dump_light_params(self):
405 print ' GLint max_lights = 0;'
406 print ' _glGetIntegerv(GL_MAX_LIGHTS, &max_lights);'
407 print ' for (GLint index = 0; index < max_lights; ++index) {'
408 print ' GLenum light = GL_LIGHT0 + index;'
409 print ' if (glIsEnabled(light)) {'
410 print ' char name[32];'
411 print ' snprintf(name, sizeof name, "GL_LIGHT%i", index);'
412 print ' json.beginMember(name);'
413 print ' json.beginObject();'
414 self.dump_atoms(glGetLight, ' GL_LIGHT0 + index')
415 print ' json.endObject();'
416 print ' json.endMember(); // GL_LIGHTi'
421 def texenv_param_target(self, name):
422 if name == 'GL_TEXTURE_LOD_BIAS':
423 return 'GL_TEXTURE_FILTER_CONTROL'
424 elif name == 'GL_COORD_REPLACE':
425 return 'GL_POINT_SPRITE'
427 return 'GL_TEXTURE_ENV'
429 def dump_texenv_params(self):
430 for target in ['GL_TEXTURE_ENV', 'GL_TEXTURE_FILTER_CONTROL', 'GL_POINT_SPRITE']:
431 print ' if (!context.ES) {'
432 print ' json.beginMember("%s");' % target
433 print ' json.beginObject();'
434 for _, _, name in glGetTexEnv.iter():
435 if self.texenv_param_target(name) == target:
436 self.dump_atom(glGetTexEnv, target, name)
437 print ' json.endObject();'
440 def dump_vertex_attribs(self):
441 print ' GLint max_vertex_attribs = 0;'
442 print ' _glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attribs);'
443 print ' for (GLint index = 0; index < max_vertex_attribs; ++index) {'
444 print ' char name[32];'
445 print ' snprintf(name, sizeof name, "GL_VERTEX_ATTRIB_ARRAY%i", index);'
446 print ' json.beginMember(name);'
447 print ' json.beginObject();'
448 self.dump_atoms(glGetVertexAttrib, 'index')
449 print ' json.endObject();'
450 print ' json.endMember(); // GL_VERTEX_ATTRIB_ARRAYi'
455 'GL_FRAGMENT_PROGRAM_ARB',
456 'GL_VERTEX_PROGRAM_ARB',
459 def dump_program_params(self):
460 for target in self.program_targets:
461 print ' if (glIsEnabled(%s)) {' % target
462 print ' json.beginMember("%s");' % target
463 print ' json.beginObject();'
464 self.dump_atoms(glGetProgramARB, target)
465 print ' json.endObject();'
468 def dump_texture_parameters(self):
470 print ' GLint active_texture = GL_TEXTURE0;'
471 print ' glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);'
472 print ' GLint max_texture_coords = 0;'
473 print ' glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);'
474 print ' GLint max_combined_texture_image_units = 0;'
475 print ' glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);'
476 print ' GLint max_units = std::max(std::max(max_combined_texture_image_units, max_texture_coords), 2);'
477 print ' for (GLint unit = 0; unit < max_units; ++unit) {'
478 print ' char name[32];'
479 print ' snprintf(name, sizeof name, "GL_TEXTURE%i", unit);'
480 print ' json.beginMember(name);'
481 print ' glActiveTexture(GL_TEXTURE0 + unit);'
482 print ' json.beginObject();'
484 for target, binding in texture_targets:
485 print ' dumpTextureTargetParameters(json, context, %s, %s);' % (target, binding)
486 print ' if (unit < max_texture_coords) {'
487 self.dump_texenv_params()
489 print ' json.endObject();'
490 print ' json.endMember(); // GL_TEXTUREi'
492 print ' glActiveTexture(active_texture);'
496 def dump_framebuffer_parameters(self):
498 print ' GLint max_color_attachments = 0;'
499 print ' glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);'
500 print ' GLint framebuffer;'
501 for target, binding in framebuffer_targets:
502 print ' // %s' % target
503 print ' framebuffer = 0;'
504 print ' glGetIntegerv(%s, &framebuffer);' % binding
505 print ' if (framebuffer) {'
506 print ' json.beginMember("%s");' % target
507 print ' json.beginObject();'
508 print ' for (GLint i = 0; i < max_color_attachments; ++i) {'
509 print ' GLint color_attachment = GL_COLOR_ATTACHMENT0 + i;'
510 print ' dumpFramebufferAttachementParameters(json, %s, color_attachment);' % target
512 print ' dumpFramebufferAttachementParameters(json, %s, GL_DEPTH_ATTACHMENT);' % target
513 print ' dumpFramebufferAttachementParameters(json, %s, GL_STENCIL_ATTACHMENT);' % target
514 print ' json.endObject();'
515 print ' json.endMember(); // %s' % target
521 def dump_attachment_parameters(self, target, attachment):
523 print ' GLint object_type = GL_NONE;'
524 print ' glGetFramebufferAttachmentParameteriv(%s, %s, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);' % (target, attachment)
525 print ' if (object_type != GL_NONE) {'
526 print ' json.beginMember(enumToString(%s));' % attachment
527 print ' json.beginObject();'
528 self.dump_atoms(glGetFramebufferAttachmentParameter, target, attachment)
529 print ' json.endObject();'
530 print ' json.endMember(); // GL_x_ATTACHMENT'
534 def dump_atoms(self, getter, *args):
535 for _, _, name in getter.iter():
536 self.dump_atom(getter, *(args + (name,)))
538 def dump_atom(self, getter, *args):
541 # Avoid crash on MacOSX
542 # XXX: The right fix would be to look at the support extensions..
544 if name == 'GL_SAMPLER_BINDING' and platform.system() == 'Darwin':
547 print ' // %s' % name
549 print ' flushErrors();'
550 type, value = getter(*args)
551 print ' if (glGetError() != GL_NO_ERROR) {'
552 #print ' std::cerr << "warning: %s(%s) failed\\n";' % (inflection, name)
553 print ' flushErrors();'
555 print ' json.beginMember("%s");' % name
556 JsonWriter().visit(type, value)
557 print ' json.endMember();'
563 if __name__ == '__main__':