Beispiel #1
0
 def on_resize(self, width, height):
     gl.glViewport(0, 0, width, height)
     gl.glMatrixMode(gl.GL_PROJECTION)
     gl.glLoadIdentity()
     gl.gluPerspective(60., width / float(height), .01, 1000.)
     gl.glMatrixMode(gl.GL_MODELVIEW)
     self.view['ball'].place([width/2, height/2], (width+height)/2)
Beispiel #2
0
    def set_3d(self):
        """ Configure OpenGL to draw in 3d.

        """
        width, height = self.get_size()

        gl.glEnable(gl.GL_DEPTH_TEST)

        gl.glViewport(0, 0, width, height)
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.gluPerspective(65.0, width / float(height), 0.1, DIST)
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()

        x, y = self.rotation
        gl.glRotatef(x, 0, 1, 0)
        gl.glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x)))
        x, y, z = self.position
        gl.glTranslatef(-x, -y, -z)

        gl.glEnable(gl.GL_LIGHTING)
        gl.glLightModelfv(gl.GL_LIGHT_MODEL_AMBIENT, GLfloat4(0.05,0.05,0.05,1.0))
        gl.glEnable(gl.GL_COLOR_MATERIAL)
        gl.glColorMaterial(gl.GL_FRONT, gl.GL_AMBIENT_AND_DIFFUSE)
        #gl.glLightfv(gl.GL_LIGHT1,gl.GL_SPOT_DIRECTION, GLfloat3(0,0,-1))
        gl.glLightfv(gl.GL_LIGHT1, gl.GL_AMBIENT, GLfloat4(0.5,0.5,0.5,1.0))
        gl.glLightfv(gl.GL_LIGHT1, gl.GL_DIFFUSE, GLfloat4(1.0,1.0,1.0,1.0))
        gl.glLightfv(gl.GL_LIGHT1, gl.GL_POSITION, GLfloat4(0.35,1.0,0.65,0.0))
        #gl.glLightfv(gl.GL_LIGHT0,gl.GL_SPECULAR, GLfloat4(1,1,1,1))
        gl.glDisable(gl.GL_LIGHT0)
        gl.glEnable(gl.GL_LIGHT1)
Beispiel #3
0
    def draw(self):
        # set up projection
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.glViewport(self.x, self.y, self.width, self.height)
        gl.glOrtho(0, self.width, 0, self.height, self.near, self.far)
        gl.glMatrixMode(gl.GL_MODELVIEW)

        fx, fy = self._determine_focus()

        w2 = self.width / 2
        h2 = self.height / 2
        x1, y1 = fx - w2, fy - h2
        x2, y2 = fx + w2, fy + h2

        gl.glPushMatrix()
        gl.glTranslatef(self.width / 2 - fx, self.height / 2 - fy, 0)
        for layer in self.layers:
            if hasattr(layer, 'x'):
                translate = layer.x or layer.y
            else:
                translate = False
            if translate:
                gl.glPushMatrix()
                gl.glTranslatef(layer.x, layer.y, 0)
            layer.draw()
            if translate:
                gl.glPopMatrix()
        gl.glPopMatrix()
Beispiel #4
0
    def paint(self, func):
        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()

        gl.gluOrtho2D(
            0,
            self.width,
            0,
            self.height
        )

        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()
        gl.glViewport(0, 0, self.width, self.height)

        gl.glBindFramebufferEXT(gl.GL_DRAW_FRAMEBUFFER_EXT,
                                self.col_buffer.gl_buffer)

        gl.glFramebufferTexture2DEXT(
            gl.GL_DRAW_FRAMEBUFFER_EXT,
            gl.GL_COLOR_ATTACHMENT0_EXT,
            self.texture.target, self.texture.id, 0)

        func()

        gl.glBindFramebufferEXT(gl.GL_DRAW_FRAMEBUFFER_EXT, 0)
Beispiel #5
0
 def on_resize(self, width, height):
     glViewport(0, 0, width, height)
     glMatrixMode(GL_PROJECTION)
     glLoadIdentity()
     glOrtho(0, width, 0, height, -1000, 1000)
     glMatrixMode(GL_MODELVIEW)
     return pyglet.event.EVENT_HANDLED
 def resizeGL(self, width, height): # bugfix, swapped args
    _import_gl()
    glViewport(0, 0, width, height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0)
    glMatrixMode(GL_MODELVIEW)
Beispiel #7
0
 def on_resize(self, x, y):
     logging.info('Window Resized to {}x{}'.format(x, y))
     x = max(x, 1)
     y = max(y, 1)
     gl.glViewport(0, 0, x, y)
     self.wm.on_resize(x, y)
     self.view.on_resize(x, y)
Beispiel #8
0
def on_resize(width, height):
    gl.glViewport(0, 0, width, height)
    gl.glMatrixMode(gl.GL_PROJECTION)
    gl.glLoadIdentity()
    gl.glOrtho(-width/2, width/2, -height/2, height/2, -1, 1)
    gl.glMatrixMode(gl.GL_MODELVIEW)
    return EVENT_HANDLED
Beispiel #9
0
    def on_resize(self, width, height):
        """Calculate the new viewport preserving aspect ratio"""

        aspect = float(WIDTH)/HEIGHT

        self.viewport_width = int(min(width, height*aspect))
        self.viewport_height = int(min(height, width/aspect))
        self.viewport_x_offs = (width-self.viewport_width) // 2
        self.viewport_y_offs = (height-self.viewport_height) // 2

        x = (width-WIDTH) / 2
        gl.glViewport(self.viewport_x_offs,
                      self.viewport_y_offs,
                      self.viewport_width,
                      self.viewport_height,
                      )
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.glOrtho(0, self.viewport_width, 0, self.viewport_height, -1, 1)
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()

        logging.debug("Viewport: %s, %s, %s, %s" % (self.viewport_x_offs,
                                                    self.viewport_y_offs,
                                                    self.viewport_width,
                                                    self.viewport_height,
                                                    ))

        # adjust elements depending on the new viewport
        self.label.x = self.viewport_width // 2
        self.label.y = self.viewport_height // 2
Beispiel #10
0
    def on_draw():
        gl.glClearColor(1.0,1.0,1.0,1.0)
	window.clear()

        # Compute
        gl.glViewport(0, 0, width, height)
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.glOrtho(0, 1, 0, 1, -1, 1)
        gl.glMatrixMode(gl.GL_MODELVIEW)

        gl.glActiveTexture( gl.GL_TEXTURE1 )
	gl.glBindTexture(texture_s.target, texture_s.id)

        gl.glActiveTexture( gl.GL_TEXTURE0 )
	gl.glBindTexture(texture_uv.target, texture_uv.id)

        gl.glBindFramebufferEXT(gl.GL_FRAMEBUFFER_EXT, framebuffer)
	reaction_shader.bind()
        texture_uv.blit(x=0.0, y=0.0, width=1.0, height=1.0)
	reaction_shader.unbind()
        gl.glBindFramebufferEXT(gl.GL_FRAMEBUFFER_EXT, 0)

        # Render
        gl.glViewport(0, 0, window.width, window.height)
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.glOrtho(0, 1, 0, 1, -1, 1)
        gl.glMatrixMode(gl.GL_MODELVIEW)

	color_shader.bind()
        texture_uv.blit(x=0.0, y=0.0, width=1.0, height=1.0)
	color_shader.bind()
