File: annotations.py

package info (click to toggle)
python-vispy 0.16.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 9,112 kB
  • sloc: python: 61,648; javascript: 6,800; ansic: 2,104; makefile: 141; sh: 6
file content (687 lines) | stat: -rw-r--r-- 17,718 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
# -*- coding: utf-8 -*-
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.

""" 
This module contains manual annotations for the gl backends. Together
with the header files, we can generatre the full ES 2.0 API.

Every function-annotations consists of sections that apply to one or
more backends. If no backends are specified in the first section, it
applies to all backends.
"""

import ctypes


# bind / gen / delete stuff


def deleteBuffer(buffer):
    # --- gl es
    n = 1  
    buffers = (ctypes.c_uint*n)(buffer)  
    ()  
    # --- pyopengl
    GL.glDeleteBuffers(1, [buffer])


def deleteFramebuffer(framebuffer):
    # --- gl es
    n = 1  
    framebuffers = (ctypes.c_uint*n)(framebuffer)  
    ()
    # --- pyopengl
    FBO.glDeleteFramebuffers(1, [framebuffer])


def deleteRenderbuffer(renderbuffer):
    # --- gl es
    n = 1  
    renderbuffers = (ctypes.c_uint*n)(renderbuffer)  
    ()
    # --- pyopengl
    FBO.glDeleteRenderbuffers(1, [renderbuffer])


def deleteTexture(texture):
    # --- gl es
    n = 1  
    textures = (ctypes.c_uint*n)(texture)  
    ()
    # --- pyopengl
    GL.glDeleteTextures([texture])


def createBuffer():
    # --- gl es
    n = 1
    buffers = (ctypes.c_uint*n)()
    ()  
    return buffers[0]
    # --- pyopengl
    return GL.glGenBuffers(1)
    # --- mock
    return 1


def createFramebuffer():
    # --- gl es
    n = 1
    framebuffers = (ctypes.c_uint*n)()
    ()
    return framebuffers[0]
    # --- pyopengl
    return FBO.glGenFramebuffers(1)
    # --- mock
    return 1


def createRenderbuffer():
    # --- gl es
    n = 1
    renderbuffers = (ctypes.c_uint*n)()
    ()
    return renderbuffers[0]
    # --- pyopengl
    return FBO.glGenRenderbuffers(1)
    # --- mock
    return 1


def createTexture():
    # --- gl es
    n = 1
    textures = (ctypes.c_uint*n)()
    ()
    return textures[0]
    # --- pyopengl
    return GL.glGenTextures(1)
    # --- mock
    return 1


# Image stuff
def texImage2D(target, level, internalformat, format, type, pixels):
    border = 0
    # --- gl es
    if isinstance(pixels, (tuple, list)):
        height, width = pixels
        pixels = ctypes.c_void_p(0)
        pixels = None
    else:
        if not pixels.flags['C_CONTIGUOUS']:
            pixels = pixels.copy('C')
        pixels_ = pixels
        pixels = pixels_.ctypes.data
        height, width = pixels_.shape[:2]
    ()
    # --- pyopengl
    if isinstance(pixels, (tuple, list)):
        height, width = pixels
        pixels = None
    else:
        height, width = pixels.shape[:2]
    GL.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels)
    

def texSubImage2D(target, level, xoffset, yoffset, format, type, pixels):
    # --- gl es
    if not pixels.flags['C_CONTIGUOUS']:
        pixels = pixels.copy('C')
    pixels_ = pixels
    pixels = pixels_.ctypes.data
    height, width = pixels_.shape[:2]
    ()
    # --- pyopengl
    height, width = pixels.shape[:2]
    GL.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels)


def readPixels(x, y, width, height, format, type):
    # --- es
    # GL_ALPHA, GL_RGB, GL_RGBA
    t = {6406:1, 6407:3, 6408:4}[format]
    # --- gl mock
    # GL_ALPHA, GL_RGB, GL_RGBA, GL_DEPTH_COMPONENT
    t = {6406:1, 6407:3, 6408:4, 6402:1}[format]
    # --- gl es mock
    # GL_UNSIGNED_BYTE, GL_FLOAT
    nb = {5121:1, 5126:4}[type]
    size = int(width*height*t*nb)
    # --- gl es
    pixels = ctypes.create_string_buffer(size)
    ()
    return pixels[:]
    # --- mock
    return size * b'\x00'


def compressedTexImage2D(target, level, internalformat, width, height, border=0, data=None):
    # border = 0  # set in args
    # --- gl es
    if not data.flags['C_CONTIGUOUS']:
        data = data.copy('C')
    data_ = data
    size = data_.size
    data = data_.ctypes.data
    ()
    # --- pyopengl
    size = data.size
    GL.glCompressedTexImage2D(target, level, internalformat, width, height, border, size, data)


def compressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, data):
    # --- gl es
    if not data.flags['C_CONTIGUOUS']:
        data = data.copy('C')
    data_ = data
    size = data_.size
    data = data_.ctypes.data
    ()
    # --- pyopengl
    size = data.size
    GL.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, size, data)


# Buffer data


def bufferData(target, data, usage):
    """Data can be numpy array or the size of data to allocate."""
    # --- gl es
    if isinstance(data, int):
        size = data
        data = ctypes.c_voidp(0)
    else:
        if not data.flags['C_CONTIGUOUS'] or not data.flags['ALIGNED']:
            data = data.copy('C')
        data_ = data
        size = data_.nbytes
        data = data_.ctypes.data
    ()
    # --- pyopengl
    if isinstance(data, int):
        size = data
        data = None
    else:
        size = data.nbytes
    GL.glBufferData(target, size, data, usage)


def bufferSubData(target, offset, data):
    # --- gl es
    if not data.flags['C_CONTIGUOUS']:
        data = data.copy('C')
    data_ = data
    size = data_.nbytes
    data = data_.ctypes.data
    ()
    # --- pyopengl
    size = data.nbytes
    GL.glBufferSubData(target, offset, size, data)


def drawElements(mode, count, type, offset):
    # --- gl es
    if offset is None:
        offset = ctypes.c_void_p(0)
    elif isinstance(offset, ctypes.c_void_p):
        pass
    elif isinstance(offset, (int, ctypes.c_int)):
        offset = ctypes.c_void_p(int(offset))
    else:
        if not offset.flags['C_CONTIGUOUS']:
            offset = offset.copy('C')
        offset_ = offset
        offset = offset.ctypes.data
    indices = offset
    ()
    # --- pyopengl
    if offset is None:
        offset = ctypes.c_void_p(0)
    elif isinstance(offset, (int, ctypes.c_int)):
        offset = ctypes.c_void_p(int(offset))
    ()


def vertexAttribPointer(indx, size, type, normalized, stride, offset):
    # --- gl es
    if offset is None:
        offset = ctypes.c_void_p(0)
    elif isinstance(offset, ctypes.c_void_p):
        pass
    elif isinstance(offset, (int, ctypes.c_int)):
        offset = ctypes.c_void_p(int(offset))
    else:
        if not offset.flags['C_CONTIGUOUS']:
            offset = offset.copy('C')
        offset_ = offset
        offset = offset.ctypes.data
        # We need to ensure that the data exists at draw time :(
        # PyOpenGL does this too
        key = '_vert_attr_'+str(indx)
        setattr(glVertexAttribPointer, key, offset_)
    ptr = offset
    ()
    # --- pyopengl
    if offset is None:
        offset = ctypes.c_void_p(0)
    elif isinstance(offset, (int, ctypes.c_int)):
        offset = ctypes.c_void_p(int(offset))
    ()


def bindAttribLocation(program, index, name):
    # --- gl es
    name = ctypes.c_char_p(name.encode('utf-8'))
    ()
    # --- pyopengl
    name = name.encode('utf-8')
    ()


# Setters


def shaderSource(shader, source):
    # Some implementation do not like getting a list of single chars
    if isinstance(source, (tuple, list)):
        strings = [s for s in source]
    else:
        strings = [source]
    # --- gl es
    count = len(strings)  
    string = (ctypes.c_char_p*count)(*[s.encode('utf-8') for s in strings])  
    length = (ctypes.c_int*count)(*[len(s) for s in strings])  
    ()
    # --- pyopengl
    GL.glShaderSource(shader, strings)


# Getters

def _getBooleanv(pname):
    # --- gl es
    params = (ctypes.c_bool*1)()
    ()
    return params[0]


def _getIntegerv(pname):
    # --- gl es
    n = 16
    d = -2**31  # smallest 32bit integer
    params = (ctypes.c_int*n)(*[d for i in range(n)])
    ()
    params = [p for p in params if p!=d]
    if len(params) == 1:
        return params[0]
    else:
        return tuple(params)


def _getFloatv(pname):
    # --- gl es
    n = 16
    d = float('Inf')
    params = (ctypes.c_float*n)(*[d for i in range(n)])
    ()
    params = [p for p in params if p!=d]
    if len(params) == 1:
        return params[0]
    else:
        return tuple(params)

# def _getString(pname):
#     # --- gl es
#     ()
#     return res.value
#     # --- mock
#     return ''


