File: sandbox.py

package info (click to toggle)
python-vispy 0.6.6-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 21,240 kB
  • sloc: python: 57,407; javascript: 6,810; makefile: 63; sh: 5
file content (618 lines) | stat: -rw-r--r-- 14,615 bytes parent folder | download | duplicates (2)
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
# -*- coding: utf-8 -*-
# vispy: testskip
# -----------------------------------------------------------------------------
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
"""
Sandbox for experimenting with vispy.visuals.shaders
"""
from PyQt5 import QtCore
from PyQt5.QtWidgets import *  # noqa
import sys
import traceback

from editor import Editor, HAVE_QSCI


presets = [
    ('Introduction', '''
"""
             ------ Shader Composition Sandbox -------

Instructions:

1) Edit this code; it is immediately executed after every change. Exceptions
   will be displayed on the right side.

2) Assign strings to VERTEX and FRAGMENT variables (see below) and they will
   appear in the windows to the right.

3) Select presets from the list above to see a few examples.

"""


from vispy.visuals.shaders import ModularProgram

vertex_shader = "void main() {}"
fragment_shader = "void main() {}"

program = ModularProgram(vertex_shader, fragment_shader)

# obligatory: these variables are used to fill the text fields on the right.
program._compile()
VERTEX = program.vert_code
FRAGMENT = program.frag_code
'''),


    ('Simple hook', '''
"""
In this example we define a 'hook' in the vertex shader: a function prototype
with no definition. By leaving this function undefined, any new function
definition may be concatenated to the shader.
"""

from vispy.visuals.shaders import ModularProgram, Function

# The hook is called 'input_position', and is used to provide the
# value for gl_Position.
vertex_shader = """
vec4 input_position();

void main() {
    gl_Position = input_position();
}
"""

fragment_shader = """
void main() {
}
"""

# ModularProgram parses the shader code for function prototypes
# and registers each as a hook.
program = ModularProgram(vertex_shader, fragment_shader)

# Now we make a new function definition and attach it to the program.
func = Function("""
    vec4 input_position() {
        return vec4(0,0,0,0);
    }
    """)

program['input_position'] = func


# obligatory: these variables are used to fill the text fields on the right.
program._compile()
VERTEX = program.vert_code
FRAGMENT = program.frag_code
'''),


    ('Anonymous functions', '''
"""
Functions may optionally be defined with '$' in front of the function name.
This indicates that the function is anonymous (has no name) and thus may be
assigned any new name in the program.

The major benefit to using anonymous functions is that the modular shader
system is free to rename functions that would otherwise conflict with each
other.

In this example, an anonymous function is assigned to a hook. When it is
compiled into the complete program, it is renamed to match the hook.
"""

from vispy.visuals.shaders import ModularProgram, Function

vertex_shader = """
vec4 input_position();

void main() {
    gl_Position = input_position();
}
"""

fragment_shader = """
void main() {
}
"""

program = ModularProgram(vertex_shader, fragment_shader)

# Now we make a new function definition and attach it to the program.
# Note that this function is anonymous (name begins with '$') and does not
# have the correct name to be attached to the input_position hook.
func = Function("""
    vec4 $my_function() {
        return vec4(0,0,0,0);
    }
    """)

program['input_position'] = func


# obligatory: these variables are used to fill the text fields on the right.
program._compile()
VERTEX = program.vert_code
FRAGMENT = program.frag_code
'''),


    ('Program variables', '''
"""
Many Functions need to define their own program variables
(uniform/attribute/varying) in order to operate correctly. However, with many
independent functions added to a ModularProgram, it is likely that two
Functions might try to define variables of the same name.

To solve this, Functions may use $anonymous_variables that will be assigned to
a real program variable at compile time.

In the next example, we will see how ModularProgram resolves name conflicts.
"""

from vispy.visuals.shaders import ModularProgram, Function
import numpy as np

vertex_shader = """
vec4 transform_position(vec4);

attribute vec4 position_a;

void main() {
    gl_Position = transform_position(position_a);
}
"""

fragment_shader = """
void main() {
}
"""

program = ModularProgram(vertex_shader, fragment_shader)

# Define a function to do a matrix transform.
# The variable $matrix will be substituted with a uniquely-named program
# variable when the function is compiled.
func = Function("""
    vec4 $matrix_transform(vec4 pos) {
        return $matrix * pos;
    }
    """)

# The definition for 'matrix' must indicate the variable type and data type.
func['matrix'] = ('uniform', 'mat4', np.eye(4))


program.set_hook('transform_position', func)


# obligatory: these variables are used to fill the text fields on the right.
program._compile()
VERTEX = program.vert_code
FRAGMENT = program.frag_code

'''),


    ('Resolving name conflicts', '''
"""
When anonymous functions and variables have conflicting names, the
ModularProgram will generate unique names by appending _N to the end of the
name.

This example demonstrates dynamic naming of a program variable.
"""

from vispy.visuals.shaders import ModularProgram, Function
import numpy as np

vertex_shader = """
vec4 projection(vec4);
vec4 modelview(vec4);

attribute vec4 position_a;

void main() {
    gl_Position = projection(modelview(position_a));
}
"""

fragment_shader = """
void main() {
}
"""

program = ModularProgram(vertex_shader, fragment_shader)

# Define two identical functions
projection = Function("""
    vec4 $matrix_transform(vec4 pos) {
        return $matrix * pos;
    }
    """)
projection['matrix'] = ('uniform', 'mat4', np.eye(4))

modelview = Function("""
    vec4 $matrix_transform(vec4 pos) {
        return $matrix * pos;
    }
    """)
modelview['matrix'] = ('uniform', 'mat4', np.eye(4))


program.set_hook('projection', projection)
program.set_hook('modelview', modelview)


# obligatory: these variables are used to fill the text fields on the right.
program._compile()
VERTEX = program.vert_code
FRAGMENT = program.frag_code

'''),


    ('Function chaining', '''
"""
Function chains are another essential component of shader composition,
allowing a list of functions to be executed in order.
"""

from vispy.visuals.shaders import ModularProgram, Function, FunctionChain

# Added a new hook to allow any number of functions to be executed
# after gl_Position is set.
vertex_shader = """
void vert_post_hook();

attribute vec4 position_a;

void main() {
    gl_Position = position_a;
    vert_post_hook();
}
"""

fragment_shader = """
void main() {
}
"""

program = ModularProgram(vertex_shader, fragment_shader)

# Add a function to flatten the z-position of the vertex
flatten = Function("""
    void flatten_func() {
        gl_Position.z = 0;
    }
    """)

# Add another function that copies an attribute to a varying
# for use in the fragment shader
read_color_attr = Function("""
    void $read_color_attr() {
        $output = $input;
    }
    """)

# ..and set two new program variables:
# (note that no value is needed for varyings)
read_color_attr['output'] = ('varying', 'vec4')
read_color_attr['input'] = ('attribute', 'vec4', 'color_a')


# Now create a chain that calls both functions in sequence
post_chain = FunctionChain('vert_post_hook', [flatten, read_color_attr])

program.set_hook('vert_post_hook', post_chain)


# obligatory: these variables are used to fill the text fields on the right.
program._compile()
VERTEX = program.vert_code
FRAGMENT = program.frag_code
'''),


    ('Function composition', '''
"""
Chains may also be used to generate a function composition where the return
value of each function call supplies the input to the next argument.
Thus, the original input is transformed in a series steps.

This is most commonly used for passing vertex positions through a composition
of transform functions.
"""

from vispy.visuals.shaders import ModularProgram, Function, FunctionChain


vertex_shader = """
vec4 transform_chain(vec4);

attribute vec4 position_a;

void main() {
    gl_Position = transform_chain(position_a);
}
"""

fragment_shader = """
void main() {
}
"""

program = ModularProgram(vertex_shader, fragment_shader)

flatten = Function("""
    vec4 flatten_func(vec4 pos) {
        pos.z = 0;
        pos.w = 1;
        return pos;
    }
    """)

# Define a scaling function
scale = Function("""
    vec4 $scale_vertex(vec4 pos) {
        return pos * vec4($scale, 1);
    }
    """)
scale['scale'] = ('uniform', 'vec3', (2, 1, 1))

# Assigning a list of both functions to a program hook will gemerate a
# composition of functions:
program['transform_chain'] = [flatten, scale]

# Internally, this creates a FunctionChain:
# transform = FunctionChain('transform_chain', [flatten, scale])


# obligatory: these variables are used to fill the text fields on the right.
program._compile()
VERTEX = program.vert_code
FRAGMENT = program.frag_code

'''),


    ('Fragment shaders', '''
"""
Although the prior examples focused on vertex shaders, these concepts
apply equally well for fragment shaders.

However: fragment shaders have one limitation that makes them very
different--they lack attributes. In order to supply attribute data
to a fragment shader, we will need to introduce some supporting code
to the vertex shader.
"""

from vispy.visuals.shaders import (ModularProgram, Function, FunctionChain)
from vispy.gloo import VertexBuffer
import numpy as np

# we require a void hook in the vertex shader that can be used
# to attach supporting code for the fragment shader.
vertex_shader = """
void vert_post_hook();

attribute vec4 position_a

void main() {
    gl_Position = position_a;
    vert_post_hook();
}
"""

# add a hook to the fragment shader to allow arbitrary color input
fragment_shader = """
vec4 fragment_color();

void main() {
    gl_FragColor = fragment_color();
}
"""

program = ModularProgram(vertex_shader, fragment_shader)

# First, define a simple fragment color function and bind it to a varying
# input:
frag_func = Function("vec4 $frag_color_input() { return $f_input; }")
frag_func['f_input'] = ('varying', 'vec4')

# Attach to the program
program['fragment_color'] = frag_func

# Next, we need a vertex shader function that will supply input
# to the varying.
vert_func = Function("void $vert_color_input() { $v_output = $v_input; }")
colors = VertexBuffer(np.array([[1,1,1,1]], dtype=np.float32))
vert_func['v_input'] = ('attribute', 'vec4', colors)

# to ensure both the vertex function output and the fragment function input
# are attached to the same varying, we use the following syntax:
vert_func['v_output'] = frag_func['f_input']

# and attach this to the vertex shader
program['vert_post_hook'] = vert_func


# obligatory: these variables are used to fill the text fields on the right.
program._compile()
VERTEX = program.vert_code
FRAGMENT = program.frag_code
'''),


    ('Sub-hooks', '''
"""
"""

from vispy.visuals.shaders import (ModularProgram, Function, FunctionChain)
from vispy.gloo import VertexBuffer
import numpy as np

vertex_shader = """
void vert_post_hook();

void main() {
    gl_Position = vec4(0,0,0,0);
    vert_post_hook();
}
"""

fragment_shader = """
void main() {
}
"""

program = ModularProgram(vertex_shader, fragment_shader)

# Create a function that calls another function
vert_func = Function("""
void $vert_func() {
    $some_other_function();
}
""")


# Create the second function:
other_func = Function("""
void $other_func() {
    gl_Position.w = 1;
}
""")

# Assign other_func to the anonymous function call in vert_func:
vert_func['some_other_function'] = other_func

# The name assigned to other_func will be inserted in place of
# the function call in vert_func

program['vert_post_hook'] = vert_func

# obligatory: these variables are used to fill the text fields on the right.
program._compile()
VERTEX = program.vert_code
FRAGMENT = program.frag_code
'''),


]