def render_to_texture():
    # select the target to draw into
    gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, framebuffer)
    draw_buffers = (gl.GLenum * 1)(gl.GL_COLOR_ATTACHMENT0)
    gl.glDrawBuffers(1, draw_buffers)
    gl.glViewport(0, 0, FB_WIDTH, FB_HEIGHT)

    # clear the destination
    gl.glClearColor(0.5, 0.6, 0.7, 1.0)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

    # prepare the rendering
    gl.glUseProgram(render_program)

    # send the vertex data
    data = (COLOR_VERTEX * 3)(((-0.6, -0.5), (1.0, 0.0, 0.0, 1.0)),
                      ((0.6, -0.5), (0.0, 1.0, 0.0, 1.0)),
                      ((0.0, 0.5), (0.0, 0.0, 1.0, 1.0)))

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, render_vertexbuffer)
    gl.glBufferData(gl.GL_ARRAY_BUFFER, ctypes.sizeof(data), data, gl.GL_DYNAMIC_DRAW)

    # draw using the vertex array for vertex information
    gl.glBindVertexArray(render_vao)
    gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3)
    gl.glBindVertexArray(0)
 def SetOrigin(self):
     size = self.GetVirtualSize()
     self.SetScrollbar(wx.HORIZONTAL, self.GetScrollPos(wx.HORIZONTAL), size[0],
                       self.map.width * 32 * self.zoom, refresh=True)
     self.SetScrollbar(wx.VERTICAL, self.GetScrollPos(wx.VERTICAL), size[1],
                       self.map.height * 32 * self.zoom, refresh=True)
     size = self.GetGLExtents()
     if size.width <= 0:
         size.width = 1
     if size.height <= 0:
         size.height = 1
     self.tilemap.updateDimmingSprite(
         int(size.width) + 2, int(size.height) + 2, 1 / self.zoom)
     gl.glViewport(0, 0, size.width, size.height)
     gl.glMatrixMode(gl.GL_PROJECTION)
     gl.glLoadIdentity()
     gl.glOrtho(
         0, size.width / self.zoom, 0, size.height / self.zoom, -1, 1)
     x = (-self.GetScrollPos(wx.HORIZONTAL)) / self.zoom
     y = ((-(self.map.height * 32) + size.height / self.zoom) +
          self.GetScrollPos(wx.VERTICAL) / self.zoom)
     gl.glTranslatef(x, y, 0)
     self.translateX = -x + size.width / 2 / self.zoom
     self.translateY = -y + size.height / 2 / self.zoom
     self.onscreenwidth = int(size.width / self.zoom)
     self.onscreenheight = int(size.height / self.zoom)
     self.tilemap.setDimXY(self.translateX - 1, self.translateY + 1)
     gl.glMatrixMode(gl.GL_MODELVIEW)
Beispiel #13
0
    def blit_buffer(self, framebuffer, parent_width, parent_height, **kwargs):
        """Draw the texture into the parent scene

        .. warning:

            This method's arguments are not part of the API yet and may change
            at any time.
        """
        gl.glViewport(0, 0, parent_width, parent_height)

        gl.glTexParameteri(gl.GL_TEXTURE_2D,
            gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)
        gl.glBindTexture(gl.GL_TEXTURE_2D, framebuffer.texture_id)
        gl.glEnable(gl.GL_TEXTURE_2D)

        gl.glColor4fv((gl.GLfloat * 4)(*self.color + (self.opacity, )))
        gl.glBlendFunc(gl.GL_ONE, gl.GL_ONE_MINUS_SRC_ALPHA)  # premultipl.
        gl.glBegin(gl.GL_TRIANGLE_STRIP)
        gl.glTexCoord2f(0, 0)
        gl.glVertex2i(0, 0)
        gl.glTexCoord2f(0, parent_height)
        gl.glVertex2i(0, parent_height)
        gl.glTexCoord2f(parent_width, 0)
        gl.glVertex2i(parent_width, 0)
        gl.glTexCoord2f(parent_width, parent_height)
        gl.glVertex2i(parent_width, parent_height)
        gl.glEnd()
        gl.glTexParameteri(gl.GL_TEXTURE_2D,
            gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)
        gl.glDisable(gl.GL_TEXTURE_2D)
        gl.glTexParameteri(gl.GL_TEXTURE_2D,
            gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

        gl.glViewport(0, 0, parent_width, parent_height)
Beispiel #14
0
def handle_resize(w, h):
    gl.glViewport(0, 0, w, h)
    gl.glMatrixMode(gl.GL_PROJECTION)
    gl.glLoadIdentity()
    gl.glOrtho(0, w, h, 0, 0, 1)
    gl.glMatrixMode(gl.GL_MODELVIEW)
    gl.glLoadIdentity()
def copy_texture_to_screen():
    # select the target to draw into
    gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
    gl.glViewport(0, 0, window.width, window.height)

    # clear the destination
    gl.glClearColor(0.4, 0.4, 0.4, 1.0)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

    # select the program for drawing
    gl.glUseProgram(copy_program)

    # send the vertex data
    data = (TEXTURE_VERTEX * 8)(((-0.9, -0.9), (0.0, 0.0)),
                                ((0.5, -0.9), (1.0, 0.0)),
                                ((0.5, 0.5), (1.0, 1.0)),
                                ((-0.9, 0.5), (0.0, 1.0)),

                                ((0.6, 0.6), (0.0, 1.0)),
                                ((1.0, 0.6), (1.0, 1.0)),
                                ((1.0, 1.0), (1.0, 0.0)),
                                ((0.6, 1.0), (0.0, 0.0)),
                                )

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, copy_vertexbuffer)
    gl.glBufferData(gl.GL_ARRAY_BUFFER, ctypes.sizeof(data), data, gl.GL_DYNAMIC_DRAW)


    # draw
    gl.glBindVertexArray(copy_vao)
    gl.glDrawArrays(gl.GL_QUADS, 0, 8)
    gl.glBindVertexArray(0)
Beispiel #16
0
    def unbind(self):
        """Unbind the FBO."""
        # Unbind the FBO
        gl.glBindFramebufferEXT(gl.GL_FRAMEBUFFER_EXT, 0)

        # Restore the old viewport size
        gl.glViewport(*self._old_viewport_size)