def getParameter(pname):
    if pname in [33902, 33901, 32773, 3106, 2931, 2928, 
                 2849, 32824, 10752, 32938]:
        # GL_ALIASED_LINE_WIDTH_RANGE GL_ALIASED_POINT_SIZE_RANGE
        # GL_BLEND_COLOR GL_COLOR_CLEAR_VALUE GL_DEPTH_CLEAR_VALUE
        # GL_DEPTH_RANGE GL_LINE_WIDTH GL_POLYGON_OFFSET_FACTOR
        # GL_POLYGON_OFFSET_UNITS GL_SAMPLE_COVERAGE_VALUE
        # --- gl es
        return _glGetFloatv(pname)
        # --- pyopengl
        return GL.glGetFloatv(pname)
        # /---
    elif pname in [7936, 7937, 7938, 35724, 7939]:
        # GL_VENDOR, GL_RENDERER, GL_VERSION, GL_SHADING_LANGUAGE_VERSION, 
        # GL_EXTENSIONS are strings
        pass  # string handled below
    else:
        # --- gl es
        return _glGetIntegerv(pname)
        # --- pyopengl
        return GL.glGetIntegerv(pname)
        # /---
    # --- gl es
    name = pname
    ()
    return ctypes.string_at(res).decode('utf-8') if res else ''
    # --- pyopengl
    res = GL.glGetString(pname)
    return res.decode('utf-8')


def getUniform(program, location):
    # --- gl es
    n = 16
    d = float('Inf')
    params = (ctypes.c_float*n)(*[d for i in range(n)])
    ()
    params = [p for p in params if p!=d]
    if len(params) == 1:
        return params[0]
    else:
        return tuple(params)
    # --- pyopengl
    n = 16
    d = float('Inf')
    params = (ctypes.c_float*n)(*[d for i in range(n)])
    GL.glGetUniformfv(program, location, params)
    params = [p for p in params if p!=d]
    if len(params) == 1:
        return params[0]
    else:
        return tuple(params)


def getVertexAttrib(index, pname):
    # --- gl es
    n = 4
    d = float('Inf')
    params = (ctypes.c_float*n)(*[d for i in range(n)])
    ()
    params = [p for p in params if p!=d]
    if len(params) == 1:
        return params[0]
    else:
        return tuple(params)
    # --- pyopengl
    # From PyOpenGL v3.1.0 the glGetVertexAttribfv(index, pname) does
    # work, but it always returns 4 values, with zeros in the empty
    # spaces. We have no way to tell whether they are empty or genuine
    # zeros. Fortunately, pyopengl also supports the old syntax.
    n = 4
    d = float('Inf')
    params = (ctypes.c_float*n)(*[d for i in range(n)])
    GL.glGetVertexAttribfv(index, pname, params)
    params = [p for p in params if p!=d]
    if len(params) == 1:
        return params[0]
    else:
        return tuple(params)


def getTexParameter(target, pname):
    # --- gl es
    d = float('Inf')
    params = (ctypes.c_float*1)(d)
    ()
    return params[0]


def getActiveAttrib(program, index):
    # --- gl es pyopengl
    bufsize = 256
    # --- gl es
    length = (ctypes.c_int*1)()
    size = (ctypes.c_int*1)()
    type = (ctypes.c_uint*1)()
    name = ctypes.create_string_buffer(bufsize)
    # --- gl es
    ()
    name = name[:length[0]].decode('utf-8')
    return name, size[0], type[0]
    # --- pyopengl
    name, size, type = GL.glGetActiveAttrib(program, index, bufSize=bufsize)
    return name.decode('utf-8'), size, type
    # --- mock
    return 'mock_val', 1, 5126


def getVertexAttribOffset(index, pname):
    # --- gl es
    pointer = (ctypes.c_void_p*1)()
    ()
    return pointer[0] or 0
    # --- pyopengl
    try:  # maybe the fixed it
        ()
    except TypeError:
        pointer = (ctypes.c_void_p*1)()
        GL.glGetVertexAttribPointerv(index, pname, pointer)
        return pointer[0] or 0
    # --- mock
    return 0

    
def getActiveUniform(program, index):
    # --- gl es
    bufsize = 256
    length = (ctypes.c_int*1)()
    size = (ctypes.c_int*1)()
    type = (ctypes.c_uint*1)()
    name = ctypes.create_string_buffer(bufsize)
    ()
    name = name[:length[0]].decode('utf-8')
    return name, size[0], type[0]
    # --- pyopengl
    name, size, type = GL.glGetActiveUniform(program, index)
    return name.decode('utf-8'), size, type


def getAttachedShaders(program):
    # --- gl es
    maxcount = 256
    count = (ctypes.c_int*1)()
    shaders = (ctypes.c_uint*maxcount)()
    ()
    return tuple(shaders[:count[0]])


def getAttribLocation(program, name):
    # --- gl es
    name = ctypes.c_char_p(name.encode('utf-8'))
    ()
    return res
    # --- pyopengl
    name = name.encode('utf-8')
    ()
    

def getUniformLocation(program, name):
    # --- gl es
    name = ctypes.c_char_p(name.encode('utf-8'))
    ()
    return res
    # --- pyopengl
    name = name.encode('utf-8')
    ()


