Beispiel #1
0
    def __init__(self):
        app.Canvas.__init__(self,
                            title='Rain [Move mouse]',
                            size=(512, 512),
                            keys='interactive')

        # Build data
        # --------------------------------------
        n = 500
        self.data = np.zeros(n, [('a_position', np.float32, 2),
                                 ('a_fg_color', np.float32, 4),
                                 ('a_size', np.float32, 1)])
        self.index = 0
        self.program = Program(vertex, fragment)
        self.vdata = VertexBuffer(self.data)
        self.program.bind(self.vdata)
        self.program['u_antialias'] = 1.00
        self.program['u_linewidth'] = 1.00
        self.program['u_model'] = np.eye(4, dtype=np.float32)
        self.program['u_view'] = np.eye(4, dtype=np.float32)

        self.activate_zoom()

        gloo.set_clear_color('white')
        gloo.set_state(blend=True,
                       blend_func=('src_alpha', 'one_minus_src_alpha'))
        self.timer = app.Timer('auto', self.on_timer, start=True)

        self.show()
Beispiel #2
0
    def setupCanvas(self):
        #Create the camera
        self.__camera = Cam3D.Camera([0, -200, 150], [0, 0, 0], [0, 0, 1],
                                     45.0,
                                     self.size[0] / float(self.size[1]),
                                     0.01,
                                     1000.0,
                                     is_2d=False)

        #Build and setup the glprogram for rendering the models
        self.program_solids = Program(vertex, fragment)

        self.program_solids['model'] = vut.rotx(90)
        self.program_solids['model'] = np.eye(4, dtype=np.float32)
        self.program_solids['view'] = self.__camera.view
        self.program_solids['u_alpha'] = np.float32(0.6)

        # build and setup glprogram for rendering the points
        self.program_points = gloo.Program(vert, frag)

        self.program_points['u_linewidth'] = 1.0
        self.program_points['u_antialias'] = 1.0
        self.program_points['u_model'] = np.eye(4, dtype=np.float32)
        self.program_points['u_view'] = self.__camera.view
        self.program_points['u_size'] = 0.3 + 0.8 / self.__camera.zoom_factor

        #Some aditional drawing variables/setups
        self.__draw_model_transparent = False
        self.context.set_clear_color(Color([0.7, 0.7, 0.7, 1.0]))
        self.__theta = 0
        self.__phi = 0
        self.timer = app.Timer('auto', self.on_timer, start=True)
        self.activate_zoom()
    def __init__(self):
        app.Canvas.__init__(self)

        # This size is used for comparison with agg (via matplotlib)
        self.size = 512, 512 + 2 * 32
        self.title = "Markers demo [press space to change marker]"

        self.vbo = VertexBuffer(data)
        self.view = np.eye(4, dtype=np.float32)
        self.model = np.eye(4, dtype=np.float32)
        self.projection = ortho(0, self.size[0], 0, self.size[1], -1, 1)
        self.programs = [
            Program(markers.vert, markers.frag + markers.tailed_arrow),
            Program(markers.vert, markers.frag + markers.disc),
            Program(markers.vert, markers.frag + markers.diamond),
            Program(markers.vert, markers.frag + markers.square),
            Program(markers.vert, markers.frag + markers.cross),
            Program(markers.vert, markers.frag + markers.arrow),
            Program(markers.vert, markers.frag + markers.vbar),
            Program(markers.vert, markers.frag + markers.hbar),
            Program(markers.vert, markers.frag + markers.clobber),
            Program(markers.vert, markers.frag + markers.ring)
        ]

        for program in self.programs:
            program.set_vars(self.vbo,
                             u_antialias=u_antialias,
                             u_size=1,
                             u_model=self.model,
                             u_view=self.view,
                             u_projection=self.projection)
        self.index = 0
        self.program = self.programs[self.index]
Beispiel #4
0
    def __init__(self):
        app.Canvas.__init__(self, size=(512, 512), keys='interactive')

        self.image = Program(image_vertex, image_fragment, 4)
        self.image['position'] = (-1, -1), (-1, +1), (+1, -1), (+1, +1)
        self.image['texcoord'] = (0, 0), (0, +1), (+1, 0), (+1, +1)
        self.image['vmin'] = +0.0
        self.image['vmax'] = +1.0
        self.image['cmap'] = 0  # Colormap index to use
        self.image['colormaps'] = colormaps
        self.image['n_colormaps'] = colormaps.shape[0]
        self.image['image'] = idxs.astype('float32')
        self.image['image'].interpolation = 'linear'

        set_viewport(0, 0, *self.physical_size)

        self.lines = Program(lines_vertex, lines_fragment)
        self.lines["position"] = np.zeros((4 + 4 + 514 + 514, 2), np.float32)
        color = np.zeros((4 + 4 + 514 + 514, 4), np.float32)
        color[1:1 + 2, 3] = 0.25
        color[5:5 + 2, 3] = 0.25
        color[9:9 + 512, 3] = 0.5
        color[523:523 + 512, 3] = 0.5
        self.lines["color"] = color

        set_state(clear_color='white',
                  blend=True,
                  blend_func=('src_alpha', 'one_minus_src_alpha'))

        self.show()
Beispiel #5
0
    def __init__(self):
        app.Canvas.__init__(self,
                            size=(512, 512),
                            title='Colored cube',
                            keys='interactive')

        # Build cube data
        V, I, _ = create_cube()
        vertices = VertexBuffer(V)
        self.indices = IndexBuffer(I)

        # Build program
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)

        # Build view, model, projection & normal
        view = np.eye(4, dtype=np.float32)
        model = np.eye(4, dtype=np.float32)
        translate(view, 0, 0, -5)
        self.program['model'] = model
        self.program['view'] = view
        self.phi, self.theta = 0, 0
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True)

        self.timer = app.Timer('auto', self.on_timer, start=True)
Beispiel #6
0
      def __init__ (self,  channels=10,timepoints=10000,srate=1017.25):
          super(TSV_TEST_GLOO, self).__init__()


          self.n_channels   = channels
          self.n_timepoints = timepoints
          self.srate        = srate


          self.magrin     = 10
          self.ticksize   = 10
          self.height     = 0.0
          self.width      = 0.0

          self._is_init     = False
          self.is_on_draw   = False

          self._init_data()

        # Build program & data
        # ----------------------------------------
          self.data_pgr = Program(vertex, fragment, count=timepoints)
          #self.data_pgr'color']    = [ (1,0,0,1), (0,1,0,1), (0,0,1,1), (1,1,0,1) ]
          #self.data_pgr['position'] = [ (-1,-1),   (-1,+1),   (+1,-1),   (+1,+1)   ]
          #self.program['scale'] = 1.0

          self.xgrid_pgr = Program(grid_vertex, grid_fragment)
          self.xgrid_pgr['position'] = self.init_xgrid()
          self.xgrid_pgr['color']    = np.array([0.0,0.0,0.0,1.0],dtype=np.float32)

          self.ygrid_pgr = Program(grid_vertex, grid_fragment)
          self.ygrid_pgr['position'] = self.init_ygrid()
          self.ygrid_pgr['color']    = np.array([0.50,0.50,0.50,1.0],dtype=np.float32)
Beispiel #7
0
    def __init__(self):
        app.Canvas.__init__(self, title='Grayscott Reaction-Diffusion',
                            size=(512, 512), keys='interactive')

        self.scale = 4
        self.comp_size = (256, 256)
        comp_w, comp_h = self.comp_size
        dt = 1.0
        dd = 1.5
        species = {
            # name : [r_u, r_v, f, k]
            'Bacteria 1': [0.16, 0.08, 0.035, 0.065],
            'Bacteria 2': [0.14, 0.06, 0.035, 0.065],
            'Coral': [0.16, 0.08, 0.060, 0.062],
            'Fingerprint': [0.19, 0.05, 0.060, 0.062],
            'Spirals': [0.10, 0.10, 0.018, 0.050],
            'Spirals Dense': [0.12, 0.08, 0.020, 0.050],
            'Spirals Fast': [0.10, 0.16, 0.020, 0.050],
            'Unstable': [0.16, 0.08, 0.020, 0.055],
            'Worms 1': [0.16, 0.08, 0.050, 0.065],
            'Worms 2': [0.16, 0.08, 0.054, 0.063],
            'Zebrafish': [0.16, 0.08, 0.035, 0.060]
        }
        P = np.zeros((comp_h, comp_w, 4), dtype=np.float32)
        P[:, :] = species['Unstable']

        UV = np.zeros((comp_h, comp_w, 4), dtype=np.float32)
        UV[:, :, 0] = 1.0
        r = 32
        UV[comp_h / 2 - r:comp_h / 2 + r,
           comp_w / 2 - r:comp_w / 2 + r, 0] = 0.50
        UV[comp_h / 2 - r:comp_h / 2 + r,
           comp_w / 2 - r:comp_w / 2 + r, 1] = 0.25
        UV += np.random.uniform(0.0, 0.01, (comp_h, comp_w, 4))
        UV[:, :, 2] = UV[:, :, 0]
        UV[:, :, 3] = UV[:, :, 1]

        self.pingpong = 1
        self.compute = Program(compute_vertex, compute_fragment, 4)
        self.compute["params"] = P
        self.compute["texture"] = UV
        self.compute["position"] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.compute["texcoord"] = [(0, 0), (0, 1), (1, 0), (1, 1)]
        self.compute['dt'] = dt
        self.compute['dx'] = 1.0 / comp_w
        self.compute['dy'] = 1.0 / comp_h
        self.compute['dd'] = dd
        self.compute['pingpong'] = self.pingpong

        self.render = Program(render_vertex, render_fragment, 4)
        self.render["position"] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.render["texcoord"] = [(0, 0), (0, 1), (1, 0), (1, 1)]
        self.render["texture"] = self.compute["texture"]
        self.render['pingpong'] = self.pingpong

        self.fbo = FrameBuffer(self.compute["texture"],
                               RenderBuffer(self.comp_size))
        set_state(depth_test=False, clear_color='black')

        self._timer = app.Timer('auto', connect=self.update, start=True)
