Added some comments and fixed typeos. Slightly refactored the way
[mesa.git] / src / mesa / glapi / glX_XML.py
1 #!/usr/bin/python2
2
3 # (C) Copyright IBM Corporation 2004
4 # All Rights Reserved.
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a
7 # copy of this software and associated documentation files (the "Software"),
8 # to deal in the Software without restriction, including without limitation
9 # on the rights to use, copy, modify, merge, publish, distribute, sub
10 # license, and/or sell copies of the Software, and to permit persons to whom
11 # the Software is furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice (including the next
14 # paragraph) shall be included in all copies or substantial portions of the
15 # Software.
16 #
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 # FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
20 # IBM AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
23 # IN THE SOFTWARE.
24 #
25 # Authors:
26 # Ian Romanick <idr@us.ibm.com>
27
28 from xml.sax import saxutils
29 from xml.sax import make_parser
30 from xml.sax.handler import feature_namespaces
31
32 import gl_XML
33 import license
34 import sys, getopt
35
36
37 def printPure():
38 print """# if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
39 # define PURE __attribute__((pure))
40 # else
41 # define PURE
42 # endif"""
43
44 def printFastcall():
45 print """# if defined(__i386__) && defined(__GNUC__)
46 # define FASTCALL __attribute__((fastcall))
47 # else
48 # define FASTCALL
49 # endif"""
50
51 def printVisibility(S, s):
52 print """# if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)
53 # define %s __attribute__((visibility("%s")))
54 # else
55 # define %s
56 # endif""" % (S, s, S)
57
58 def printNoinline():
59 print """# if defined(__GNUC__)
60 # define NOINLINE __attribute__((noinline))
61 # else
62 # define NOINLINE
63 # endif"""
64
65
66 class glXItemFactory(gl_XML.glItemFactory):
67 """Factory to create GLX protocol oriented objects derived from glItem."""
68
69 def create(self, context, name, attrs):
70 if name == "function":
71 return glXFunction(context, name, attrs)
72 elif name == "enum":
73 return glXEnum(context, name, attrs)
74 elif name == "param":
75 return glXParameter(context, name, attrs)
76 else:
77 return gl_XML.glItemFactory.create(self, context, name, attrs)
78
79 class glXEnumFunction:
80 def __init__(self, name):
81 self.name = name
82
83 # "enums" is a set of lists. The element in the set is the
84 # value of the enum. The list is the list of names for that
85 # value. For example, [0x8126] = {"POINT_SIZE_MIN",
86 # "POINT_SIZE_MIN_ARB", "POINT_SIZE_MIN_EXT",
87 # "POINT_SIZE_MIN_SGIS"}.
88
89 self.enums = {}
90
91 # "count" is indexed by count values. Each element of count
92 # is a list of index to "enums" that have that number of
93 # associated data elements. For example, [4] =
94 # {GL_AMBIENT, GL_DIFFUSE, GL_SPECULAR, GL_EMISSION,
95 # GL_AMBIENT_AND_DIFFUSE} (the enum names are used here,
96 # but the actual hexadecimal values would be in the array).
97
98 self.count = {}
99
100
101 def append(self, count, value, name):
102 if self.enums.has_key( value ):
103 self.enums[value].append(name)
104 else:
105 if not self.count.has_key(count):
106 self.count[count] = []
107
108 self.enums[value] = []
109 self.enums[value].append(name)
110 self.count[count].append(value)
111
112
113 def signature( self ):
114 sig = ""
115 for i in self.count:
116 for e in self.count[i]:
117 sig += "%04x,%u," % (e, i)
118
119 return sig;
120
121
122 def PrintUsingTable(self):
123 """Emit the body of the __gl*_size function using a pair
124 of look-up tables and a mask. The mask is calculated such
125 that (e & mask) is unique for all the valid values of e for
126 this function. The result of (e & mask) is used as an index
127 into the first look-up table. If it matches e, then the
128 same entry of the second table is returned. Otherwise zero
129 is returned.
130
131 It seems like this should cause better code to be generated.
132 However, on x86 at least, the resulting .o file is about 20%
133 larger then the switch-statment version. I am leaving this
134 code in because the results may be different on other
135 platforms (e.g., PowerPC or x86-64)."""
136
137 return 0
138 count = 0
139 for a in self.enums:
140 count += 1
141
142 # Determine if there is some mask M, such that M = (2^N) - 1,
143 # that will generate unique values for all of the enums.
144
145 mask = 0
146 for i in [1, 2, 3, 4, 5, 6, 7, 8]:
147 mask = (1 << i) - 1
148
149 fail = 0;
150 for a in self.enums:
151 for b in self.enums:
152 if a != b:
153 if (a & mask) == (b & mask):
154 fail = 1;
155
156 if not fail:
157 break;
158 else:
159 mask = 0
160
161 if (mask != 0) and (mask < (2 * count)):
162 masked_enums = {}
163 masked_count = {}
164
165 for i in range(0, mask + 1):
166 masked_enums[i] = "0";
167 masked_count[i] = 0;
168
169 for c in self.count:
170 for e in self.count[c]:
171 i = e & mask
172 masked_enums[i] = '0x%04x /* %s */' % (e, self.enums[e][0])
173 masked_count[i] = c
174
175
176 print ' static const GLushort a[%u] = {' % (mask + 1)
177 for e in masked_enums:
178 print ' %s, ' % (masked_enums[e])
179 print ' };'
180
181 print ' static const GLubyte b[%u] = {' % (mask + 1)
182 for c in masked_count:
183 print ' %u, ' % (masked_count[c])
184 print ' };'
185
186 print ' const unsigned idx = (e & 0x%02xU);' % (mask)
187 print ''
188 print ' return (e == a[idx]) ? (GLint) b[idx] : 0;'
189 return 1;
190 else:
191 return 0;
192
193 def PrintUsingSwitch(self):
194 """Emit the body of the __gl*_size function using a
195 switch-statement."""
196
197 print ' switch( e ) {'
198
199 for c in self.count:
200 for e in self.count[c]:
201 first = 1
202
203 # There may be multiple enums with the same
204 # value. This happens has extensions are
205 # promoted from vendor-specific or EXT to
206 # ARB and to the core. Emit the first one as
207 # a case label, and emit the others as
208 # commented-out case labels.
209
210 for j in self.enums[e]:
211 if first:
212 print ' case %s:' % (j)
213 first = 0
214 else:
215 print '/* case %s:*/' % (j)
216
217 print ' return %u;' % (c)
218
219 print ' default: return 0;'
220 print ' }'
221
222
223 def Print(self, name):
224 print 'INTERNAL PURE FASTCALL GLint'
225 print '__gl%s_size( GLenum e )' % (name)
226 print '{'
227
228 if not self.PrintUsingTable():
229 self.PrintUsingSwitch()
230
231 print '}'
232 print ''
233
234
235
236 class glXEnum(gl_XML.glEnum):
237 def __init__(self, context, name, attrs):
238 gl_XML.glEnum.__init__(self, context, name, attrs)
239 self.glx_functions = []
240
241 def startElement(self, name, attrs):
242 if name == "size":
243 n = attrs.get('name', None)
244 if not self.context.glx_enum_functions.has_key( n ):
245 f = glXEnumFunction( n )
246 self.context.glx_enum_functions[ f.name ] = f
247
248 temp = attrs.get('count', None)
249 try:
250 c = int(temp)
251 except Exception,e:
252 raise RuntimeError('Invalid count value "%s" for enum "%s" in function "%s" when an integer was expected.' % (temp, self.name, n))
253
254 self.context.glx_enum_functions[ n ].append( c, self.value, self.name )
255 else:
256 gl_XML.glEnum.startElement(self, context, name, attrs)
257 return
258
259
260 class glXParameter(gl_XML.glParameter):
261 def __init__(self, context, name, attrs):
262 self.order = 1;
263 gl_XML.glParameter.__init__(self, context, name, attrs);
264
265
266 class glXParameterIterator:
267 """Class to iterate over a list of glXParameters.
268
269 Objects of this class are returned by the parameterIterator method of
270 the glXFunction class. They are used to iterate over the list of
271 parameters to the function."""
272
273 def __init__(self, data, skip_output, max_order):
274 self.data = data
275 self.index = 0
276 self.order = 0
277 self.skip_output = skip_output
278 self.max_order = max_order
279
280 def __iter__(self):
281 return self
282
283 def next(self):
284 if len( self.data ) == 0:
285 raise StopIteration
286
287 while 1:
288 if self.index == len( self.data ):
289 if self.order == self.max_order:
290 raise StopIteration
291 else:
292 self.order += 1
293 self.index = 0
294
295 i = self.index
296 self.index += 1
297
298 if self.data[i].order == self.order and not (self.data[i].is_output and self.skip_output):
299 return self.data[i]
300
301
302 class glXFunction(gl_XML.glFunction):
303 glx_rop = 0
304 glx_sop = 0
305 glx_vendorpriv = 0
306
307 # If this is set to true, it means that GLdouble parameters should be
308 # written to the GLX protocol packet in the order they appear in the
309 # prototype. This is different from the "classic" ordering. In the
310 # classic ordering GLdoubles are written to the protocol packet first,
311 # followed by non-doubles. NV_vertex_program was the first extension
312 # to break with this tradition.
313
314 glx_doubles_in_order = 0
315
316 vectorequiv = None
317 handcode = 0
318 ignore = 0
319 can_be_large = 0
320
321 def __init__(self, context, name, attrs):
322 self.vectorequiv = attrs.get('vectorequiv', None)
323 self.count_parameters = None
324 self.counter = None
325 self.output = None
326 self.can_be_large = 0
327 self.reply_always_array = 0
328
329 gl_XML.glFunction.__init__(self, context, name, attrs)
330 return
331
332
333 def parameterIterator(self, skip_output, max_order):
334 return glXParameterIterator(self.fn_parameters, skip_output, max_order)
335
336
337 def startElement(self, name, attrs):
338 """Process elements within a function that are specific to GLX."""
339
340 if name == "glx":
341 self.glx_rop = int(attrs.get('rop', "0"))
342 self.glx_sop = int(attrs.get('sop', "0"))
343 self.glx_vendorpriv = int(attrs.get('vendorpriv', "0"))
344
345 if attrs.get('handcode', "false") == "true":
346 self.handcode = 1
347 else:
348 self.handcode = 0
349
350 if attrs.get('ignore', "false") == "true":
351 self.ignore = 1
352 else:
353 self.ignore = 0
354
355 if attrs.get('large', "false") == "true":
356 self.can_be_large = 1
357 else:
358 self.can_be_large = 0
359
360 if attrs.get('doubles_in_order', "false") == "true":
361 self.glx_doubles_in_order = 1
362 else:
363 self.glx_doubles_in_order = 0
364
365 if attrs.get('always_array', "false") == "true":
366 self.reply_always_array = 1
367 else:
368 self.reply_always_array = 0
369
370 else:
371 gl_XML.glFunction.startElement(self, name, attrs)
372
373
374 def append(self, tag_name, p):
375 gl_XML.glFunction.append(self, tag_name, p)
376
377 if p.is_variable_length_array():
378 p.order = 2;
379 elif not self.glx_doubles_in_order and p.p_type.size == 8:
380 p.order = 0;
381
382 if p.p_count_parameters != None:
383 self.count_parameters = p.p_count_parameters
384
385 if p.is_counter:
386 self.counter = p.name
387
388 if p.is_output:
389 self.output = p
390
391 return
392
393 def variable_length_parameter(self):
394 for param in self.fn_parameters:
395 if param.is_variable_length_array():
396 return param
397
398 return None
399
400
401 def command_payload_length(self):
402 size = 0
403 size_string = ""
404 for p in gl_XML.glFunction.parameterIterator(self):
405 if p.is_output: continue
406 temp = p.size_string()
407 try:
408 s = int(temp)
409 size += s
410 except Exception,e:
411 size_string = size_string + " + __GLX_PAD(%s)" % (temp)
412
413 return [size, size_string]
414
415 def command_length(self):
416 [size, size_string] = self.command_payload_length()
417
418 if self.glx_rop != 0:
419 size += 4
420
421 size = ((size + 3) & ~3)
422 return "%u%s" % (size, size_string)
423
424
425 def opcode_real_value(self):
426 """Get the true numeric value of the GLX opcode
427
428 Behaves similarly to opcode_value, except for
429 X_GLXVendorPrivate and X_GLXVendorPrivateWithReply commands.
430 In these cases the value for the GLX opcode field (i.e.,
431 16 for X_GLXVendorPrivate or 17 for
432 X_GLXVendorPrivateWithReply) is returned. For other 'single'
433 commands, the opcode for the command (e.g., 101 for
434 X_GLsop_NewList) is returned."""
435
436 if self.glx_vendorpriv != 0:
437 if self.needs_reply():
438 return 17
439 else:
440 return 16
441 else:
442 return self.opcode_value()
443
444 def opcode_value(self):
445 """Get the unique protocol opcode for the glXFunction"""
446
447 if self.glx_rop != 0:
448 return self.glx_rop
449 elif self.glx_sop != 0:
450 return self.glx_sop
451 elif self.glx_vendorpriv != 0:
452 return self.glx_vendorpriv
453 else:
454 return -1
455
456 def opcode_rop_basename(self):
457 """Return either the name to be used for GLX protocol enum.
458
459 Returns either the name of the function or the name of the
460 name of the equivalent vector (e.g., glVertex3fv for
461 glVertex3f) function."""
462
463 if self.vectorequiv == None:
464 return self.name
465 else:
466 return self.vectorequiv
467
468 def opcode_name(self):
469 """Get the unique protocol enum name for the glXFunction"""
470
471 if self.glx_rop != 0:
472 return "X_GLrop_%s" % (self.opcode_rop_basename())
473 elif self.glx_sop != 0:
474 return "X_GLsop_%s" % (self.name)
475 elif self.glx_vendorpriv != 0:
476 return "X_GLvop_%s" % (self.name)
477 else:
478 return "ERROR"
479
480 def opcode_real_name(self):
481 """Get the true protocol enum name for the GLX opcode
482
483 Behaves similarly to opcode_name, except for
484 X_GLXVendorPrivate and X_GLXVendorPrivateWithReply commands.
485 In these cases the string 'X_GLXVendorPrivate' or
486 'X_GLXVendorPrivateWithReply' is returned. For other
487 single or render commands 'X_GLsop' or 'X_GLrop' plus the
488 name of the function returned."""
489
490 if self.glx_vendorpriv != 0:
491 if self.needs_reply():
492 return "X_GLXVendorPrivateWithReply"
493 else:
494 return "X_GLXVendorPrivate"
495 else:
496 return self.opcode_name()
497
498
499 def return_string(self):
500 if self.fn_return_type != 'void':
501 return "return retval;"
502 else:
503 return "return;"
504
505
506 def needs_reply(self):
507 return self.fn_return_type != 'void' or self.output != None
508
509
510 class GlxProto(gl_XML.FilterGLAPISpecBase):
511 name = "glX_proto_send.py (from Mesa)"
512
513 def __init__(self):
514 gl_XML.FilterGLAPISpecBase.__init__(self)
515 self.factory = glXItemFactory()
516 self.glx_enum_functions = {}
517
518
519 def endElement(self, name):
520 if name == 'OpenGLAPI':
521 # Once all the parsing is done, we have to go back and
522 # fix-up some cross references between different
523 # functions.
524
525 for k in self.functions:
526 f = self.functions[k]
527 if f.vectorequiv != None:
528 equiv = self.find_function(f.vectorequiv)
529 if equiv != None:
530 f.glx_doubles_in_order = equiv.glx_doubles_in_order
531 f.glx_rop = equiv.glx_rop
532 else:
533 raise RuntimeError("Could not find the vector equiv. function %s for %s!" % (f.name, f.vectorequiv))
534 else:
535 gl_XML.FilterGLAPISpecBase.endElement(self, name)
536 return