Ejemplo n.º 1
0
 def draw00(event):
     print('  {0:7}: {1}'.format('0', bgcolors[0]))
     if bgcolors[0] is not None:
         gl.glViewport(0, 0, *list(_win_size))
         gl.glClearColor(*bgcolors[0])
         gl.glClear(gl.GL_COLOR_BUFFER_BIT)
         gl.glFinish()
Ejemplo n.º 2
0
 def on_resize(self, event):
     width, height = event.size
     gl.glViewport(0, 0, width, height)
     self.projection = ortho(0, width, 0, height, -100, 100)
     self.u_size = width / 512.0
     self.program['u_projection'] = self.projection
     self.program['u_size'] = self.u_size
Ejemplo n.º 3
0
    def on_paint(self, event):

        # Set framebuffer input output
        self._program['u_texture'] = self._tex1
        self._fbo.attach_color(self._tex2)

        with self._fbo:
            # Init
            gl.glViewport(0, 0, im1.shape[1], im1.shape[0])
            gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
            # Draw
            self._program.draw(gl.GL_TRIANGLE_STRIP)

        # Draw to the normal color buffer (i.e. the screen)
        self._program['u_texture'] = self._tex2
        # Init
        gl.glViewport(0, 0, self.size[0], self.size[1])
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
        # Draw
        self._program.draw(gl.GL_TRIANGLE_STRIP)

        # Prepare for next round
        self._tex1, self._tex2 = self._tex2, self._tex1

        # Force redraw
        self.update()
Ejemplo n.º 4
0
 def draw11(event):
     print('  {0:7}: {1}'.format('1', bgcolors[1]))
     if bgcolors[1] is not None:
         gl.glViewport(0, 0, *list(_win_size))
         gl.glClearColor(*bgcolors[1])
         gl.glClear(gl.GL_COLOR_BUFFER_BIT)
         gl.glFinish()
Ejemplo n.º 5
0
def _test_functionality(backend):
    """Create app and canvas so we have a context. Then run tests."""
    # use the backend
    gl.use_gl(backend)

    with Canvas() as canvas:
        _clear_screen()

        # Prepare
        w, h = canvas.size
        gl.glViewport(0, 0, w, h)
        gl.glScissor(0, 0, w, h)  # touch
        gl.glClearColor(0.0, 0.0, 0.0, 1.0)

        # Setup visualization, ensure to do it in a draw event
        objects = _prepare_vis()
        _clear_screen()
        _draw1()
        _clear_screen()
        _draw2()
        _clear_screen()
        _draw3()

        # Clean up
        for delete_func, handle in objects:
            delete_func(handle)
        gl.glFinish()
Ejemplo n.º 6
0
 def on_paint(self, event):
     
     # Set framebuffer input output
     self._program['u_texture'] = self._tex1
     self._fbo.attach_color(self._tex2)
     
     with self._fbo:
         # Init
         gl.glViewport(0, 0, im1.shape[1], im1.shape[0])
         gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
         # Draw
         self._program.draw(gl.GL_TRIANGLE_STRIP)
     
     # Draw to the normal color buffer (i.e. the screen)
     self._program['u_texture'] = self._tex2
     # Init
     gl.glViewport(0, 0, self.size[0], self.size[1])
     gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
     # Draw
     self._program.draw(gl.GL_TRIANGLE_STRIP)
     
     # Prepare for next round
     self._tex1, self._tex2 = self._tex2, self._tex1
     
     # Force redraw
     self.update()
Ejemplo n.º 7
0
 def paint0(event):
     print('  {0:7}: {1}'.format(backend + '_0', bgcolors[0]))
     if bgcolors[0] is not None:
         gl.glViewport(0, 0, *list(_win_size))
         gl.glClearColor(*bgcolors[0])
         gl.glClear(gl.GL_COLOR_BUFFER_BIT)
         gl.glFinish()
Ejemplo n.º 8
0
 def on_resize(self, event):
     width, height = event.size
     gl.glViewport(0, 0, width, height)
     self.projection = ortho(0, width, 0, height, -100, 100)
     self.u_size = width / 512.0
     self.program['u_projection'] = self.projection
     self.program['u_size'] = self.u_size
Ejemplo n.º 9
0
def _test_functonality(backend):
    """ Create app and canvas so we have a context. Then run tests.
    """
    # use the backend
    gl.use_gl(backend)
    
    with Canvas() as canvas:
        _clear_screen()
        
        # Prepare
        w, h = canvas.size
        gl.glViewport(0, 0, w, h)
        gl.glScissor(0, 0, w, h)  # touch
        gl.glClearColor(0.0, 0.0, 0.0, 1.0)
        
        # Setup visualization, ensure to do it in a draw event
        objects = _prepare_vis()
        _clear_screen()
        _draw1()
        _clear_screen()
        _draw2()
        _clear_screen()
        _draw3()

        # Clean up
        for delete_func, handle in objects:
            delete_func(handle)
        gl.glFinish()