Beispiel #8
0
def test_context_sharing():
    """Test context sharing"""
    with Canvas() as c1:
        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)
        program['pos'] = [1, 2, 3, 4]
        program.activate()  # should print

        def check():
            program.activate()
            check_error()

        with Canvas() as c2:
            # pyglet always shares
            if 'pyglet' not in c2.app.backend_name.lower():
                assert_raises(RuntimeError, check)
        if c1.app.backend_name.lower() in ('glut',):
            assert_raises(RuntimeError, Canvas, context=c1.context)
        else:
            with Canvas(context=c1.context) as c2:
                assert c1.context is c2.context  # Same context object
                check()
Beispiel #9
0
class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, size=(512, 512), title='Rotating quad',
                            keys='interactive')
        self.timer = app.Timer('auto', self.on_timer)

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

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

        self.clock = 0
        self.timer.start()

        self.show()

    def on_draw(self, event):
        gloo.set_clear_color('white')
        gloo.clear(color=True)
        self.program.draw('triangle_strip')

    def on_resize(self, event):
        gloo.set_viewport(0, 0, *event.physical_size)

    def on_timer(self, event):
        self.clock += 0.001 * 1000.0 / 60.
        self.program['theta'] = self.clock
        self.update()
Beispiel #10
0
class Canvas(app.Canvas):
    def __init__(self):
        self.image = Program(img_vertex, img_fragment, 4)
        self.image["position"] = (-1, -1), (-1, +1), (+1, -1), (+1, +1)
        self.image["texcoord"] = (0, 0), (0, +1), (+1, 0), (+1, +1)
        self.image["vmin"] = +0.1
        self.image["vmax"] = +0.9
        self.image["cmap"] = 0  # Colormap index to use

        self.image["colormaps"] = colormaps
        self.image["colormaps"].interpolation = "linear"
        self.image["colormaps_shape"] = colormaps.shape[1], colormaps.shape[0]

        self.image["image"] = I
        self.image["image"].interpolation = "linear"
        self.image["image_shape"] = I.shape[1], I.shape[0]
        app.Canvas.__init__(self, show=True, size=(512, 512), keys="interactive")

    def on_initialize(self, event):
        set_clear_color("black")

    def on_resize(self, event):
        width, height = event.size
        set_viewport(0, 0, *event.size)

    def on_draw(self, event):
        clear(color=True, depth=True)
        self.image.draw("triangle_strip")
Beispiel #11
0
def test_context_sharing():
    """Test context sharing"""
    with Canvas() as c1:
        vert = "attribute vec4 pos;\nvoid main (void) {gl_Position = pos;}"
        frag = "void main (void) {gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);}"
        program = Program(vert, frag)
        program['pos'] = [(1, 2, 3, 1), (4, 5, 6, 1)]
        program.draw('points')

        def check():
            # Do something to program and see if it worked
            program['pos'] = [(1, 2, 3, 1), (4, 5, 6, 1)]  # Do command
            program.draw('points')
            check_error()

        # Check while c1 is active
        check()

        # Check while c2 is active (with different context)
        with Canvas() as c2:
            # pyglet always shares
            if 'pyglet' not in c2.app.backend_name.lower():
                assert_raises(Exception, check)

        # Check while c2 is active (with *same* context)
        with Canvas(shared=c1.context) as c2:
            assert c1.context.shared is c2.context.shared  # same object
            check()
Beispiel #12
0
class Canvas(app.Canvas):
    
    def __init__(self):
        app.Canvas.__init__(self)
        
        # Create program
        self._program = Program(VERT_SHADER, FRAG_SHADER)
        
        # Set uniforms and samplers
        self._program['a_position'] = VertexBuffer(positions)
        self._program['a_texcoord'] = VertexBuffer(texcoords)
        #
        self._program['u_texture1'] = Texture2D(im1)
        self._program['u_texture2'] = Texture2D(im2)
        self._program['u_texture3'] = Texture2D(im3)
    
    
    def on_initialize(self, event):
        gl.glClearColor(1,1,1,1)
    
    
    def on_resize(self, event):
        width, height = event.size
        gl.glViewport(0, 0, width, height)
    
    
    def on_paint(self, event):
        
        # Clear
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
        
        # Draw shape with texture, nested context
        self._program.draw(gl.GL_TRIANGLE_STRIP)
Beispiel #13
0
def initialize_renderer():
    """Initialize the OpenGL renderer.

    For an OpenGL based renderer this sets up the viewport and creates
    the shader programs.

    """
    global fbuffer
    global fbuffer_prog
    global default_prog

    fbuffer = FrameBuffer()

    vertices = np.array(
        [[-1.0, -1.0], [+1.0, -1.0], [-1.0, +1.0], [+1.0, +1.0]], np.float32)
    texcoords = np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]],
                         dtype=np.float32)

    fbuf_vertices = VertexBuffer(data=vertices)
    fbuf_texcoords = VertexBuffer(data=texcoords)

    fbuffer_prog = Program(src_fbuffer.vert, src_fbuffer.frag)
    fbuffer_prog['texcoord'] = fbuf_texcoords
    fbuffer_prog['position'] = fbuf_vertices

    default_prog = Program(src_default.vert, src_default.frag)

    reset_view()
Beispiel #14
0
    def __init__(self):
        app.Canvas.__init__(self,
                            size=(512, 512),
                            title='Textured cube',
                            keys='interactive')
        self.timer = app.Timer('auto', self.on_timer)

        # Build cube data
        V, I, _ = create_cube()
        vertices = VertexBuffer(V)
        self.indices = IndexBuffer(I)

        # Build program
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)

        # Build view, model, projection & normal
        view = translate((0, 0, -5))
        model = np.eye(4, dtype=np.float32)
        self.program['model'] = model
        self.program['view'] = view
        self.program['texture'] = checkerboard()

        self.activate_zoom()

        self.phi, self.theta = 0, 0

        # OpenGL initalization
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True)
        self.timer.start()

        self.show()
Beispiel #15
0
    def __init__(self):
        self.use_shaders = True
        app.Canvas.__init__(self, size=(512, 512), keys='interactive')
        # Note: read as bytes, then decode; py2.6 compat
        with open(op.join(this_dir, 'vertex_vispy.glsl'), 'rb') as fid:
            vert = fid.read().decode('ASCII')
        with open(op.join(this_dir, 'fragment_seed.glsl'), 'rb') as f:
            frag_seed = f.read().decode('ASCII')
        with open(op.join(this_dir, 'fragment_flood.glsl'), 'rb') as f:
            frag_flood = f.read().decode('ASCII')
        with open(op.join(this_dir, 'fragment_display.glsl'), 'rb') as f:
            frag_display = f.read().decode('ASCII')
        self.programs = [
            Program(vert, frag_seed),
            Program(vert, frag_flood),
            Program(vert, frag_display)
        ]
        # Initialize variables
        # using two FBs slightly faster than switching on one
        self.fbo_to = [FrameBuffer(), FrameBuffer()]
        self._setup_textures('shape1.tga')
        vtype = np.dtype([('position', 'f4', 2), ('texcoord', 'f4', 2)])
        vertices = np.zeros(4, dtype=vtype)
        vertices['position'] = [[-1., -1.], [-1., 1.], [1., -1.], [1., 1.]]
        vertices['texcoord'] = [[0., 0.], [0., 1.], [1., 0.], [1., 1.]]
        vertices = VertexBuffer(vertices)
        for program in self.programs:
            program.bind(vertices)
        self._timer = app.Timer('auto', self.update, start=True)

        self.show()
