def rotate(self,ang,rx,ry,rz): glPushMatrix() glLoadIdentity() glRotatef(ang,rx,ry,rz) glMultMatrixf(self.matrix) self.matrix=get_model_matrix() glPopMatrix()
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)
def _drawLUTtoScreen(self): """(private) Used to set the LUT in Bits++ mode. Should not be needed by user if attached to a ``psychopy.visual.Window()`` since this will automatically draw the LUT as part of the screen refresh. """ #push the projection matrix and set to orthorgaphic GL.glMatrixMode(GL.GL_PROJECTION) GL.glPushMatrix() GL.glLoadIdentity() GL.glOrtho( 0, self.win.size[0],self.win.size[1], 0, 0, 1 ) #this also sets the 0,0 to be top-left #but return to modelview for rendering GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() #draw the pixels GL.glActiveTextureARB(GL.GL_TEXTURE0_ARB) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glActiveTextureARB(GL.GL_TEXTURE1_ARB) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glRasterPos2i(0,1) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) GL.glDrawPixels(len(self._HEADandLUT),1, GL.GL_RGB,GL.GL_UNSIGNED_BYTE, self._HEADandLUTstr) #GL.glDrawPixels(524,1, GL.GL_RGB,GL.GL_UNSIGNED_BYTE, self._HEADandLUTstr) #return to 3D mode (go and pop the projection matrix) GL.glMatrixMode( GL.GL_PROJECTION ) GL.glPopMatrix() GL.glMatrixMode( GL.GL_MODELVIEW )
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)
def translate(self,dx,dy,dz): glPushMatrix() glLoadIdentity() glTranslatef(dx,dy,dz) glMultMatrixf(self.matrix) self.matrix=get_model_matrix() glPopMatrix()
def world_projection(self, aspect): """ Sets OpenGL projection and modelview matrices such that the window is centered on self.(x,y), shows at least scale world units in every direction, and is oriented by angle. """ glMatrixMode(GL_PROJECTION) glLoadIdentity() if aspect < 1: gluOrtho2D( -self.scale, +self.scale, -self.scale / aspect, +self.scale / aspect) else: gluOrtho2D( -self.scale * aspect, +self.scale * aspect, -self.scale, +self.scale) glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt( self.x, self.y, +1.0, self.x, self.y, -1.0, sin(self.angle), cos(self.angle), 0.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()
def _reset_projection(self): if self.fullcanvas: if self._pygimage is None: return width, height = self._pygimage.width, self._pygimage.height else: size = self.GetClientSize() width, height = size.width, size.height b = 0 t = height if self.flip_lr: l = width r = 0 else: l = 0 r = width if self.rotate_180: l,r=r,l b,t=t,b if width==0 or height==0: # prevent OpenGL error return self.wxcontext.SetCurrent() gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.glOrtho(l,r,b,t, -1, 1) gl.glMatrixMode(gl.GL_MODELVIEW)
def predraw(w,h): gl.glLightfv(gl.GL_LIGHT0, gl.GL_POSITION,vec(1,1,10, 3)) gl.glLightModelfv( gl.GL_LIGHT_MODEL_AMBIENT|gl.GL_LIGHT_MODEL_TWO_SIDE, vec(1,1,1, 1.0) ) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() #glOrtho(-1, 1, -1, 1, -1, 1) #(w,h) = self.get_size() gl.glScalef( float(min(w,h))/w, -float(min(w,h))/h, 1 ) gl.gluPerspective(45.0, 1, 0.1, 1000.0) gl.gluLookAt( camera.x, camera.y, camera.z, 0,0,0, camera.up[0], camera.up[1], camera.up[2] )
def on_draw(): pyglet.clock.tick() window.clear() gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() (w, h) = window.get_size() gl.glScalef( float(min(w, h))/w, -float(min(w, h))/h, 1 ) gl.gluPerspective(45.0, 1, 0.1, 1000.0) gl.gluLookAt(0, 0, 2.4, 0, 0, 0, 0, 1, 0) for vision in window.visions.values(): gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() vision() buf = pyglet.image.get_buffer_manager().get_color_buffer() rawimage = buf.get_image_data() window.texture = rawimage.get_texture()
def update(self): self.x += (self.target_x - self.x) * 0.1 self.y += (self.target_y - self.y) * 0.1 self.scale += (self.target_scale - self.scale) * 0.1 self.angle += (self.target_angle - self.angle) * 0.1 "Set projection and modelview matrices ready for rendering" glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D( -self.scale * self.aspect, +self.scale * self.aspect, -self.scale, +self.scale) # Set modelview matrix to move, scale & rotate to camera position" glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt( self.x, self.y, +1.0, self.x, self.y, -1.0, sin(self.angle), cos(self.angle), 0.0) print 'gluLookAt:', self.x,self.y, self.angle
def hud_mode(self): "Set matrices ready for drawing HUD, like fps counter" glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0, self.win_width, 0, self.win_height) glMatrixMode(GL_MODELVIEW) glLoadIdentity()
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 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 select_object(x, y, objects=None): from miru.context import context if objects is None: objects = context.camera.objects # following technique is adapted from # http://www.cse.msu.edu/~cse872/tutorial9.html w = context.window.width h = context.window.height select_buffer = ctypes.cast((100 * gl.GLuint)(), ctypes.POINTER(gl.GLuint)) gl.glSelectBuffer(100, select_buffer) viewport = (4 * gl.GLint)() gl.glGetIntegerv(gl.GL_VIEWPORT, viewport) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() # rotate the camera first angle = context.camera.angle gl.glRotatef(angle.z, 0, 0, 1) gl.glRotatef(angle.y, 0, 1, 0) gl.glRotatef(angle.x, 1, 0, 0) gl.gluPickMatrix(x, y, 3, 3, viewport) gl.glRenderMode(gl.GL_SELECT) gl.gluPerspective(45., w / float(h), 0.1, 1000.) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glInitNames() gl.glPushName(-1) context.camera.render(select_pass=1, visible=objects) gl.glFlush() hits = gl.glRenderMode(gl.GL_RENDER) gl.glPopName() selected = None if hits: try: m = sys.maxint << 100 idx = 0 for i in range(0, 100, 4): if not select_buffer[i]: selected = objects[idx] break m = min(select_buffer[i+1], m) if m == select_buffer[i+1]: idx = select_buffer[i+3] except IndexError: pass context.window.on_resize(context.window.width, context.window.height) return selected
def on_draw(): gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() # draw_obj(bear, bear_tex) draw_obj(ball, ball_tex)
def run(self, dt): ## UPDATE ## # timestep ala http://gafferongames.com/game-physics/fix-your-timestep/ if dt > .25: # avoid spiral of death (updating taking longer than framerate) dt = .25 self.accumulatedFrameTime += dt while self.accumulatedFrameTime >= self.updateRate: self.accumulatedFrameTime -= self.updateRate self.levelTime = time.time() - self.levelStartTime for entity in self.groups['updating']: entity.update(self.updateRate) # update all entities self._processRemoving() self._processAdding() for level in self.groups['level']: level.update(self.updateRate) # this will do the physics ## DRAW ## gl.glClearColor(0,0,0, 0) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glLoadIdentity() self.camera.track() # does camera work (such as what it focuses on) for name in self.drawLayerNames: shift = Vec2d() if name.startswith('UI') else None with self.camera.shiftView(shift): for entity in self.drawLayers[name]: # TODO: not iterate over batched things entity.draw() self.drawLayersBatch[name].draw() self.fps_display.draw()
def _layerProjectLocalToScreen(self): """Maps self.coordLocal to self.coordScreen within OpenGL.""" if self._scissorBox is None and self.localBounds is None: return gl.glMatrixMode(gl.GL_PROJECTION) gl.glPushMatrix() gl.glLoadIdentity() # gluOrtho2D declares the render space for the corners of the window. # So, we want to set it up in such a way that our layer renders in # the right place. In other words, determine window corners that # map cl -> cs. All clipping, etc is already handled by the coordsLocal # getter. cs = self.coordsScreen cl = self.coordsLocal sw = self.scene.width sh = self.scene.height # Determine the window width and height. We want a local-sized chunk # of this to correspond to a screen-sized chunk of the screen. That is, # cl[2] / ww == cs[2] / sw ww = cl[2] * sw / cs[2] wh = cl[3] * sh / cs[3] # cs[0] / sw = (x - nx) / ww nx = cl[0] - cs[0] * ww / sw ny = cl[1] - cs[1] * wh / sh gl.gluOrtho2D(nx, nx+ww, ny, ny+wh) gl.glMatrixMode(gl.GL_MODELVIEW)
def gl_setup(): # general GL setup glMatrixMode(GL_PROJECTION) glMatrixMode(GL_MODELVIEW) gluOrtho2D(0, WIDTH, 0, HEIGHT) # dont understand, check this # TODO glLoadIdentity() glTranslatef(CENTX, CENTY, 0) glClear(GL_COLOR_BUFFER_BIT)
def on_draw(self, gl=pyglet.gl): """Clear the current OpenGL context, reset the model/view matrix and invoke the `draw()` methods of the renderers in order """ gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glLoadIdentity() BaseWorld.draw_renderers(self)
def on_draw(): update_grid() window.clear() gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.glOrtho(0, 200, 200, 0, 0, 1) grid.draw()
def draw_text(text, start_x, start_y, color, size): """ Draw text to the screen. Args: :text: Text to display. :start_x: x coordinate of top left text point. :start_y: y coordinate of top left text point. :color: color, specified in a list of 3 or 4 bytes in RGB or RGBA format. Example: >>> import arcade >>> arcade.open_window("Drawing Example", 800, 600) >>> arcade.set_background_color(arcade.color.WHITE) >>> arcade.start_render() >>> arcade.draw_text("Text Example", 250, 300, arcade.color.BLACK, 10) >>> arcade.finish_render() >>> arcade.quick_run(0.25) """ if len(color) == 3: color = (color[0], color[1], color[2], 255) label = pyglet.text.Label(text, font_name='Times New Roman', font_size=size, x=start_x, y=start_y, color=color) GL.glLoadIdentity() label.draw()
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
def draw(self): self.loadStartPosition() gl.glRotatef(90.0, 0.0, 0.0, 1.0) gl.glBegin(gl.GL_QUADS) gl.glColor3f(1.0, 1.0, 0.0) tenth = math.pi * 2.0 / 10.0 for z in [-0.1, 0.1]: for i in xrange(5): a = float(i) * tenth * 2.0 gl.glVertex3f(0.0, 0.0, z) gl.glVertex3f(0.4 * math.cos(a - tenth), 0.4 * math.sin(a - tenth), z) gl.glVertex3f(math.cos(a), math.sin(a), z) gl.glVertex3f(0.4 * math.cos(a + tenth), 0.4 * math.sin(a + tenth), z) for i in xrange(5): a = float(i) * tenth * 2.0 gl.glVertex3f(0.4 * math.cos(a - tenth), 0.4 * math.sin(a - tenth), 0.1) gl.glVertex3f(math.cos(a), math.sin(a), 0.1) gl.glVertex3f(math.cos(a), math.sin(a), -0.1) gl.glVertex3f(0.4 * math.cos(a - tenth), 0.4 * math.sin(a - tenth), -0.1) gl.glVertex3f(0.4 * math.cos(a + tenth), 0.4 * math.sin(a + tenth), 0.1) gl.glVertex3f(math.cos(a), math.sin(a), 0.1) gl.glVertex3f(math.cos(a), math.sin(a), -0.1) gl.glVertex3f(0.4 * math.cos(a + tenth), 0.4 * math.sin(a + tenth), -0.1) gl.glEnd() self.loadStartPosition() gl.glTranslatef(0.0, 0.0, 0.1) gl.glScalef(0.01, 0.01, 0.0) self.label.draw() gl.glLoadIdentity()
def draw(self, frame): # The gneneral plan here is: # 1. Get the dots in the range of 0-255. # 2. Create a texture with the dots data. # 3. Draw the texture, scaled up with nearest-neighbor. # 4. Draw a mask over the dots to give them a slightly more realistic look. gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glLoadIdentity() # Draw the dots in this color: #gl.glColor3f(1.0, 0.5, 0.25) gl.glScalef(1, -1, 1) gl.glTranslatef(0, -DMD_SIZE[1]*DMD_SCALE, 0) #data = frame.get_data_mult() #this new jk_get_data will read the dots using the dmd function #and convert them via the map to rGB. data = self.jk_get_data(frame) image = pyglet.image.ImageData(DMD_SIZE[0], DMD_SIZE[1], 'RGB', data, pitch=DMD_SIZE[0] * 3) gl.glTexParameteri(image.get_texture().target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) image.blit(0, 0, width=DMD_SIZE[0]*DMD_SCALE, height=DMD_SIZE[1]*DMD_SCALE) del image gl.glScalef(DMD_SCALE/float(MASK_SIZE), DMD_SCALE/float(MASK_SIZE), 1.0) gl.glColor4f(1.0, 1.0, 1.0, 1.0) self.mask_texture.blit_tiled(x=0, y=0, z=0, width=DMD_SIZE[0]*MASK_SIZE, height=DMD_SIZE[1]*MASK_SIZE)
def set_camera_projection (self): lander_width = self.scaleFactor * self.simulator.lander_width lander_height = self.scaleFactor * -self.simulator.lander.colliders['pos'][1].min() (pad_x, pad_y) = (0.0, lander_height) (lander_x, lander_y) = self.scaleFactor * self.simulator.lander.pos self.display_width = abs(pad_x - lander_x) + 2*lander_width self.display_height = abs(pad_y - lander_y) + 2*lander_width if self.display_width*self.height > self.display_height*self.width: self.display_height = self.display_width * self.height / self.width else: self.display_width = self.display_height * self.width / self.height self.camera_x = (pad_x + lander_x) / 2.0 self.camera_y = (pad_y + lander_y) / 2.0 self.camera_z = self.display_height / (2.0 * math.tan(self.fov_y/2.0)) moon_radius = self.scaleFactor * 1.7371e6 self.camera_near = self.camera_y / math.tan(self.fov_y/2.0) # self.camera_far = 500*self.scaleFactor self.camera_far = math.sqrt(2*moon_radius*self.camera_y) gl.glLoadIdentity() gl.gluPerspective (math.degrees(self.fov_y), self.display_width/self.display_height, self.camera_near, self.camera_far)
def world_projection(self): """ Sets OpenGL projection and modelview matrices such that the window is centered on self.(x,y), shows at least 'scale' world units in every direction, and is oriented by rot. """ left = bottom = -self.scale right = top = self.scale aspect = self.width / self.height if aspect >= 1: # landscape left *= aspect right *= aspect else: # portrait bottom /= aspect top /= aspect glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(left, right, bottom, top) glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt( self.x, self.y, +1.0, self.x, self.y, -1.0, sin(self.rot), cos(self.rot), 0.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()
def on_draw(self): self.window.clear() gl.glMatrixMode(gl.GL_PROJECTION) gl.glPushMatrix() gl.glLoadIdentity() self.camera() gl.glEnable(self.grass.target) gl.glEnable(gl.GL_BLEND) gl.glBindTexture(self.grass.target, self.grass.id) W = 10000. graphics.draw(4, gl.GL_QUADS, ('v2f', (-W, -W, W, -W, W, W, -W, W)), ('t2f', (0., 0., W*5., 0., W*5., W*5., 0., W*5.)) ) gl.glDisable(self.grass.target) for lane in self.lanes: self.draw_lane_surface(lane) for lane in self.lanes: self.draw_lane_lines(lane) for obj in self.objects: self.draw_object(obj) for car in self.cars: if car!=self.main_car and car not in self.visible_cars: self.draw_car(self.anim_x[car], car.color) if self.heat is not None: self.draw_heatmap() for car in self.cars: if car==self.main_car or car in self.visible_cars: self.draw_car(self.anim_x[car], car.color) gl.glPopMatrix() if isinstance(self.main_car, Car): self.label.text = 'Speed: %.2f'%self.anim_x[self.main_car][3] self.label.draw() if self.output is not None: pyglet.image.get_buffer_manager().get_color_buffer().save(self.output.format(self.frame))
def on_draw(): gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() # Gradient sky l, b = world_to_screen((0, 0)) r, t = world_to_screen((W, H)) horizon = 177 / 255.0, 202 / 255.0, 1.0 zenith = 68 / 255.0, 0.5, 1.0 pyglet.graphics.draw(4, gl.GL_QUADS, ('v2f', [l, b, l, t, r, t, r, b]), ('c3f', sum([horizon, zenith, zenith, horizon], ())), ) cx, cy = camera tx, ty = world_to_screen((-cx + W * 0.5, -cy + H * 0.5)) gl.glTranslatef(tx, ty, 0) batch.draw() # Water l, b = world_to_screen((0, 0)) r, t = world_to_screen((1000, WATER_LEVEL)) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) pyglet.graphics.draw(4, gl.GL_QUADS, ('v2f', [l, b, l, t, r, t, r, b]), ('c4f', [0, 0.2, 0.8, 0.5] * 4), )
def draw_texture_rectangle(center_x: float, center_y: float, width: float, height: float, texture: Texture, angle: float = 0, alpha: float = 1, transparent: bool = True, repeat_count_x=1, repeat_count_y=1): """ Draw a textured rectangle on-screen. Args: :center_x: x coordinate of rectangle center. :center_y: y coordinate of rectangle center. :width: width of the rectangle. :height: height of the rectangle. :texture: identifier of texture returned from load_texture() call :angle: rotation of the rectangle. Defaults to zero. :alpha: Transparency of image. Returns: None Raises: None :Example: >>> import arcade >>> arcade.open_window(800,600,"Drawing Example") >>> arcade.set_background_color(arcade.color.WHITE) >>> arcade.start_render() >>> arcade.draw_text("draw_bitmap", 483, 3, arcade.color.BLACK, 12) >>> name = "arcade/examples/images/playerShip1_orange.png" >>> texture = arcade.load_texture(name) >>> scale = .6 >>> arcade.draw_texture_rectangle(540, 120, scale * texture.width, \ scale * texture.height, texture, 0) >>> arcade.draw_texture_rectangle(540, 60, scale * texture.width, \ scale * texture.height, texture, 90) >>> arcade.draw_texture_rectangle(540, 60, scale * texture.width, \ scale * texture.height, texture, 90, 1, False) >>> arcade.finish_render() >>> arcade.quick_run(0.25) """ if transparent: gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) else: gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_TEXTURE_2D) gl.glHint(gl.GL_POLYGON_SMOOTH_HINT, gl.GL_NICEST) gl.glHint(gl.GL_PERSPECTIVE_CORRECTION_HINT, gl.GL_NICEST) gl.glLoadIdentity() gl.glColor4f(1, 1, 1, alpha) z = 0.5 # pylint: disable=invalid-name x1 = -width / 2 + center_x x2 = width / 2 + center_x y1 = -height / 2 + center_y y2 = height / 2 + center_y p1 = x1, y1 p2 = x2, y1 p3 = x2, y2 p4 = x1, y2 if angle: p1 = rotate_point(p1[0], p1[1], center_x, center_y, angle) p2 = rotate_point(p2[0], p2[1], center_x, center_y, angle) p3 = rotate_point(p3[0], p3[1], center_x, center_y, angle) p4 = rotate_point(p4[0], p4[1], center_x, center_y, angle) gl.glBindTexture(gl.GL_TEXTURE_2D, texture.texture_id) gl.glBegin(gl.GL_POLYGON) gl.glNormal3f(0.0, 0.0, 1.0) gl.glTexCoord2f(0, 0) gl.glVertex3f(p1[0], p1[1], z) gl.glTexCoord2f(repeat_count_x, 0) gl.glVertex3f(p2[0], p2[1], z) gl.glTexCoord2f(repeat_count_x, repeat_count_y) gl.glVertex3f(p3[0], p3[1], z) gl.glTexCoord2f(0, repeat_count_y) gl.glVertex3f(p4[0], p4[1], z) gl.glEnd() gl.glDisable(gl.GL_TEXTURE_2D)
def unset_state(self): gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity()
def set_state(self): gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() gl.glTranslatef(self.position.x, self.position.y, 0) gl.glRotatef(self.angle, 0, 0, 1)
def on_draw(self): """ Run the actual draw calls. """ if self._profile: profiler = self.Profiler() profiler.start() self._update_meshes() gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glLoadIdentity() # pull the new camera transform from the scene transform_camera = np.linalg.inv(self.scene.camera_transform) # apply the camera transform to the matrix stack gl.glMultMatrixf(rendering.matrix_to_gl(transform_camera)) # we want to render fully opaque objects first, # followed by objects which have transparency node_names = collections.deque(self.scene.graph.nodes_geometry) # how many nodes did we start with count_original = len(node_names) count = -1 # if we are rendering an axis marker at the world if self._axis and not self.view['axis'] == 'without_world': # we stored it as a vertex list self._axis.draw(mode=gl.GL_TRIANGLES) if self._grid: self._grid.draw(mode=gl.GL_LINES) while len(node_names) > 0: count += 1 current_node = node_names.popleft() if current_node in self._nodes_hidden: continue # get the transform from world to geometry and mesh name transform, geometry_name = self.scene.graph.get(current_node) # if no geometry at this frame continue without rendering if geometry_name is None: continue # if a geometry is marked as fixed apply the inverse view transform if self.fixed is not None and geometry_name in self.fixed: # remove altered camera transform from fixed geometry transform_fix = np.linalg.inv( np.dot(self._initial_camera_transform, transform_camera)) # apply the transform so the fixed geometry doesn't move transform = np.dot(transform, transform_fix) # get a reference to the mesh so we can check transparency mesh = self.scene.geometry[geometry_name] if mesh.is_empty: continue # get the GL mode of the current geometry mode = self.vertex_list_mode[geometry_name] # if you draw a coplanar line with a triangle it will z-fight # the best way to do this is probably a shader but this works fine if mode == gl.GL_LINES: # apply the offset in camera space transform = util.multi_dot([ transform, np.linalg.inv(transform_camera), self._line_offset, transform_camera ]) # add a new matrix to the model stack gl.glPushMatrix() # transform by the nodes transform gl.glMultMatrixf(rendering.matrix_to_gl(transform)) # draw an axis marker for each mesh frame if self.view['axis'] == 'all': self._axis.draw(mode=gl.GL_TRIANGLES) elif self.view['axis'] == 'without_world': if count > 0: self._axis.draw(mode=gl.GL_TRIANGLES) # transparent things must be drawn last if (hasattr(mesh, 'visual') and hasattr(mesh.visual, 'transparency') and mesh.visual.transparency): # put the current item onto the back of the queue if count < count_original: # add the node to be drawn last node_names.append(current_node) # pop the matrix stack for now gl.glPopMatrix() # come back to this mesh later continue # if we have texture enable the target texture texture = None if geometry_name in self.textures: texture = self.textures[geometry_name] gl.glEnable(texture.target) gl.glBindTexture(texture.target, texture.id) # draw the mesh with its transform applied self.vertex_list[geometry_name].draw(mode=mode) # pop the matrix stack as we drew what we needed to draw gl.glPopMatrix() # disable texture after using if texture is not None: gl.glDisable(texture.target) if self._profile: profiler.stop() print(profiler.output_text(unicode=True, color=True))
def update(self): gl.glLoadIdentity() gl.glTranslatef(-self.x, -self.y, -self.z) gl.glRotatef(self.rx, 1, 0, 0) gl.glRotatef(self.ry, 0, 1, 0) gl.glRotatef(self.rz, 0, 0, 1)
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) # texture size may be increased by pyglet to a power of 2 tw, th = image_data.texture.owner.width, image_data.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()
def init_rot_matrix(self): pgl.glPushMatrix() pgl.glLoadIdentity() self._rot = get_model_matrix() pgl.glPopMatrix()
def render(self): glTranslatef(self.x, self.y, 0) glRotatef(self.angle, 0.0, 0.0, 1.0) glTranslatef(self.xoff, 0, 0) self.label.draw() glLoadIdentity() # Restores ordinary drawing
def _draw_rects(shape_list: List[Sprite], vertex_buffer: VertexBuffer, texture_coord_buffer: TextureCoordBuffer, color_buffer: ColorBuffer, change_x: float, change_y: float): """ Draw a set of rectangles using vertex buffers. This is more efficient than drawing them individually. """ if len(shape_list) == 0: return gl.glEnable(gl.GL_BLEND) gl.glEnable(gl.GL_TEXTURE_2D ) # As soon as this happens, can't use drawing commands gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glHint(gl.GL_POLYGON_SMOOTH_HINT, gl.GL_NICEST) gl.glHint(gl.GL_PERSPECTIVE_CORRECTION_HINT, gl.GL_NICEST) vertex_buffer.bind() color_buffer.bind() texture_coord_buffer.bind() gl.glLoadIdentity() gl.glTranslatef(change_x, change_y, 0) # Ideally, we want to draw these in "batches." # We seek to find groups of squares with the same texture. Then draw # them all at once. last_texture_id = None batch_count = 0 offset = 0 batch_offset = 0 texture_coord_vbo_id = None for shape in shape_list: if shape.texture.texture_id != last_texture_id: # Ok, if the 'if' triggered above, we are now looking at a different # texture than we looked at with the last loop. So draw the last # "batch" of squares. We'll start a new batch with the current # square but not draw it yet if batch_count > 0: _render_rect_filled(batch_offset, last_texture_id, texture_coord_vbo_id, batch_count) batch_count = 0 batch_offset = offset last_texture_id = shape.texture.texture_id batch_count += 4 offset += 4 # Draw the last batch, if it exists _render_rect_filled(batch_offset, last_texture_id, texture_coord_vbo_id, batch_count) # Must do this, or drawing commands won't work. gl.glDisable(gl.GL_TEXTURE_2D)
def set_viewport(self, width, height): 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)
def draw(self): gl.glLoadIdentity() self.batch.draw()
def _draw_rects(shape_list: List[Sprite], vertex_vbo_id: gl.GLuint, texture_coord_vbo_id: gl.GLuint, change_x: float, change_y: float): """ Draw a set of rectangles using vertex buffers. This is more efficient than drawing them individually. """ if len(shape_list) == 0: return gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_TEXTURE_2D ) # As soon as this happens, can't use drawing commands # gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) # gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glHint(gl.GL_POLYGON_SMOOTH_HINT, gl.GL_NICEST) gl.glHint(gl.GL_PERSPECTIVE_CORRECTION_HINT, gl.GL_NICEST) # gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) # gl.glMatrixMode(gl.GL_MODELVIEW) # gl.glDisable(gl.GL_BLEND) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vertex_vbo_id) gl.glEnableClientState(gl.GL_TEXTURE_COORD_ARRAY) gl.glEnableClientState(gl.GL_VERTEX_ARRAY) gl.glVertexPointer(2, gl.GL_FLOAT, 0, 0) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, texture_coord_vbo_id) last_alpha = shape_list[0].alpha gl.glColor4f(1, 1, 1, last_alpha) gl.glLoadIdentity() # gl.glLoadIdentity() gl.glTranslatef(change_x, change_y, 0) # Ideally, we want to draw these in "batches." # We seek to find groups of squares with the same texture. Then draw # them all at once. last_texture_id = None last_alpha = 1 batch_count = 0 offset = 0 batch_offset = 0 texture_coord_vbo_id = None for shape in shape_list: if shape.texture.texture_id != last_texture_id or shape.alpha != last_alpha: # Ok, if the 'if' triggered above, we are now looking at a different # texture than we looked at with the last loop. So draw the last # "batch" of squares. We'll start a new batch with the current # square but not draw it yet if batch_count > 0: gl.glColor4f(1, 1, 1, last_alpha) _render_rect_filled(batch_offset, last_texture_id, texture_coord_vbo_id, batch_count) batch_count = 0 batch_offset = offset last_texture_id = shape.texture.texture_id last_alpha = shape.alpha batch_count += 4 offset += 4 # Draw the last batch, if it exists _render_rect_filled(batch_offset, last_texture_id, texture_coord_vbo_id, batch_count) gl.glDisable(gl.GL_TEXTURE_2D)
def on_draw(): pyglet.clock.tick() window.clear() gl.glLoadIdentity() draw()
def _draw_ortho(self): glLoadIdentity() self._info_label.draw()
def render(self, mode='human', close=False, text=False): """ Render the environment for human viewing """ if close: if self.window: self.window.close() return top_down = mode == 'top_down' # Render the image top = self._render_img(WINDOW_WIDTH, WINDOW_HEIGHT, self.multi_fbo_human, self.final_fbo_human, self.img_array_human, top_down=True) bot = self._render_img(WINDOW_WIDTH, WINDOW_HEIGHT, self.multi_fbo_human, self.final_fbo_human, self.img_array_human, top_down=False) win_width = WINDOW_WIDTH if self._view_mode == FULL_VIEW_MODE: img = np.concatenate((top, bot), axis=1) win_width = 2 * WINDOW_WIDTH elif self._view_mode == TOP_DOWN_VIEW_MODE: img = top else: img = bot if self.window is not None: self.window.set_size(win_width, WINDOW_HEIGHT) # self.undistort - for UndistortWrapper if self.distortion and not self.undistort and mode != "free_cam": img = self.camera_model.distort(img) if mode == 'rgb_array': return img from pyglet import gl, window, image if self.window is None: config = gl.Config(double_buffer=False) self.window = window.Window(width=win_width, height=WINDOW_HEIGHT, resizable=False, config=config) self.window.clear() self.window.switch_to() self.window.dispatch_events() # Bind the default frame buffer gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) # 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 = img.shape[1] height = img.shape[0] img = np.ascontiguousarray(np.flip(img, axis=0)) img_data = image.ImageData( width, height, 'RGB', img.ctypes.data_as(POINTER(gl.GLubyte)), pitch=width * 3, ) img_data.blit(0, 0, 0, width=WINDOW_WIDTH, height=WINDOW_HEIGHT) # Display position/state information if text and mode != "free_cam": x, y, z = self.cur_pos self.text_label.text = "pos: (%.2f, %.2f, %.2f), angle: %d, steps: %d, speed: %.2f m/s" % ( x, y, z, int(self.cur_angle * 180 / math.pi), self.step_count, self.speed) self.text_label.draw() # Force execution of queued commands gl.glFlush()
def update(dt): """ pyglet update :param dt: We don't care about no dt :return: none """ path_cost = None # run simulation. If incrementalAnimation then animate the search at each step # else just show the end result #global flag if shared.incrementalAnimation: if shared.running: if shared.node_count < shared.max_nodes: shared.method() else: while shared.running: if shared.node_count < shared.max_nodes: shared.method() # draw optimized path if len(shared.optimizedPath) > 0: node1 = shared.optimizedPath[0] for node2 in shared.optimizedPath[1:]: #node1.root_path_color() #print((node1.parent.x, node1.parent.y), (node1.x, node1.y)) shared.batch.add(2, gl.GL_LINES, None, ('v2f', (node1.x, node1.y, node2.x, node2.y)), ('c3B', (0, 255, 255, 0, 255, 2))) node1 = node2 shared.optimizedPath = [] ''' if flag: for i in range(20): shared.nodes[i].remove_node() print("delete node") ''' # draws the bottom row stuff gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glLoadIdentity() if shared.root_path_length != sys.maxsize: path_cost = pyglet.text.Label("Path Cost: %6.2f" % shared.root_path_length, font_size=18, x=shared.window_width // 3, y=24, anchor_x='center', anchor_y='center', color=(128, 128, 128, 128)) node_label = pyglet.text.Label("Nodes: %d" % shared.node_count, font_size=18, x=2 * shared.window_width // 3, y=24, anchor_x='center', anchor_y='center', color=(128, 128, 128, 128)) label = pyglet.text.Label(shared.method.__name__, font_size=36, x=shared.window_width - 10, y=24, anchor_x='right', anchor_y='center', color=(128, 128, 128, 128)) pyglet.graphics.draw( 4, gl.GL_QUADS, ('v2f', (0, 50, shared.window_width, 50, shared.window_width, 48, 0, 48)), ('c4f', (0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5))) # draws the square that indicates mode if shared.running: if shared.node_count >= shared.max_nodes: pyglet.graphics.draw(4, gl.GL_QUADS, ('v2f', (shared.window_width // 5 - 20, 24 - 10, shared.window_width // 5 - 20, 24 + 10, shared.window_width // 5, 24 + 10, shared.window_width // 5, 24 - 10)), ('c4f', (0.5, 0.25, 0.0, 0.5, 0.5, 0.25, 0.0, 0.5, 0.5, 0.25, 0.0, 0.5, 0.5, 0.25, 0.0, 0.5))) else: pyglet.graphics.draw(4, gl.GL_QUADS, ('v2f', (shared.window_width // 5 - 20, 24 - 10, shared.window_width // 5 - 20, 24 + 10, shared.window_width // 5, 24 + 10, shared.window_width // 5, 24 - 10)), ('c4f', (0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5))) else: pyglet.graphics.draw( 4, gl.GL_QUADS, ('v2f', (shared.window_width // 5 - 20, 24 - 10, shared.window_width // 5 - 20, 24 + 10, shared.window_width // 5, 24 + 10, shared.window_width // 5, 24 - 10)), ('c4f', (0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.5))) # draw optimized path #print("OPTIMUS: ", shared.optimizedPath) shared.batch.draw() #fps_display.draw() label.draw() node_label.draw() if path_cost is not None: path_cost.draw()
def on_draw(self): self.update_bottom_toolbar() # Main area: # Window background color gl.glClearColor(33 / 255, 33 / 255, 33 / 255, 1) # Set viewport gl.glViewport(0, 0, self.width, self.height) # Initialize Projection matrix gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() # Set orthographic projection matrix gl.gluOrtho2D(self.left, self.right, self.bottom, self.top) # Initialize Modelview matrix gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() # Clear window with ClearColor gl.glClear(gl.GL_COLOR_BUFFER_BIT) # Draw blank canvas self.canvas_bg_sprite.draw() # Draw pixels if pixel_batch: pixel_batch.draw() # ??? if holder_patch: holder_patch.draw() # Draw pixel cursor if not self.pixel_cursor_sprite == None: self.pixel_cursor_sprite.draw() # Draw grid lines if options["grid_on"] and self.zoom_level < 0.5: draw_grid(self.width, self.height) # Bottom toolbar: # Set viewport gl.glViewport(0, 0, self.width, 20) # Initialize Projection matrix gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() # Set orthographic projection matrix gl.gluOrtho2D(0, self.width, 0, 20) # Initialize Modelview matrix gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() # Draw bottom toolbar self.bottom_toolbar_bg_sprite.draw() self.size_label.draw() self.zoom_label.draw() if self.mouse_on_canvas: self.position_label.draw() # Top toolbar: # Set viewport gl.glViewport(0, self.height - 80, self.width, 80) # Initialize Projection matrix gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() # Set orthographic projection matrix gl.gluOrtho2D(0, self.width, 0, 80) # Initialize Modelview matrix gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() # Draw background for top toolbar self.top_toolbar_bg_sprite.draw() # Draw top toolbar palette top_toolbar_batch.draw() # Draw color selection displays self.palette_colorleft_sprite.draw() self.palette_colorright_sprite.draw() self.colorleft_label.draw() self.colorright_label.draw()
def draw(self): gl.glLineWidth(1) ecsm = game_scene.ecsm phys_comp_list = ecsm.comps[phys.PhysicsEcsComponent.name()] grav_comp_list = ecsm.comps[phys.GravityEcsComponent.name()] coll_comp_list = ecsm.comps[collision.CollisionEcsComponent.name()] planet_comp_list = ecsm.comps[planet.PlanetEcsComponent.name()] ship_comp_list = ecsm.comps[ship.ShipEcsComponent.name()] base_comp_list = ecsm.comps[base.BaseEcsComponent.name()] entities = ecsm.entities player_entity_id = ecsm.get_system( player.PlayerEscSystem.name()).player_entity_id player_physc = ecsm.get_entity_comp(player_entity_id, phys.PhysicsEcsComponent.name()) # if player_physc: # tx = (-player_physc.pos.x * ZOOM) + const.WIDTH // 2 # ty = (-player_physc.pos.y * ZOOM) + const.HEIGHT // 2 # else: tx = const.WIDTH // 2 ty = const.HEIGHT // 2 gl.glColor3f(0, 0, 0.2) for i in range(0, const.WIDTH, 50): gl.glBegin(gl.GL_LINES) gl.glVertex2f(i, 0.0) gl.glVertex2f(i, const.HEIGHT) gl.glEnd() for i in range(0, const.HEIGHT, 50): gl.glBegin(gl.GL_LINES) gl.glVertex2f(0.0, i) gl.glVertex2f(const.WIDTH, i) gl.glEnd() gl.glPushMatrix() gl.glLoadIdentity() gl.glTranslatef(tx, ty, 0.0) # planet orbots for idx, eid in enumerate(entities): planetc = planet_comp_list[idx] physc = phys_comp_list[idx] if planetc and physc.static: # rpc = rend_plan_comp_list[idx] # render.draw_circle(physc.pos.x * ZOOM, physc.pos.y * ZOOM, collc.radius * ZOOM) distance = physc.pos.length if distance: render.draw_circle(0, 0, distance * ZOOM, mode=gl.GL_LINES, color=(.5, .5, .5, 1)) for idx, eid in enumerate(entities): shipc = ship_comp_list[idx] basec = base_comp_list[idx] planetc = planet_comp_list[idx] physc = phys_comp_list[idx] collc = coll_comp_list[idx] if basec and basec.crew_load > 0: render.draw_circle(physc.pos.x * ZOOM, physc.pos.y * ZOOM, TOKEN_SIZE * ZOOM, color=(1, 1, 0, 1)) # show planet elif planetc: # rpc = rend_plan_comp_list[idx] render.draw_circle(physc.pos.x * ZOOM, physc.pos.y * ZOOM, collc.radius * ZOOM, color=(.8, .8, .8, 1)) # gc = grav_comp_list[idx] # if gc and gc.gravity_radius: # render.draw_circle(physc.pos.x * ZOOM, physc.pos.y * ZOOM, gc.gravity_radius * ZOOM, None, gl.GL_LINE_LOOP, color=(.3, .3, .3, 1)) # labels for idx, eid in enumerate(entities): planetc = planet_comp_list[idx] physc = phys_comp_list[idx] collc = coll_comp_list[idx] if planetc: if planetc.pname: label = pyglet.text.Label( planetc.pname, font_name=font.FONT_MONO.name, font_size=12, x=physc.pos.x * ZOOM, y=(physc.pos.y + (collc.radius + 500)) * ZOOM, # + collc.radius + 5 anchor_x='center', anchor_y='center', color=(255, 255, 255, 120)) label.draw() # show player position if player_physc: render.draw_circle(player_physc.pos.x * ZOOM, player_physc.pos.y * ZOOM, TOKEN_SIZE * ZOOM, color=(1, 0, 0, 1)) gl.glPopMatrix()
def _render(self, mode='human', close=False): if not self.render_mode: return if close: if self.viewer is not None: self.viewer.close() self.viewer = None return try: small_img = self.current_obs if small_img is None: small_img = np.zeros(shape=(SCREEN_X, SCREEN_Y, 3), dtype=np.uint8) vae_img = resize(self._decode(self.z), (64, 64)) WINDOW_HEIGHT = 600 if DEBUG: small_img = resize(small_img, (64, 64)) if DEBUG_NEXT: next_img = resize(self._decode(self.next_z), (64, 64)) img = np.concatenate((small_img, next_img), axis=1) else: img = np.concatenate((small_img, vae_img), axis=1) WINDOW_WIDTH = 1200 else: WINDOW_WIDTH = 800 img = vae_img if mode == 'rgb_array': return img elif mode == 'human': from pyglet import gl, window, image if self.window is None: config = gl.Config(double_buffer=False) self.window = window.Window(width=WINDOW_WIDTH, height=WINDOW_HEIGHT, resizable=False, config=config) self.window.clear() self.window.switch_to() self.window.dispatch_events() gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() gl.glOrtho(0, WINDOW_WIDTH, 0, WINDOW_HEIGHT, 0, 10) width = img.shape[1] height = img.shape[0] img = np.ascontiguousarray(np.flip(img, axis=0)) from ctypes import POINTER img_data = image.ImageData( width, height, 'RGB', img.ctypes.data_as(POINTER(gl.GLubyte)), pitch=width * 3, ) img_data.blit(0, 0, 0, width=WINDOW_WIDTH, height=WINDOW_HEIGHT) except Exception as e: print(e) # Duckietown has been closed
def on_draw(self): """ Run the actual draw calls. """ self._update_meshes() gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glLoadIdentity() # pull the new camera transform from the scene transform_camera = self.scene.graph.get( frame_to='world', frame_from=self.scene.camera.name)[0] # apply the camera transform to the matrix stack gl.glMultMatrixf(rendering.matrix_to_gl(transform_camera)) # dragging the mouse moves the view # but doesn't alter the scene view = view_to_transform(self.view) # add the view transform to the stack gl.glMultMatrixf(rendering.matrix_to_gl(view)) # we want to render fully opaque objects first, # followed by objects which have transparency node_names = collections.deque(self.scene.graph.nodes_geometry) # how many nodes did we start with count_original = len(node_names) count = -1 # if we are rendering an axis marker at the world if self._axis: # we stored it as a vertex list self._axis.draw(mode=gl.GL_TRIANGLES) while len(node_names) > 0: count += 1 current_node = node_names.popleft() # get the transform from world to geometry and mesh name transform, geometry_name = self.scene.graph[current_node] # if no geometry at this frame continue without rendering if geometry_name is None: continue # if a geometry is marked as fixed apply the inverse view transform if self.fixed is not None and geometry_name in self.fixed: transform = np.dot(np.linalg.inv(view), transform) # get a reference to the mesh so we can check transparency mesh = self.scene.geometry[geometry_name] if mesh.is_empty: continue # add a new matrix to the model stack gl.glPushMatrix() # transform by the nodes transform gl.glMultMatrixf(rendering.matrix_to_gl(transform)) # draw an axis marker for each mesh frame if self.view['axis'] == 'all': self._axis.draw(mode=gl.GL_TRIANGLES) # transparent things must be drawn last if (hasattr(mesh, 'visual') and hasattr(mesh.visual, 'transparency') and mesh.visual.transparency): # put the current item onto the back of the queue if count < count_original: # add the node to be drawn last node_names.append(current_node) # pop the matrix stack for now gl.glPopMatrix() # come back to this mesh later continue # if we have texture enable the target texture texture = None if geometry_name in self.textures: texture = self.textures[geometry_name] gl.glEnable(texture.target) gl.glBindTexture(texture.target, texture.id) # get the mode of the current geometry mode = self.vertex_list_mode[geometry_name] # draw the mesh with its transform applied self.vertex_list[geometry_name].draw(mode=mode) # pop the matrix stack as we drew what we needed to draw gl.glPopMatrix() # disable texture after using if texture is not None: gl.glDisable(texture.target)
def draw(self): gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() gl.glTranslatef(-self.x, -self.y, 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) # texture size may be increased by pyglet to a power of 2 tw, th = image_data.texture.owner.width, image_data.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 = 1 gl.glPointSize(psz) distance = (1, 0, 0) gl.glPointParameterfv(gl.GL_POINT_DISTANCE_ATTENUATION, (gl.GLfloat * 3)(*distance)) 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) gl.glDisable(gl.GL_MULTISAMPLE) # for true 1px points with MSAA on vertex_list.draw(gl.GL_POINTS) gl.glDisable(texture.target) 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)
def draw(self): gl.glLoadIdentity() #gl.glTranslatef(p[0], p[1], 0) self.vl.draw(pyglet.gl.GL_LINE_LOOP)
def draw(self, _Stage, _View, _isClear=False): """ Draw current batch of triangle vertices, acknowledging the scaling and rotation of the current display (stage settings) """ for iWin, win in enumerate(pyglet.app.windows): win.switch_to() xScale = _Stage.scalX_umPerPix * _Stage.winXCorrFact * win.scale yScale = _Stage.scalY_umPerPix * _Stage.winXCorrFact * win.scale yWin_5 = win.height // 2 xWin_5 = win.width // 2 xWin_25 = win.width // 4 if len(win.caption) == 0: GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GL.glOrtho(-xWin_5, xWin_5, -yWin_5, yWin_5, -1, 1) GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() GL.glPushMatrix() GL.glTranslatef(_Stage.centOffX_pix, _Stage.centOffY_pix, 0) GL.glScalef(xScale, yScale, 0.0) GL.glRotatef(_Stage.rot_angle, 0, 0, 1) if not _isClear: self.Batch.draw() self.BatchSpr.draw() GL.glPopMatrix() else: if _Stage.useScrOvl: # Draw on first (left) screen # GL.glViewport(0, 0, win.width // 2, win.height) GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GL.glOrtho(-xWin_25 * _Stage.hFlipScr1, xWin_25 * _Stage.hFlipScr1, -yWin_5 * _Stage.vFlipScr1, yWin_5 * _Stage.vFlipScr1, -1, 1) GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() GL.glPushMatrix() x = _Stage.centOffX_pix y = _Stage.centOffY_pix GL.glTranslatef(x, y, 0) GL.glScalef(xScale, yScale, 0.0) GL.glRotatef(_Stage.rot_angle, 0, 0, 1) if not _isClear: self.Batch.draw() self.BatchSpr.draw() GL.glPopMatrix() # Draw on second (right) screen # GL.glViewport(win.width // 2, 0, win.width // 2, win.height) GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GL.glOrtho(-xWin_25 * _Stage.hFlipScr2, xWin_25 * _Stage.hFlipScr2, -yWin_5 * _Stage.vFlipScr2, yWin_5 * _Stage.vFlipScr2, -1, 1) GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() GL.glPushMatrix() self.add_rect_data(win.Scr2Vert) x = _Stage.centOffX_pix + _Stage.offXScr2_pix y = _Stage.centOffY_pix + _Stage.offYScr2_pix GL.glTranslatef(x, y, 0) GL.glScalef(xScale, yScale, 0.0) GL.glRotatef(_Stage.rot_angle, 0, 0, 1) if not _isClear: self.Batch2.draw() self.Batch2Spr.draw() GL.glPopMatrix() else: GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GL.glOrtho(-xWin_5, xWin_5, -yWin_5, yWin_5, -1, 1) GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() GL.glPushMatrix() GL.glTranslatef(_Stage.centOffX_pix, _Stage.centOffY_pix, 0) GL.glScalef(xScale, yScale, 0.0) GL.glRotatef(_Stage.rot_angle, 0, 0, 1) if not _isClear: self.Batch.draw() self.BatchSpr.draw() GL.glPopMatrix()
def on_draw(): window.clear() gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.glOrtho(-wx, wx, -wy, wy, -1, 1) gl.glBegin(gl.GL_QUADS) gl.glColor3f(1, 0.5, 1) gl.glVertex3f(d, d, 0) gl.glColor3f(1, 1, 0.5) gl.glVertex3f(d, -d, 0) gl.glColor3f(0.5, 1, 1) gl.glVertex3f(-d, -d, 0) gl.glColor3f(1, 0.5, 0.5) gl.glVertex3f(-d, d, 0) gl.glColor3f(1, 1, 1) gl.glEnd() pattern = '0b1111000011110000' gl.glLineStipple(2, int(pattern, 2)) gl.glColor3f(1, 0.5, 0.5) gl.glBegin(gl.GL_LINES) gl.glVertex3f(-20*d, 0, 0) gl.glVertex3f(20*d, 0, 0) gl.glVertex3f(0, -20*d, 0) gl.glVertex3f(0, 20*d, 0) gl.glEnd() gl.glDisable(gl.GL_LINE_STIPPLE) gl.glColor3f(1, 1, 1) gl.glBegin(gl.GL_LINE_LOOP) for i in range(0, 5): gl.glVertex3f(f(2*np.pi*i/5, d)[0], f(2*np.pi*i/5, d)[1], 0) gl.glEnd() gl.glBegin(gl.GL_POINTS) gl.glVertex3f(0, 0, 0) gl.glEnd() gl.glDisable(gl.GL_POINT_SMOOTH) gl.glBegin(gl.GL_POINTS) for i in range(0, 5): gl.glVertex3f(f(2*np.pi*i/5, d)[0], f(2*np.pi*i/5, d)[1], 0) gl.glEnd() graphics.draw(3, gl.GL_TRIANGLES, ('v2f', ( f((2*np.pi*1/3)+ np.pi/2, d/3)[0], f((2*np.pi*1/3)+ np.pi/2, d/3)[1], f((2*np.pi*2/3)+ np.pi/2, d/3)[0], f((2*np.pi*2/3)+ np.pi/2, d/3)[1], f((2*np.pi*3/3)+ np.pi/2, d/3)[0], f((2*np.pi*3/3)+ np.pi/2, d/3)[1] )), ('c3f', ( 1, 0, 0, 0, 1, 0, 0, 0, 1 )))
def view_setup(): # general GL setup glMatrixMode(GL_PROJECTION) glMatrixMode(GL_MODELVIEW) gluOrtho2D(0, WIDTH, 0, HEIGHT) glLoadIdentity() glTranslatef(CENTX, CENTY, 0)
def apply_transformation(self): pgl.glLoadIdentity() pgl.glTranslatef(self._x, self._y, -self._dist) if self._rot is not None: pgl.glMultMatrixf(self._rot) pgl.glScalef(*self._get_scale())
def hud_mode(self, width, height): glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0, width, 0, height) glMatrixMode(GL_MODELVIEW) glLoadIdentity()
def _render_img(self, width, height, multi_fbo, final_fbo, img_array, top_down=True): """ Render an image of the environment into a frame buffer Produce a numpy RGB array image as output """ if not self.graphics: return # Switch to the default context # This is necessary on Linux nvidia drivers # pyglet.gl._shadow_window.switch_to() self.shadow_window.switch_to() from pyglet import gl # Bind the multisampled frame buffer gl.glEnable(gl.GL_MULTISAMPLE) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, multi_fbo) gl.glViewport(0, 0, width, height) # Clear the color and depth buffers c0, c1, c2 = self.horizon_color gl.glClearColor(c0, c1, c2, 1.0) gl.glClearDepth(1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) # Set the projection matrix gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.gluPerspective(self.cam_fov_y, width / float(height), 0.04, 100.0) # Set modelview matrix # Note: we add a bit of noise to the camera position for data augmentation pos = self.cur_pos angle = self.cur_angle if self.domain_rand: pos = pos + self.randomization_settings['camera_noise'] x, y, z = pos + self.cam_offset dx, dy, dz = self.get_dir_vec(angle) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() if self.draw_bbox: y += 0.8 gl.glRotatef(90, 1, 0, 0) elif not top_down: y += self.cam_height gl.glRotatef(self.cam_angle[0], 1, 0, 0) gl.glRotatef(self.cam_angle[1], 0, 1, 0) gl.glRotatef(self.cam_angle[2], 0, 0, 1) gl.glTranslatef( 0, 0, self._perturb(gym_duckietown.simulator.CAMERA_FORWARD_DIST)) if top_down: gl.gluLookAt( # Eye position (self.grid_width * self.road_tile_size) / 2, self.top_cam_height, (self.grid_height * self.road_tile_size) / 2, # Target (self.grid_width * self.road_tile_size) / 2, 0, (self.grid_height * self.road_tile_size) / 2, # Up vector 0, 0, -1.0) else: gl.gluLookAt( # Eye position x, y, z, # Target x + dx, y + dy, z + dz, # Up vector 0, 1.0, 0.0) # Draw the ground quad gl.glDisable(gl.GL_TEXTURE_2D) gl.glColor3f(*self.ground_color) gl.glPushMatrix() gl.glScalef(50, 1, 50) self.ground_vlist.draw(gl.GL_QUADS) gl.glPopMatrix() # Draw the ground/noise triangles self.tri_vlist.draw(gl.GL_TRIANGLES) # Draw the road quads gl.glEnable(gl.GL_TEXTURE_2D) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) # For each grid tile for j in range(self.grid_height): for i in range(self.grid_width): # Get the tile type and angle tile = self._get_tile(i, j) if tile is None: continue # kind = tile['kind'] angle = tile['angle'] color = tile['color'] texture = tile['texture'] gl.glColor3f(*color) gl.glPushMatrix() gl.glTranslatef((i + 0.5) * self.road_tile_size, 0, (j + 0.5) * self.road_tile_size) gl.glRotatef(angle * 90, 0, 1, 0) # Bind the appropriate texture texture.bind() self.road_vlist.draw(gl.GL_QUADS) gl.glPopMatrix() if self.draw_curve and tile['drivable']: # Find curve with largest dotproduct with heading curves = self._get_tile(i, j)['curves'] curve_headings = curves[:, -1, :] - curves[:, 0, :] curve_headings = curve_headings / np.linalg.norm( curve_headings).reshape(1, -1) dirVec = get_dir_vec(angle) dot_prods = np.dot(curve_headings, dirVec) # Current ("closest") curve drawn in Red pts = curves[np.argmax(dot_prods)] bezier_draw(pts, n=20, red=True) pts = self._get_curve(i, j) for idx, pt in enumerate(pts): # Don't draw current curve in blue if idx == np.argmax(dot_prods): continue bezier_draw(pt, n=20) # For each object for idx, obj in enumerate(self.objects): obj.render(self.draw_bbox) # Draw the agent's own bounding box if self.draw_bbox: corners = get_agent_corners(pos, angle) gl.glColor3f(1, 0, 0) gl.glBegin(gl.GL_LINE_LOOP) gl.glVertex3f(corners[0, 0], 0.01, corners[0, 1]) gl.glVertex3f(corners[1, 0], 0.01, corners[1, 1]) gl.glVertex3f(corners[2, 0], 0.01, corners[2, 1]) gl.glVertex3f(corners[3, 0], 0.01, corners[3, 1]) gl.glEnd() if top_down: gl.glPushMatrix() gl.glTranslatef(*self.cur_pos) gl.glScalef(1, 1, 1) gl.glRotatef(self.cur_angle * 180 / np.pi, 0, 1, 0) # glColor3f(*self.color) self.mesh.render() gl.glPopMatrix() # Resolve the multisampled frame buffer into the final frame buffer gl.glBindFramebuffer(gl.GL_READ_FRAMEBUFFER, multi_fbo) gl.glBindFramebuffer(gl.GL_DRAW_FRAMEBUFFER, final_fbo) gl.glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, gl.GL_COLOR_BUFFER_BIT, gl.GL_LINEAR) # Copy the frame buffer contents into a numpy array # Note: glReadPixels reads starting from the lower left corner gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, final_fbo) gl.glReadPixels(0, 0, width, height, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, img_array.ctypes.data_as(POINTER(gl.GLubyte))) # Unbind the frame buffer gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) # Flip the image because OpenGL maps (0,0) to the lower-left corner # Note: this is necessary for gym.wrappers.Monitor to record videos # properly, otherwise they are vertically inverted. img_array = np.ascontiguousarray(np.flip(img_array, axis=0)) return img_array def render_obs(self): """ Render an observation from the point of view of the agent """ observation = self._render_img(self.camera_width, self.camera_height, self.multi_fbo, self.final_fbo, self.img_array, top_down=True) # self.undistort - for UndistortWrapper if self.distortion and not self.undistort: observation = self.camera_model.distort(observation) return observation
def render(self, world_state, goals=[], time_step = None, wait=True): """" Renders the world state. Spawn a window if called for the first time. Parameters ---------- world_state: state of the world as an instance of `roboball2d.physics.world_state.WorldState` goals: list of tuple (x1, x2, (r,g,b)). For each item, a goal will be drawn on the ground, using the specified color time_step: allows to force a frame rate by either; - having rendering waiting a suitable amount of time (wait=True) or - skipping some frames (wait=False) wait: see time_step above """ if time_step is not None: # if wait : sleep the right amount of time such that the correct framerate is met # TODO: Does it make sense to wait before actually having rendered? This will result in a slower # framerate than desired. Should be right before self.window.flip() if wait: if self._t_last_frame is None: sleep_time = 0.0 else: sleep_time = max(0.0, time_step - (time.time() - self._t_last_frame)) time.sleep(sleep_time) self._t_last_frame = time.time() # if not wait : skipping frame if required else : t = time.time() if self._t_last_frame is None: self._t_last_frame = t if t-self._t_last_frame < time_step : return self._t_last_frame = t if self.window is None: self.window = pyglet.window.Window(width = self.rendering_config.window.width, height = self.rendering_config.window.height, vsync = False, resizable = True) self.window.set_location(self.rendering_config.location[0], self.rendering_config.location[1]) gl.glClearColor(*self.rendering_config.background_color) @self.window.event def on_resize(width, height): gl.glViewport(0, 0, width, height) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.glOrtho(0., self.rendering_config.visible_area_width, -0.1*float(height)/width*self.rendering_config.visible_area_width, 0.9*float(height)/width*self.rendering_config.visible_area_width, -1., 1.) gl.glMatrixMode(gl.GL_MODELVIEW) return pyglet.event.EVENT_HANDLED self.window.clear() self.window.switch_to() self.window.dispatch_events() gl.glLoadIdentity() # enable depth test (objects with higher values of the z coordinate # will occlude other objects; if z coordinates are the same, newer # object will occlude older one) pyglet.graphics.glEnable(pyglet.graphics.GL_DEPTH_TEST) gl.glDepthFunc(gl.GL_LEQUAL) # balls if self.ball_configs: for ball,config in zip(world_state.balls,self.ball_configs): draw_ball(ball.position, ball.angle, config.radius, 16, config.color, config.line_color) # robots for robot in world_state.robots: robot.render() gl.glBegin(gl.GL_QUADS) gl.glColor3f(*self.rendering_config.ground_color) gl.glVertex2f(0., 0.) gl.glVertex2f(0., -10.) gl.glVertex2f(self.rendering_config.visible_area_width, -10.) gl.glVertex2f(self.rendering_config.visible_area_width, 0.) gl.glEnd() # goals (if any) for goal in goals: x1,x2,color = goal draw_box([(x1+x2)/2.0, -0.5*self.rendering_config.visual_height], max(x1,x2)-min(x1,x2), self.rendering_config.visual_height, 0., color) for callback in self._callbacks: callback(world_state) self.window.flip()