Beispiel #17
0
	def _resize(self, width, height):
		aspect = float(self._width)/self._height

		self._viewport_width = int(min(width, height*aspect))
		self._viewport_height = int(min(height, width/aspect))
		self._viewport_x_offs = (width-self._viewport_width) // 2
		self._viewport_y_offs = (height-self._viewport_height) // 2

		x = (width-self._width) / 2
		gl.glViewport(self._viewport_x_offs,
			self._viewport_y_offs,
			self._viewport_width,
			self._viewport_height,
		)
		gl.glMatrixMode(gl.GL_PROJECTION)
		gl.glLoadIdentity()
		gl.glOrtho(0, self._viewport_width, 0, self._viewport_height, -1, 1)
		gl.glMatrixMode(gl.GL_MODELVIEW)
		gl.glLoadIdentity()

		logging.debug("Viewport: %s, %s, %s, %s" % (self._viewport_x_offs,
			self._viewport_y_offs,
			self._viewport_width,
			self._viewport_height,
		))
 def on_resize(self, width, height):
     '''
     calculate perspective matrix
     '''
     v_ar = width/float(height)
     usableWidth = int(min(width, height*v_ar))
     usableHeight = int(min(height, width/v_ar))
     ox = (width - usableWidth) // 2
     oy = (height - usableHeight) // 2
     glViewport(ox, oy, usableWidth, usableHeight)
     glMatrixMode(GL_PROJECTION)
     glLoadIdentity()
     gluPerspective(60, usableWidth/float(usableHeight), 0.1, 3000.0)
     ''' set camera position on modelview matrix
     '''
     glMatrixMode(GL_MODELVIEW)
     glLoadIdentity()
     gluLookAt(width/2.0, height/2.0, height/1.1566,
         width/2.0, height/2.0, 0,
         0.0, 1.0, 0.0)
     ''' update scene controller with size
     '''
     self.controller.resize(width, height)
     #clears to a grey.
     glClearColor(0.4,0.4,0.4,0.)
     return pyglet.event.EVENT_HANDLED
Beispiel #19
0
    def _set_texture(self, t):
        self._texture = t
        from pyglet import gl
        try:
            gl.glFramebufferTexture2DEXT(
                gl.GL_FRAMEBUFFER_EXT,
                gl.GL_COLOR_ATTACHMENT0_EXT,
                t.target, t.id, 0,
            )
        except gl.GLException:
            # HACK: Some Intel card return errno == 1286L
            # which means GL_INVALID_FRAMEBUFFER_OPERATION_EXT
            # but IT ACTUALLY WORKS FINE!!
            pass

        gl.glViewport(0, 0, t.width, t.height)

        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.gluOrtho2D(0, t.width, 0, t.height)

        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()

        # ATI cards hack
        gl.glBegin(gl.GL_LINES)
        gl.glEnd()
Beispiel #20
0
def on_resize(width, height):
    # Override the default on_resize handler to create a 3D projection
    glViewport(0, 0, width, height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(60., width / float(height), .1, 1000.)
    glMatrixMode(GL_MODELVIEW)
    return EVENT_HANDLED
Beispiel #21
0
 def on_draw(self):
     self.update()
     global pen
     pen.update()
     gl.glViewport(0, 0, int(app_size[0]*self._scale), int(app_size[1]*self._scale))
     if self.window:
         self.window.clear()
     self.batch.draw()
Beispiel #22
0
 def on_resize(self, width, height, x=0, y=0):
     gl.glViewport(x, y, width, height)
     gl.glMatrixMode(gl.GL_PROJECTION)
     gl.glLoadIdentity()
     height = height or 1
     gl.gluPerspective(45., width / float(height), 0.1, 1000.)
     gl.glMatrixMode(gl.GL_MODELVIEW)
     self._setLightsAndEffects()
Beispiel #23
0
 def before_render(self, texture):
     self.pbuf.switch_to()
     gl.glViewport(0, 0, self.pbuf.width, self.pbuf.height)
     gl.glMatrixMode(gl.GL_PROJECTION)
     gl.glLoadIdentity()
     gl.glOrtho(0, self.pbuf.width, 0, self.pbuf.height, -1, 1)
     gl.glMatrixMode(gl.GL_MODELVIEW)
     gl.glEnable(gl.GL_TEXTURE_2D)
Beispiel #24
0
def draw_camera():
    gl.glViewport(0, 0, w, h)
    gl.glMatrixMode(gl.GL_PROJECTION)
    gl.glLoadIdentity()
    gl.glOrtho(0, w, 0, h, -1, 1)
    gl.glMatrixMode(gl.GL_MODELVIEW)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT)
    gl.glLoadIdentity()
Beispiel #25
0
 def __enter__(self):
     width, height = self.window.get_size()
     gl.glViewport(0, 0, width, height)
     gl.glMatrixMode(gl.GL_PROJECTION)
     gl.glLoadIdentity()
     gl.glOrtho(0, width, 0, height, -1, 1)
     gl.glMatrixMode(gl.GL_MODELVIEW)
     gl.glLoadIdentity()
Beispiel #26
0
    def activate(self):

        gl.glBindFramebufferEXT(gl.GL_FRAMEBUFFER_EXT, self._buffer)

        gl.glPushAttrib(gl.GL_VIEWPORT_BIT)
        gl.glViewport(0, 0, *self.render_target_size)

        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
Beispiel #27
0
 def on_resize(self, width, height, x=0, y=0):
     gl.glViewport(x, y, width, height)
     gl.glMatrixMode(gl.GL_PROJECTION)
     gl.glLoadIdentity()
     h = height or 1
     w = width / float(h)
     gl.glOrtho(-w, w, -1, 1, -1, 1000.)
     gl.glMatrixMode(gl.GL_MODELVIEW)
     self._setLightsAndEffects()
Beispiel #28
0
def bind_window(w, h):
    gl.glBindFramebufferEXT(gl.GL_DRAW_FRAMEBUFFER_EXT, 0)
    gl.glMatrixMode(gl.GL_MODELVIEW)
    gl.glLoadIdentity()
    gl.glViewport(0, 0, w, h)
    gl.glScissor(0, 0, w, h);
    gl.glMatrixMode(gl.GL_PROJECTION)
    gl.glLoadIdentity()
    gl.gluOrtho2D(0, w, h, 0)
Beispiel #29
0
 def on_resize(self, width, height):
     from options import options
     z = options.zoom
     glViewport(0, 0, int(width * z), int(height * z))
     glMatrixMode(GL_PROJECTION)
     glLoadIdentity()
     glOrtho(0, width, 0, height, -1000, 1000)
     glMatrixMode(GL_MODELVIEW)
     return pyglet.event.EVENT_HANDLED