Beispiel #16
0
class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self,
                            size=(512, 512),
                            title='Rotating quad',
                            keys='interactive')
        self.timer = app.Timer('auto', self.on_timer)

        # Build program & data
        self.program = Program(vertex, fragment, count=4)
        self.program['color'] = [(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1),
                                 (1, 1, 0, 1)]
        self.program['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.program['theta'] = 0.0
        self.clock = 0
        self.timer.start()

    def on_draw(self, event):
        gloo.set_clear_color('white')
        gloo.clear(color=True)
        self.program.draw('triangle_strip')

    def on_resize(self, event):
        gloo.set_viewport(0, 0, *event.size)

    def on_timer(self, event):
        self.clock += 0.001 * 1000.0 / 60.
        self.program['theta'] = self.clock
        self.update()
Beispiel #17
0
    def set_shaders(self, vertex_shader=None, fragment_shader=None):
        #
        vs = vertex_shader if vertex_shader else self._vertex_shader
        fs = fragment_shader if fragment_shader else self._fragment_shader
        self._program = Program(vs, fs, count=4)

        #
        self._data = np.zeros(4,
                              dtype=[('a_position', np.float32, 2),
                                     ('a_texcoord', np.float32, 2)])

        #
        self._data['a_texcoord'] = np.array([[0., 1.], [1., 1.], [0., 0.],
                                             [1., 0.]])

        #
        self._program['u_model'] = np.eye(4, dtype=np.float32)
        self._program['u_view'] = np.eye(4, dtype=np.float32)

        #
        self._coordinate = [0, 0]
        self._origin = [0, 0]

        #
        self._program['texture'] = np.zeros((self._height, self._width),
                                            dtype='uint8')

        #
        self.apply_magnification()
Beispiel #18
0
	def __init__(self):
		super().__init__(src_fbuffer, src_default)
		self.normal_prog = Program(src_normal.vert, src_normal.frag)
		self.phong_prog = Program(src_phong.vert, src_phong.frag)
		self.lookat_matrix = np.identity(4)
		self.material = BasicMaterial(self.fill_color)

		# Camera position
		self.camera_pos = np.zeros(3)
		# Blinn-Phong Parameters
		self.ambient = np.array([0.2]*3)
		self.diffuse = np.array([0.6]*3)
		self.specular = np.array([0.8]*3)
		self.shininess = 8
		# Lights
		self.MAX_LIGHTS_PER_CATEGORY = 8
		self.ambient_light_color = GlslList(self.MAX_LIGHTS_PER_CATEGORY, 3, np.float32)
		self.directional_light_dir = GlslList(self.MAX_LIGHTS_PER_CATEGORY, 3, np.float32)
		self.directional_light_color = GlslList(self.MAX_LIGHTS_PER_CATEGORY, 3, np.float32)
		self.directional_light_specular = GlslList(self.MAX_LIGHTS_PER_CATEGORY, 3, np.float32)
		self.point_light_color = GlslList(self.MAX_LIGHTS_PER_CATEGORY, 3, np.float32)
		self.point_light_pos = GlslList(self.MAX_LIGHTS_PER_CATEGORY, 3, np.float32)
		self.point_light_specular = GlslList(self.MAX_LIGHTS_PER_CATEGORY, 3, np.float32)
		self.const_falloff = GlslList(self.MAX_LIGHTS_PER_CATEGORY, 1, np.float32)
		self.linear_falloff = GlslList(self.MAX_LIGHTS_PER_CATEGORY, 1, np.float32)
		self.quadratic_falloff = GlslList(self.MAX_LIGHTS_PER_CATEGORY, 1, np.float32)
		self.curr_linear_falloff, self.curr_quadratic_falloff, self.curr_constant_falloff = 0.0, 0.0, 0.0
		self.light_specular = np.array([0.0]*3)
Beispiel #19
0
class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self)

        # Create program
        self._program = Program(VERT_SHADER, FRAG_SHADER)

        # Set uniforms and samplers
        self._program['a_position'] = VertexBuffer(positions)
        self._program['a_texcoord'] = VertexBuffer(texcoords)
        #
        self._program['u_texture1'] = Texture2D(im1)
        self._program['u_texture2'] = Texture2D(im2)
        self._program['u_texture3'] = Texture2D(im3)

    def on_initialize(self, event):
        gl.glClearColor(1, 1, 1, 1)

    def on_resize(self, event):
        width, height = event.size
        gl.glViewport(0, 0, width, height)

    def on_paint(self, event):

        # Clear
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

        # Draw shape with texture, nested context
        self._program.draw(gl.GL_TRIANGLE_STRIP)
Beispiel #20
0
class Canvas(app.Canvas):
    def __init__(self):
        self.image = Program(img_vertex, img_fragment, 4)
        self.image['position'] = (-1, -1), (-1, +1), (+1, -1), (+1, +1)
        self.image['texcoord'] = (0, 0), (0, +1), (+1, 0), (+1, +1)
        self.image['vmin'] = +0.1
        self.image['vmax'] = +0.9
        self.image['cmap'] = 0  # Colormap index to use

        self.image['colormaps'] = colormaps
        self.image['colormaps'].interpolation = 'linear'
        self.image['colormaps_shape'] = colormaps.shape[1], colormaps.shape[0]

        self.image['image'] = I.astype('float32')
        self.image['image'].interpolation = 'linear'
        app.Canvas.__init__(self, show=True, size=(512, 512),
                            keys='interactive')

    def on_initialize(self, event):
        set_clear_color('black')

    def on_resize(self, event):
        width, height = event.size
        set_viewport(0, 0, *event.size)

    def on_draw(self, event):
        clear(color=True, depth=True)
        self.image.draw('triangle_strip')
Beispiel #21
0
    def on_initialize(self, event):
        # Build cube data
        V, F, O = create_cube()
        vertices = VertexBuffer(V)
        self.faces = IndexBuffer(F)
        self.outline = IndexBuffer(O)

        # Build view, model, projection & normal
        # --------------------------------------
        self.view = np.eye(4, dtype=np.float32)
        model = np.eye(4, dtype=np.float32)
        translate(self.view, 0, 0, -5)
        normal = np.array(np.matrix(np.dot(self.view, model)).I.T)

        # Build program
        # --------------------------------------
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)
        self.program["u_light_position"] = 2, 2, 2
        self.program["u_light_intensity"] = 1, 1, 1
        self.program["u_model"] = model
        self.program["u_view"] = self.view
        self.program["u_normal"] = normal
        self.phi, self.theta = 0, 0

        # OpenGL initalization
        # --------------------------------------
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True,
                       polygon_offset=(1, 1),
                       blend_func=('src_alpha', 'one_minus_src_alpha'),
                       line_width=0.75)
        self.timer.start()
Beispiel #22
0
    def __init__(self):
        app.Canvas.__init__(self, size=(512, 512),
                            keys='interactive')

        self.image = Program(image_vertex, image_fragment, 4)
        self.image['position'] = (-1, -1), (-1, +1), (+1, -1), (+1, +1)
        self.image['texcoord'] = (0, 0), (0, +1), (+1, 0), (+1, +1)
        self.image['vmin'] = +0.0
        self.image['vmax'] = +1.0
        self.image['cmap'] = 0  # Colormap index to use
        self.image['colormaps'] = colormaps
        self.image['n_colormaps'] = colormaps.shape[0]
        self.image['image'] = I.astype('float32')
        self.image['image'].interpolation = 'linear'

        set_viewport(0, 0, *self.physical_size)

        self.lines = Program(lines_vertex, lines_fragment)
        self.lines["position"] = np.zeros((4+4+514+514, 2), np.float32)
        color = np.zeros((4+4+514+514, 4), np.float32)
        color[1:1+2, 3] = 0.25
        color[5:5+2, 3] = 0.25
        color[9:9+512, 3] = 0.5
        color[523:523+512, 3] = 0.5
        self.lines["color"] = color

        set_state(clear_color='white', blend=True,
                  blend_func=('src_alpha', 'one_minus_src_alpha'))

        self.show()
