def draw_objects(self): '''called in the middle of ondraw after the buffer has been cleared''' self.create_objects() glPushMatrix() if self.orthographic: glTranslatef(0, 0, -3 * self.dist) # Move back else: glTranslatef(0, 0, -self.dist) # Move back # Rotate according to trackball glMultMatrixd(build_rotmatrix(self.basequat)) # Move origin to bottom left of platform platformx0 = -self.build_dimensions[3] - self.parent.platform.width / 2 platformy0 = -self.build_dimensions[4] - self.parent.platform.depth / 2 glTranslatef(platformx0, platformy0, 0) for obj in self.parent.objects: if not obj.model \ or not obj.model.loaded \ or not obj.model.initialized: continue glPushMatrix() glTranslatef(*(obj.offsets)) glTranslatef(*(obj.centeroffset)) glRotatef(obj.rot, 0.0, 0.0, 1.0) glScalef(*obj.scale) obj.model.display() glPopMatrix() glPopMatrix()
def flush_labels(self): gl.glClear(gl.GL_DEPTH_BUFFER_BIT) gl.glPushMatrix() gl.glTranslatef(-self.game.camera_x * defs.WINDOW_SCALE[0], -self.game.camera_y * defs.WINDOW_SCALE[1], 0) for label, x, y, scale in self.labels: if scale: gl.glPushMatrix() label.anchor_x = 'center' label.anchor_y = 'center' gl.glTranslatef(x * defs.WINDOW_SCALE[0], y * defs.WINDOW_SCALE[1], 0) gl.glScalef(*scale) label.x = label.y = 0 label.draw() gl.glPopMatrix() else: label.x = x * defs.WINDOW_SCALE[0] label.y = y * defs.WINDOW_SCALE[1] label.draw() self.labels = [] gl.glColor3f(1, 1, 1) gl.glEnable(gl.GL_DEPTH_TEST) gl.glPopMatrix() # self.fps_label.draw() self.game.score.draw()
def on_draw(self): pyglet.gl.glClearColor(0.2,0.2,0.8,1) self.clear() gl.glPushMatrix() gl.glTranslatef(self.camera[0], self.camera[1], 0) pyglet.gl.glColor4f(1,1,1,1) for territory in self.landmass.land_terrs: for tri in territory.triangles: pyglet.gl.glColor4f(*territory.color) pyglet.graphics.draw( 3, pyglet.gl.GL_TRIANGLES, ('v2f', tri) ) for line in territory.lines: pyglet.gl.glColor4f(*line.color) self.draw_line(line.a.x, line.a.y, line.b.x, line.b.y) for terr in self.landmass.sea_terrs: for line in terr.lines: pyglet.gl.glColor4f(*line.color) self.draw_line(line.a.x, line.a.y, line.b.x, line.b.y) if self.draw_capitals: for terr in itertools.chain(self.landmass.land_terrs, self.landmass.sea_terrs): pyglet.gl.glColor4f(1,1,1,1) w = terr.label.content_width/2+2 h = terr.label.content_height/2 self.draw_rect(terr.x-w, terr.y-h, terr.x+w, terr.y+h) pyglet.gl.glColor4f(1,1,1,1) self.batch.draw() gl.glPopMatrix()
def draw_ents(self, ents): for ent in ents: glPushMatrix() glTranslatef(ent.body.position.x, ent.body.position.y, 0) glRotatef(ent.body.angle * 180 / pi, 0, 0, 1) ent.batch.draw() glPopMatrix()
def on_draw(self, dt=0): env.dt = dt if self.load_countdown == 0: if self.music_countdown > 0: self.music_countdown -= dt if self.music_countdown <= 0: music.new_song('The_Creature_Sneaks') if self.mode == GUI: gl.glLoadIdentity() if env.scale_factor != 1.0: gl.glPushMatrix() env.scale() gl.glClearColor(1,1,1,1) self.clear() gui.draw_card() if gui.current_card == gui.START: self.start_game() if gui.current_card == gui.QUIT: pyglet.app.exit() if gui.current_card == gui.LOAD: self.load_game() if env.scale_factor != 1.0: gl.glPopMatrix() elif self.load_countdown > 1: self.draw_load_screen() self.load_countdown -= 1 else: self.init_resources() self.init_gui() self.load_countdown = 0
def draw_axes(self): 'draw x y z axis in r g b with text labels' gl.glPushMatrix() gl.glScalef( 1.1, 1.1, 1.1) o = 0, 0, 0 x = 1, 0, 0 y = 0, 1, 0 z = 0, 0, 1 verts = numpy.array([ o, x, o, y, o, z], dtype=constants.DTYPE ) colors = numpy.array([ x, x, y, y, z, z], dtype=constants.DTYPE ) idxs = numpy.cast[constants.INTDTYPE]( numpy.mgrid[:6] ) self.drawlines( verts, colors, idxs) def draw_axis_label( name, xyz): 'draw a single label' gl.glPushMatrix() gl.glTranslatef( xyz[0], xyz[1], xyz[2] ) gl.glScalef( .01, .01, .01 ) gl.glRotatef( 90, 0, 1, 0 ) gl.glRotatef( 90, 0, 0, 1 ) pyglet.text.Label(name).draw() gl.glPopMatrix() draw_axis_label( 'x', x) draw_axis_label( 'y', y) draw_axis_label( 'z', z) gl.glPopMatrix()
def draw(self): if self.graph: glPushMatrix() glScalef(self.scale, self.scale, 1.0) self.graph.draw() glPopMatrix() self.grid.batch.draw()
def display(self, mode_2d=False): with self.lock: glPushMatrix() glTranslatef(self.offset_x, self.offset_y, 0) glEnableClientState(GL_VERTEX_ARRAY) has_vbo = isinstance(self.vertex_buffer, VertexBufferObject) if self.display_travels: self._display_travels(has_vbo) glEnable(GL_LIGHTING) glEnableClientState(GL_NORMAL_ARRAY) glEnableClientState(GL_COLOR_ARRAY) glMaterialfv(GL_FRONT, GL_SPECULAR, vec(1, 1, 1, 1)) glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, vec(0, 0, 0, 0)) glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 50) glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE) self._display_movements(has_vbo) glDisable(GL_LIGHTING) glDisableClientState(GL_COLOR_ARRAY) glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_NORMAL_ARRAY) glPopMatrix()
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 draw(self): glPushMatrix() self.transform() if self.enabled: self.vertex.draw(pyglet.gl.GL_LINES) glPopMatrix()
def translate(self,dx,dy,dz): glPushMatrix() glLoadIdentity() glTranslatef(dx,dy,dz) glMultMatrixf(self.matrix) self.matrix=get_model_matrix() glPopMatrix()
def circle(pos, radius, color=(1.0,1.0,1.0), alpha=1.0,segments=6): """ Draws a circle with gluDisk :param pos: center of the circle :type pos: 2-float tuple :param radius: radius of the circle :type radius: float :param color: the color in [0..1] range :type color: 3-float tuple :param alpha: the alpha value in [0..1] range :param segments: number of segments :type segments: int """ glDisable(GL_TEXTURE_2D) c = gluNewQuadric() glColor4f(color[0], color[1], color[2], alpha) glPushMatrix() glTranslatef(pos[0], pos[1], 0) gluDisk(c, 0, radius, segments, 1) glPopMatrix() glColor4f(1.0,1.0,1.0,1.0) glEnable(GL_TEXTURE_2D)
def rotate(self,ang,rx,ry,rz): glPushMatrix() glLoadIdentity() glRotatef(ang,rx,ry,rz) glMultMatrixf(self.matrix) self.matrix=get_model_matrix() glPopMatrix()
def render(self): gl.glPushMatrix() gl.glTranslatef(self.x + self.width / 2, self.y + self.height / 2, 0) gl.glRotatef(self.angle, 0, 0, 1) gl.glTranslatef(-self.x - self.width / 2, -self.y - self.height / 2, 0) self.batch.draw() gl.glPopMatrix() gl.glPushMatrix() cx, cy, cw, ch = cannon_rects[0] gl.glTranslatef(self.x + cx + cw / 2, self.y + cy + ch / 2, 0) gl.glRotatef(self.cannon_angle - 90, 0, 0, 1) gl.glTranslatef(-self.x - cx - cw / 2, -self.y - cy, 0) self.cannon_batch.draw() gl.glPopMatrix() self.batch = pyglet.graphics.Batch() self.cannon_batch = pyglet.graphics.Batch()
def drawSpace(self, window): gl.glPushMatrix() # GL matrices are applied last-added-first, so this *is* the right # order for pushing them. gl.glTranslatef(-self.viewportOrigin[0], -self.viewportOrigin[1], 0.0) if self.shake is not None: # We want to rotate around the center of the current viewport # vpc = view port center vpc_x = self.viewportOrigin[0] + self.windowProps.windowWidth//2 vpc_y = self.viewportOrigin[1] + self.windowProps.windowHeight//2 gl.glTranslatef(vpc_x, vpc_y, 0.0) gl.glRotatef(self.shake.getAngle(), 0, 0, 1) gl.glTranslatef(-vpc_x, -vpc_y, 0.0) ge = self.gameElements ge.starField.draw() ge.swarm.draw() if not self.explodedMarker.done(): ge.ship.draw() if self.endGame and not self.drawFrameMarker.done(): self.endGame.draw(window) for shot in ge.shots: if shot.alive: shot.draw() gl.glPopMatrix()
def draw_world_items(self, glyphs): ''' Draw all passed glyphs ''' shader = None for position, orientation, glyph in glyphs: gl.glPushMatrix() gl.glTranslatef(*position) if orientation and orientation != Orientation.Identity: gl.glMultMatrixf(orientation.matrix) if glyph.shader is not shader: shader = glyph.shader shader.use() gl_wrap.glBindVertexArray(glyph.vao) gl.glDrawElements( gl.GL_TRIANGLES, len(glyph.glindices), glyph.index_type, glyph.glindices ) gl.glPopMatrix() gl_wrap.glBindVertexArray(0) Shader.unuse()
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 draw_objects(self): '''called in the middle of ondraw after the buffer has been cleared''' self.create_objects() glPushMatrix() # Rotate according to trackball glMultMatrixd(build_rotmatrix(self.basequat)) # Move origin to bottom left of platform platformx0 = -self.build_dimensions[3] - self.parent.platform.width / 2 platformy0 = -self.build_dimensions[4] - self.parent.platform.depth / 2 glTranslatef(platformx0, platformy0, 0) light_z = max(self.parent.platform.width, self.parent.platform.depth) glLightfv(GL_LIGHT0, GL_POSITION, vec(0, self.parent.platform.depth / 2, light_z, 0)) glLightfv(GL_LIGHT1, GL_POSITION, vec(self.parent.platform.width, self.parent.platform.depth / 2, light_z, 0)) for obj in self.parent.objects: if not obj.model \ or not obj.model.loaded \ or not obj.model.initialized: continue glPushMatrix() glTranslatef(*(obj.offsets)) glTranslatef(*(obj.centeroffset)) glRotatef(obj.rot, 0.0, 0.0, 1.0) glScalef(*obj.scale) obj.model.display() glPopMatrix() glPopMatrix()
def draw(self): glPushMatrix() glTranslatef(self.xoffset, self.yoffset, self.zoffset) def color(i): if i % self.graduations_major == 0: glColor4f(*self.color_grads_major) elif i % (self.graduations_major / 2) == 0: glColor4f(*self.color_grads_interm) else: if self.light: return False glColor4f(*self.color_grads_minor) return True # draw the grid glBegin(GL_LINES) for i in range(0, int(math.ceil(self.width + 1))): if color(i): glVertex3f(float(i), 0.0, 0.0) glVertex3f(float(i), self.depth, 0.0) for i in range(0, int(math.ceil(self.depth + 1))): if color(i): glVertex3f(0, float(i), 0.0) glVertex3f(self.width, float(i), 0.0) glEnd() # draw fill glColor4f(*self.color_fill) glRectf(0.0, 0.0, float(self.width), float(self.depth)) glPopMatrix()
def draw(self, win=None): """Draw the current frame to a particular visual.Window (or to the default win for this object if not specified). The current position in the movie will be determined automatically. This method should be called on every frame that the movie is meant to appear. """ if (self.status == NOT_STARTED or (self.status == FINISHED and self.loop)): self.play() elif self.status == FINISHED and not self.loop: return if win is None: win = self.win self._selectWindow(win) self._updateFrameTexture() # will check if it's needed # scale the drawing frame and get to centre of field GL.glPushMatrix() # push before drawing, pop after # push the data for client attributes GL.glPushClientAttrib(GL.GL_CLIENT_ALL_ATTRIB_BITS) self.win.setScale('pix') # move to centre of stimulus and rotate vertsPix = self.verticesPix # bind textures GL.glActiveTexture(GL.GL_TEXTURE1) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glEnable(GL.GL_TEXTURE_2D) GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID) GL.glEnable(GL.GL_TEXTURE_2D) # sets opacity (1,1,1 = RGB placeholder) GL.glColor4f(1, 1, 1, self.opacity) array = (GL.GLfloat * 32)( 1, 1, # texture coords vertsPix[0, 0], vertsPix[0, 1], 0., # vertex 0, 1, vertsPix[1, 0], vertsPix[1, 1], 0., 0, 0, vertsPix[2, 0], vertsPix[2, 1], 0., 1, 0, vertsPix[3, 0], vertsPix[3, 1], 0., ) # 2D texture array, 3D vertex array GL.glInterleavedArrays(GL.GL_T2F_V3F, 0, array) GL.glDrawArrays(GL.GL_QUADS, 0, 4) GL.glPopClientAttrib() GL.glPopAttrib() GL.glPopMatrix() # unbind the textures GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glEnable(GL.GL_TEXTURE_2D) # implicitly disables 1D
def render(self, scene): """Add the cone to the scene. :param scene: The view to render the model into :type scene: pyglet_helper.objects.View """ if self.radius == 0: return self.init_model(scene) coverage_levels = [10, 30, 90, 250, 450] lod = self.lod_adjust(scene, coverage_levels, self.pos, self.radius) length = self.axis.mag() gl.glPushMatrix() self.model_world_transform(scene.gcf, Vector([length, self.radius, self.radius])).gl_mult() self.color.gl_set(self.opacity) if self.translucent: gl.glEnable(gl.GL_CULL_FACE) # Render the back half. gl.glCullFace(gl.GL_FRONT) scene.cone_model[lod].gl_render() # Render the front half. gl.glCullFace(gl.GL_BACK) scene.cone_model[lod].gl_render() else: scene.cone_model[lod].gl_render() gl.glPopMatrix()
def paint(self, peg): batch = self.get_batch() glPushMatrix() glTranslatef(peg.x, peg.y, 0) glRotatef(peg.angle, 0, 0, 1) batch.draw() glPopMatrix()
def _layerProjectLocalToScreenUndo(self): """Undoes the _layerProjectLocalToScreen() operation.""" if self._scissorBox is None and self.localBounds is None: return gl.glMatrixMode(gl.GL_PROJECTION) gl.glPopMatrix() gl.glMatrixMode(gl.GL_MODELVIEW)
def draw(): window.clear() for x in range(0, window.width+space_img.width, space_img.width): for y in range(0, window.height+space_img.height, space_img.height): space_img.blit(x=x, y=y) exhaust_batch.draw() for y_offset in (-window.height, 0, window.height): gl.glPushMatrix() gl.glTranslatef(0, y_offset, 0) ufo_batch.draw() gl.glPopMatrix() for x_offset in (-window.width, 0, window.width): for y_offset in (-window.height, 0, window.height): gl.glPushMatrix() gl.glTranslatef(x_offset, y_offset, 0) main_batch.draw() gl.glPopMatrix() for i in range(ship.lives): life_sprite.y = 40 life_sprite.x = 30 + 40 * i life_sprite.draw() level_label.draw()
def draw(self): if self._dirty: self._context = Context() self._parts = [] self.free() self.render() self.build_vbo() self._dirty = False # set gl.glEnable(self._texture.target) gl.glBindTexture(self._texture.target, self._texture.id) gl.glPushAttrib(gl.GL_COLOR_BUFFER_BIT) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glPushMatrix() self.transform() # cuadric.begin() self._vertex_list.draw(gl.GL_TRIANGLES) # cuadric.end() # unset gl.glPopMatrix() gl.glPopAttrib() gl.glDisable(self._texture.target)
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 render(self, geometry): """ Add the sphere to the view. :param scene: The view to render the model into :type scene: pyglet_helper.objects.View """ # Renders a simple sphere with the #2 level of detail. if self.radius == 0.0: return self.init_model(geometry) coverage_levels = [30, 100, 500, 5000] lod = self.lod_adjust(geometry, coverage_levels, self.pos, self.radius) gl.glPushMatrix() self.model_world_transform(geometry.gcf, self.scale).gl_mult() self.color.gl_set(self.opacity) if self.translucent: # Spheres are convex, so we don't need to sort gl.glEnable(gl.GL_CULL_FACE) # Render the back half (inside) gl.glCullFace(gl.GL_FRONT) geometry.sphere_model[lod].gl_render() # Render the front half (outside) gl.glCullFace(gl.GL_BACK) geometry.sphere_model[lod].gl_render() else: # Render a simple sphere. geometry.sphere_model[lod].gl_render() gl.glPopMatrix()
def draw(self): if self.batch is not None: glPushMatrix() glScalef(self.scale, self.scale, 0) self.batch.draw() glPopMatrix() self.grid.batch.draw()
def chain(self): gl.glPushMatrix() p = self.position r = self.rotation gl.glMultMatrixf( raw( r[0][0], r[1][0], r[2][0], 0.0, r[0][1], r[1][1], r[2][1], 0.0, r[0][2], r[1][2], r[2][2], 0.0, p[0], p[1], p[2], 1.0, ) ) self.material.apply() self.render() self.material.unapply() for c in self.children: c.chain() gl.glPopMatrix()
def draw(self): # Update list of entities # TODO this should actually update instead of recomputing all day, but, whatever entity_batch = pyglet.graphics.Batch() for _, entity in self.map_layer.children_names['entities'].children: x, y = entity.position w, h = entity.size x0 = entity.position[0] - entity.image_anchor[0] * entity.scale y0 = entity.position[1] - entity.image_anchor[1] * entity.scale x1, y1 = x0 + w, y0 + h entity_batch.add(4, gl.GL_QUADS, self.outlines_group, ('v2f', (x0, y0, x0, y1, x1, y1, x1, y0)), ('c4f', (1.0, 1.0, 0.0, 0.5) * 4)) # This is a diamond but at scale it looks enough like a dot D = 3 entity_batch.add(4, gl.GL_QUADS, None, ('v2f', (x + D, y, x, y - D, x - D, y, x, y + D)), ('c4f', (1.0, 1.0, 0.0, 1.0) * 4)) # Collision footprint... kinda R = entity.entity_type.shape entity_batch.add(4, gl.GL_QUADS, None, ('v2f', (x - R, y - R, x + R, y - R, x + R, y + R, x - R, y + R)), ('c4f', (1.0, 1.0, 0.0, 0.2) * 4)) # TODO wtf is GL_CURRENT_BIT gl.glPushMatrix() self.transform() self.grid_batch.draw() entity_batch.draw() gl.glPopMatrix()
def draw_objects(self): '''called in the middle of ondraw after the buffer has been cleared''' self.create_objects() glPushMatrix() glTranslatef(0, 0, -self.dist) glMultMatrixd(build_rotmatrix( self.basequat)) # Rotate according to trackball glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.2, 0.2, 0.2, 1)) glTranslatef(-self.build_dimensions[3] - self.platform.width / 2, -self.build_dimensions[4] - self.platform.depth / 2, 0) # Move origin to bottom left of platform # Draw platform glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glDisable(GL_LIGHTING) self.platform.draw() glEnable(GL_LIGHTING) # Draw mouse glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) inter = self.mouse_to_plane(self.mousepos[0], self.mousepos[1], plane_normal=(0, 0, 1), plane_offset=0, local_transform=False) if inter is not None: glPushMatrix() glTranslatef(inter[0], inter[1], inter[2]) glBegin(GL_TRIANGLES) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(1, 0, 0, 1)) glNormal3f(0, 0, 1) glVertex3f(2, 2, 0) glVertex3f(-2, 2, 0) glVertex3f(-2, -2, 0) glVertex3f(2, -2, 0) glVertex3f(2, 2, 0) glVertex3f(-2, -2, 0) glEnd() glPopMatrix() # Draw objects glDisable(GL_CULL_FACE) glPushMatrix() glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0.3, 0.7, 0.5, 1)) for i in self.parent.models: model = self.parent.models[i] glPushMatrix() glTranslatef(*(model.offsets)) glRotatef(model.rot, 0.0, 0.0, 1.0) glTranslatef(*(model.centeroffset)) glScalef(*model.scale) model.batch.draw() glPopMatrix() glPopMatrix() glEnable(GL_CULL_FACE) # Draw cutting plane if self.parent.cutting: # FIXME: make this a proper Actor axis = self.parent.cutting_axis fixed_dist = self.parent.cutting_dist dist, plane_width, plane_height = self.get_cutting_plane( axis, fixed_dist) if dist is not None: glPushMatrix() if axis == "x": glRotatef(90, 0, 1, 0) glRotatef(90, 0, 0, 1) glTranslatef(0, 0, dist) elif axis == "y": glRotatef(90, 1, 0, 0) glTranslatef(0, 0, -dist) elif axis == "z": glTranslatef(0, 0, dist) glDisable(GL_CULL_FACE) glBegin(GL_TRIANGLES) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0, 0.9, 0.15, 0.3)) glNormal3f(0, 0, self.parent.cutting_direction) glVertex3f(plane_width, plane_height, 0) glVertex3f(0, plane_height, 0) glVertex3f(0, 0, 0) glVertex3f(plane_width, 0, 0) glVertex3f(plane_width, plane_height, 0) glVertex3f(0, 0, 0) glEnd() glEnable(GL_CULL_FACE) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glEnable(GL_LINE_SMOOTH) orig_linewidth = (GLfloat)() glGetFloatv(GL_LINE_WIDTH, orig_linewidth) glLineWidth(4.0) glBegin(GL_LINE_LOOP) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, vec(0, 0.8, 0.15, 1)) glVertex3f(0, 0, 0) glVertex3f(0, plane_height, 0) glVertex3f(plane_width, plane_height, 0) glVertex3f(plane_width, 0, 0) glEnd() glLineWidth(orig_linewidth) glDisable(GL_LINE_SMOOTH) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glPopMatrix() glPopMatrix()
def unset_state(self): gl.glPopMatrix() SceneViewer._gl_unset_background() self._unset_view()
def unset_state(self): if self.texture: gl.glDisable(self.texture.target) gl.glPopMatrix()
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 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)) # 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.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 # 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.glColor4ub(255, 255, 255, 255) gl.glPushMatrix() self.transform() self.img.blit(0, 0) gl.glPopMatrix()
def mult_rot_matrix(self, rot): pgl.glPushMatrix() pgl.glLoadMatrixf(rot) pgl.glMultMatrixf(self._rot) self._rot = get_model_matrix() pgl.glPopMatrix()
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 draw(self, win=None): """ Draw the current frame to a particular visual.Window (or to the default win for this object if not specified). The current position in the movie will be determined automatically. This method should be called on every frame that the movie is meant to appear""" if self.status == NOT_STARTED or (self.status == FINISHED and self.loop): self.play() elif self.status == FINISHED and not self.loop: return if win is None: win = self.win self._selectWindow(win) self._updateFrameTexture( ) #will check if it's needed yet in the function #make sure that textures are on and GL_TEXTURE0 is active GL.glActiveTexture(GL.GL_TEXTURE0) GL.glEnable(GL.GL_TEXTURE_2D) GL.glColor4f(1, 1, 1, self.opacity) # sets opacity (1,1,1 = RGB placeholder) GL.glPushMatrix() self.win.setScale('pix') #move to centre of stimulus and rotate vertsPix = self.verticesPix array = (GL.GLfloat * 32)( 1, 1, #texture coords vertsPix[0, 0], vertsPix[0, 1], 0., #vertex 0, 1, vertsPix[1, 0], vertsPix[1, 1], 0., 0, 0, vertsPix[2, 0], vertsPix[2, 1], 0., 1, 0, vertsPix[3, 0], vertsPix[3, 1], 0., ) GL.glPushAttrib(GL.GL_ENABLE_BIT) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID) GL.glPushClientAttrib(GL.GL_CLIENT_VERTEX_ARRAY_BIT) #2D texture array, 3D vertex array GL.glInterleavedArrays(GL.GL_T2F_V3F, 0, array) GL.glDrawArrays(GL.GL_QUADS, 0, 4) GL.glPopClientAttrib() GL.glPopAttrib() GL.glPopMatrix() #unbind the textures GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glDisable(GL.GL_TEXTURE_2D) #implicitly disables 1D
if self.vitesse.norm != 0: vec_prim = Primitive2DGL.create_vector( self.vitesse.norm * 10, get_color_scale(self.vitesse.norm / settings.maxBallAcceleration)) for p in self.primitives + vec_prim: gl.glColor3f(*p.color) gl.glBegin(p.primtype) for vert in p.verts: gl.glVertex2f(*vert) gl.glEnd() except Exception, e: time.sleep(0.0001) print(e, traceback.print_exc()) finally: gl.glPopMatrix() class Primitive2DGL(object): @staticmethod def create_circle(radius, color=None, prct=1., angle=0.): if not color: color = [1, 1, 1] steps = int(10 * radius * math.pi * prct) s = math.sin(2 * math.pi / steps) c = math.cos(2 * math.pi / steps) dx, dy = math.cos(angle) * radius, math.sin(angle) * radius res = [(0., 0.)] for i in range(steps): res.append((dx, dy)) dx, dy = (dx * c - dy * s), (dy * c + dx * s)
def disable(self): glPopMatrix()
def batch_draw(csl): glPushMatrix() glLoadIdentity() vertices = [] for cs in csl: ax, ay = cs.abs_coords() if cs.ft_anim: qs = cs.question_scale bs = cs.back_scale aa = cs.ftanim_alpha ca = cs.ftanim_cardalpha if cs.gray: c = (.66, .66, .66, ca) else: c = (1., 1., 1., ca) vertices += cs.img.get_t2c4n3v3_vertices(c, ax, ay) n, s = cs.number, cs.suit if n: vertices += game_res.cardnum[s % 2 * 13 + n - 1].get_t2c4n3v3_vertices( c, ax + 5, ay + 105) if s: vertices += game_res.suit[s - 1].get_t2c4n3v3_vertices( c, ax + 6, ay + 94) c = (1, 1, 1, aa) if qs: vertices += game_res.card_question.get_t2c4n3v3_vertices( c, ax + (1 - qs) * 45, ay, 0, qs * 91) if bs: vertices += game_res.card_hidden.get_t2c4n3v3_vertices( c, ax + (1 - bs) * 45, ay, 0, bs * 91) else: a = cs.alpha if cs.gray: c = (.66, .66, .66, a) else: c = (1., 1., 1., a) vertices += cs.img.get_t2c4n3v3_vertices(c, ax, ay) resides_in = cs.card.resides_in if resides_in and resides_in.type == 'showncards': vertices += game_res.card_showncardtag.get_t2c4n3v3_vertices( c, ax, ay) n, s = cs.number, cs.suit if n: vertices += game_res.cardnum[s % 2 * 13 + n - 1].get_t2c4n3v3_vertices( c, ax + 5, ay + 105) if s: vertices += game_res.suit[s - 1].get_t2c4n3v3_vertices( c, ax + 6, ay + 94) vertices += game_res.card_shinesoft.get_t2c4n3v3_vertices( (1., 1., 1., cs.shine_alpha), ax - 6, ay - 6) if vertices: n = len(vertices) buf = (GLfloat * n)() buf[:] = vertices glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glInterleavedArrays(GL_T2F_C4F_N3F_V3F, 0, buf) with get_atlas('card').texture: glDrawArrays(GL_QUADS, 0, n / 12) glPopClientAttrib() glPopMatrix()
def euler_rotate(self, angle, x, y, z): pgl.glPushMatrix() pgl.glLoadMatrixf(self._rot) pgl.glRotatef(angle, x, y, z) self._rot = get_model_matrix() pgl.glPopMatrix()
def init_rot_matrix(self): pgl.glPushMatrix() pgl.glLoadIdentity() self._rot = get_model_matrix() pgl.glPopMatrix()
def draw(self, camera): gl.glPushMatrix() gl.glTranslatef(self.pos.x, self.pos.y, self.dz) self.node.draw(camera) gl.glPopMatrix()
def draw(self): self.plot._render_lock.acquire() self.camera.apply_transformation() calc_verts_pos, calc_verts_len = 0, 0 calc_cverts_pos, calc_cverts_len = 0, 0 should_update_caption = (clock() - self.last_caption_update > self.caption_update_interval) if len(self.plot._functions.values()) == 0: self.drawing_first_object = True try: dict.iteritems except AttributeError: # Python 3 iterfunctions = iter(self.plot._functions.values()) else: # Python 2 iterfunctions = self.plot._functions.itervalues() for r in iterfunctions: if self.drawing_first_object: self.camera.set_rot_preset(r.default_rot_preset) self.drawing_first_object = False pgl.glPushMatrix() r._draw() pgl.glPopMatrix() # might as well do this while we are # iterating and have the lock rather # than locking and iterating twice # per frame: if should_update_caption: try: if r.calculating_verts: calc_verts_pos += r.calculating_verts_pos calc_verts_len += r.calculating_verts_len if r.calculating_cverts: calc_cverts_pos += r.calculating_cverts_pos calc_cverts_len += r.calculating_cverts_len except ValueError: pass for r in self.plot._pobjects: pgl.glPushMatrix() r._draw() pgl.glPopMatrix() if should_update_caption: self.update_caption(calc_verts_pos, calc_verts_len, calc_cverts_pos, calc_cverts_len) self.last_caption_update = clock() if self.plot._screenshot: self.plot._screenshot._execute_saving() self.plot._render_lock.release()
def draw(self): gl.glPushMatrix() self.transform() self.title_label.draw() gl.glPopMatrix()
def draw(self, win=None): """Draw the current frame to a particular visual.Window (or to the default win for this object if not specified). The current position in the movie will be determined automatically. This method should be called on every frame that the movie is meant to appear. Parameters ---------- win : :class:`~psychopy.visual.Window` or None Window the video is being drawn to. If `None`, the window specified by property `win` will be used. Default is `None`. """ if (self.status == NOT_STARTED or (self.status == FINISHED and self.loop)): self.play() elif self.status == FINISHED and not self.loop: return if win is None: win = self.win self._selectWindow(win) self._updateFrameTexture() # will check if it's needed # scale the drawing frame and get to centre of field GL.glPushMatrix() # push before drawing, pop after # push the data for client attributes GL.glPushClientAttrib(GL.GL_CLIENT_ALL_ATTRIB_BITS) self.win.setScale('pix') # move to centre of stimulus and rotate vertsPix = self.verticesPix # bind textures GL.glActiveTexture(GL.GL_TEXTURE1) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glEnable(GL.GL_TEXTURE_2D) GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID) GL.glEnable(GL.GL_TEXTURE_2D) # sets opacity (1,1,1 = RGB placeholder) GL.glColor4f(1, 1, 1, self.opacity) array = (GL.GLfloat * 32)( 1, 1, # texture coords vertsPix[0, 0], vertsPix[0, 1], 0., # vertex 0, 1, vertsPix[1, 0], vertsPix[1, 1], 0., 0, 0, vertsPix[2, 0], vertsPix[2, 1], 0., 1, 0, vertsPix[3, 0], vertsPix[3, 1], 0., ) # 2D texture array, 3D vertex array GL.glInterleavedArrays(GL.GL_T2F_V3F, 0, array) GL.glDrawArrays(GL.GL_QUADS, 0, 4) GL.glPopClientAttrib() GL.glPopMatrix() # unbind the textures GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glEnable(GL.GL_TEXTURE_2D) # implicitly disables 1D
def draw(self): mid_x, mid_y = self.get_center() glLineWidth(2) if self.displayType == ANALOG_CLOCK: radius = min(self.width, self.height) / 2.0 - 10 radius_end = radius - 10 glPushMatrix() glTranslatef(mid_x, mid_y, 0) if self.clockLabels is not None or self.drawLines: for i in xrange(0, 12): glPushMatrix() angle = get_mark_angle(i + 1) x_value = math.cos(angle) y_value = math.sin(angle) if self.drawLines: glBegin(GL_LINES) glColor3ub(*self.color) glVertex2f(x_value * radius_end, y_value * radius_end) glVertex2f(x_value * (radius - 20), y_value * (radius - 20)) glEnd() if self.clockLabels is not None: x = x_value * radius y = y_value * radius glTranslatef(x, y, 0) self.clockLabels[-i].draw() glPopMatrix() # second pointer second, minute, hour = self.get_time() if self.displaySeconds: display_pointer(get_second_minute_angle(second), self.secondsColor, radius_end) if self.displayHours: display_pointer(get_hour_angle(hour + minute / 60.0), self.hoursColor, radius_end / 1.5) if self.displayMinutes: display_pointer( get_second_minute_angle(minute + second / 60.0), self.minutesColor, radius_end) glPopMatrix() if self.border is not None: glPushMatrix() glTranslatef(self.x + 20, self.y - 20, 0.0) self.border.draw(GL_LINE_LOOP) glPopMatrix() elif self.displayType in (DIGITAL_CLOCK, CALENDAR): text = self.get_text() if text != self.text: self.label.text = text self.text = text glPushMatrix() glTranslatef(self.x, self.y, 0) self.label.draw() if self.displayType == DIGITAL_CLOCK and self.drawBorder: glBegin(GL_LINE_LOOP) glColor3ub(*self.color) glVertex2f(0, 0) glVertex2f(self.width, 0) glVertex2f(self.width, -self.height) glVertex2f(0, -self.height) glEnd() glPopMatrix()
def draw(self, camera): gl.glPushMatrix() gl.glTranslatef(0, 6 * math.sin(5 * self.scenegraph.t), 0) super(FloatyImage, self).draw(camera) gl.glPopMatrix()
def pushed_matrix(): gl.glPushMatrix() try: yield finally: gl.glPopMatrix()
def render(self): if not self.visible: return if self.phase > self.deactivatephase or self.phase < self.activatephase: return gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) if self.deadly: gl.glPushMatrix() for i in range(0, 2): randnum = (math.sin(self.angle / 4) + (random.random() / 10)) / 17 gl.glTranslatef(self.x + self.w / 2, self.y + self.h / 2, 0.0) gl.glScalef(.7 - randnum, .7 - randnum, .7) gl.glRotatef(self.angle, 0.0, 0.0, 1.0) gl.glTranslatef(-(self.x + self.w / 2), -(self.y + self.h / 2), 0.0) gl.glBegin(gl.GL_QUADS) c = random.random() / 4.0 gl.glColor4f(c, 0.0, 0.0, 1.0 - random.random() / 5) gl.glVertex2f(self.x - self.xmod, self.y) gl.glVertex2f(self.x + self.w + self.xmod, self.y) gl.glVertex2f(self.x + self.w + self.xmod, self.y + self.h) gl.glVertex2f(self.x - self.xmod, self.y + self.h) gl.glEnd() gl.glPopMatrix() gl.glPushMatrix() gl.glTranslatef(self.x + self.w / 2, self.y + self.h / 2, 0.0) randnum = (math.sin(self.angle / 4) + (random.random() / 10)) / 17 gl.glScalef(1.0 - randnum, 1.0 - randnum, 1.0) gl.glRotatef(self.angle, 0.0, 1.0, 1.0) gl.glTranslatef(-(self.x + self.w / 2), -(self.y + self.h / 2), 0.0) if self.artifact and self.placed: gl.glBegin(gl.GL_QUADS) for i in range(0, 3): c = random.random() / 4.0 color = (.7 - c, .7 - c, .7 - c, random.random()) h = random.randint(1, 40) w = random.randint(1, 10) gl.glColor4f(*color) gl.glVertex2f(self.x + w / 2 + self.w / 4, self.y + 28) gl.glVertex2f(self.x + self.w / 2 + self.w / 4 - w / 2, self.y + 28) gl.glVertex2f(self.x + self.w / 2 + self.w / 4 - w / 2, self.y + self.h + h + 64 + 28 + self.ymod) gl.glVertex2f(self.x + w / 2 + self.w / 4, self.y + self.h + h + 64 + 28 + self.ymod) gl.glEnd() if self.blockable and self.static and not self.deadly: gl.glBegin(gl.GL_QUADS) else: gl.glBegin(gl.GL_LINE_LOOP) if self.artifact or self.pedestal or self.deadly or self.player: v = 0 for vert in self.vertices: v += 1 c = math.fabs(math.sin(self.life + v)) if self.deadly: gl.glColor4f(c, 0.0, 0.0, 1.0 - random.random() / 5) elif self.player: gl.glColor4f(.35, .35, 1.0 - c / 1.5, 1.0 - random.random() / 5) else: gl.glColor4f(c, c, c, 1.0 - random.random() / 5) if self.player: gl.glVertex2f(self.x + vert[0], self.y + vert[1]) else: gl.glVertex2f(vert[0], vert[1]) else: gl.glColor4f(*self.color) gl.glVertex2f(self.x - self.xmod, self.y) gl.glVertex2f(self.x + self.w + self.xmod, self.y) gl.glVertex2f(self.x + self.w + self.xmod, self.y + self.h) gl.glVertex2f(self.x - self.xmod, self.y + self.h) gl.glEnd() if self.deadly: gl.glPopMatrix() gl.glDisable(gl.GL_BLEND)
def hide(self): if not self.drawable: raise Exception('Trying to draw non-drawable shape') glPushMatrix() self.vlist = pyglet.graphics.vertex_list(0, ('v2f', [])) glPopMatrix()
def unset_state(self): gl.glPopMatrix() gl.glMatrixMode(gl.GL_PROJECTION) gl.glPopMatrix() gl.glMatrixMode(gl.GL_MODELVIEW)
def draw(self): """Draw the particles system""" gl.glPushMatrix() self.transform() # color preserve - at least nvidia 6150SE needs that gl.glPushAttrib(gl.GL_CURRENT_BIT) # glPointSize(self.get_scaled_particle_size()) gl.glEnable(gl.GL_TEXTURE_2D) gl.glEnable(gl.GL_PROGRAM_POINT_SIZE) # glBindTexture(GL_TEXTURE_2D, self.texture.id) gl.glEnable(gl.GL_POINT_SPRITE) gl.glTexEnvi(gl.GL_POINT_SPRITE, gl.GL_COORD_REPLACE, gl.GL_TRUE) gl.glEnableClientState(gl.GL_VERTEX_ARRAY) vertex_ptr = PointerToNumpy(self.particle_pos) gl.glVertexPointer(2, gl.GL_FLOAT, 0, vertex_ptr) gl.glEnableClientState(gl.GL_COLOR_ARRAY) color_ptr = PointerToNumpy(self.particle_color) gl.glColorPointer(4, gl.GL_FLOAT, 0, color_ptr) gl.glEnableVertexAttribArray(self.particle_size_idx) size_ptr = PointerToNumpy(self.particle_size_scaled) gl.glVertexAttribPointer(self.particle_size_idx, 1, gl.GL_FLOAT, False, 0, size_ptr) gl.glPushAttrib(gl.GL_COLOR_BUFFER_BIT) gl.glEnable(gl.GL_BLEND) if self.blend_additive: gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE) else: gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) # mode = GLint() # glTexEnviv( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, mode ) # # if self.color_modulate: # glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) # else: # glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE ) self.sprite_shader.install() self.sprite_shader.usetTex('sprite_texture', 0, gl.GL_TEXTURE_2D, self.texture.id) gl.glDrawArrays(gl.GL_POINTS, 0, self.total_particles) self.sprite_shader.uninstall() # un -blend gl.glPopAttrib() # color restore gl.glPopAttrib() # restore env mode # glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, mode) # disable states gl.glDisableVertexAttribArray(self.particle_size_idx) gl.glDisableClientState(gl.GL_COLOR_ARRAY) gl.glDisableClientState(gl.GL_VERTEX_ARRAY) gl.glDisable(gl.GL_POINT_SPRITE) gl.glDisable(gl.GL_PROGRAM_POINT_SIZE) gl.glDisable(gl.GL_TEXTURE_2D) gl.glPopMatrix()
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 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 _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 draw(self): gl.glPushMatrix() self.transform() self.batch.draw() gl.glPopMatrix()
def blit_to_texture(self, target, level, x, y, z, internalformat=None): '''Draw this image to to the currently bound texture at `target`. If `internalformat` is specified, glTexImage is used to initialise the texture; otherwise, glTexSubImage is used to update a region. ''' data_format = self.format data_pitch = abs(self._current_pitch) # Determine pixel format from format string matrix = None format, type = self._get_gl_format_and_type(data_format) if format is None: if (len(data_format) in (3, 4) and gl.gl_info.have_extension('GL_ARB_imaging')): # Construct a color matrix to convert to GL_RGBA def component_column(component): try: pos = 'RGBA'.index(component) return [0] * pos + [1] + [0] * (3 - pos) except ValueError: return [0, 0, 0, 0] # pad to avoid index exceptions lookup_format = data_format + 'XXX' matrix = (component_column(lookup_format[0]) + component_column(lookup_format[1]) + component_column(lookup_format[2]) + component_column(lookup_format[3])) format = {3: gl.GL_RGB, 4: gl.GL_RGBA}.get(len(data_format)) type = gl.GL_UNSIGNED_BYTE gl.glMatrixMode(gl.GL_COLOR) gl.glPushMatrix() gl.glLoadMatrixf((gl.GLfloat * 16)(*matrix)) else: # Need to convert data to a standard form data_format = { 1: 'L', 2: 'LA', 3: 'RGB', 4: 'RGBA' }.get(len(data_format)) format, type = self._get_gl_format_and_type(data_format) # Workaround: don't use GL_UNPACK_ROW_LENGTH if gl.current_context._workaround_unpack_row_length: data_pitch = self.width * len(data_format) # Get data in required format (hopefully will be the same format it's # already in, unless that's an obscure format, upside-down or the # driver is old). data = self._convert(data_format, data_pitch) if data_pitch & 0x1: alignment = 1 elif data_pitch & 0x2: alignment = 2 else: alignment = 4 row_length = data_pitch / len(data_format) gl.glPushClientAttrib(gl.GL_CLIENT_PIXEL_STORE_BIT) gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, alignment) gl.glPixelStorei(gl.GL_UNPACK_ROW_LENGTH, row_length) self._apply_region_unpack() gl.glTexParameteri(target, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(target, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(target, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) if target == gl.GL_TEXTURE_3D: assert not internalformat gl.glTexSubImage3D(target, level, x, y, z, self.width, self.height, 1, format, type, data) elif internalformat: gl.glTexImage2D(target, level, internalformat, self.width, self.height, 0, format, type, data) else: gl.glTexSubImage2D(target, level, x, y, self.width, self.height, format, type, data) gl.glPopClientAttrib() if matrix: gl.glPopMatrix() gl.glMatrixMode(gl.GL_MODELVIEW)