Beispiel #30
0
    def on_draw(self, dt):
        self.window.clear()

        # This is where the code to auto-resize the window begins.

        # Set it up to draw to the whole space of the window.
        glViewport(0, 0, self.window.width, self.window.height)

        # Switch to projection matrix.
        glMatrixMode(gl.GL_PROJECTION)
        glLoadIdentity()

        # Calculate the size of our display.
        base_size = 240.0
        size_x = 0.0
        size_y = 0.0
        if (self.window.width >= self.window.height):
            size_x = base_size * (self.window.width/float(self.window.height))
            size_y = base_size
        else:
            size_x = base_size
            size_y = base_size * (self.window.height/float(self.window.width))

        # Set the orthogonal projection.
        glOrtho(-size_x/2.0, size_x/2.0, -size_y/2.0, size_y/2.0, -100, 100)

        # Switch back to model view so we can do the rest of our drawing.
        glMatrixMode(gl.GL_MODELVIEW)
        glLoadIdentity()

        # Draw stuff in the level.
        glPushMatrix()
        glTranslatef(int(-self.player1.x), int(-self.player1.y), 0.0)

        self.bg.draw()

        for platform in self.platforms:
            platform.render()

        self.player1.draw()
        if const.DRAW_SENSORS:
            for sensor in self.player1.sensors:
                sensor.render()
        
        glPopMatrix()

        # Draw HUD.
        self.fps_display.text = 'FPS: %d' % (1 / dt)
        self.fps_display.draw()

        self.debug_text[0].text = str(int(self.player1.hlock))
        self.debug_text[1].text = str(self.player1.state)
        self.debug_text[2].text = str(self.player1.rangle)
        self.debug_text[0].draw()
        self.debug_text[1].draw()
        self.debug_text[2].draw()
Beispiel #31
0
    def render(self, mode='human', close=False):
        if close:
            if self.window:
                self.window.close()
            return

        if mode == 'rgb_array':
            return self.img

        import pyglet
        from pyglet import gl
        if self.window is None:
            context = pyglet.gl.get_current_context()
            self.window = pyglet.window.Window(
                width=WINDOW_WIDTH,
                height=WINDOW_HEIGHT
            )

        self.window.switch_to()
        self.window.dispatch_events()

        gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
        gl.glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT)

        self.window.clear()

        # Setup orghogonal projection
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()
        gl.glOrtho(0, WINDOW_WIDTH, 0, WINDOW_HEIGHT, 0, 10)

        # Draw the image to the rendering window
        width = self.img.shape[1]
        height = self.img.shape[0]
        imgData = pyglet.image.ImageData(
            width,
            height,
            'RGB',
            self.img.tobytes(),
            pitch = width * 3,
        )
        imgData.blit(0, 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT)

        if mode == 'human':
            self.window.flip()
Beispiel #32
0
def set_viewport(left: float, right: float, bottom: float, top: float):
    """
    This sets what coordinates the window will cover.

    By default, the lower left coordinate will be (0, 0) and the top y
    coordinate will be the height of the window in pixels, and the right x
    coordinate will be the width of the window in pixels.

    If a program is making a game where the user scrolls around a larger
    world, this command can help out.

    Note: It is recommended to only set the view port to integer values that
    line up with the pixels on the screen. Otherwise if making a tiled game
    the blocks may not line up well, creating rectangle artifacts.

    :param Number left: Left-most (smallest) x value.
    :param Number right: Right-most (largest) x value.
    :param Number bottom: Bottom (smallest) y value.
    :param Number top: Top (largest) y value.
    """
    global _left
    global _right
    global _bottom
    global _top
    global _projection
    global _scaling

    _left = left
    _right = right
    _bottom = bottom
    _top = top

    # Needed for sprites
    if _scaling is None:
        _scaling = get_scaling_factor(_window)
    gl.glViewport(0, 0, _window.width * _scaling, _window.height * _scaling)

    # Needed for drawing
    # gl.glMatrixMode(gl.GL_PROJECTION)
    # gl.glLoadIdentity()
    # gl.glOrtho(_left, _right, _bottom, _top, -1, 1)
    # gl.glMatrixMode(gl.GL_MODELVIEW)
    # gl.glLoadIdentity()

    _projection = create_orthogonal_projection(left=_left, right=_right,
                                               bottom=_bottom, top=_top,
                                               near=-1000, far=100, dtype=np.float32)
Beispiel #33
0
    def on_draw(self):
        gl.glClearColor(0.0, 0.0, 0.0, 0.0)
        self.clear()

        if time.time() - self.start_time > 0.1:
            gl.glViewport(0, 0, self.tex_width, self.tex_height)
            with self.fbo:
                with self.reaction_shader:
                    gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)

            gl.glViewport(0, 0, self.width, self.height)
            with self.render_shader:
                gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)
                self.frame_count += 1

        if self.video_on and (self.frame_count % self.sample_rate == 0):
            self.write_video_frame()
Beispiel #34
0
    def on_configure(self, wid, event):
        if not self.context:
            return

        width = wid.allocation.width
        height = wid.allocation.height
        if width > 1:
            # make the context current
            # and setup opengl
            #
            # **** this only can be with the window realized ****
            #
            self.switch_to()
            if not self.gl_initialized:
                self.setup()
                self.gl_initialized = 1
            gl.glViewport(0, 0, width, height)
Beispiel #35
0
    def set_2d(self):
        screen_width, screen_height = self.get_size()
        width, height = self._world.width, self._world.height

        glDisable(GL_DEPTH_TEST)
        glViewport(0, 0, screen_width, screen_height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(
            -screen_width/2, screen_width/2,
            -screen_height/2, screen_height/2,
            -1, 1)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        # We add 10% to bounds so Asteroids port between bounds smoothly
        glScalef(screen_width / width * 1.1,
                 screen_height / height * 1.1, 1.0)
Beispiel #36
0
 def set_3d(self):
     width, height = self.get_size()
     glEnable(GL_CULL_FACE)
     glEnable(GL_DEPTH_TEST)
     glDepthFunc(GL_LESS)
     glViewport(0, 0, width, height)
     glMatrixMode(GL_PROJECTION)
     glLoadIdentity()
     gluPerspective(45.0, width / float(height), 0.1, 60.0)
     glMatrixMode(GL_MODELVIEW)
     glLoadIdentity()
     yaw, pitch = self.camera.rotation
     glRotatef(yaw, 0, 1, 0)
     glRotatef(-pitch, math.cos(math.radians(yaw)), 0,
               math.sin(math.radians(yaw)))
     x, y, z = self.camera.position
     glTranslatef(-x, -y, -z)
Beispiel #37
0
    def on_resize(self, width, height):
        super(GameMain, self).on_resize(width, height)
        logging.info(f"Resize {width} * {height}")
        gl.glViewport(0, 0, width, height)

        self.player.view_width = width
        self.player.view_height = height
        self.f3.y = self.height - 10
        self.f3.width = self.width // 3

        self.back_to_game = GuiButton(self.on_back_to_game, self.window,
                                      self.window.width / 2,
                                      self.window.height / 2 + 25,
                                      'Back to game')
        self.save_game = GuiButton(self.on_back_to_game, self.window,
                                   self.window.width / 2,
                                   self.window.height / 2,
                                   'Save and quit to title')
Beispiel #38
0
    def set_3d(self):
        """ Configure Opengl.GL to draw in 3d.

        """
        width, height = self.get_size()
        gl.glEnable(gl.GL_DEPTH_TEST)
        viewport = self.get_viewport_size()
        gl.glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1]))
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.gluPerspective(65.0, width / float(height), 0.1, 60.0)
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()
        x, y = self.rotation
        gl.glRotatef(x, 0, 1, 0)
        gl.glRotatef(-y, math.cos(math.radians(x)), 0,
                     math.sin(math.radians(x)))
        x, y, z = self.position
        gl.glTranslatef(-x, -y, -z)
    def on_resize(self, width, height):
        # load HZ matrix into OpenGL equivalent
        x0 = 0
        y0 = 0

        self.gl_viewport_args = x0, y0, self.img.width, self.img.height
        gl.glViewport(*self.gl_viewport_args)
        znear, zfar = .1, 1000.
        proj = convert_hz_intrinsic_to_opengl_projection(self.calib['intrinsic'],
                                                         x0,y0,self.img.width,self.img.height, znear, zfar,
                                                         window_coords=self.window_coords)

        m = map(float,proj.T.flat)
        m = (gl.GLfloat * 16)(*m)

        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadMatrixf(m)
        gl.glMatrixMode(gl.GL_MODELVIEW)
        return pyglet.event.EVENT_HANDLED