Beispiel #23
0
    def on_initialize(self, event):
        self.rho = 0.0
        # Build cube data
        # --------------------------------------
        self.checker = Program(cube_vertex, cube_fragment)
        self.checker['texture'] = checkerboard()
        self.checker['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.checker['texcoord'] = [(0, 0), (0, 1), (1, 0), (1, 1)]

        # sheet, indices = make_sheet((960, 1080))
        # sheet_buffer = VertexBuffer(sheet)

        left_eye = Texture2D((960, 1080, 3), interpolation='linear')
        self.left_eye_buffer = FrameBuffer(left_eye, RenderBuffer((960, 1080)))
        # Build program
        # --------------------------------------
        self.view = np.eye(4, dtype=np.float32)
        self.program = Program(vertex, fragment)
        distortion_buffer = VertexBuffer(make_distortion())
        self.program.bind(distortion_buffer)
        self.program['rotation'] = self.view
        self.program['texture'] = left_eye

        # OpenGL and Timer initalization
        # --------------------------------------
        set_state(clear_color=(.3, .3, .35, 1), depth_test=True)
        self.timer = app.Timer('auto', connect=self.on_timer, start=True)
        self._set_projection(self.size)
Beispiel #24
0
    def __init__(self):
        app.Canvas.__init__(self, size=(512, 512),
                            keys='interactive')
        self.image = Program(img_vertex, img_fragment, 4)
        self.image['position'] = (-1, -1), (-1, +1), (+1, -1), (+1, +1)
        self.image['texcoord'] = (0, 0), (0, +1), (+1, 0), (+1, +1)
        #self.image['vmin'] = +0.1
        #self.image['vmax'] = +0.9
        self.image['vmin'] = 0.1
        self.image['vmax'] = 1.0
        self.image['cmap'] = 1  # Colormap index to use

        self.image['colormaps'] = colormaps
        self.image['colormaps'].interpolation = 'linear'
        self.image['colormaps_shape'] = colormaps.shape[1], colormaps.shape[0]

        self.image['image'] = I.astype('float32')
        self.image['image'].interpolation = 'linear'

        set_clear_color('black')

        self.timer = app.Timer(0.25, self.on_timer)
        self.timer.start()

        self.show()
Beispiel #25
0
 def on_initialize(self, event):
     # Build program & data
     self.program = Program(vertex, fragment, count=4)
     self.program['color'] = [(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1),
                              (1, 1, 0, 1)]
     self.program['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
     self.clock = 0
     self.timer.start()
Beispiel #26
0
    def __init__(self):
        app.Canvas.__init__(self, title="Grayscott Reaction-Diffusion", size=(512, 512), keys="interactive")

        self.scale = 4
        self.comp_size = self.size
        comp_w, comp_h = self.comp_size
        dt = 1.0
        dd = 1.5
        species = {
            # name : [r_u, r_v, f, k]
            "Bacteria 1": [0.16, 0.08, 0.035, 0.065],
            "Bacteria 2": [0.14, 0.06, 0.035, 0.065],
            "Coral": [0.16, 0.08, 0.060, 0.062],
            "Fingerprint": [0.19, 0.05, 0.060, 0.062],
            "Spirals": [0.10, 0.10, 0.018, 0.050],
            "Spirals Dense": [0.12, 0.08, 0.020, 0.050],
            "Spirals Fast": [0.10, 0.16, 0.020, 0.050],
            "Unstable": [0.16, 0.08, 0.020, 0.055],
            "Worms 1": [0.16, 0.08, 0.050, 0.065],
            "Worms 2": [0.16, 0.08, 0.054, 0.063],
            "Zebrafish": [0.16, 0.08, 0.035, 0.060],
        }
        P = np.zeros((comp_h, comp_w, 4), dtype=np.float32)
        P[:, :] = species["Unstable"]

        UV = np.zeros((comp_h, comp_w, 4), dtype=np.float32)
        UV[:, :, 0] = 1.0
        r = 32
        UV[comp_h / 2 - r : comp_h / 2 + r, comp_w / 2 - r : comp_w / 2 + r, 0] = 0.50
        UV[comp_h / 2 - r : comp_h / 2 + r, comp_w / 2 - r : comp_w / 2 + r, 1] = 0.25
        UV += np.random.uniform(0.0, 0.01, (comp_h, comp_w, 4))
        UV[:, :, 2] = UV[:, :, 0]
        UV[:, :, 3] = UV[:, :, 1]

        self.pingpong = 1
        self.compute = Program(compute_vertex, compute_fragment, 4)
        self.compute["params"] = P
        self.compute["texture"] = UV
        self.compute["position"] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.compute["texcoord"] = [(0, 0), (0, 1), (1, 0), (1, 1)]
        self.compute["dt"] = dt
        self.compute["dx"] = 1.0 / comp_w
        self.compute["dy"] = 1.0 / comp_h
        self.compute["dd"] = dd
        self.compute["pingpong"] = self.pingpong

        self.render = Program(render_vertex, render_fragment, 4)
        self.render["position"] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.render["texcoord"] = [(0, 0), (0, 1), (1, 0), (1, 1)]
        self.render["texture"] = self.compute["texture"]
        self.render["pingpong"] = self.pingpong

        self.fbo = FrameBuffer(self.compute["texture"], RenderBuffer(self.comp_size))
        set_state(depth_test=False, clear_color="black")

        self._timer = app.Timer("auto", connect=self.update, start=True)

        self.show()
Beispiel #27
0
class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self,
                            size=(750, 750),
                            title='Textured cube',
                            keys='interactive')
        self.timer = app.Timer('auto', self.on_timer)
        self.counter = 0

        # Build cube data
        V, I, _ = create_cube()
        vertices = VertexBuffer(V)
        self.indices = IndexBuffer(I)

        # Build program
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)

        # Build view, model, projection & normal
        view = translate((0, 0, -5))
        model = np.eye(4, dtype=np.float32)
        self.program['model'] = model
        self.program['view'] = view
        self.program['texture'] = cam  # checkerboard()

        self.activate_zoom()

        self.phi, self.theta = 0, 0

        # OpenGL initalization
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True)
        self.timer.start()

        self.show()

    def on_draw(self, event):
        gloo.clear(color=True, depth=True)
        self.program.draw('triangles', self.indices)

    def on_resize(self, event):
        self.activate_zoom()

    def activate_zoom(self):
        gloo.set_viewport(0, 0, *self.physical_size)
        projection = perspective(45.0, self.size[0] / float(self.size[1]), 2.0,
                                 10.0)
        self.program['projection'] = projection

    def on_timer(self, event):
        self.counter += 1
        print("on_timer", self.counter)
        self.theta += .5
        self.phi += .5
        self.program['model'] = np.dot(rotate(self.theta, (0, 1, 0)),
                                       rotate(self.phi, (0, 1, 0)))
        # self.program['texture'] = im if self.counter % 200 else checkerboard()
        self.update()
Beispiel #28
0
class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self,
                            title='Rain [Move mouse]',
                            size=(512, 512),
                            keys='interactive')

        # Build data
        # --------------------------------------
        n = 500
        self.data = np.zeros(n, [('a_position', np.float32, 2),
                                 ('a_fg_color', np.float32, 4),
                                 ('a_size', np.float32, 1)])
        self.index = 0
        self.program = Program(vertex, fragment)
        self.vdata = VertexBuffer(self.data)
        self.program.bind(self.vdata)
        self.program['u_antialias'] = 1.00
        self.program['u_linewidth'] = 1.00
        self.program['u_model'] = np.eye(4, dtype=np.float32)
        self.program['u_view'] = np.eye(4, dtype=np.float32)

        self.activate_zoom()

        gloo.set_clear_color('white')
        gloo.set_state(blend=True,
                       blend_func=('src_alpha', 'one_minus_src_alpha'))
        self.timer = app.Timer('auto', self.on_timer, start=True)

        self.show()

    def on_draw(self, event):
        gloo.clear()
        self.program.draw('points')

    def on_resize(self, event):
        self.activate_zoom()

    def activate_zoom(self):
        gloo.set_viewport(0, 0, *self.physical_size)
        projection = ortho(0, self.size[0], 0, self.size[1], -1, +1)
        self.program['u_projection'] = projection

    def on_timer(self, event):
        self.data['a_fg_color'][..., 3] -= 0.01
        self.data['a_size'] += 1.0
        self.vdata.set_data(self.data)
        self.update()

    def on_mouse_move(self, event):
        x, y = event.pos
        h = self.size[1]
        self.data['a_position'][self.index] = x, h - y
        self.data['a_size'][self.index] = 5
        self.data['a_fg_color'][self.index] = 0, 0, 0, 1
        self.index = (self.index + 1) % 500
Beispiel #29
0
class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, title='Rain [Move mouse]',
                            size=(512, 512), keys='interactive')

        # Build data
        # --------------------------------------
        n = 500
        self.data = np.zeros(n, [('a_position', np.float32, 2),
                                 ('a_fg_color', np.float32, 4),
                                 ('a_size',     np.float32, 1)])
        self.index = 0
        self.program = Program(vertex, fragment)
        self.vdata = VertexBuffer(self.data)
        self.program.bind(self.vdata)
        self.program['u_antialias'] = 1.00
        self.program['u_linewidth'] = 1.00
        self.program['u_model'] = np.eye(4, dtype=np.float32)
        self.program['u_view'] = np.eye(4, dtype=np.float32)

        self.activate_zoom()

        gloo.set_clear_color('white')
        gloo.set_state(blend=True,
                       blend_func=('src_alpha', 'one_minus_src_alpha'))
        self.timer = app.Timer('auto', self.on_timer, start=True)

        self.show()

    def on_draw(self, event):
        gloo.clear()
        self.program.draw('points')

    def on_resize(self, event):
        self.activate_zoom()

    def activate_zoom(self):
        gloo.set_viewport(0, 0, *self.physical_size)
        projection = ortho(0, self.size[0], 0,
                           self.size[1], -1, +1)
        self.program['u_projection'] = projection

    def on_timer(self, event):
        self.data['a_fg_color'][..., 3] -= 0.01
        self.data['a_size'] += 1.0
        self.vdata.set_data(self.data)
        self.update()

    def on_mouse_move(self, event):
        x, y = event.pos
        h = self.size[1]
        self.data['a_position'][self.index] = x, h - y
        self.data['a_size'][self.index] = 5
        self.data['a_fg_color'][self.index] = 0, 0, 0, 1
        self.index = (self.index + 1) % 500