def getProgramInfoLog(program):
    # --- gl es
    bufsize = 1024
    length = (ctypes.c_int*1)()
    infolog = ctypes.create_string_buffer(bufsize)
    ()
    return infolog[:length[0]].decode('utf-8')
    # --- pyopengl
    res = GL.glGetProgramInfoLog(program)
    return res.decode('utf-8') if isinstance(res, bytes) else res


def getShaderInfoLog(shader):
    # --- gl es
    bufsize = 1024
    length = (ctypes.c_int*1)()
    infolog = ctypes.create_string_buffer(bufsize)
    ()
    return infolog[:length[0]].decode('utf-8')
    # --- pyopengl
    res = GL.glGetShaderInfoLog(shader)
    return res.decode('utf-8') if isinstance(res, bytes) else res


def getProgramParameter(program, pname):
    # --- gl es
    params = (ctypes.c_int*1)()
    ()
    return params[0]


def getShaderParameter(shader, pname):
    # --- gl es
    params = (ctypes.c_int*1)()
    ()
    return params[0]


def getShaderPrecisionFormat(shadertype, precisiontype):
    # --- gl es
    range = (ctypes.c_int*1)()
    precision = (ctypes.c_int*1)()
    ()
    return range[0], precision[0]


def getShaderSource(shader):
    # --- gl es
    bufsize = 1024*1024
    length = (ctypes.c_int*1)()
    source = (ctypes.c_char*bufsize)()
    ()
    return source.value[:length[0]].decode('utf-8')
    # --- pyopengl
    res = GL.glGetShaderSource(shader)
    return res.decode('utf-8')
    

def getBufferParameter(target, pname):
    # --- gl es
    d = -2**31  # smallest 32bit integer
    params = (ctypes.c_int*1)(d)
    ()
    return params[0]


def getFramebufferAttachmentParameter(target, attachment, pname):
    # --- gl es
    d = -2**31  # smallest 32bit integer
    params = (ctypes.c_int*1)(d)
    ()
    return params[0]
    # --- pyopengl
    d = -2**31  # smallest 32bit integer
    params = (ctypes.c_int*1)(d)
    FBO.glGetFramebufferAttachmentParameteriv(target, attachment, pname, params)
    return params[0]


def getRenderbufferParameter(target, pname):
    # --- gl es
    d = -2**31  # smallest 32bit integer
    params = (ctypes.c_int*1)(d)
    ()
    return params[0]
    # --- pyopengl
    d = -2**31  # smallest 32bit integer
    params = (ctypes.c_int*1)(d)
    FBO.glGetRenderbufferParameteriv(target, pname, params)
    return params[0]



## ============================================================================


class FunctionAnnotation:
    def __init__(self, name, args, output):
        self.name = name
        self.args = args
        self.output = output
        self.lines = []  # (line, comment) tuples
    
    def __repr__(self):
        return '<FunctionAnnotation for %s>' % self.name
        
    def get_lines(self, call, backend):
        """ Get the lines for this function based on the given backend. 
        The given API call is inserted at the correct location.
        """
        if backend is None:
            raise RuntimeError("Backend must be specified!")
        backend_selector = (backend, )  # first lines are for all backends
        lines = []
        for line in self.lines:
            if line.lstrip().startswith('# ---'):
                backend_selector = line.strip().split(' ')
                continue
            if line.lstrip().startswith('# /---'):
                backend_selector = backend
                continue
            if backend in backend_selector:
                if line.strip() == '()':
                    indent = line.split('(')[0][4:]
                    line = indent + call
                lines.append(line)
        return lines
    
    def is_arg_set(self, name):
        """Get whether a given variable name is set.

        This allows checking whether a variable that is an input to the C
        function is not an input for the Python function, and may be an output.

        """
        needle = '%s =' % name
        for line, comment in self.lines:
            if line.startswith(needle):
                return True
        else:
            return False


def parse_anotations():
    """Parse this annotations file and produce a dictionary of FunctionAnnotation objects."""
    functions = {}
    function = None
    
    for line in open(__file__, 'rt').readlines():
        # Stop?
        if '='*40 in line:
            break
        
        if line.startswith('def '):
            name = line.split(' ')[1].split('(')[0]
            args = line.split('(')[1].split(')')[0].split(', ')
            args = [arg for arg in args if arg]
            out = line.partition('->')[2].strip()
            function = FunctionAnnotation(name, args, out)
            functions[name] = function
            continue
        elif not function:
            continue
        
        # Add line
        line = line.rstrip()
        indent = len(line) - len(line.strip())
        if line.strip() and indent >= 4:
            function.lines.append(line)

    return functions


if __name__ == '__main__':
    print(parse_anotations().keys())