Beispiel #40
0
    def bind(self):
        assert Framebuffer.current_fbo is None
        from pyglet import gl
        t = self.texture
        gl.glBindFramebufferEXT(gl.GL_FRAMEBUFFER_EXT, self.fbo_id)
        gl.glPushAttrib(gl.GL_VIEWPORT_BIT | gl.GL_TRANSFORM_BIT)
        if t:
            gl.glViewport(0, 0, t.width, t.height)
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glPushMatrix()
        if t:
            gl.glLoadIdentity()
            gl.gluOrtho2D(0, t.width, 0, t.height)
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glPushMatrix()
        if t:
            gl.glLoadIdentity()

        Framebuffer.current_fbo = self
Beispiel #41
0
 def on_resize(self, width, height):
     try:
         # for high DPI screens viewport size
         # will be different then the passed size
         width, height = self.get_viewport_size()
     except BaseException:
         # older versions of pyglet may not have this
         pass
     # set the new viewport size
     gl.glViewport(0, 0, width, height)
     gl.glMatrixMode(gl.GL_PROJECTION)
     gl.glLoadIdentity()
     gl.gluPerspective(60.,
                       width / float(height),
                       .01,
                       self.scene.scale * 5.0)
     gl.glMatrixMode(gl.GL_MODELVIEW)
     self.view['ball'].place([width / 2, height / 2],
                             (width + height) / 2)
Beispiel #42
0
def on_resize(width, height):
    glViewport(0, 0, width, height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(45, width / float(height), .1, 1000)

    gluLookAt(
        0,
        0,
        4,  # eye
        0,
        0,
        0,  # target
        0,
        1,
        0  # up
    )
    glMatrixMode(GL_MODELVIEW)
    return EVENT_HANDLED
    def window_coordinates_ydown(self):

        # These are screen coords. Y increases downward, with 0 at top
        # of initial window. (Standard OpenGL has 0 at bottom and Y
        # increasing upward.)

        gl.glPushMatrix()
        gl.glLoadIdentity()
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glPushMatrix()
        gl.glLoadIdentity()
        gl.glOrtho(0, self.width, 0, self.height, -1, 1)
        gl.glViewport(0, 0, self.width, self.height)

        yield # perform drawing

        gl.glViewport(*self.gl_viewport_args)
        gl.glPopMatrix()
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glPopMatrix()
Beispiel #44
0
    def _update_perspective(self, width, height):
        try:
            # for high DPI screens viewport size
            # will be different then the passed size
            width, height = self.get_viewport_size()
        except BaseException:
            # older versions of pyglet may not have this
            pass

        # set the new viewport size
        gl.glViewport(0, 0, width, height)
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()

        # get field of view from camera
        fovY = self.scene.camera.fov[1]
        gl.gluPerspective(fovY, width / float(height), .01, 1000.)
        gl.glMatrixMode(gl.GL_MODELVIEW)

        return width, height
Beispiel #45
0
    def OnReshape(self, width, height):
        '''Reshape the OpenGL viewport based on the dimensions of the window.'''

        # Zero values occasionally appear during window setup.  Ignore these until real values appear
        if width == 0 or height == 0:
            return

        if not self.GLinitialized:
            self.OnInitGL()

        gl.glViewport(0, 0, width, height)
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.glOrtho(0, width, 0, height, 1, -1)
        gl.glMatrixMode(gl.GL_MODELVIEW)
        # pyglet stuff

        # Wrap text to the width of the window
        if self.GLinitialized:
            GLPanel.pygletcontext.set_current()
            self.update_object_resize()
Beispiel #46
0
    def OnReshape(self):
        """Reshape the OpenGL viewport based on the size of the window"""
        size = self.GetClientSize() * self.GetContentScaleFactor()
        oldwidth, oldheight = self.width, self.height
        width, height = size.width, size.height
        if width < 1 or height < 1:
            return
        self.width = max(float(width), 1.0)
        self.height = max(float(height), 1.0)
        self.OnInitGL(call_reshape=False)
        # print('glViewport', width)
        glViewport(0, 0, width, height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        if self.orthographic:
            glOrtho(-width / 2, width / 2, -height / 2, height / 2,
                    -5 * self.dist, 5 * self.dist)
        else:
            gluPerspective(60., float(width) / height, 10.0, 3 * self.dist)
            glTranslatef(0, 0, -self.dist)  # Move back
        glMatrixMode(GL_MODELVIEW)

        if not self.mview_initialized:
            self.reset_mview(0.9)
            self.mview_initialized = True
        elif oldwidth is not None and oldheight is not None:
            wratio = self.width / oldwidth
            hratio = self.height / oldheight

            factor = min(wratio * self.zoomed_width,
                         hratio * self.zoomed_height)
            x, y, _ = self.mouse_to_3d(self.width / 2, self.height / 2)
            self.zoom(factor, (x, y))
            self.zoomed_width *= wratio / factor
            self.zoomed_height *= hratio / factor

        # Wrap text to the width of the window
        if self.GLinitialized:
            self.pygletcontext.set_current()
            self.update_object_resize()
Beispiel #47
0
    def _render_view(self):

        gl.glClearBufferfv(gl.GL_COLOR, 0, (gl.GLfloat * 4)(0.25, 0.25, 0.25,
                                                            1))

        if not self.view:
            return

        w, h, d = self.view.shape
        size = w, h
        window_size = self.get_size()

        ob = render_view(self)

        vm = make_view_matrix(window_size, size, self.zoom, self.offset)
        vm = (gl.GLfloat * 16)(*vm)
        gl.glViewport(0, 0, *window_size)

        self._update_border(self.view.shape)
        with self.border_vao, self.line_program:
            gl.glUniformMatrix4fv(0, 1, gl.GL_FALSE, vm)
            r, g, b, a = self.drawing.palette.colors[
                0]  # Color 0 is currently hardcoded background
            gl.glUniform3f(1, r / 256, g / 256, b / 256)
            gl.glDrawArrays(gl.GL_TRIANGLE_FAN, 0, 4)

        with self.vao, self.copy_program:
            # Draw the actual drawing
            with ob["color"]:
                gl.glEnable(gl.GL_BLEND)
                gl.glUniformMatrix4fv(0, 1, gl.GL_FALSE,
                                      (gl.GLfloat * 16)(*vm))
                gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6)
            self._draw_mouse_cursor()

        with self.border_vao, self.line_program:
            gl.glUniform3f(1, 0., 0., 0.)
            gl.glLineWidth(1)
            gl.glDrawArrays(gl.GL_LINE_LOOP, 0, 4)
Beispiel #48
0
    def on_draw(self):
        gl.glClearColor(0, 0, 0, 0)
        self.clear()
        gl.glViewport(0, 0, self.width, self.height)
        now = time.clock() - self._start_time
        now *= self._speed
        with self.bufferA:
            with self.shaderA:
                self.shaderA.uniformf("iTime", now)
                self.shaderA.uniformi("iFrame", self._frame_count)
                gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)

        with self.bufferB:
            with self.shaderB:
                self.shaderB.uniformf("iTime", now)
                gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)

        with self.shaderC:
            self.shaderC.uniformf("iTime", now)
            gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)

        self._frame_count += 1
    def updateProjection(self):
        """
        Recalculates the necessary projection.
        """
        gl.glViewport(0, 0, self.window.width, self.window.height)

        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()

        ratio = float(self.window.width) / self.window.height

        extents = b2Vec2(ratio * 25.0, 25.0)
        extents *= self._viewZoom

        lower = self._viewCenter - extents
        upper = self._viewCenter + extents

        # L/R/B/T
        gl.gluOrtho2D(lower.x, upper.x, lower.y, upper.y)

        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()