Beispiel #30
0
    def on_initialize(self, event):
        self.scale = 4
        self.comp_size = (256, 256)
        comp_w, comp_h = self.comp_size
        dt = 1.0
        dd = 1.5
        species = {
            # name : [r_u, r_v, f, k]
            'Bacteria 1': [0.16, 0.08, 0.035, 0.065],
            'Bacteria 2': [0.14, 0.06, 0.035, 0.065],
            'Coral': [0.16, 0.08, 0.060, 0.062],
            'Fingerprint': [0.19, 0.05, 0.060, 0.062],
            'Spirals': [0.10, 0.10, 0.018, 0.050],
            'Spirals Dense': [0.12, 0.08, 0.020, 0.050],
            'Spirals Fast': [0.10, 0.16, 0.020, 0.050],
            'Unstable': [0.16, 0.08, 0.020, 0.055],
            'Worms 1': [0.16, 0.08, 0.050, 0.065],
            'Worms 2': [0.16, 0.08, 0.054, 0.063],
            'Zebrafish': [0.16, 0.08, 0.035, 0.060]
        }
        P = np.zeros((comp_h, comp_w, 4), dtype=np.float32)
        P[:, :] = species['Unstable']

        UV = np.zeros((comp_h, comp_w, 4), dtype=np.float32)
        UV[:, :, 0] = 1.0
        r = 32
        UV[comp_h / 2 - r:comp_h / 2 + r, comp_w / 2 - r:comp_w / 2 + r,
           0] = 0.50
        UV[comp_h / 2 - r:comp_h / 2 + r, comp_w / 2 - r:comp_w / 2 + r,
           1] = 0.25
        UV += np.random.uniform(0.0, 0.01, (comp_h, comp_w, 4))
        UV[:, :, 2] = UV[:, :, 0]
        UV[:, :, 3] = UV[:, :, 1]

        self.pingpong = 1
        self.compute = Program(compute_vertex, compute_fragment, 4)
        self.compute["params"] = P
        self.compute["texture"] = UV
        self.compute["position"] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.compute["texcoord"] = [(0, 0), (0, 1), (1, 0), (1, 1)]
        self.compute['dt'] = dt
        self.compute['dx'] = 1.0 / comp_w
        self.compute['dy'] = 1.0 / comp_h
        self.compute['dd'] = dd
        self.compute['pingpong'] = self.pingpong

        self.render = Program(render_vertex, render_fragment, 4)
        self.render["position"] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.render["texcoord"] = [(0, 0), (0, 1), (1, 0), (1, 1)]
        self.render["texture"] = self.compute["texture"]
        self.render['pingpong'] = self.pingpong

        self.fbo = FrameBuffer(self.compute["texture"],
                               DepthBuffer(self.comp_size))
        set_state(depth_test=False, clear_color='black')
Beispiel #31
0
    def on_initialize(self, event):
        self.scale = 4
        self.comp_size = (256, 256)
        comp_w, comp_h = self.comp_size
        dt = 1.0
        dd = 1.5
        species = {
            # name : [r_u, r_v, f, k]
            'Bacteria 1': [0.16, 0.08, 0.035, 0.065],
            'Bacteria 2': [0.14, 0.06, 0.035, 0.065],
            'Coral': [0.16, 0.08, 0.060, 0.062],
            'Fingerprint': [0.19, 0.05, 0.060, 0.062],
            'Spirals': [0.10, 0.10, 0.018, 0.050],
            'Spirals Dense': [0.12, 0.08, 0.020, 0.050],
            'Spirals Fast': [0.10, 0.16, 0.020, 0.050],
            'Unstable': [0.16, 0.08, 0.020, 0.055],
            'Worms 1': [0.16, 0.08, 0.050, 0.065],
            'Worms 2': [0.16, 0.08, 0.054, 0.063],
            'Zebrafish': [0.16, 0.08, 0.035, 0.060]
        }
        P = np.zeros((comp_h, comp_w, 4), dtype=np.float32)
        P[:, :] = species['Unstable']

        UV = np.zeros((comp_h, comp_w, 4), dtype=np.float32)
        UV[:, :, 0] = 1.0
        r = 32
        UV[comp_h / 2 - r:comp_h / 2 + r,
           comp_w / 2 - r:comp_w / 2 + r, 0] = 0.50
        UV[comp_h / 2 - r:comp_h / 2 + r,
           comp_w / 2 - r:comp_w / 2 + r, 1] = 0.25
        UV += np.random.uniform(0.0, 0.01, (comp_h, comp_w, 4))
        UV[:, :, 2] = UV[:, :, 0]
        UV[:, :, 3] = UV[:, :, 1]

        self.pingpong = 1
        self.compute = Program(compute_vertex, compute_fragment, 4)
        self.compute["params"] = P
        self.compute["texture"] = UV
        self.compute["position"] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.compute["texcoord"] = [(0, 0), (0, 1), (1, 0), (1, 1)]
        self.compute['dt'] = dt
        self.compute['dx'] = 1.0 / comp_w
        self.compute['dy'] = 1.0 / comp_h
        self.compute['dd'] = dd
        self.compute['pingpong'] = self.pingpong

        self.render = Program(render_vertex, render_fragment, 4)
        self.render["position"] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.render["texcoord"] = [(0, 0), (0, 1), (1, 0), (1, 1)]
        self.render["texture"] = self.compute["texture"]
        self.render['pingpong'] = self.pingpong

        self.fbo = FrameBuffer(self.compute["texture"],
                               DepthBuffer(self.comp_size))
        set_state(depth_test=False, clear_color='black')
Beispiel #32
0
    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()
Beispiel #33
0
def test_use_texture3D():
    """Test using a 3D texture"""
    vals = [0, 200, 100, 0, 255, 0, 100]
    d, h, w = len(vals), 3, 5
    data = np.zeros((d, h, w), np.float32)

    VERT_SHADER = """
    attribute vec2 a_pos;
    varying vec2 v_pos;

    void main (void)
    {
        v_pos = a_pos;
        gl_Position = vec4(a_pos, 0., 1.);
    }
    """

    FRAG_SHADER = """
    uniform sampler3D u_texture;
    varying vec2 v_pos;
    uniform float i;
    void main()
    {
        gl_FragColor = texture3D(u_texture,
                                 vec3((v_pos.y+1.)/2., (v_pos.x+1.)/2., i));
        gl_FragColor.a = 1.;
    }
    """
    # populate the depth "slices" with different gray colors in the bottom left
    for ii, val in enumerate(vals):
        data[ii, :2, :3] = val / 255.
    with Canvas(size=(100, 100)) as c:
        if not has_pyopengl():
            t = Texture3D(data)
            assert_raises(ImportError, t.glir.flush, c.context.shared.parser)
            return
        program = Program(VERT_SHADER, FRAG_SHADER)
        program['a_pos'] = [[-1., -1.], [1., -1.], [-1., 1.], [1., 1.]]
        tex = Texture3D(data, interpolation='nearest')
        assert_equal(tex.width, w)
        assert_equal(tex.height, h)
        assert_equal(tex.depth, d)
        program['u_texture'] = tex
        for ii, val in enumerate(vals):
            set_viewport(0, 0, w, h)
            clear(color='black')
            iii = (ii + 0.5) / float(d)
            print(ii, iii)
            program['i'] = iii
            program.draw('triangle_strip')
            out = _screenshot()[:, :, 0].astype(int)[::-1]
            expected = np.zeros_like(out)
            expected[:2, :3] = val
            assert_allclose(out, expected, atol=1./255.)
Beispiel #34
0
    def __init__(self):
        app.Canvas.__init__(self,
                            title="Conway game of life",
                            size=(512, 512),
                            keys='interactive')

        # Build programs
        # --------------
        self.comp_size = self.size
        size = self.comp_size + (4, )
        Z = np.zeros(size, dtype=np.float32)
        Z[...] = np.random.randint(0, 2, size)
        Z[:256, :256, :] = 0
        gun = """
        ........................O...........
        ......................O.O...........
        ............OO......OO............OO
        ...........O...O....OO............OO
        OO........O.....O...OO..............
        OO........O...O.OO....O.O...........
        ..........O.....O.......O...........
        ...........O...O....................
        ............OO......................"""
        x, y = 0, 0
        for i in range(len(gun)):
            if gun[i] == '\n':
                y += 1
                x = 0
            elif gun[i] == 'O':
                Z[y, x] = 1
            x += 1

        self.pingpong = 1
        self.compute = Program(compute_vertex, compute_fragment, 4)
        self.compute["texture"] = Z
        self.compute["position"] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.compute["texcoord"] = [(0, 0), (0, 1), (1, 0), (1, 1)]
        self.compute['dx'] = 1.0 / size[1]
        self.compute['dy'] = 1.0 / size[0]
        self.compute['pingpong'] = self.pingpong

        self.render = Program(render_vertex, render_fragment, 4)
        self.render["position"] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.render["texcoord"] = [(0, 0), (0, 1), (1, 0), (1, 1)]
        self.render["texture"] = self.compute["texture"]
        self.render['pingpong'] = self.pingpong

        self.fbo = FrameBuffer(self.compute["texture"],
                               RenderBuffer(self.comp_size))
        set_state(depth_test=False, clear_color='black')

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

        self.show()
