How to use vispy - 10 common examples

To help you get started, we’ve selected a few vispy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github vispy / vispy / examples / demo / gloo / realtime_signals.py View on Github external
void main() {
    gl_FragColor = v_color;

    // Discard the fragments between the signals (emulate glMultiDrawArrays).
    if ((fract(v_index.x) > 0.) || (fract(v_index.y) > 0.))
        discard;

    // Clipping test.
    vec2 test = abs((v_position.xy-v_ab.zw)/v_ab.xy);
    if ((test.x > 1) || (test.y > 1))
        discard;
}
"""


class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, title='Use your wheel to zoom!',
                            keys='interactive')
        self.program = gloo.Program(VERT_SHADER, FRAG_SHADER)
        self.program['a_position'] = y.reshape(-1, 1)
        self.program['a_color'] = color
        self.program['a_index'] = index
        self.program['u_scale'] = (1., 1.)
        self.program['u_size'] = (nrows, ncols)
        self.program['u_n'] = n

        gloo.set_viewport(0, 0, *self.physical_size)

        self._timer = app.Timer('auto', connect=self.on_timer, start=True)

        gloo.set_state(clear_color='black', blend=True,
github vispy / vispy / examples / tutorial / gloo / textured_quad.py View on Github external
uniform sampler2D texture;
    varying vec2 v_texcoord;
    void main()
    {
        gl_FragColor = texture2D(texture, v_texcoord);
    } """


def checkerboard(grid_num=8, grid_size=32):
    row_even = grid_num // 2 * [0, 1]
    row_odd = grid_num // 2 * [1, 0]
    Z = np.row_stack(grid_num // 2 * (row_even, row_odd)).astype(np.uint8)
    return 255 * Z.repeat(grid_size, axis=0).repeat(grid_size, axis=1)


class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, size=(512, 512), title='Textured quad',
                            keys='interactive')

        # Build program & data
        self.program = Program(vertex, fragment, count=4)
        self.program['position'] = [(-1, -1), (-1, +1),
                                    (+1, -1), (+1, +1)]
        self.program['texcoord'] = [(0, 0), (1, 0), (0, 1), (1, 1)]
        self.program['texture'] = checkerboard()

        gloo.set_viewport(0, 0, *self.physical_size)

        self.show()

    def on_draw(self, event):