Beispiel #50
0
def render_to_texture(in_size, out_size, view_z=None):
    z0, z1 = (0, in_size[2]) if view_z == None else view_z
    vertices = (VERTEX * 6)(((-1, -1), (0, 0)), ((1, -1), (1, 0)),
                            ((1, 1), (1, 1)), ((1, 1), (1, 1)),
                            ((-1, 1), (0, 1)), ((-1, -1), (0, 0)))
    gl.glBindTexture(gl.GL_TEXTURE_3D, rendered_texture)
    gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, framebuffer)
    draw_buffers = (gl.GLenum * 1)(gl.GL_COLOR_ATTACHMENT0)
    gl.glDrawBuffers(1, draw_buffers)
    gl.glViewport(0, 0, out_size[0], out_size[1])
    gl.glUseProgram(render_program)
    loc_depth = gl.glGetUniformLocation(render_program,
                                        ctypes.create_string_buffer(b'depth'))
    loc_texelSize = gl.glGetUniformLocation(
        render_program, ctypes.create_string_buffer(b'texelSize'))
    gl.glUniform3f(loc_texelSize, 1 / in_size[0], 1 / in_size[1],
                   1 / in_size[2])
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, render_vertexbuffer)
    gl.glBufferData(gl.GL_ARRAY_BUFFER, ctypes.sizeof(vertices), vertices,
                    gl.GL_DYNAMIC_DRAW)
    gl.glBindVertexArray(render_vao)
    gl.glClearColor(0.0, 0.0, 0.0, 0.0)
    for z in range(out_size[2]):
        gl.glFramebufferTexture3D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0,
                                  gl.GL_TEXTURE_3D, rendered_texture, 0, z)
        fbs = gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER)
        assert fbs == gl.GL_FRAMEBUFFER_COMPLETE, 'FramebufferStatus is {}'.format(
            fbs)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
        gl.glUniform1f(loc_depth,
                       (z0 + z * (z1 - z0)) / in_size[2] / out_size[2])
        gl.glBindTexture(gl.GL_TEXTURE_3D, input_texture)
        gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6)
        if z % 10 == 0:
            gl.glFinish()
            print('\033[K{}/{}'.format(z, out_size[2] - 1), end='\r')
    gl.glFinish()

    gl.glBindVertexArray(0)
Beispiel #51
0
    def _set_view(self):
        left = int(self._pixel_per_point[0] * self.rect.left)
        bottom = int(self._pixel_per_point[1] * self.rect.bottom)
        width = int(self._pixel_per_point[0] * self.rect.width)
        height = int(self._pixel_per_point[1] * self.rect.height)

        gl.glPushAttrib(gl.GL_ENABLE_BIT)
        gl.glEnable(gl.GL_SCISSOR_TEST)
        gl.glScissor(left, bottom, width, height)

        self._mode = (gl.GLint)()
        gl.glGetIntegerv(gl.GL_MATRIX_MODE, self._mode)
        self._viewport = (gl.GLint * 4)()
        gl.glGetIntegerv(gl.GL_VIEWPORT, self._viewport)

        gl.glViewport(left, bottom, width, height)
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glPushMatrix()
        gl.glLoadIdentity()
        near = 0.01
        far = 1000.
        gl.gluPerspective(self.scene.camera.fov[1], width / height, near, far)
        gl.glMatrixMode(gl.GL_MODELVIEW)
    def on_draw(self):
        gl.glClearColor(0, 0, 0, 0)
        self.clear()
        gl.glViewport(0, 0, self.width, self.height)
        self._last = self._now
        self._now = time.clock()
        itime = self._now - self._start_time
        idate = get_idate()
        delta = self._now - self._last
        with self.bufferA:
            with self.shaderA:
                self.shaderA.uniformf("iTime", itime)
                self.shaderA.uniformf("iDate", *idate)
                self.shaderA.uniformf("iTimeDelta", delta)
                gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)

        with self.shaderB:
            self.shaderB.uniformf("iTime", itime)
            self.shaderB.uniformf("iDate", *idate)
            self.shaderB.uniformf("iTimeDelta", delta)
            gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)

        self._frame_count += 1
Beispiel #53
0
    def paint(self, func):
        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()

        gl.gluOrtho2D(0, self.width, 0, self.height)

        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()
        gl.glViewport(0, 0, self.width, self.height)

        gl.glBindFramebufferEXT(gl.GL_DRAW_FRAMEBUFFER_EXT,
                                self.col_buffer.gl_buffer)

        gl.glFramebufferTexture2DEXT(gl.GL_DRAW_FRAMEBUFFER_EXT,
                                     gl.GL_COLOR_ATTACHMENT0_EXT,
                                     self.texture.target, self.texture.id, 0)

        func()

        gl.glBindFramebufferEXT(gl.GL_DRAW_FRAMEBUFFER_EXT, 0)
Beispiel #54
0
def set_projection3D(self):
    """Sets a 3D projection mantaining the aspect ratio of the original window size"""
    # virtual (desired) view size
    vw, vh = self.get_window_size()

    nw, nh = native_width(self.window)
    gl.glViewport(self._offset_x, self._offset_y, nw, nh)
    gl.glMatrixMode(gl.GL_PROJECTION)
    gl.glLoadIdentity()
    gl.gluPerspective(60, nw / float(nh), 0.1, 3000.0)
    gl.glMatrixMode(gl.GL_MODELVIEW)

    gl.glLoadIdentity()
    gl.gluLookAt(
        vw / 2.0,
        vh / 2.0,
        vh / 1.1566,  # eye
        vw / 2.0,
        vh / 2.0,
        0,  # center
        0.0,
        1.0,
        0.0  # up vector
    )