qsci_note = """
#  [[ NOTE: Install PyQt.QsciScintilla for improved code editing ]]
#  [[ (Debian packages: python-qscintilla2 or python3-pyqt5.qsci ]]

"""
if not HAVE_QSCI:
    presets[0] = (presets[0][0], qsci_note + presets[0][1])


app = QApplication([])

win = QMainWindow()
cw = QWidget()
win.setCentralWidget(cw)
layout = QGridLayout()
cw.setLayout(layout)

editor = Editor(language='Python')
vertex = Editor(language='CPP')
fragment = Editor(language='CPP')
for i in range(3):
    editor.zoomOut()
    vertex.zoomOut()
    fragment.zoomOut()

hsplit = QSplitter(QtCore.Qt.Horizontal)
vsplit = QSplitter(QtCore.Qt.Vertical)

layout.addWidget(hsplit)
hsplit.addWidget(editor)
hsplit.addWidget(vsplit)
vsplit.addWidget(vertex)
vsplit.addWidget(fragment)

menubar = win.menuBar()

last_loaded = -1


def load_example(name):
    global last_loaded
    if isinstance(name, int):
        code = presets[name][1]
        editor.setText(code)
        last_loaded = name
    else:
        for i, preset in enumerate(presets):
            n, code = preset
            if n == name:
                editor.setText(code)
                last_loaded = i
                return