Ejemplo n.º 10
0
 def draw00(event):
     print("  {0:7}: {1}".format("0", bgcolors[0]))
     if bgcolors[0] is not None:
         gl.glViewport(0, 0, *list(_win_size))
         gl.glClearColor(*bgcolors[0])
         gl.glClear(gl.GL_COLOR_BUFFER_BIT)
         gl.glFinish()
Ejemplo n.º 11
0
    def on_initialize(self, event):
        # Build & activate program
        self.program = gl.glCreateProgram()
        vertex = gl.glCreateShader(gl.GL_VERTEX_SHADER)
        fragment = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
        gl.glShaderSource(vertex, vertex_code)
        gl.glShaderSource(fragment, fragment_code)
        gl.glCompileShader(vertex)
        gl.glCompileShader(fragment)
        gl.glAttachShader(self.program, vertex)
        gl.glAttachShader(self.program, fragment)
        gl.glLinkProgram(self.program)
        gl.glDetachShader(self.program, vertex)
        gl.glDetachShader(self.program, fragment)
        gl.glUseProgram(self.program)

        # Build vertex buffer
        n = 10000
        self.data = np.zeros(n,
                             dtype=[('lifetime', np.float32),
                                    ('start', np.float32, 3),
                                    ('end', np.float32, 3)])
        vbuffer = gl.glCreateBuffer()
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbuffer)
        gl.glBufferData(gl.GL_ARRAY_BUFFER, self.data, gl.GL_DYNAMIC_DRAW)

        # Bind buffer attributes
        stride = self.data.strides[0]

        offset = 0
        loc = gl.glGetAttribLocation(self.program, "lifetime")
        gl.glEnableVertexAttribArray(loc)
        gl.glVertexAttribPointer(loc, 1, gl.GL_FLOAT, False, stride, offset)

        offset = self.data.dtype["lifetime"].itemsize
        loc = gl.glGetAttribLocation(self.program, "start")
        gl.glEnableVertexAttribArray(loc)
        gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, stride, offset)

        offset = self.data.dtype["start"].itemsize
        loc = gl.glGetAttribLocation(self.program, "end")
        gl.glEnableVertexAttribArray(loc)
        gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, stride, offset)

        # OpenGL initalization
        self.elapsed_time = 0
        gl.glClearColor(0, 0, 0, 1)
        gl.glDisable(gl.GL_DEPTH_TEST)
        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE)
        gl.glEnable(34370)  # gl.GL_VERTEX_PROGRAM_POINT_SIZE
        gl.glEnable(34913)  # gl.GL_POINT_SPRITE
        gl.glViewport(0, 0, *self.physical_size)
        self.new_explosion()
        self.timer = app.Timer('auto', self.on_timer, start=True)
Ejemplo n.º 12
0
    def on_initialize(self, event):
        # Build & activate program
        self.program = gl.glCreateProgram()
        vertex = gl.glCreateShader(gl.GL_VERTEX_SHADER)
        fragment = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
        gl.glShaderSource(vertex, vertex_code)
        gl.glShaderSource(fragment, fragment_code)
        gl.glCompileShader(vertex)
        gl.glCompileShader(fragment)
        gl.glAttachShader(self.program, vertex)
        gl.glAttachShader(self.program, fragment)
        gl.glLinkProgram(self.program)
        gl.glDetachShader(self.program, vertex)
        gl.glDetachShader(self.program, fragment)
        gl.glUseProgram(self.program)

        # Build vertex buffer
        n = 10000
        self.data = np.zeros(n, dtype=[('lifetime', np.float32, 1),
                                       ('start',    np.float32, 3),
                                       ('end',      np.float32, 3)])
        vbuffer = gl.glCreateBuffer()
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbuffer)
        gl.glBufferData(gl.GL_ARRAY_BUFFER, self.data, gl.GL_DYNAMIC_DRAW)

        # Bind buffer attributes
        stride = self.data.strides[0]

        offset = 0
        loc = gl.glGetAttribLocation(self.program, "lifetime")
        gl.glEnableVertexAttribArray(loc)
        gl.glVertexAttribPointer(loc, 1, gl.GL_FLOAT, False, stride, offset)

        offset = self.data.dtype["lifetime"].itemsize
        loc = gl.glGetAttribLocation(self.program, "start")
        gl.glEnableVertexAttribArray(loc)
        gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, stride, offset)

        offset = self.data.dtype["start"].itemsize
        loc = gl.glGetAttribLocation(self.program, "end")
        gl.glEnableVertexAttribArray(loc)
        gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, stride, offset)

        # OpenGL initalization
        self.elapsed_time = 0
        gl.glClearColor(0, 0, 0, 1)
        gl.glDisable(gl.GL_DEPTH_TEST)
        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE)
        gl.glEnable(34370)  # gl.GL_VERTEX_PROGRAM_POINT_SIZE
        gl.glEnable(34913)  # gl.GL_POINT_SPRITE
        gl.glViewport(0, 0, *self.physical_size)
        self.new_explosion()
        self.timer = app.Timer('auto', self.on_timer, start=True)
