• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2
3# (C) Copyright IBM Corporation 2005
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
28import argparse
29import string
30
31import gl_XML, glX_XML, glX_proto_common, license
32
33
34class PrintGlxDispatch_h(gl_XML.gl_print_base):
35    def __init__(self):
36        gl_XML.gl_print_base.__init__(self)
37
38        self.name = "glX_proto_recv.py (from Mesa)"
39        self.license = license.bsd_license_template % ( "(C) Copyright IBM Corporation 2005", "IBM")
40
41        self.header_tag = "_INDIRECT_DISPATCH_H_"
42        return
43
44
45    def printRealHeader(self):
46        print '#  include <X11/Xfuncproto.h>'
47        print ''
48        print 'struct __GLXclientStateRec;'
49        print ''
50        return
51
52
53    def printBody(self, api):
54        for func in api.functionIterateAll():
55            if not func.ignore and not func.vectorequiv:
56                if func.glx_rop:
57                    print 'extern _X_HIDDEN void __glXDisp_%s(GLbyte * pc);' % (func.name)
58                    print 'extern _X_HIDDEN _X_COLD void __glXDispSwap_%s(GLbyte * pc);' % (func.name)
59                elif func.glx_sop or func.glx_vendorpriv:
60                    print 'extern _X_HIDDEN int __glXDisp_%s(struct __GLXclientStateRec *, GLbyte *);' % (func.name)
61                    print 'extern _X_HIDDEN _X_COLD int __glXDispSwap_%s(struct __GLXclientStateRec *, GLbyte *);' % (func.name)
62
63                    if func.glx_sop and func.glx_vendorpriv:
64                        n = func.glx_vendorpriv_names[0]
65                        print 'extern _X_HIDDEN int __glXDisp_%s(struct __GLXclientStateRec *, GLbyte *);' % (n)
66                        print 'extern _X_HIDDEN _X_COLD int __glXDispSwap_%s(struct __GLXclientStateRec *, GLbyte *);' % (n)
67
68        return
69
70
71class PrintGlxDispatchFunctions(glX_proto_common.glx_print_proto):
72    def __init__(self, do_swap):
73        gl_XML.gl_print_base.__init__(self)
74        self.name = "glX_proto_recv.py (from Mesa)"
75        self.license = license.bsd_license_template % ( "(C) Copyright IBM Corporation 2005", "IBM")
76
77        self.real_types = [ '', '', 'uint16_t', '', 'uint32_t', '', '', '', 'uint64_t' ]
78        self.do_swap = do_swap
79        return
80
81
82    def printRealHeader(self):
83        print '#include <inttypes.h>'
84        print '#include "glxserver.h"'
85        print '#include "indirect_size.h"'
86        print '#include "indirect_size_get.h"'
87        print '#include "indirect_dispatch.h"'
88        print '#include "glxbyteorder.h"'
89        print '#include "indirect_util.h"'
90        print '#include "singlesize.h"'
91        print ''
92        print 'typedef struct {'
93        print '    __GLX_PIXEL_3D_HDR;'
94        print '} __GLXpixel3DHeader;'
95        print ''
96        print 'extern GLboolean __glXErrorOccured( void );'
97        print 'extern void __glXClearErrorOccured( void );'
98        print ''
99        print 'static const unsigned dummy_answer[2] = {0, 0};'
100        print ''
101        return
102
103
104    def printBody(self, api):
105        if self.do_swap:
106            self.emit_swap_wrappers(api)
107
108
109        for func in api.functionIterateByOffset():
110            if not func.ignore and not func.server_handcode and not func.vectorequiv and (func.glx_rop or func.glx_sop or func.glx_vendorpriv):
111                self.printFunction(func, func.name)
112                if func.glx_sop and func.glx_vendorpriv:
113                    self.printFunction(func, func.glx_vendorpriv_names[0])
114
115
116        return
117
118    def fptrType(self, name):
119	fptr = "pfngl" + name + "proc"
120	return fptr.upper()
121
122    def printFunction(self, f, name):
123        if (f.glx_sop or f.glx_vendorpriv) and (len(f.get_images()) != 0):
124            return
125
126        if not self.do_swap:
127            base = '__glXDisp'
128        else:
129            base = '__glXDispSwap'
130
131        if f.glx_rop:
132            print 'void %s_%s(GLbyte * pc)' % (base, name)
133        else:
134            print 'int %s_%s(__GLXclientState *cl, GLbyte *pc)' % (base, name)
135
136        print '{'
137
138        if not f.is_abi():
139            print '    %s %s = __glGetProcAddress("gl%s");' % (self.fptrType(name), name, name)
140
141        if f.glx_rop or f.vectorequiv:
142            self.printRenderFunction(f)
143        elif f.glx_sop or f.glx_vendorpriv:
144            if len(f.get_images()) == 0:
145                self.printSingleFunction(f, name)
146        else:
147            print "/* Missing GLX protocol for %s. */" % (name)
148
149        print '}'
150        print ''
151        return
152
153
154    def swap_name(self, bytes):
155        return 'bswap_%u_array' % (8 * bytes)
156
157
158    def emit_swap_wrappers(self, api):
159        self.type_map = {}
160        already_done = [ ]
161
162        for t in api.typeIterate():
163            te = t.get_type_expression()
164            t_size = te.get_element_size()
165
166            if t_size > 1 and t.glx_name:
167
168                t_name = "GL" + t.name
169                self.type_map[ t_name ] = t.glx_name
170
171                if t.glx_name not in already_done:
172                    real_name = self.real_types[t_size]
173
174                    print 'static _X_UNUSED %s' % (t_name)
175                    print 'bswap_%s(const void * src)' % (t.glx_name)
176                    print '{'
177                    print '    union { %s dst; %s ret; } x;' % (real_name, t_name)
178                    print '    x.dst = bswap_%u(*(%s *) src);' % (t_size * 8, real_name)
179                    print '    return x.ret;'
180                    print '}'
181                    print ''
182                    already_done.append( t.glx_name )
183
184        for bits in [16, 32, 64]:
185            print 'static void *'
186            print 'bswap_%u_array(uint%u_t * src, unsigned count)' % (bits, bits)
187            print '{'
188            print '    unsigned  i;'
189            print ''
190            print '    for (i = 0 ; i < count ; i++) {'
191            print '        uint%u_t temp = bswap_%u(src[i]);' % (bits, bits)
192            print '        src[i] = temp;'
193            print '    }'
194            print ''
195            print '    return src;'
196            print '}'
197            print ''
198
199
200    def fetch_param(self, param):
201        t = param.type_string()
202        o = param.offset
203        element_size = param.size() / param.get_element_count()
204
205        if self.do_swap and (element_size != 1):
206            if param.is_array():
207                real_name = self.real_types[ element_size ]
208
209                swap_func = self.swap_name( element_size )
210                return ' (%-8s)%s( (%s *) (pc + %2s), %s )' % (t, swap_func, real_name, o, param.count)
211            else:
212                t_name = param.get_base_type_string()
213                return ' (%-8s)bswap_%-7s( pc + %2s )' % (t, self.type_map[ t_name ], o)
214        else:
215            if param.is_array():
216                return ' (%-8s)(pc + %2u)' % (t, o)
217            else:
218                return '*(%-8s *)(pc + %2u)' % (t, o)
219
220        return None
221
222
223    def emit_function_call(self, f, retval_assign, indent):
224        list = []
225        prefix = "gl" if f.is_abi() else ""
226
227        for param in f.parameterIterator():
228            if param.is_padding:
229                continue
230
231            if param.is_counter or param.is_image() or param.is_output or param.name in f.count_parameter_list or len(param.count_parameter_list):
232                location = param.name
233            else:
234                location = self.fetch_param(param)
235
236            list.append( '%s        %s' % (indent, location) )
237
238        print '%s    %s%s%s(%s);' % (indent, retval_assign, prefix, f.name, string.join(list, ',\n'))
239
240
241    def common_func_print_just_start(self, f, indent):
242        align64 = 0
243        need_blank = 0
244
245
246        f.calculate_offsets()
247        for param in f.parameterIterateGlxSend():
248            # If any parameter has a 64-bit base type, then we
249            # have to do alignment magic for the while thing.
250
251            if param.is_64_bit():
252                align64 = 1
253
254
255            # FIXME img_null_flag is over-loaded.  In addition to
256            # FIXME being used for images, it is used to signify
257            # FIXME NULL data pointers for vertex buffer object
258            # FIXME related functions.  Re-name it to null_data
259            # FIXME or something similar.
260
261            if param.img_null_flag:
262                print '%s    const CARD32 ptr_is_null = *(CARD32 *)(pc + %s);' % (indent, param.offset - 4)
263                cond = '(ptr_is_null != 0) ? NULL : '
264            else:
265                cond = ""
266
267
268            type_string = param.type_string()
269
270            if param.is_image():
271                offset = f.offset_of( param.name )
272
273                print '%s    %s const %s = (%s) (%s(pc + %s));' % (indent, type_string, param.name, type_string, cond, offset)
274
275                if param.depth:
276                    print '%s    __GLXpixel3DHeader * const hdr = (__GLXpixel3DHeader *)(pc);' % (indent)
277                else:
278                    print '%s    __GLXpixelHeader * const hdr = (__GLXpixelHeader *)(pc);' % (indent)
279
280                need_blank = 1
281            elif param.is_counter or param.name in f.count_parameter_list:
282                location = self.fetch_param(param)
283                print '%s    const %s %s = %s;' % (indent, type_string, param.name, location)
284                need_blank = 1
285            elif len(param.count_parameter_list):
286                if param.size() == 1 and not self.do_swap:
287                    location = self.fetch_param(param)
288                    print '%s    %s %s = %s%s;' % (indent, type_string, param.name, cond, location)
289                else:
290                    print '%s    %s %s;' % (indent, type_string, param.name)
291                need_blank = 1
292
293
294
295        if need_blank:
296            print ''
297
298        if align64:
299            print '#ifdef __GLX_ALIGN64'
300
301            if f.has_variable_size_request():
302                self.emit_packet_size_calculation(f, 4)
303                s = "cmdlen"
304            else:
305                s = str((f.command_fixed_length() + 3) & ~3)
306
307            print '    if ((unsigned long)(pc) & 7) {'
308            print '        (void) memmove(pc-4, pc, %s);' % (s)
309            print '        pc -= 4;'
310            print '    }'
311            print '#endif'
312            print ''
313
314
315        need_blank = 0
316        if self.do_swap:
317            for param in f.parameterIterateGlxSend():
318                if param.count_parameter_list:
319                    o = param.offset
320                    count = param.get_element_count()
321                    type_size = param.size() / count
322
323                    if param.counter:
324                        count_name = param.counter
325                    else:
326                        count_name = str(count)
327
328                    # This is basically an ugly special-
329                    # case for glCallLists.
330
331                    if type_size == 1:
332                        x = []
333                        x.append( [1, ['BYTE', 'UNSIGNED_BYTE', '2_BYTES', '3_BYTES', '4_BYTES']] )
334                        x.append( [2, ['SHORT', 'UNSIGNED_SHORT']] )
335                        x.append( [4, ['INT', 'UNSIGNED_INT', 'FLOAT']] )
336
337                        print '    switch(%s) {' % (param.count_parameter_list[0])
338                        for sub in x:
339                            for t_name in sub[1]:
340                                print '    case GL_%s:' % (t_name)
341
342                            if sub[0] == 1:
343                                print '        %s = (%s) (pc + %s); break;' % (param.name, param.type_string(), o)
344                            else:
345                                swap_func = self.swap_name(sub[0])
346                                print '        %s = (%s) %s( (%s *) (pc + %s), %s ); break;' % (param.name, param.type_string(), swap_func, self.real_types[sub[0]], o, count_name)
347                        print '    default:'
348                        print '        return;'
349                        print '    }'
350                    else:
351                        swap_func = self.swap_name(type_size)
352                        compsize = self.size_call(f, 1)
353                        print '    %s = (%s) %s( (%s *) (pc + %s), %s );' % (param.name, param.type_string(), swap_func, self.real_types[type_size], o, compsize)
354
355                    need_blank = 1
356
357        else:
358            for param in f.parameterIterateGlxSend():
359                if param.count_parameter_list:
360                    print '%s    %s = (%s) (pc + %s);' % (indent, param.name, param.type_string(), param.offset)
361                    need_blank = 1
362
363
364        if need_blank:
365            print ''
366
367
368        return
369
370
371    def printSingleFunction(self, f, name):
372        if name not in f.glx_vendorpriv_names:
373            print '    xGLXSingleReq * const req = (xGLXSingleReq *) pc;'
374        else:
375            print '    xGLXVendorPrivateReq * const req = (xGLXVendorPrivateReq *) pc;'
376
377        print '    int error;'
378
379        if self.do_swap:
380            print '    __GLXcontext * const cx = __glXForceCurrent(cl, bswap_CARD32( &req->contextTag ), &error);'
381        else:
382            print '    __GLXcontext * const cx = __glXForceCurrent(cl, req->contextTag, &error);'
383
384        print ''
385        if name not in f.glx_vendorpriv_names:
386            print '    pc += __GLX_SINGLE_HDR_SIZE;'
387        else:
388            print '    pc += __GLX_VENDPRIV_HDR_SIZE;'
389
390        print '    if ( cx != NULL ) {'
391        self.common_func_print_just_start(f, "    ")
392
393
394        if f.return_type != 'void':
395            print '        %s retval;' % (f.return_type)
396            retval_string = "retval"
397            retval_assign = "retval = "
398        else:
399            retval_string = "0"
400            retval_assign = ""
401
402
403        type_size = 0
404        answer_string = "dummy_answer"
405        answer_count = "0"
406        is_array_string = "GL_FALSE"
407
408        for param in f.parameterIterateOutputs():
409            answer_type = param.get_base_type_string()
410            if answer_type == "GLvoid":
411                answer_type = "GLubyte"
412
413
414            c = param.get_element_count()
415            type_size = (param.size() / c)
416            if type_size == 1:
417                size_scale = ""
418            else:
419                size_scale = " * %u" % (type_size)
420
421
422            if param.count_parameter_list:
423                print '        const GLuint compsize = %s;' % (self.size_call(f, 1))
424                print '        %s answerBuffer[200];' %  (answer_type)
425                print '        %s %s = __glXGetAnswerBuffer(cl, compsize%s, answerBuffer, sizeof(answerBuffer), %u);' % (param.type_string(), param.name, size_scale, type_size )
426                answer_string = param.name
427                answer_count = "compsize"
428
429                print ''
430                print '        if (%s == NULL) return BadAlloc;' % (param.name)
431                print '        __glXClearErrorOccured();'
432                print ''
433            elif param.counter:
434                print '        %s answerBuffer[200];' %  (answer_type)
435                print '        %s %s = __glXGetAnswerBuffer(cl, %s%s, answerBuffer, sizeof(answerBuffer), %u);' % (param.type_string(), param.name, param.counter, size_scale, type_size)
436                answer_string = param.name
437                answer_count = param.counter
438                print ''
439                print '        if (%s == NULL) return BadAlloc;' % (param.name)
440                print '        __glXClearErrorOccured();'
441                print ''
442            elif c >= 1:
443                print '        %s %s[%u];' % (answer_type, param.name, c)
444                answer_string = param.name
445                answer_count = "%u" % (c)
446
447            if f.reply_always_array:
448                is_array_string = "GL_TRUE"
449
450
451        self.emit_function_call(f, retval_assign, "    ")
452
453
454        if f.needs_reply():
455            if self.do_swap:
456                for param in f.parameterIterateOutputs():
457                    c = param.get_element_count()
458                    type_size = (param.size() / c)
459
460                    if type_size > 1:
461                        swap_name = self.swap_name( type_size )
462                        print '        (void) %s( (uint%u_t *) %s, %s );' % (swap_name, 8 * type_size, param.name, answer_count)
463
464
465                reply_func = '__glXSendReplySwap'
466            else:
467                reply_func = '__glXSendReply'
468
469            print '        %s(cl->client, %s, %s, %u, %s, %s);' % (reply_func, answer_string, answer_count, type_size, is_array_string, retval_string)
470        #elif f.note_unflushed:
471        #	print '        cx->hasUnflushedCommands = GL_TRUE;'
472
473        print '        error = Success;'
474        print '    }'
475        print ''
476        print '    return error;'
477        return
478
479
480    def printRenderFunction(self, f):
481        # There are 4 distinct phases in a rendering dispatch function.
482        # In the first phase we compute the sizes and offsets of each
483        # element in the command.  In the second phase we (optionally)
484        # re-align 64-bit data elements.  In the third phase we
485        # (optionally) byte-swap array data.  Finally, in the fourth
486        # phase we actually dispatch the function.
487
488        self.common_func_print_just_start(f, "")
489
490        images = f.get_images()
491        if len(images):
492            if self.do_swap:
493                pre = "bswap_CARD32( & "
494                post = " )"
495            else:
496                pre = ""
497                post = ""
498
499            img = images[0]
500
501            # swapBytes and lsbFirst are single byte fields, so
502            # the must NEVER be byte-swapped.
503
504            if not (img.img_type == "GL_BITMAP" and img.img_format == "GL_COLOR_INDEX"):
505                print '    glPixelStorei(GL_UNPACK_SWAP_BYTES, hdr->swapBytes);'
506
507            print '    glPixelStorei(GL_UNPACK_LSB_FIRST, hdr->lsbFirst);'
508
509            print '    glPixelStorei(GL_UNPACK_ROW_LENGTH, (GLint) %shdr->rowLength%s);' % (pre, post)
510            if img.depth:
511                print '    glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, (GLint) %shdr->imageHeight%s);' % (pre, post)
512            print '    glPixelStorei(GL_UNPACK_SKIP_ROWS, (GLint) %shdr->skipRows%s);' % (pre, post)
513            if img.depth:
514                print '    glPixelStorei(GL_UNPACK_SKIP_IMAGES, (GLint) %shdr->skipImages%s);' % (pre, post)
515            print '    glPixelStorei(GL_UNPACK_SKIP_PIXELS, (GLint) %shdr->skipPixels%s);' % (pre, post)
516            print '    glPixelStorei(GL_UNPACK_ALIGNMENT, (GLint) %shdr->alignment%s);' % (pre, post)
517            print ''
518
519
520        self.emit_function_call(f, "", "")
521        return
522
523
524def _parser():
525    """Parse any arguments passed and return a namespace."""
526    parser = argparse.ArgumentParser()
527    parser.add_argument('-f',
528                        dest='filename',
529                        default='gl_API.xml',
530                        help='an xml file describing an OpenGL API')
531    parser.add_argument('-m',
532                        dest='mode',
533                        default='dispatch_c',
534                        choices=['dispatch_c', 'dispatch_h'],
535                        help='what file to generate')
536    parser.add_argument('-s',
537                        dest='swap',
538                        action='store_true',
539                        help='emit swap in GlXDispatchFunctions')
540    return parser.parse_args()
541
542
543def main():
544    """Main function."""
545    args = _parser()
546
547    if args.mode == "dispatch_c":
548        printer = PrintGlxDispatchFunctions(args.swap)
549    elif args.mode == "dispatch_h":
550        printer = PrintGlxDispatch_h()
551
552    api = gl_XML.parse_GL_API(
553        args.filename, glX_proto_common.glx_proto_item_factory())
554
555    printer.Print(api)
556
557
558if __name__ == '__main__':
559    main()
560