github vispy / vispy / examples / basics / visuals / modular_mesh.py View on Github external
# Lay out meshes in a grid
        grid = (3, 3)
        s = 300. / max(grid)
        for i, mesh in enumerate(self.meshes):
            x = 800. * (i % grid[0]) / grid[0] + 400. / grid[0] - 2
            y = 800. * (i // grid[1]) / grid[1] + 400. / grid[1] + 2
            mesh.transform = ChainTransform([STTransform(translate=(x, y),
                                                         scale=(s, s, 1)),
                                             self.rotation])
            mesh.tr_sys = visuals.transforms.TransformSystem(self)
            mesh.tr_sys.visual_to_document = mesh.transform

        self.show()

        self.timer = app.Timer(connect=self.rotate)
        self.timer.start(0.016)
github vispy / vispy / examples / basics / visuals / mesh.py View on Github external
self.meshes.append(visuals.MeshVisual(verts, faces, vcolor,
                                              shading='flat'))
        self.meshes.append(visuals.MeshVisual(verts, faces, vcolor,
                                              shading='smooth'))

        # Lay out meshes in a grid
        grid = (3, 3)
        s = 300. / max(grid)
        for i, mesh in enumerate(self.meshes):
            x = 800. * (i % grid[0]) / grid[0] + 400. / grid[0] - 2
            y = 800. * (i // grid[1]) / grid[1] + 400. / grid[1] + 2
            transform = ChainTransform([STTransform(translate=(x, y),
                                                    scale=(s, s, s)),
                                        self.rotation])
            mesh.transform = transform
            mesh.transforms.scene_transform = STTransform(scale=(1, 1, 0.01))

        self.show()

        self.timer = app.Timer(connect=self.rotate)
        self.timer.start(0.016)
github janpipek / physt / examples / test_vispy.py View on Github external
from physt import h2, h3, plotting
from physt.plotting import vispy as vp
import numpy as np
from matplotlib import pyplot as plt
from vispy import app

data = np.random.normal(0, 10, (1000, 3))
print(data)

H = h3(data)
vp.voxel(H)

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

"""
# -*- coding: utf-8 -*-
github vispy / vispy / examples / benchmark / scene_test_2.py View on Github external
title="VisualCanvas")

    # Scenegraph version
    scanvas = scene.SceneCanvas(show=True, keys='interactive', 
                                title="SceneCanvas")
    
    scanvas.size = 800, 600
    grid = scanvas.central_widget.add_grid(margin=0)

    lines = []
    for i in range(10):
        lines.append([])
        for j in range(10):
            vb = grid.add_view(camera='panzoom', row=i, col=j)
            vb.camera.set_range([0, 100], [-5, 5], margin=0)
            line = scene.visuals.Line(pos=data, color='w', method='gl')
            vb.add(line)
    scanvas.show()

    import sys
    if sys.flags.interactive != 1:
        app.run()
github alifelab / alife_book_src / test / vispy_test10.py View on Github external
def __init__(self, x, y, w, h):
        # Initialize the visual with a vertex shader and fragment shader
        visuals.Visual.__init__(self, vertex_shader, fragment_shader)

        # vertices for two triangles forming a rectangle
        self.vbo = gloo.VertexBuffer(np.array([
            [x, y], [x+w, y], [x+w, y+h],
            [x, y], [x+w, y+h], [x, y+h]
        ], dtype=np.float32))

        # Assign values to the $position and $color template variables in
        # the shaders. ModularProgram automatically handles generating the
        # necessary attribute and uniform declarations with unique variable
        # names.
        self.shared_program.vert['position'] = self.vbo
        self.shared_program.frag['color'] = (1, 0, 0, 1)
        self._draw_mode = 'triangles'
github vispy / vispy / vispy / util / _testing.py View on Github external
out += 'Backend:  %s\n' % this_app.backend_name
        out += 'Qt:       %s\n' % backends.has_qt(return_which=True)[1]
        out += 'Pyglet:   %s\n' % backends.has_pyglet(return_which=True)[1]
        out += 'glfw:     %s\n' % backends.has_glfw(return_which=True)[1]
        out += 'glut:     %s\n' % backends.has_glut(return_which=True)[1]
        out += '\n'
        # We need an OpenGL context to get GL info
        if 'glut' in this_app.backend_name.lower():
            # glut causes problems
            out += 'OpenGL information omitted for glut backend\n'
        else:
            canvas = Canvas('Test', (10, 10), show=False, app=this_app)
            canvas._backend._vispy_set_current()
            out += 'GL version:  %s\n' % gl.glGetParameter(gl.GL_VERSION)
            x_ = gl.GL_MAX_TEXTURE_SIZE
            out += 'MAX_TEXTURE_SIZE: %d\n' % gl.glGetParameter(x_)
            out += 'Extensions: %s\n' % gl.glGetParameter(gl.GL_EXTENSIONS)
            canvas.close()
    except Exception:  # don't stop printing info
        out += '\nInfo-gathering error:\n%s' % traceback.format_exc()
        pass
    if fname is not None:
        with open(fname, 'w') as fid:
            fid.write(out)
    return out
github vispy / vispy / doc / ext / gloooverviewgenerator.py View on Github external
def get_docs_for_class(klass):
    """ Get props and methods for a class.
    """

    # Prepare
    baseatts = dir(gloo.GLObject)
    functype = type(gloo.GLObject.delete)
    proptype = type(gloo.GLObject.id)
    props, funcs = set(), set()

    for att in sorted(dir(klass)):
        if att.startswith('_') or att.lower() != att:
            continue
        # Get ob and module name
        attob = getattr(klass, att)
        modulename = klass.__module__.split('.')[-1]
        # Get actual klass
        actualklass = klass
        while True:
            tmp = actualklass.__base__
            if att in dir(tmp):
                actualklass = tmp
            else:
                break
github aigamedev / nuclai16 / animation / display.py View on Github external
self.colors.append(color)
            line = vispy.scene.Line(parent=self.view.scene, color=color, connect='strip', method='agg', width=path_width)
            line.transform = vispy.visuals.transforms.MatrixTransform()
            self.lines.append(line)

        self.timer_toggle = True
        self.player_position = numpy.asarray([0,0])
        if not os.path.exists('dota2.csv'):
            print("ERROR: Please download and extract this file...\nhttps://github.com/aigamedev/nuclai16/releases/download/0.0/dota2.csv.bz2\n")
            sys.exit(-1)
        self.data = data.Data('dota2.csv', self.params)
        # init the searched point with some random value - after first mouse move it's a
        self.data.mouse_xy = ( ( numpy.random.rand(2) * 10 - 5 ) - numpy.asarray(self.canvas.size) / 2 ) * self.params.SCALE_FACTOR

        self.grid = vispy.scene.visuals.GridLines(parent=self.view.scene, color=(1, 1, 1, 1))
        self.grid.transform = vispy.visuals.transforms.MatrixTransform()
        self.grid.transform.translate(numpy.asarray(self.canvas.size) / 2)
        self.canvas.show(visible=True)
        # HACK: Bug in VisPy 0.5.0-dev requires a click for layout to occur.
        self.canvas.events.mouse_press()


        @self.canvas.events.key_press.connect
        def on_key_press(event):
            if event.key.name == ' ':
                if self.timer_toggle: self.timer.stop()
                else: self.timer.start()
                self.timer_toggle = not self.timer_toggle


        @self.canvas.events.resize.connect
        def on_resize(event):