Ejemplo n.º 13
0
def _test_functonality(backend):
    """ Create app and canvas so we have a context. Then run tests.
    """

    # use the backend
    gl.use(backend)
    
    # Note that we explicitly use pyglet because with Qt we seem
    # to get errors for this test
    
    with app_opengl_context('qt') as context:
        
        _clear_screen()
        
        # Prepare
        w, h = context.c.size
        gl.glViewport(0, 0, w, h)
        gl.glScissor(0, 0, w, h)  # touch
        gl.glClearColor(0.0, 0.0, 0.0, 1.0)
        
        # Setup visualization, ensure to do it in a paint event
        objects = context.test(_prepare_vis)
        
        _clear_screen()
        
        # Draw 1
        context.test(_draw1)
        if SHOW:
            context.c.swap_buffers()
            app.process_events()
            time.sleep(1.0)
        
        _clear_screen()
        
        # Draw 2
        context.test(_draw2)
        if SHOW:
            context.c.swap_buffers()
            app.process_events()
            time.sleep(1.0)
        
        _clear_screen()
        
        # Draw 3
        context.test(_draw3)
        if SHOW:
            context.c.swap_buffers()
            app.process_events()
            time.sleep(1.0)
        
        # Clean up
        for delete_func, handle in objects:
            delete_func(handle)
Ejemplo n.º 14
0
    def on_paint(self, event):
        # Paint events are "manually" propagated to the viewport instances,
        # because we first want to set the glViewport for each one.

        # Prepare
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        w1 = self.size[0] // 2
        w2 = self.size[0] - w1
        # Left
        gl.glViewport(0, 0, w1, self.size[1])
        self.left.on_paint()
        # Right
        gl.glViewport(w1, 0, w2, self.size[1])
        self.right.on_paint()

        # Invoke new draw
        self.update()
Ejemplo n.º 15
0
    def on_paint(self, event):
        # Paint events are "manually" propagated to the viewport instances,
        # because we first want to set the glViewport for each one.

        # Prepare
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        w1 = self.size[0] // 2
        w2 = self.size[0] - w1
        # Left
        gl.glViewport(0, 0, w1, self.size[1])
        self.left.on_paint()
        # Right
        gl.glViewport(w1, 0, w2, self.size[1])
        self.right.on_paint()

        # Invoke new draw
        self.update()
Ejemplo n.º 16
0
    def on_resize(self, event):
        width, height = event.size
        gl.glViewport(0, 0, width, height)
        self.projection = ortho( 0, width, 0, height, -100, 100 )
        self.program['u_projection'] = self.projection

        # Compute thje new size of the quad 
        r = width/float(height)
        R = W/float(H)
        if r < R:
            w,h = width, width/R
            x,y = 0, int((height-h)/2)
        else:
            w,h = height*R, height
            x,y = int((width-w)/2), 0
        data['a_position'] = np.array([[x, y], [x+w, y], [x, y+h], [x+w, y+h]])
        self.program.set_vars(gloo.VertexBuffer(data))
Ejemplo n.º 17
0
    def on_resize(self, event):
        width, height = event.size
        gl.glViewport(0, 0, width, height)
        self.projection = ortho(0, width, 0, height, -100, 100)
        self.program['u_projection'] = self.projection

        # Compute thje new size of the quad
        r = width / float(height)
        R = W / float(H)
        if r < R:
            w, h = width, width / R
            x, y = 0, int((height - h) / 2)
        else:
            w, h = height * R, height
            x, y = int((width - w) / 2), 0
        data['a_position'] = np.array([[x, y], [x + w, y], [x, y + h],
                                       [x + w, y + h]])
        self.program.set_vars(gloo.VertexBuffer(data))