def load_next():
    global last_loaded
    try:
        load_example(last_loaded+1)
    except IndexError:
        pass


def mk_load_callback(name):
    return lambda: load_example(name)

example_menu = menubar.addMenu('Load example..')
for i, preset in enumerate(presets):
    name = preset[0]
    action = example_menu.addAction("%d. %s" % (i, name),
                                    mk_load_callback(name))

next_action = menubar.addAction("Next example", load_next)

win.show()
win.resize(1800, 1100)
hsplit.setSizes([900, 900])

load_example(0)


def update():
    code = editor.text()
    local = {}
    glob = {}
    try:
        exec(code, local, glob)
        vert = glob['VERTEX']
        frag = glob['FRAGMENT']
        editor.clear_marker()
    except Exception:
        vert = traceback.format_exc()
        frag = ""
        tb = sys.exc_info()[2]
        while tb is not None:
            #print(tb.tb_lineno, tb.tb_frame.f_code.co_filename)
            try:
                if tb.tb_frame.f_code.co_filename == '<string>':
                    editor.set_marker(tb.tb_lineno-1)
            except Exception:
                pass
            tb = tb.tb_next

    vertex.setText(vert)
    fragment.setText(frag)

editor.textChanged.connect(update)
update()

if __name__ == '__main__':
    app.exec_()