Beispiel #55
0
    def render(self, position, chunk_meshes):

        gl.glViewport(0, 0, *self.size)
        gl.glDisable(gl.GL_BLEND)
        gl.glDisable(gl.GL_ALPHA_TEST)
        gl.glEnable(gl.GL_CULL_FACE)

        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glDepthFunc(gl.GL_LEQUAL)
        gl.glDepthMask(gl.GL_TRUE)

        x, y, z = position

        view_matrices = [
            Matrix4.new_scale(-1, -1, 1).rotatey(pi / 2).translate(-x, -y,
                                                                   -z),  # +X
            Matrix4.new_scale(-1, -1,
                              1).rotatey(-pi / 2).translate(-x, -y, -z),  # -X
            Matrix4.new_rotatex(-pi / 2).translate(-x, -y, -z),  # +Y
            Matrix4.new_rotatex(pi / 2).translate(-x, -y, -z),  # -Y
            Matrix4.new_scale(-1, -1, 1).rotatey(pi).translate(-x, -y,
                                                               -z),  # +Z
            Matrix4.new_scale(-1, -1, 1).translate(-x, -y, -z)  # -Z
        ]

        model_matrix = Matrix4.new_scale(
            1, 1, constants.WALL_TEXTURE_HEIGHT /
            (constants.WALL_TEXTURE_WIDTH / sqrt(2) * (sqrt(3))))
        gl.glUniformMatrix4fv(1, 1, gl.GL_FALSE, gl_matrix(model_matrix))
        with self.program, self.name:

            view_matrix = make_view_matrix_persp(position)
            gl.glUniformMatrix4fv(0, 1, gl.GL_FALSE, gl_matrix(view_matrix))

            for chunk, mesh in chunk_meshes.items():
                mesh.draw()
    def on_draw(self):
        gl.glClearColor(0, 0, 0, 0)
        self.clear()
        gl.glViewport(0, 0, self.width, self.height)
        now = time.perf_counter() - self._start_time
        with self.bufferA:
            with self.shaderA:
                self.shaderA.uniformf("iTime", now)
                self.shaderA.uniformi("iFrame", self._frame_count)
                gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)

        with self.bufferB:
            with self.shaderB:
                self.shaderB.uniformf("iTime", now)
                gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)

        with self.shaderC:
            self.shaderC.uniformf("iTime", now)
            gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)

        if self.video_on and (self._frame_count % self.sample_rate == 0):
            self.write_video_frame()

        self._frame_count += 1
    def render(self, mode='human'):
        if self.viewer is None:
            from gym.envs.classic_control import rendering
            self.viewer = rendering.Viewer(WINDOW_W, WINDOW_H)
            self.score_label = pyglet.text.Label('0000',
                                                 font_size=36,
                                                 x=20,
                                                 y=WINDOW_H * 2.5 / 40.00,
                                                 anchor_x='left',
                                                 anchor_y='center',
                                                 color=(255, 255, 255, 255))
            self.transform = rendering.Transform()

        if "t" not in self.__dict__: return  # reset() not called yet

        zoom = ZOOM * SCALE
        zoom_state = ZOOM * SCALE * STATE_W / WINDOW_W
        zoom_video = ZOOM * SCALE * VIDEO_W / WINDOW_W
        scroll_x = self.car.hull.position[0]
        scroll_y = self.car.hull.position[1]
        angle = -self.car.hull.angle
        vel = self.car.hull.linearVelocity
        if np.linalg.norm(vel) > 0.5:
            angle = math.atan2(vel[0], vel[1])
        self.transform.set_scale(zoom, zoom)
        self.transform.set_translation(
            WINDOW_W / 2 - (scroll_x * zoom * math.cos(angle) -
                            scroll_y * zoom * math.sin(angle)),
            WINDOW_H / 4 - (scroll_x * zoom * math.sin(angle) +
                            scroll_y * zoom * math.cos(angle)))
        self.transform.set_rotation(angle)

        self.car.draw(self.viewer, mode != "state_pixels")

        arr = None
        win = self.viewer.window
        if mode != 'state_pixels':
            win.switch_to()
            win.dispatch_events()
        if mode == "rgb_array" or mode == "state_pixels":
            win.clear()
            t = self.transform
            if mode == 'rgb_array':
                VP_W = VIDEO_W
                VP_H = VIDEO_H
            else:
                VP_W = STATE_W
                VP_H = STATE_H
            gl.glViewport(0, 0, VP_W, VP_H)
            t.enable()
            self.render_road()
            for geom in self.viewer.onetime_geoms:
                geom.render()
            t.disable()
            self.render_indicators(WINDOW_W,
                                   WINDOW_H)  # TODO: find why 2x needed, wtf
            image_data = pyglet.image.get_buffer_manager().get_color_buffer(
            ).get_image_data()
            arr = np.fromstring(image_data.data, dtype=np.uint8, sep='')
            arr = arr.reshape(VP_H, VP_W, 4)
            arr = arr[::-1, :, 0:3]

        if mode == "rgb_array" and not self.human_render:  # agent can call or not call env.render() itself when recording video.
            win.flip()

        if mode == 'human':
            self.human_render = True
            win.clear()
            t = self.transform
            gl.glViewport(0, 0, WINDOW_W, WINDOW_H)
            t.enable()
            self.render_road()
            for geom in self.viewer.onetime_geoms:
                geom.render()
            t.disable()
            self.render_indicators(WINDOW_W, WINDOW_H)
            win.flip()

        self.viewer.onetime_geoms = []
        return arr