Ejemplo n.º 18
0
 def resize(self, width, height):
     gl.glViewport(0, 0, width, height)
     data_width = self._data_lim[0][1] - self._data_lim[0][0]
     data_height = self._data_lim[1][1] - self._data_lim[1][0]
     data_aspect = data_width / float(data_height)
     frame_aspect = width / float(height)
     if frame_aspect >= data_aspect:
         padding = (frame_aspect * data_height - data_width) / 2.
         frame_lim = [
             [self._data_lim[0][0] - padding,
              self._data_lim[0][1] + padding],
             [self._data_lim[1][0],
              self._data_lim[1][1]]]
     else:
         padding = (data_width / frame_aspect - data_height) / 2.
         frame_lim = [
             [self._data_lim[0][0],
              self._data_lim[0][1]],
             [self._data_lim[1][0] - padding,
              self._data_lim[1][1] + padding]]
     args_ortho = frame_lim[0][::(1 if self._dir_x_right else -1)]
     args_ortho += frame_lim[1][::(1 if self._dir_y_top else -1)]
     args_ortho += -1000, 1000
     self.program['projection'] = ortho(*args_ortho)
Ejemplo n.º 19
0
 def on_paint(self, ev):
     gl.glViewport(0, 0, *self.size)
     self.program.draw(gl.GL_LINE_STRIP)
Ejemplo n.º 20
0
 def paint(event):
     print('  {0:7}: {1}'.format(backend, bgcolor[backend]))
     gl.glViewport(0, 0, *list(_win_size))
     gl.glClearColor(*bgcolor[backend])
     gl.glClear(gl.GL_COLOR_BUFFER_BIT)
     gl.glFinish()
Ejemplo n.º 21
0
 def on_resize(self, event):
     width, height = event.size
     gl.glViewport(0, 0, width, height)
     projection = perspective(35.0, width / float(height), 2.0, 10.0)
     loc = gl.glGetUniformLocation(self.cube, "u_projection")
     gl.glUniformMatrix4fv(loc, 1, False, projection)
Ejemplo n.º 22
0
 def on_resize(self, event):
     gl.glViewport(0, 0, *event.size)