Beispiel #35
0
def test_use_texture3D():
    """Test using a 3D texture"""
    vals = [0, 200, 100, 0, 255, 0, 100]
    d, h, w = len(vals), 3, 5
    data = np.zeros((d, h, w), np.float32)

    VERT_SHADER = """
    attribute vec2 a_pos;
    varying vec2 v_pos;

    void main (void)
    {
        v_pos = a_pos;
        gl_Position = vec4(a_pos, 0., 1.);
    }
    """

    FRAG_SHADER = """
    uniform sampler3D u_texture;
    varying vec2 v_pos;
    uniform float i;
    void main()
    {
        gl_FragColor = texture3D(u_texture,
                                 vec3((v_pos.y+1.)/2., (v_pos.x+1.)/2., i));
        gl_FragColor.a = 1.;
    }
    """
    # populate the depth "slices" with different gray colors in the bottom left
    for ii, val in enumerate(vals):
        data[ii, :2, :3] = val / 255.
    with Canvas(size=(100, 100)) as c:
        if not has_pyopengl():
            t = Texture3D(data)
            assert_raises(ImportError, t.glir.flush, c.context.shared.parser)
            return
        program = Program(VERT_SHADER, FRAG_SHADER)
        program['a_pos'] = [[-1., -1.], [1., -1.], [-1., 1.], [1., 1.]]
        tex = Texture3D(data, interpolation='nearest')
        assert_equal(tex.width, w)
        assert_equal(tex.height, h)
        assert_equal(tex.depth, d)
        program['u_texture'] = tex
        for ii, val in enumerate(vals):
            set_viewport(0, 0, w, h)
            clear(color='black')
            iii = (ii + 0.5) / float(d)
            print(ii, iii)
            program['i'] = iii
            program.draw('triangle_strip')
            out = _screenshot()[:, :, 0].astype(int)[::-1]
            expected = np.zeros_like(out)
            expected[:2, :3] = val
            assert_allclose(out, expected, atol=1. / 255.)
Beispiel #36
0
    def __init__(self):
        app.Canvas.__init__(self,
                            size=(512, 512),
                            title='Colored quad',
                            keys='interactive')

        # Build program & data
        self.program = Program(vertex, fragment, count=4)
        self.program['color'] = [(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1),
                                 (1, 1, 0, 1)]
        self.program['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
    def __init__(self):
        app.Canvas.__init__(self)

        # Time
        self._t = time.time()
        self._pos = 0.0, 0.0
        self._button = None

        # Create program
        self.program = Program(VERT_SHADER, FRAG_SHADER)
        self.program['color'] = VertexBuffer(particles['color'], client=True)
        self.program['size'] = VertexBuffer(particles['size'], client=True)
Beispiel #38
0
class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, size=(512, 512),
                            keys='interactive')
        self.image = Program(img_vertex, img_fragment, 4)
        self.image['position'] = (-1, -1), (-1, +1), (+1, -1), (+1, +1)
        self.image['texcoord'] = (0, 0), (0, +1), (+1, 0), (+1, +1)
        #self.image['vmin'] = +0.1
        #self.image['vmax'] = +0.9
        self.image['vmin'] = 0.1
        self.image['vmax'] = 1.0
        self.image['cmap'] = 1  # Colormap index to use

        self.image['colormaps'] = colormaps
        self.image['colormaps'].interpolation = 'linear'
        self.image['colormaps_shape'] = colormaps.shape[1], colormaps.shape[0]

        self.image['image'] = I.astype('float32')
        self.image['image'].interpolation = 'linear'

        set_clear_color('black')

        self.timer = app.Timer(0.25, self.on_timer)
        self.timer.start()

        self.show()

    def on_resize(self, event):
        width, height = event.physical_size
        set_viewport(0, 0, *event.physical_size)

    def on_draw(self, event):
        clear(color=True, depth=True)
        self.image.draw('triangle_strip')

    def on_timer(self, event):
        #self.clock += 0.001 * 1000.0 / 60.
        #self.program['theta'] = self.clock
        global I
        psi=iterate(psi)
        I=abs(psi[0])
        self.I = I
        #print psi
        self.image['image'] = I.astype('float32')
        self.update()
        #self.timer.stop()

    def on_key_press(self, ev):
        if ev.key.name == 'Space':
            if self.timer.running:
                self.timer.stop()
            else:
                self.timer.start()
Beispiel #39
0
    def __init__(self):
        app.Canvas.__init__(self,
                            size=(800, 800),
                            title='Colored quad',
                            keys='interactive')

        self.program = Program(vertex, fragment, count=4)
        self.program['color'] = [(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1),
                                 (1, 1, 0, 1)]
        self.program['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        gloo.set_viewport(0, 0, *self.physical_size)
        self.show()
Beispiel #40
0
    def __init__(self):
        app.Canvas.__init__(self, title="Conway game of life",
                            size=(512, 512), keys='interactive')

        # Build programs
        # --------------
        self.comp_size = self.size
        size = self.comp_size + (4,)
        Z = np.zeros(size, dtype=np.float32)
        Z[...] = np.random.randint(0, 2, size)
        Z[:256, :256, :] = 0
        gun = """
        ........................O...........
        ......................O.O...........
        ............OO......OO............OO
        ...........O...O....OO............OO
        OO........O.....O...OO..............
        OO........O...O.OO....O.O...........
        ..........O.....O.......O...........
        ...........O...O....................
        ............OO......................"""
        x, y = 0, 0
        for i in range(len(gun)):
            if gun[i] == '\n':
                y += 1
                x = 0
            elif gun[i] == 'O':
                Z[y, x] = 1
            x += 1

        self.pingpong = 1
        self.compute = Program(compute_vertex, compute_fragment, 4)
        self.compute["texture"] = Z
        self.compute["position"] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.compute["texcoord"] = [(0, 0), (0, 1), (1, 0), (1, 1)]
        self.compute['dx'] = 1.0 / size[1]
        self.compute['dy'] = 1.0 / size[0]
        self.compute['pingpong'] = self.pingpong

        self.render = Program(render_vertex, render_fragment, 4)
        self.render["position"] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.render["texcoord"] = [(0, 0), (0, 1), (1, 0), (1, 1)]
        self.render["texture"] = self.compute["texture"]
        self.render['pingpong'] = self.pingpong

        self.fbo = FrameBuffer(self.compute["texture"],
                               RenderBuffer(self.comp_size))
        set_state(depth_test=False, clear_color='black')

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

        self.show()
    def __init__(self):
        app.Canvas.__init__(self)

        # Create program
        self._program = Program(VERT_SHADER, FRAG_SHADER)

        # Set uniforms and samplers
        self._program['a_position'] = VertexBuffer(positions)
        self._program['a_texcoord'] = VertexBuffer(texcoords)
        #
        self._program['u_texture1'] = Texture2D(im1)
        self._program['u_texture2'] = Texture2D(im2)
        self._program['u_texture3'] = Texture2D(im3)
Beispiel #42
0
    def reset_view(self):
        self.viewport = (
            0,
            0,
            int(builtins.width * builtins.pixel_x_density),
            int(builtins.height * builtins.pixel_y_density),
        )
        self.texture_viewport = (
            0,
            0,
            builtins.width,
            builtins.height,
        )

        gloo.set_viewport(*self.viewport)  # pylint: disable=no-member

        cz = (builtins.height / 2) / math.tan(math.radians(30))
        self.projection_matrix = matrix.perspective_matrix(
            math.radians(60),
            builtins.width / builtins.height,
            0.1 * cz,
            10 * cz
        )
        self.modelview_matrix = matrix.translation_matrix(-builtins.width / 2,
                                                          builtins.height / 2,
                                                          -cz)
        self.modelview_matrix = self.modelview_matrix.dot(
            matrix.scale_transform(1, -1, 1))

        self.transform_matrix = np.identity(4)

        self.default_prog['modelview'] = self.modelview_matrix.T.flatten()
        self.default_prog['projection'] = self.projection_matrix.T.flatten()

        self.texture_prog['modelview'] = self.modelview_matrix.T.flatten()
        self.texture_prog['projection'] = self.projection_matrix.T.flatten()

        self.line_prog = Program(src_line.vert, src_line.frag)

        self.line_prog['modelview'] = self.modelview_matrix.T.flatten()
        self.line_prog['projection'] = self.projection_matrix.T.flatten()
        self.line_prog["height"] = builtins.height

        self.fbuffer_tex_front = Texture2D(
            (builtins.height, builtins.width, 3))
        self.fbuffer_tex_back = Texture2D((builtins.height, builtins.width, 3))

        for buf in [self.fbuffer_tex_front, self.fbuffer_tex_back]:
            self.fbuffer.color_buffer = buf
            with self.fbuffer:
                self.clear()
Beispiel #43
0
class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, size=(512, 512), title='Textured cube',
                            keys='interactive')
        self.timer = app.Timer('auto', self.on_timer)

        # Build cube data
        V, I, _ = create_cube()
        vertices = VertexBuffer(V)
        self.indices = IndexBuffer(I)

        # Build program
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)

        # Build view, model, projection & normal
        view = translate((0, 0, -5))
        model = np.eye(4, dtype=np.float32)
        self.program['model'] = model
        self.program['view'] = view
        self.program['texture'] = checkerboard()

        self.activate_zoom()

        self.phi, self.theta = 0, 0

        # OpenGL initalization
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True)
        self.timer.start()

        self.show()

    def on_draw(self, event):
        gloo.clear(color=True, depth=True)
        self.program.draw('triangles', self.indices)

    def on_resize(self, event):
        self.activate_zoom()

    def activate_zoom(self):
        gloo.set_viewport(0, 0, *self.physical_size)
        projection = perspective(45.0, self.size[0] / float(self.size[1]),
                                 2.0, 10.0)
        self.program['projection'] = projection

    def on_timer(self, event):
        self.theta += .5
        self.phi += .5
        self.program['model'] = np.dot(rotate(self.theta, (0, 0, 1)),
                                       rotate(self.phi, (0, 1, 0)))
        self.update()