Beispiel #58
0
    def on_draw():
        window.clear()

        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glEnable(gl.GL_LINE_SMOOTH)

        width, height = window.get_size()
        gl.glViewport(0, 0, width, height)

        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.gluPerspective(60, width / float(height), 0.01, 20)

        gl.glMatrixMode(gl.GL_TEXTURE)
        gl.glLoadIdentity()
        # texcoords are [0..1] and relative to top-left pixel corner, add 0.5 to center
        gl.glTranslatef(0.5 / image_data.width, 0.5 / image_data.height, 0)
        image_texture = image_data.get_texture()
        # texture size may be increased by pyglet to a power of 2
        tw, th = image_texture.owner.width, image_texture.owner.height
        gl.glScalef(image_data.width / float(tw),
                    image_data.height / float(th), 1)

        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()

        gl.gluLookAt(0, 0, 0, 0, 0, 1, 0, -1, 0)

        gl.glTranslatef(0, 0, state.distance)
        gl.glRotated(state.pitch, 1, 0, 0)
        gl.glRotated(state.yaw, 0, 1, 0)

        if any(state.mouse_btns):
            axes(0.1, 4)

        gl.glTranslatef(0, 0, -state.distance)
        gl.glTranslatef(*state.translation)

        gl.glColor3f(0.5, 0.5, 0.5)
        gl.glPushMatrix()
        gl.glTranslatef(0, 0.5, 0.5)
        grid()
        gl.glPopMatrix()

        psz = max(window.get_size()) / float(max(w, h)) if state.scale else 1
        gl.glPointSize(psz)
        distance = (0, 0, 1) if state.attenuation else (1, 0, 0)
        gl.glPointParameterfv(gl.GL_POINT_DISTANCE_ATTENUATION,
                              (gl.GLfloat * 3)(*distance))

        if state.lighting:
            ldir = [0.5, 0.5, 0.5]  # world-space lighting
            ldir = np.dot(state.rotation, (0, 0, 1))  # MeshLab style lighting
            ldir = list(ldir) + [0]  # w=0, directional light
            gl.glLightfv(gl.GL_LIGHT0, gl.GL_POSITION, (gl.GLfloat * 4)(*ldir))
            gl.glLightfv(gl.GL_LIGHT0, gl.GL_DIFFUSE,
                         (gl.GLfloat * 3)(1.0, 1.0, 1.0))
            gl.glLightfv(gl.GL_LIGHT0, gl.GL_AMBIENT,
                         (gl.GLfloat * 3)(0.75, 0.75, 0.75))
            gl.glEnable(gl.GL_LIGHT0)
            gl.glEnable(gl.GL_NORMALIZE)
            gl.glEnable(gl.GL_LIGHTING)

        gl.glColor3f(1, 1, 1)
        texture = image_data.get_texture()
        gl.glEnable(texture.target)
        gl.glBindTexture(texture.target, texture.id)
        gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER,
                           gl.GL_NEAREST)

        # comment this to get round points with MSAA on
        gl.glEnable(gl.GL_POINT_SPRITE)

        if not state.scale and not state.attenuation:
            gl.glDisable(gl.GL_MULTISAMPLE)  # for true 1px points with MSAA on
        vertex_list.draw(gl.GL_POINTS)
        gl.glDisable(texture.target)
        if not state.scale and not state.attenuation:
            gl.glEnable(gl.GL_MULTISAMPLE)

        gl.glDisable(gl.GL_LIGHTING)

        gl.glColor3f(0.25, 0.25, 0.25)
        frustum(depth_intrinsics)
        axes()

        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.glOrtho(0, width, 0, height, -1, 1)
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()
        gl.glMatrixMode(gl.GL_TEXTURE)
        gl.glLoadIdentity()
        gl.glDisable(gl.GL_DEPTH_TEST)

        fps_display.draw()
Beispiel #59
0
    def render(self, mode='human'):
        assert mode in ['human', 'state_pixels', 'rgb_array']
        if self.viewer is None:
            from gym.envs.classic_control import rendering
            self.viewer = rendering.Viewer(WINDOW_W, WINDOW_H)
            self.score_label = pyglet.text.Label('0000', font_size=36,
                x=20, y=WINDOW_H*2.5/40.00, anchor_x='left', anchor_y='center',
                color=(255,255,255,255))
            self.transform = rendering.Transform()

        if "t" not in self.__dict__: return  # reset() not called yet

        zoom = 0.1*SCALE*max(1-self.t, 0) + ZOOM*SCALE*min(self.t, 1)   # Animate zoom first second
        zoom_state  = ZOOM*SCALE*STATE_W/WINDOW_W
        zoom_video  = ZOOM*SCALE*VIDEO_W/WINDOW_W
        scroll_x = self.car.hull.position[0]
        scroll_y = self.car.hull.position[1]
        angle = -self.car.hull.angle
        vel = self.car.hull.linearVelocity
        if np.linalg.norm(vel) > 0.5:
            angle = math.atan2(vel[0], vel[1])
        self.transform.set_scale(zoom, zoom)
        self.transform.set_translation(
            WINDOW_W/2 - (scroll_x*zoom*math.cos(angle) - scroll_y*zoom*math.sin(angle)),
            WINDOW_H/4 - (scroll_x*zoom*math.sin(angle) + scroll_y*zoom*math.cos(angle)) )
        self.transform.set_rotation(angle)

        self.car.draw(self.viewer, mode!="state_pixels")

        arr = None
        win = self.viewer.window
        win.switch_to()
        win.dispatch_events()

        win.clear()
        t = self.transform
        if mode=='rgb_array':
            VP_W = VIDEO_W
            VP_H = VIDEO_H
        elif mode == 'state_pixels':
            VP_W = STATE_W
            VP_H = STATE_H
        else:
            pixel_scale = 1
            if hasattr(win.context, '_nscontext'):
                pixel_scale = win.context._nscontext.view().backingScaleFactor()  # pylint: disable=protected-access
            VP_W = pixel_scale * WINDOW_W
            VP_H = pixel_scale * WINDOW_H

        gl.glViewport(0, 0, VP_W, VP_H)
        t.enable()
        self.render_road()
        for geom in self.viewer.onetime_geoms:
            geom.render()
        self.viewer.onetime_geoms = []
        t.disable()
        self.render_indicators(WINDOW_W, WINDOW_H)

        if mode == 'human':
            win.flip()
            return self.viewer.isopen

        image_data = pyglet.image.get_buffer_manager().get_color_buffer().get_image_data()
        arr = np.fromstring(image_data.data, dtype=np.uint8, sep='')
        arr = arr.reshape(VP_H, VP_W, 4)
        arr = arr[::-1, :, 0:3]

        return arr
Beispiel #60
0
def set_viewport(left: Number, right: Number, bottom: Number, top: Number):
    """
    This sets what coordinates the window will cover.

    By default, the lower left coordinate will be (0, 0) and the top y
    coordinate will be the height of the window in pixels, and the right x
    coordinate will be the width of the window in pixels.

    If a program is making a game where the user scrolls around a larger
    world, this command can help out.

    Note: It is recommended to only set the view port to integer values that
    line up with the pixels on the screen. Otherwise if making a tiled game
    the blocks may not line up well, creating rectangle artifacts.

    Args:
        :left: Left-most (smallest) x value.
        :right: Right-most (largest) x value.
        :bottom: Bottom (smallest) y value.
        :top: Top (largest) y value.
    Returns:
        None
    Raises:
        None

    :Example:

    >>> import arcade
    >>> arcade.open_window(800,600,"Drawing Example")
    >>> set_viewport(-1, 1, -1, 1)
    >>> arcade.quick_run(0.25)

    """
    global _left
    global _right
    global _bottom
    global _top
    global _projection

    _left = left
    _right = right
    _bottom = bottom
    _top = top

    # Needed for sprites
    gl.glViewport(0, 0, _window.width, _window.height)

    # Needed for drawing
    # gl.glMatrixMode(gl.GL_PROJECTION)
    # gl.glLoadIdentity()
    # gl.glOrtho(_left, _right, _bottom, _top, -1, 1)
    # gl.glMatrixMode(gl.GL_MODELVIEW)
    # gl.glLoadIdentity()

    _projection = create_orthogonal_projection(left=_left,
                                               right=_right,
                                               bottom=_bottom,
                                               top=_top,
                                               near=-1000,
                                               far=100,
                                               dtype=np.float32)