Ejemplo n.º 23
0
def test_application():
    """Test application running"""
    app = use_app()
    print(app)  # __repr__ without app
    app.create()
    wrong = 'glut' if app.backend_name.lower() != 'glut' else 'pyglet'
    assert_raises(RuntimeError, use_app, wrong)
    app.process_events()
    print(app)  # test __repr__

    assert_raises(ValueError, Canvas, keys='foo')
    assert_raises(TypeError, Canvas, keys=dict(escape=1))
    assert_raises(ValueError, Canvas, keys=dict(escape='foo'))  # not an attr

    pos = [0, 0] if app.backend_module.capability['position'] else None
    size = (100, 100)
    # Use "with" statement so failures don't leave open window
    # (and test context manager behavior)
    title = 'default'
    with Canvas(title=title, size=size, app=app, show=True,
                position=pos) as canvas:
        assert_true(canvas.create_native() is None)  # should be done already
        assert_is(canvas.app, app)
        assert_true(canvas.native)
        assert_equal('swap_buffers', canvas.events.draw.callback_refs[-1])

        canvas.measure_fps(0.001)
        sleep(0.002)
        canvas.update()
        app.process_events()
        assert_true(canvas.fps > 0)

        # Other methods
        print(canvas)  # __repr__
        assert_equal(canvas.title, title)
        canvas.title = 'you'
        with use_log_level('warning', record=True, print_msg=False) as l:
            if app.backend_module.capability['position']:
                # todo: disable more tests based on capability
                canvas.position = pos
            canvas.size = size
        if 'ipynb_vnc' in canvas.app.backend_name.lower():
            assert_true(len(l) >= 1)
        else:
            assert_true(len(l) == 0)
        canvas.connect(on_mouse_move)
        assert_raises(ValueError, canvas.connect, _on_mouse_move)
        if sys.platform != 'darwin':  # XXX knownfail, prob. needs warmup
            canvas.show(False)
            canvas.show()
        app.process_events()
        assert_raises(ValueError, canvas.connect, on_nonexist)
        # deprecation of "paint"
        with use_log_level('info', record=True, print_msg=False) as log:
            olderr = sys.stderr
            try:
                with open(os.devnull, 'w') as fid:
                    sys.stderr = fid

                    @canvas.events.paint.connect
                    def fake(event):
                        pass
            finally:
                sys.stderr = olderr
        assert_equal(len(log), 1)
        assert_in('deprecated', log[0])

        # screenshots
        gl.glViewport(0, 0, *size)
        ss = _screenshot()
        assert_array_equal(ss.shape, size + (4,))
        assert_equal(len(canvas._backend._vispy_get_geometry()), 4)
        if (app.backend_name.lower() != 'glut' and  # XXX knownfail for Almar
                sys.platform != 'win32'):  # XXX knownfail for windows
            assert_array_equal(canvas.size, size)
        assert_equal(len(canvas.position), 2)  # XXX knawnfail, doesn't "take"

        # GLOO: should have an OpenGL context already, so these should work
        vert = VertexShader("void main (void) {gl_Position = pos;}")
        frag = FragmentShader("void main (void) {gl_FragColor = pos;}")
        program = Program(vert, frag)
        assert_raises(RuntimeError, program.activate)

        vert = VertexShader("uniform vec4 pos;"
                            "void main (void) {gl_Position = pos;}")
        frag = FragmentShader("uniform vec4 pos;"
                              "void main (void) {gl_FragColor = pos;}")
        program = Program(vert, frag)
        #uniform = program.uniforms[0]
        program['pos'] = [1, 2, 3, 4]
        program.activate()  # should print
        #uniform.upload(program)
        program.detach(vert)
        program.detach(frag)
        assert_raises(RuntimeError, program.detach, vert)
        assert_raises(RuntimeError, program.detach, frag)

        vert = VertexShader("attribute vec4 pos;"
                            "void main (void) {gl_Position = pos;}")
        frag = FragmentShader("void main (void) {}")
        program = Program(vert, frag)
        #attribute = program.attributes[0]
        program["pos"] = [1, 2, 3, 4]
        program.activate()
        #attribute.upload(program)
        # cannot get element count
        #assert_raises(RuntimeError, program.draw, 'POINTS')

        # use a real program
        vert = ("uniform mat4 u_model;"
                "attribute vec2 a_position; attribute vec4 a_color;"
                "varying vec4 v_color;"
                "void main (void) {v_color = a_color;"
                "gl_Position = u_model * vec4(a_position, 0.0, 1.0);"
                "v_color = a_color;}")
        frag = "void main() {gl_FragColor = vec4(0, 0, 0, 1);}"
        n, p = 250, 50
        T = np.random.uniform(0, 2 * np.pi, n)
        position = np.zeros((n, 2), dtype=np.float32)
        position[:, 0] = np.cos(T)
        position[:, 1] = np.sin(T)
        color = np.ones((n, 4), dtype=np.float32) * (1, 1, 1, 1)
        data = np.zeros(n * p, [('a_position', np.float32, 2),
                                ('a_color', np.float32, 4)])
        data['a_position'] = np.repeat(position, p, axis=0)
        data['a_color'] = np.repeat(color, p, axis=0)

        program = Program(vert, frag)
        program.bind(VertexBuffer(data))
        program['u_model'] = np.eye(4, dtype=np.float32)
        # different codepath if no call to activate()
        program.draw(gl.GL_POINTS)
        subset = IndexBuffer(np.arange(10, dtype=np.uint32))
        program.draw(gl.GL_POINTS, subset)

        # bad programs
        frag_bad = ("varying vec4 v_colors")  # no semicolon
        program = Program(vert, frag_bad)
        assert_raises(RuntimeError, program.activate)
        frag_bad = None  # no fragment code. no main is not always enough
        program = Program(vert, frag_bad)
        assert_raises(ValueError, program.activate)

        # Timer
        timer = Timer(interval=0.001, connect=on_mouse_move, iterations=2,
                      start=True, app=app)
        timer.start()
        timer.interval = 0.002
        assert_equal(timer.interval, 0.002)
        assert_true(timer.running)
        sleep(.003)
        assert_true(timer.elapsed >= 0.002)
        timer.stop()
        assert_true(not timer.running)
        assert_true(timer.native)
        timer.disconnect()

        # test that callbacks take reasonable inputs
        _test_callbacks(canvas)

        # cleanup
        canvas.swap_buffers()
        canvas.update()
        app.process_events()
        # put this in even though __exit__ will call it to make sure we don't
        # have problems calling it multiple times
        canvas.close()  # done by context
Ejemplo n.º 24
0
 def on_resize(self, event):
     gl.glViewport(0, 0, *event.physical_size)
Ejemplo n.º 25
0
 def on_resize(self, event):
     width, height = event.size
     gl.glViewport(0, 0, width, height)
Ejemplo n.º 26
0
 def on_resize(self, event):
     gl.glViewport(0, 0, event.size[0], event.size[1])