Beispiel #44
0
    def __init__(self):
        vertices, indices, _ = create_cube()
        vertices = VertexBuffer(vertices)
        self.indices = IndexBuffer(indices)
        self.program = Program(self.cube_vertex, self.cube_fragment)

        self.model = np.eye(4)
        self.view = np.eye(4)

        self.program.bind(vertices)
        self.program['texture'] = utils.checkerboard()
        self.program['texture'].interpolation = 'linear'
        self.program['model'] = self.model
        self.program['view'] = self.view
Beispiel #45
0
class GpaphicBlueprint:
    def __init__(self):
        self.kind = ''
        self._color = (0, 0, 0)
        self._program = None
        self._indices = None
        self._mesh = None

    def getProgram(self):
        return self._program

    def getIndices(self):
        return self._indices

    def setColor(self, newColor):
        '''

        Mit dieser Methode koennen andere Klassen die Farb-Uniform des _programs setzen.

        Parameter: newColor
        Rueckgabewerte: -

        '''

        self._color = newColor
        self._program['color'] = self._color

    def buildProgram(self):
        '''

        In dieser Methode wird das Programm samt Indices einer Kugel errechnet. Das Ganze wird mithilfe der
        Bibliothek vispy.gloo gemacht.

        Parameter: -
        Rueckgabewerte: -

        '''

        vertices = np.zeros(self._mesh.getVertices().shape[0],
                            [("position", np.float32, 3)])
        vertices["position"] = self._mesh.getVertices()
        vertices = VertexBuffer(vertices)
        indices = self._mesh.getIndices()
        self._indices = IndexBuffer(indices)
        self._program = Program(vertex, fragment)
        self._program.bind(vertices)
        self._program['color'] = self._color
        self._program['model'] = None
        self._program['view'] = None
        self._program['drawHorizon'] = -3
Beispiel #46
0
    def on_initialize(self, event):
        # Build cube data
        # --------------------------------------

        texcoord = [(0, 0), (0, 1), (1, 0), (1, 1)]
        vertices = [(-2, -1, 0), (-2, +1, 0), (+2, -1, 0), (+2, +1, 0)]

        vertices = VertexBuffer(vertices)

        camera_pitch = 0.0 # Degrees
        self.rotate = [camera_pitch, 0, 0]
        self.translate = [0, 0, -3]

        # Build program
        # --------------------------------------
        view = np.eye(4, dtype=np.float32)
        model = np.eye(4, dtype=np.float32)
        scale(model, 1, 1, 1)
        self.phi = 0

        self.cube = Program(cube_vertex, cube_fragment)
        self.cube['position'] = vertices
        # 4640 x 2256
        imtex = cv2.imread(os.path.join(img_path, 'stage.jpg')) 
        self.cube['texcoord'] = texcoord
        self.cube["texture"] = np.uint8(np.clip(imtex + np.random.randint(-60, 20, size=imtex.shape), 0, 255)) + 5
        self.cube["texture"].interpolation = 'linear'
        self.cube['model'] = model
        self.cube['view'] = view


        color = Texture2D((640, 640, 3), interpolation='linear')
        self.framebuffer = FrameBuffer(color, RenderBuffer((640, 640)))

        self.quad = Program(quad_vertex, quad_fragment)
        self.quad['texcoord'] = [(0, 0), (0, 1), (1, 0), (1, 1)]

        self.quad['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]

        self.quad['texture'] = color

        self.objects = [self.cube]

        # OpenGL and Timer initalization
        # --------------------------------------
        set_state(clear_color=(.3, .3, .35, 1), depth_test=True)
        self.timer = app.Timer('auto', connect=self.on_timer, start=True)
        self.pub_timer = app.Timer(0.1, connect=self.send_ros_img, start=True)
        self._set_projection(self.size)
Beispiel #47
0
class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, size=(512, 512), title='Textured cube',
                            close_keys='escape')
        self.timer = app.Timer(1./60., self.on_timer)

    def on_initialize(self, event):
        # Build cube data
        V, I, _ = cube()
        vertices = VertexBuffer(V)
        self.indices = IndexBuffer(I)

        # Build program
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)

        # Build view, model, projection & normal
        view = np.eye(4, dtype=np.float32)
        model = np.eye(4, dtype=np.float32)
        translate(view, 0, 0, -5)
        self.program['model'] = model
        self.program['view'] = view
        self.program['texture'] = checkerboard()

        self.phi, self.theta = 0, 0

        # OpenGL initalization
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True)
        self.timer.start()

    def on_draw(self, event):
        gloo.clear(color=True, depth=True)
        self.program.draw('triangles', self.indices)

    def on_resize(self, event):
        gloo.set_viewport(0, 0, *event.size)
        projection = perspective(45.0, event.size[0] / float(event.size[1]),
                                 2.0, 10.0)
        self.program['projection'] = projection

    def on_timer(self, event):
        self.theta += .5
        self.phi += .5
        model = np.eye(4, dtype=np.float32)
        rotate(model, self.theta, 0, 0, 1)
        rotate(model, self.phi, 0, 1, 0)
        self.program['model'] = model
        self.update()
Beispiel #48
0
    def on_initialize(self, event):
        # Build cube data
        V, F, O = create_cube()
        vertices = VertexBuffer(V)
        self.faces = IndexBuffer(F)
        self.outline = IndexBuffer(O)

        # Build view, model, projection & normal
        # --------------------------------------
        self.view = np.eye(4, dtype=np.float32)
        model = np.eye(4, dtype=np.float32)
        translate(self.view, 0, 0, -5)
        normal = np.array(np.matrix(np.dot(self.view, model)).I.T)

        # Build program
        # --------------------------------------
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)
        self.program["u_light_position"] = 2, 2, 2
        self.program["u_light_intensity"] = 1, 1, 1
        self.program["u_model"] = model
        self.program["u_view"] = self.view
        self.program["u_normal"] = normal
        self.phi, self.theta = 0, 0

        # OpenGL initalization
        # --------------------------------------
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True,
                       polygon_offset=(1, 1),
                       blend_func=('src_alpha', 'one_minus_src_alpha'),
                       line_width=0.75)
        self.timer.start()
Beispiel #49
0
    def __init__(self):
        app.Canvas.__init__(self, title='Rain [Move mouse]',
                            size=(512, 512), keys='interactive')

        # Build data
        # --------------------------------------
        n = 500
        self.data = np.zeros(n, [('a_position', np.float32, 2),
                                 ('a_fg_color', np.float32, 4),
                                 ('a_size',     np.float32, 1)])
        self.index = 0
        self.program = Program(vertex, fragment)
        self.vdata = VertexBuffer(self.data)
        self.program.bind(self.vdata)
        self.program['u_antialias'] = 1.00
        self.program['u_linewidth'] = 1.00
        self.program['u_model'] = np.eye(4, dtype=np.float32)
        self.program['u_view'] = np.eye(4, dtype=np.float32)

        self.activate_zoom()

        gloo.set_clear_color('white')
        gloo.set_state(blend=True,
                       blend_func=('src_alpha', 'one_minus_src_alpha'))
        self.timer = app.Timer('auto', self.on_timer, start=True)

        self.show()