Ejemplo n.º 27
0
 def on_resize(self, event):
     w, h = event.size
     gl.glViewport(0, 0, w, h)
     self.projection = perspective(45.0, w / float(h), 2.0, 10.0)
Ejemplo n.º 28
0
 def _resize(self, width, height, physical_width, physical_height):
     gl.glViewport(0, 0, physical_width, physical_height)
     projection = perspective(35.0, width / float(height), 2.0, 10.0)
     loc = gl.glGetUniformLocation(self.cube, "u_projection")
     gl.glUniformMatrix4fv(loc, 1, False, projection)
Ejemplo n.º 29
0
Archivo: cube.py Proyecto: Lx37/vispy
 def _resize(self, width, height, physical_width, physical_height):
     gl.glViewport(0, 0, physical_width, physical_height)
     projection = perspective(35.0, width / float(height), 2.0, 10.0)
     loc = gl.glGetUniformLocation(self.cube, "u_projection")
     gl.glUniformMatrix4fv(loc, 1, False, projection)
Ejemplo n.º 30
0
def _test_application(backend):
    """Test application running"""
    app = Application()
    assert_raises(ValueError, app.use, "foo")
    app.use(backend)
    wrong = "Glut" if app.backend_name != "Glut" else "Pyglet"
    assert_raises(RuntimeError, app.use, wrong)
    app.process_events()
    if backend is not None:
        # "in" b/c "qt" in "PySide (qt)"
        assert_in(backend, app.backend_name)
    print(app)  # test __repr__

    # Canvas
    pos = [0, 0]
    size = (100, 100)
    # Use "with" statement so failures don't leave open window
    # (and test context manager behavior)
    title = "default" if backend is None else backend
    with Canvas(title=title, size=size, app=app, show=True, position=pos) as canvas:
        assert_is(canvas.app, app)
        assert_true(canvas.native)
        assert_equal("swap_buffers", canvas.events.paint.callback_refs[-1])
        print(canvas)  # __repr__
        assert_array_equal(canvas.size, size)
        assert_equal(canvas.title, title)
        canvas.title = "you"
        canvas.position = pos
        canvas.size = size
        canvas.connect(on_mouse_move)
        assert_raises(ValueError, canvas.connect, _on_mouse_move)
        if sys.platform != "darwin":  # XXX knownfail, prob. needs warmup
            canvas.show(False)
            canvas.show()
        app.process_events()
        assert_raises(ValueError, canvas.connect, on_nonexist)

        # screenshots
        gl.glViewport(0, 0, *size)
        ss = _screenshot()
        assert_array_equal(ss.shape, size + (3,))
        assert_equal(len(canvas._backend._vispy_get_geometry()), 4)
        assert_array_equal(canvas.size, size)
        assert_equal(len(canvas.position), 2)  # XXX knawnfail, doesn't "take"

        # GLOO: should have an OpenGL context already, so these should work
        vert = VertexShader("void main (void) {gl_Position = pos;}")
        frag = FragmentShader("void main (void) {gl_FragColor = pos;}")
        program = Program(vert, frag)
        assert_raises(RuntimeError, program.activate)

        vert = VertexShader("uniform vec4 pos;" "void main (void) {gl_Position = pos;}")
        frag = FragmentShader("uniform vec4 pos;" "void main (void) {gl_FragColor = pos;}")
        program = Program(vert, frag)
        # uniform = program.uniforms[0]
        program["pos"] = [1, 2, 3, 4]
        program.activate()  # should print
        # uniform.upload(program)
        program.detach(vert)
        program.detach(frag)
        assert_raises(RuntimeError, program.detach, vert)
        assert_raises(RuntimeError, program.detach, frag)

        vert = VertexShader("attribute vec4 pos;" "void main (void) {gl_Position = pos;}")
        frag = FragmentShader("void main (void) {}")
        program = Program(vert, frag)
        # attribute = program.attributes[0]
        program["pos"] = [1, 2, 3, 4]
        program.activate()
        # attribute.upload(program)
        # cannot get element count
        # assert_raises(RuntimeError, program.draw, 'POINTS')

        # use a real program
        vert = (
            "uniform mat4 u_model;"
            "attribute vec2 a_position; attribute vec4 a_color;"
            "varying vec4 v_color;"
            "void main (void) {v_color = a_color;"
            "gl_Position = u_model * vec4(a_position, 0.0, 1.0);"
            "v_color = a_color;}"
        )
        frag = "void main() {gl_FragColor = vec4(0, 0, 0, 1);}"
        n, p = 250, 50
        T = np.random.uniform(0, 2 * np.pi, n)
        position = np.zeros((n, 2), dtype=np.float32)
        position[:, 0] = np.cos(T)
        position[:, 1] = np.sin(T)
        color = np.ones((n, 4), dtype=np.float32) * (1, 1, 1, 1)
        data = np.zeros(n * p, [("a_position", np.float32, 2), ("a_color", np.float32, 4)])
        data["a_position"] = np.repeat(position, p, axis=0)
        data["a_color"] = np.repeat(color, p, axis=0)

        program = Program(vert, frag)
        program.bind(VertexBuffer(data))
        program["u_model"] = np.eye(4, dtype=np.float32)
        # different codepath if no call to activate()
        program.draw(gl.GL_POINTS)
        subset = IndexBuffer(np.arange(10, dtype=np.uint32))
        program.draw(gl.GL_POINTS, subset)

        # bad programs
        frag_bad = "varying vec4 v_colors"  # no semicolon
        program = Program(vert, frag_bad)
        assert_raises(RuntimeError, program.activate)
        frag_bad = None  # no fragment code. no main is not always enough
        program = Program(vert, frag_bad)
        assert_raises(ValueError, program.activate)

        # Timer
        timer = Timer(interval=0.001, connect=on_mouse_move, iterations=2, start=True, app=app)
        timer.start()
        timer.interval = 0.002
        assert_equal(timer.interval, 0.002)
        assert_true(timer.running)
        timer.stop()
        assert_true(not timer.running)
        assert_true(timer.native)
        timer.disconnect()

        # test that callbacks take reasonable inputs
        _test_callbacks(canvas)

        # cleanup
        canvas.swap_buffers()
        canvas.update()
        app.process_events()
Ejemplo n.º 31
0
 def on_resize(self, event):
     gl.glViewport(0, 0, *event.size)
Ejemplo n.º 32
0
 def on_resize(self, event):
     width, height = event.size
     gl.glViewport(0, 0, width, height)
Ejemplo n.º 33
0
 def on_resize(self, event):
     width, height = event.size
     gl.glViewport(0, 0, width, height)
     self.projection = perspective(45.0, width / float(height), 1.0, 1000.0)
     self.program['u_projection'] = self.projection
Ejemplo n.º 34
0
Archivo: atom.py Proyecto: ds604/vispy
 def on_resize(self, event):
     width, height = event.size
     gl.glViewport(0, 0, width, height)
     self.projection = perspective( 45.0, width/float(height), 1.0, 1000.0 )
     self.program['u_projection'] = self.projection
Ejemplo n.º 35
0
 def on_resize(self, event):
     w, h = event.size
     gl.glViewport(0, 0, w, h)
     self.projection = perspective(45.0, w / float(h), 2.0, 10.0)
Ejemplo n.º 36
0
def test_application():
    """Test application running"""
    app = use_app()
    print(app)  # __repr__ without app
    app.create()
    wrong = 'glfw' if app.backend_name.lower() != 'glfw' else 'pyqt4'
    assert_raises(RuntimeError, use_app, wrong)
    app.process_events()
    print(app)  # test __repr__

    assert_raises(ValueError, Canvas, keys='foo')
    assert_raises(TypeError, Canvas, keys=dict(escape=1))
    assert_raises(ValueError, Canvas, keys=dict(escape='foo'))  # not an attr

    pos = [0, 0] if app.backend_module.capability['position'] else None
    size = (100, 100)
    # Use "with" statement so failures don't leave open window
    # (and test context manager behavior)
    title = 'default'
    with Canvas(title=title, size=size, app=app, show=True,
                position=pos) as canvas:
        context = canvas.context
        assert_true(canvas.create_native() is None)  # should be done already
        assert_is(canvas.app, app)
        assert_true(canvas.native)
        assert_equal('swap_buffers', canvas.events.draw.callback_refs[-1])

        canvas.measure_fps(0.001)
        sleep(0.002)
        canvas.update()
        app.process_events()
        assert_true(canvas.fps > 0)

        # Other methods
        print(canvas)  # __repr__
        assert_equal(canvas.title, title)
        canvas.title = 'you'
        with use_log_level('warning', record=True, print_msg=False) as l:
            if app.backend_module.capability['position']:
                # todo: disable more tests based on capability
                canvas.position = pos
            canvas.size = size
        if 'ipynb_vnc' in canvas.app.backend_name.lower():
            assert_true(len(l) >= 1)
        else:
            assert_true(len(l) == 0)
        canvas.connect(on_mouse_move)
        assert_raises(ValueError, canvas.connect, _on_mouse_move)
        if sys.platform != 'darwin':  # XXX knownfail, prob. needs warmup
            canvas.show(False)
            canvas.show()
        app.process_events()
        assert_raises(ValueError, canvas.connect, on_nonexist)
        # deprecation of "paint"
        with use_log_level('info', record=True, print_msg=False) as log:
            olderr = sys.stderr
            try:
                fid = StringIO()
                sys.stderr = fid

                @canvas.events.paint.connect
                def fake(event):
                    pass
            finally:
                sys.stderr = olderr
        assert_equal(len(log), 1)
        assert_in('deprecated', log[0])

        # screenshots
        gl.glViewport(0, 0, *size)
        ss = _screenshot()
        assert_array_equal(ss.shape, size + (4,))
        assert_equal(len(canvas._backend._vispy_get_geometry()), 4)
        if sys.platform != 'win32':  # XXX knownfail for windows
            assert_array_equal(canvas.size, size)
        assert_equal(len(canvas.position), 2)  # XXX knawnfail, doesn't "take"

        # GLOO: should have an OpenGL context already, so these should work
        vert = "void main (void) {gl_Position = pos;}"
        frag = "void main (void) {gl_FragColor = pos;}"
        program = Program(vert, frag)
        assert_raises(RuntimeError, program.glir.flush, context.shared.parser)
        
        vert = "uniform vec4 pos;\nvoid main (void) {gl_Position = pos;}"
        frag = "uniform vec4 pos;\nvoid main (void) {gl_FragColor = pos;}"
        program = Program(vert, frag)
        #uniform = program.uniforms[0]
        program['pos'] = [1, 2, 3, 4]
        
        vert = "attribute vec4 pos;\nvoid main (void) {gl_Position = pos;}"
        frag = "void main (void) {}"
        program = Program(vert, frag)
        #attribute = program.attributes[0]
        program["pos"] = [1, 2, 3, 4]
        
        # use a real program
        program._glir.clear()
        vert = ("uniform mat4 u_model;"
                "attribute vec2 a_position; attribute vec4 a_color;"
                "varying vec4 v_color;"
                "void main (void) {v_color = a_color;"
                "gl_Position = u_model * vec4(a_position, 0.0, 1.0);"
                "v_color = a_color;}")
        frag = "void main() {gl_FragColor = vec4(0, 0, 0, 1);}"
        n, p = 250, 50
        T = np.random.uniform(0, 2 * np.pi, n)
        position = np.zeros((n, 2), dtype=np.float32)
        position[:, 0] = np.cos(T)
        position[:, 1] = np.sin(T)
        color = np.ones((n, 4), dtype=np.float32) * (1, 1, 1, 1)
        data = np.zeros(n * p, [('a_position', np.float32, 2),
                                ('a_color', np.float32, 4)])
        data['a_position'] = np.repeat(position, p, axis=0)
        data['a_color'] = np.repeat(color, p, axis=0)

        program = Program(vert, frag)
        program.bind(VertexBuffer(data))
        program['u_model'] = np.eye(4, dtype=np.float32)
        # different codepath if no call to activate()
        program.draw(gl.GL_POINTS)
        subset = IndexBuffer(np.arange(10, dtype=np.uint32))
        program.draw(gl.GL_POINTS, subset)

        # bad programs
        frag_bad = ("varying vec4 v_colors")  # no semicolon
        program = Program(vert, frag_bad)
        assert_raises(RuntimeError, program.glir.flush, context.shared.parser)
        frag_bad = None  # no fragment code. no main is not always enough
        assert_raises(ValueError, Program, vert, frag_bad)

        # Timer
        timer = Timer(interval=0.001, connect=on_mouse_move, iterations=2,
                      start=True, app=app)
        timer.start()
        timer.interval = 0.002
        assert_equal(timer.interval, 0.002)
        assert_true(timer.running)
        sleep(.003)
        assert_true(timer.elapsed >= 0.002)
        timer.stop()
        assert_true(not timer.running)
        assert_true(timer.native)
        timer.disconnect()

        # test that callbacks take reasonable inputs
        _test_callbacks(canvas)

        # cleanup
        canvas.swap_buffers()
        canvas.update()
        app.process_events()
        # put this in even though __exit__ will call it to make sure we don't
        # have problems calling it multiple times
        canvas.close()  # done by context
Ejemplo n.º 37
0
 def on_paint(self, ev):
     gl.glViewport(0, 0, *self.size)
     self.program.draw(gl.GL_LINE_STRIP)
Ejemplo n.º 38
0
 def on_resize(self, event):
     gl.glViewport(0, 0, event.size[0], event.size[1])
Ejemplo n.º 39
0
 def on_resize(self, event):
     gl.glViewport(0, 0, *event.physical_size)