Beispiel #50
0
    def __init__(self):
        app.Canvas.__init__(self, size=(512, 512), title='Textured cube',
                            keys='interactive')
        self.timer = app.Timer('auto', self.on_timer)

        # Build cube data
        V, I, _ = create_cube()
        vertices = VertexBuffer(V)
        self.indices = IndexBuffer(I)

        # Build program
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)

        # Build view, model, projection & normal
        view = np.eye(4, dtype=np.float32)
        model = np.eye(4, dtype=np.float32)
        translate(view, 0, 0, -5)
        self.program['model'] = model
        self.program['view'] = view
        self.program['texture'] = checkerboard()

        self.phi, self.theta = 0, 0

        # OpenGL initalization
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True)
        self.timer.start()
Beispiel #51
0
    def on_initialize(self, event):
        # Build cube data
        V, I, O = create_cube()
        vertices = VertexBuffer(V)
        self.faces = IndexBuffer(I)
        self.outline = IndexBuffer(O)

        # Build program
        # --------------------------------------
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)

        # Build view, model, projection & normal
        # --------------------------------------
        view = np.eye(4, dtype=np.float32)
        model = np.eye(4, dtype=np.float32)
        translate(view, 0, 0, -5)
        self.program['u_model'] = model
        self.program['u_view'] = view
        self.phi, self.theta = 0, 0

        # OpenGL initalization
        # --------------------------------------
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True,
                       polygon_offset=(1, 1), line_width=0.75,
                       blend_func=('src_alpha', 'one_minus_src_alpha'))
        self.timer.start()
Beispiel #52
0
    def __init__(self):
        app.Canvas.__init__(self, size=(512, 512), title='Colored cube',
                            keys='interactive')

        # Build cube data
        V, I, _ = create_cube()
        vertices = VertexBuffer(V)
        self.indices = IndexBuffer(I)

        # Build program
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)

        # Build view, model, projection & normal
        view = translate((0, 0, -5))
        model = np.eye(4, dtype=np.float32)
        self.program['model'] = model
        self.program['view'] = view
        self.phi, self.theta = 0, 0
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True)

        self.activate_zoom()

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

        self.show()
Beispiel #53
0
    def __init__(self, *args, **kwargs):
        '''Drawable(*args, **kwargs) -> Drawable
        Everything is tracked internally, different drawables will handle things differently
        Inherit from this for all drawables.

        Inheriting:
            You must define a make_mesh, make_shaders, and draw method. 
            If you do not make shaders, you will get a default
            If you do not make a mesh, you'll get a square that takes up the screen

        '''
        self.model = np.eye(4)
        self.view = np.eye(4)
        self.projection = np.eye(4)

        self.mesh = self.make_mesh()
        self.vert_shader, self.frag_shader = self.make_shaders()
        self.program = Program(self.vert_shader, self.frag_shader)
        self.program.bind(VertexBuffer(self.mesh))
        if hasattr(self, make_texture):
            self.texture = self.make_texture()
            assert isinstance(self.texture, Texture2D), "Texture passed is not a texture!"

        self.program['texture'] = self.texture
        cube["texture"].interpolation = 'linear'
Beispiel #54
0
 def on_initialize(self, event):
     # 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()
Beispiel #55
0
    def __init__(self):
        app.Canvas.__init__(self, size=(512, 512), title='Rotating cube',
                            keys='interactive')
        self.timer = app.Timer('auto', self.on_timer)

        # Build cube data
        V, I, outline = create_cube()
        vertices = VertexBuffer(V)
        self.faces = IndexBuffer(I)
        self.outline = IndexBuffer(outline)

        # Build program
        # --------------------------------------
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)

        # Build view, model, projection & normal
        # --------------------------------------
        view = translate((0, 0, -5))
        model = np.eye(4, dtype=np.float32)

        self.program['u_model'] = model
        self.program['u_view'] = view
        self.phi, self.theta = 0, 0

        self.activate_zoom()

        # OpenGL initialization
        # --------------------------------------
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True,
                       polygon_offset=(1, 1), line_width=0.75,
                       blend_func=('src_alpha', 'one_minus_src_alpha'))
        self.timer.start()

        self.show()
Beispiel #56
0
 def on_initialize(self, event):
     # Build program & data
     self.program = Program(vertex, fragment, count=4)
     self.program['color'] = [(1, 0, 0, 1), (0, 1, 0, 1),
                              (0, 0, 1, 1), (1, 1, 0, 1)]
     self.program['position'] = [(-1, -1), (-1, +1),
                                 (+1, -1), (+1, +1)]
Beispiel #57
0
    def __init__(self):
        '''Map drawable - contains the goddamn map
        '''
        self.projection = np.eye(4)
        self.view = np.eye(4)

        self.model = scale(np.eye(4), 0.6)
        orientation_vector = (0, 1, 0)
        unit_orientation_angle = np.array(orientation_vector) / np.linalg.norm(orientation_vector)
        rotate(self.model, -30, *unit_orientation_angle)
        translate(self.model, -2.2, -2.4, -9)
        
        height, width = 5.0, 5.0  # Meters

        # Add texture coordinates
        # Rectangle of height height
        self.vertices = np.array([
            [-width / 2, -height / 2, 0],
            [ width / 2, -height / 2, 0],
            [ width / 2,  height / 2, 0],
            [-width / 2,  height / 2, 0],
        ], dtype=np.float32)

        self.tex_coords = np.array([
            [0, 1],
            [1, 1],
            [1, 0],
            [0, 0],
        ], dtype=np.float32)

        self.indices = IndexBuffer([
            0, 1, 2,
            2, 3, 0,
        ])

        ###### TESTING
        self.position_lla = self.ecef2llh((738575.65, -5498374.10, 3136355.42))
        ###### TESTING

        self.map, self.ranges = self.cache_map(self.position_lla[:2])
        self.map, self.ranges = self.get_map(self.position_lla[:2])
        self.program = Program(self.frame_vertex_shader, self.frame_frag_shader)

        default_map_transform = np.eye(4)

        self.program['vertex_position'] = self.vertices
        self.program['default_texcoord'] = self.tex_coords
        self.program['zoom'] = 1
        self.program['view'] = self.view
        self.program['model'] = self.model
        self.program['projection'] = self.projection

        self.program['map_transform'] = default_map_transform
        self.program['map_center'] = self.position_lla[:2]
        self.program['map_texture'] = self.map
        self.program['corners'] = self.ranges
        self.program['user_position'] = self.position_lla[:2]
        self.program['hide'] = 0
Beispiel #58
0
class Example(Drawable):
    '''Draw a cube'''    
    cube_vertex = """
        #version 120
        uniform mat4 model;
        uniform mat4 view;
        uniform mat4 projection;
        attribute vec3 position;
        attribute vec2 texcoord;
        varying vec2 v_texcoord;
        void main()
        {
            gl_Position = projection * view * model * vec4(position, 1.0);
            v_texcoord = texcoord;
        }
    """
    
    cube_fragment = """
        #version 120
        uniform sampler2D texture;
        varying vec2 v_texcoord;
        void main()
        {
            float r = texture2D(texture, v_texcoord).r;
            gl_FragColor = vec4(0, r, r, 1);
        }
    """

    def __init__(self):
        vertices, indices, _ = create_cube()
        vertices = VertexBuffer(vertices)
        self.indices = IndexBuffer(indices)
        self.program = Program(self.cube_vertex, self.cube_fragment)

        self.model = np.eye(4)
        self.view = np.eye(4)

        self.program.bind(vertices)
        self.program['texture'] = utils.checkerboard()
        self.program['texture'].interpolation = 'linear'
        self.program['model'] = self.model
        self.program['view'] = self.view

    def draw(self):
        self.program.draw('triangles', self.indices)
Beispiel #59
0
    def on_initialize(self, event):
        # Build programs
        # --------------
        self.comp_size = (512, 512)
        size = self.comp_size + (4,)
        Z = np.zeros(size, dtype=np.float32)
        Z[...] = np.random.randint(0, 2, size)
        Z[:256, :256, :] = 0
        gun = """
        ........................O...........
        ......................O.O...........
        ............OO......OO............OO
        ...........O...O....OO............OO
        OO........O.....O...OO..............
        OO........O...O.OO....O.O...........
        ..........O.....O.......O...........
        ...........O...O....................
        ............OO......................"""
        x, y = 0, 0
        for i in range(len(gun)):
            if gun[i] == '\n':
                y += 1
                x = 0
            elif gun[i] == 'O':
                Z[y, x] = 1
            x += 1

        self.pingpong = 1
        self.compute = Program(compute_vertex, compute_fragment, 4)
        self.compute["texture"] = Z
        self.compute["position"] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.compute["texcoord"] = [(0, 0), (0, 1), (1, 0), (1, 1)]
        self.compute['dx'] = 1.0 / size[1]
        self.compute['dy'] = 1.0 / size[0]
        self.compute['pingpong'] = self.pingpong

        self.render = Program(render_vertex, render_fragment, 4)
        self.render["position"] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.render["texcoord"] = [(0, 0), (0, 1), (1, 0), (1, 1)]
        self.render["texture"] = self.compute["texture"]
        self.render['pingpong'] = self.pingpong

        self.fbo = FrameBuffer(self.compute["texture"],
                               DepthBuffer(self.comp_size))
        set_state(depth_test=False, clear_color='black')