Exemple #1
0
 def draw(self):
     """ Render the point """
     # [1]. If OGL transforms enabled , Translate and rotate the OGL state machine to desired rendering frame
     if self.trnsByOGL:
         glTranslated(
             *self.pos3D
         )  # This moves the origin of drawing , so that we can use the above coordinates at each draw location
     # ( Rotation is not applicable to points )
     # [2]. Set color & size
     glColor3ub(*self.colors[0])
     glPointSize(self.size)
     # [3]. Render!
     # print "DEBUG ," , "self.vertX:  " , self.vertX
     # print "DEBUG ," , "self.indices:" , self.indices
     pyglet.graphics.draw_indexed(
         1,  # --------------------- Number of seqential triplet in vertex list
         GL_POINTS,  # ------------- Draw quadrilaterals
         self.
         indices,  # ----------------- Indices where the coordinates are stored
         (
             'v3f', self.vertX
         )  # -- vertex list , OpenGL offers an optimized vertex list object , but this is not it
     )
     # [4]. If OGL transforms enabled , Translate and rotate the OGL state machine to desired rendering frame
     # ( Rotation is not applicable to points )
     if self.trnsByOGL:
         glTranslated(*np.multiply(self.pos3D,
                                   -1))  # Reset the transform coordinates
Exemple #2
0
 def state_untransform(self):
     """ Unset the transformation matrix in the OGL state machine for this object , so that other shapes can set it for themselves """
     # If OGL transforms enabled , Return the OGL state machine to previous rendering frame
     if self.rotnByOGL:  # Unrotate first
         glRotated(-self.thetaDeg, *self.rotAxis)
     if self.trnsByOGL:  # Untranslate last
         glTranslated(*np.multiply(self.pos3D,
                                   -1))  # Reset the transform coordinates
Exemple #3
0
 def state_transform(self):
     """ Set the transformation matrix in the OGL state machine for this object """
     # If OGL transforms enabled , Translate and rotate the OGL state machine to desired rendering frame
     if self.trnsByOGL:  # Translate first
         glTranslated(
             *self.pos3D
         )  # This moves the origin of drawing , so that we can use the above coordinates at each draw location
     if self.rotnByOGL:  # Rotate last
         glRotated(self.thetaDeg, *self.rotAxis)
Exemple #4
0
 def move(self, dx, dy):
     self.x += dx
     self.y += dy
     dxi, dyi = int(dx), int(dy)
     translation_acc_x_i = int(self._translation_acc_x)
     translation_acc_y_i = int(self._translation_acc_y)
     self._translation_acc_x -= translation_acc_x_i
     self._translation_acc_y -= translation_acc_y_i
     gl.glTranslated(-(dxi+translation_acc_x_i), -(dyi+translation_acc_y_i), 0)
     self._translation_acc_x += dx - dxi
     self._translation_acc_y += dy - dyi
Exemple #5
0
    def apply_transformation(self):
        self.rect.set_viewport()

        # Translation
        gl.glTranslated(self.x, self.y, 0)

        # Scale
        gl.glScaled(self.zoom_level, self.zoom_level, 1)

        # Rotation
        gl.glRotatef(self.rotation_x, 1.0, 0.0, 0.0)
        gl.glRotatef(self.rotation_y, 0.0, 1.0, 0.0)
        return None
Exemple #6
0
    def draw(self):
        """ Draws all of the tiles and tray """
        gl.glPushMatrix()
        gl.glTranslated(self.rect.x, self.rect.y, 0)
        for y in range(self.height):
            for x in range(self.width):
                gl.glBegin(gl.GL_QUADS)
                gl.glColor3ub(*[30 + ((x + y) % 2) * 50] * 3)
                gl.glVertex2f(x * TILE_SIZE * self.scale,
                              y * TILE_SIZE * self.scale)
                gl.glVertex2f((x + 1) * TILE_SIZE * self.scale,
                              y * TILE_SIZE * self.scale)
                gl.glVertex2f((x + 1) * TILE_SIZE * self.scale,
                              (y + 1) * TILE_SIZE * self.scale)
                gl.glVertex2f(x * TILE_SIZE * self.scale,
                              (y + 1) * TILE_SIZE * self.scale)
                gl.glEnd()

        for y in range(self.height):
            for x in range(self.width):
                if self(x, y):
                    self(x, y).draw((x + 0.5) * TILE_SIZE * self.scale,
                                    (y + 0.5) * TILE_SIZE * self.scale,
                                    self.scale)
                    if self(x, y).highlighted:
                        gl.glBegin(gl.GL_QUADS)
                        gl.glColor4ub(*[255, 0, 0, 180])
                        gl.glVertex2f(x * TILE_SIZE * self.scale,
                                      y * TILE_SIZE * self.scale)
                        gl.glVertex2f((x + 1) * TILE_SIZE * self.scale,
                                      y * TILE_SIZE * self.scale)
                        gl.glVertex2f((x + 1) * TILE_SIZE * self.scale,
                                      (y + 1) * TILE_SIZE * self.scale)
                        gl.glVertex2f(x * TILE_SIZE * self.scale,
                                      (y + 1) * TILE_SIZE * self.scale)
                        gl.glEnd()

        row = 0
        col = 0
        for tile in self.tray:
            if col == self.tray_cols:
                col = 0
                row += 1
            x = self.tray_start_x + ((col + 0.5) * self.tray_cols_width)
            y = self.rect.height - ((row + 0.5) * self.tray_cols_width)
            tile.draw(x, y, TRAY_SCALE * self.scale * 9 / 10)
            col += 1
        gl.glPopMatrix()
        if self.dragging:
            self.dragging.draw(self.dragging.x, self.dragging.y,
                               self.scale * DRAG_SCALE)
Exemple #7
0
    def draw_ground_plane (self):

        znear = self.camera_z - self.camera_near
        zfar = self.camera_z - self.camera_far
        wnear = self.camera_near * math.tan(self.fov_x/2.0)
        wfar = self.camera_far * math.tan(self.fov_x/2.0)
        x = self.camera_x

        coords = (x-wnear, znear, x+wnear, znear, x+wfar, zfar, x-wfar, zfar)

        with push_matrix(gl.GL_TEXTURE):
            gl.glLoadIdentity()
            gl.glTranslated(0.5, 0.5, 0)
            gl.glScaled(1.0/(200*self.scaleFactor), 1.0/(200*self.scaleFactor), 0.0)
            with bound_texture(self.ground_tex.target, self.ground_tex.id):
                pyglet.graphics.draw (4, gl.GL_QUADS, ('v2f', coords), ('t2f', coords))
Exemple #8
0
        def lookAt(self,ex,ey,ez,cx,cy,cz,ux,uy,uz):
                _import_gl()
                F = [cx-ex, cy-ey, cz-ez]
                Fmag = math.sqrt(sum([a*a for a in F]))
                fnorm = [a/Fmag for a in F]

                Up = [ux,uy,uz]
                Upmag = math.sqrt(sum([a*a for a in Up]))
                upnorm = [a/Upmag for a in Up]

                def cross(v1,v2):
                        return [v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]]

                s = cross( fnorm, upnorm )
                u = cross( s, fnorm )

                glmult([ s[0], s[1], s[2], 0, u[0], u[1], u[2], 0, - fnorm[0], -fnorm[1], -fnorm[2], 0, 0, 0, 0, 1 ])
                glTranslated(-ex, -ey, -ez)
Exemple #9
0
    def draw_ground_plane(self):

        znear = self.camera_z - self.camera_near
        zfar = self.camera_z - self.camera_far
        wnear = self.camera_near * math.tan(self.fov_x / 2.0)
        wfar = self.camera_far * math.tan(self.fov_x / 2.0)
        x = self.camera_x

        coords = (x - wnear, znear, x + wnear, znear, x + wfar, zfar, x - wfar,
                  zfar)

        with push_matrix(gl.GL_TEXTURE):
            gl.glLoadIdentity()
            gl.glTranslated(0.5, 0.5, 0)
            gl.glScaled(1.0 / (200 * self.scaleFactor),
                        1.0 / (200 * self.scaleFactor), 0.0)
            with bound_texture(self.ground_tex.target, self.ground_tex.id):
                pyglet.graphics.draw(4, gl.GL_QUADS, ('v2f', coords),
                                     ('t2f', coords))
Exemple #10
0
 def draw(self):
     """ Draws all of the tiles and tray """
     gl.glPushMatrix()
     gl.glTranslated(self.rect.x,self.rect.y,0)
     for y in range(self.height):
         for x in range(self.width):
             gl.glBegin(gl.GL_QUADS)
             gl.glColor3ub(*[30+((x+y)%2)*50]*3)
             gl.glVertex2f(x*TILE_SIZE*self.scale,y*TILE_SIZE*self.scale)
             gl.glVertex2f((x+1)*TILE_SIZE*self.scale,y*TILE_SIZE*self.scale)
             gl.glVertex2f((x+1)*TILE_SIZE*self.scale,(y+1)*TILE_SIZE*self.scale)
             gl.glVertex2f(x*TILE_SIZE*self.scale,(y+1)*TILE_SIZE*self.scale)
             gl.glEnd()
             
     
     for y in range(self.height):
         for x in range(self.width):
             if self(x,y):
                 self(x,y).draw((x+0.5)*TILE_SIZE*self.scale,(y+0.5)*TILE_SIZE*self.scale,self.scale) 
                 if self(x,y).highlighted:
                     gl.glBegin(gl.GL_QUADS)
                     gl.glColor4ub(*[255,0,0,180])
                     gl.glVertex2f(x*TILE_SIZE*self.scale,y*TILE_SIZE*self.scale)
                     gl.glVertex2f((x+1)*TILE_SIZE*self.scale,y*TILE_SIZE*self.scale)
                     gl.glVertex2f((x+1)*TILE_SIZE*self.scale,(y+1)*TILE_SIZE*self.scale)
                     gl.glVertex2f(x*TILE_SIZE*self.scale,(y+1)*TILE_SIZE*self.scale)
                     gl.glEnd()
     
     row = 0
     col = 0
     for tile in self.tray:
         if col == self.tray_cols:
             col = 0
             row += 1
         x = self.tray_start_x + ((col+0.5)*self.tray_cols_width)
         y = self.rect.height - ((row+0.5)*self.tray_cols_width)
         tile.draw(x,y,TRAY_SCALE*self.scale*9/10)
         col += 1
     gl.glPopMatrix()
     if self.dragging: self.dragging.draw(self.dragging.x,self.dragging.y,self.scale*DRAG_SCALE)
    def on_draw(self):
        self.clear()

        glLoadIdentity()

        glLightfv(GL_LIGHT0, GL_POSITION, self.lightfv(-1.0, 1.0, 1.0, 0.0))
        glEnable(GL_LIGHT0)

        self.trans[2] = -3  # center is z -3, dont move in z
        glTranslated(*self.trans)
        glRotatef(self.rots[0], 1.0, 0.0, 0.0)
        glRotatef(self.rots[1], 0.0, 1.0, 0.0)
        glRotatef(self.rots[2], 0.0, 0.0, 1.0)
        glRotatef(-25.0, 1.0, 0.0, 0.0)
        glRotatef(45.0, 0.0, 0.0, 1.0)

        glEnable(GL_LIGHTING)

        # cannot figure out how to make this always flat
        #self.bg.blit(0,0)
        visualization.draw(self.brain)

        print("draw @", self.trans, self.rots)
Exemple #12
0
 def center_camera(self):
     glRotatef(-self.pitch, 1, 0, 0)
     glRotatef(-self.yaw, 0, 1, 0)
     glRotatef(-self.roll, 0, 0, 1)
     x, y, z = self.position
     glTranslated(-x, -y - 23, -z)
def main(level_file):
    clock = events.dispatcher('Clock')
    keyboard = events.dispatcher('Keyboard')
    pygame.init()
    pygame.display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8)

    pygame.display.set_mode((1000, 600), pygame.OPENGL | pygame.DOUBLEBUF | pygame.RESIZABLE)
    handle_resize(1000, 600)
    screen_center = (500, 300)
    camera_offset = 230
    gl.glEnable(gl.GL_TEXTURE_2D)

    gl.glEnable(gl.GL_BLEND)
    gl.glBlendEquation(gl.GL_FUNC_ADD)
    gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
    gl.glClearColor(0, 0, 0, 1)

    tick_event = pygame.event.Event(constants.TICK)
    datadir = find_datadir()
    loader = pyglet.resource.Loader(datadir)

    player1 = viking(datadir, clock, keyboard,
                     pygame.K_a, pygame.K_d, pygame.K_w, pygame.K_j)
    player2 = viking(datadir, clock, keyboard,
                     pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_RETURN)
    player2.location[0] = 900

    entities = [player1, player2]
    scream = pygame.mixer.Sound(os.path.join(datadir, 'wilhelm.wav'))
    background = load_sprite(datadir, 'background')
    backgroundbuf = GLBuffer(4 * 4, numpy.float32, gl.GL_STATIC_DRAW)
    backgroundbuf[:] = background.xyuv
    if level_file is None:
        walls = [components.hitbox((-5, -5), (10, 610)),
                 components.hitbox((995, -5), (10, 610)),
                 components.hitbox((-5, 595), (1010, 5)), ]
    else:
        walls = level.load(level_file)
        for w in walls:
            numpy.round(w.point, out=w.point)
            numpy.round(w.size, out=w.size)
    walls_tlbr = numpy.empty((2, len(walls), 2))
    walls_tlbr[0] = [w.point for w in walls]
    walls_tlbr[1] = [w.point + w.size for w in walls]

    # vertex positions for walls
    quads = numpy.empty((len(walls), 4, 2), dtype=numpy.float32)
    quads[:, 0, :] = [w.point for w in walls]
    quads[:, 2, :] = [w.size for w in walls]
    quads[:, 2, :] += quads[:, 0, :]
    quads[:, 1, 0] = quads[:, 0, 0]
    quads[:, 1, 1] = quads[:, 2, 1]
    quads[:, 3, 0] = quads[:, 2, 0]
    quads[:, 3, 1] = quads[:, 0, 1]
    wallbuf = GLBuffer(quads.size, numpy.float32, gl.GL_STATIC_DRAW)
    wallbuf[:] = quads
    del quads

    # contains vertex and texture positions for sprites
    entitybuf = GLBuffer(dtype=numpy.float32)

    # walls program
    wallprog = shaders.wall()

    spriteprog = shaders.sprite()

    dragonprog = shaders.psycho()
    dragonpalette = load_texture(os.path.join(datadir, 'wallpalette.png'), dimensions=1)
    dragonsprite_scales = load_sprite(datadir, 'dragon_scales')
    dragonsprite_contours = load_sprite(datadir, 'dragon_contours')
    dragonbuf = GLBuffer(4 * 4, numpy.float32, gl.GL_STATIC_DRAW)
    dragonbuf[:] = dragonsprite_scales.xyuv + (-100, 145, 0, 0)
    contourbuf = GLBuffer(4 * 4, numpy.float32, gl.GL_STATIC_DRAW)
    contourbuf[:] = dragonsprite_contours.xyuv + (-100, 145, 0, 0)

    debug_draw = False
    pause = False
    do_frame = False
    ticks_done = 0
    while True:
        start = time.clock()

        key_events = []
        resize_event = None
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return 0
            elif event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                key_events.append(event)
            elif event.type == pygame.VIDEORESIZE:
                resize_event = event

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return 0
                if event.key == pygame.K_F2:
                    debug_draw = not debug_draw
                elif event.key == pygame.K_F3:
                    entities.append(sheep(datadir, clock))
                elif event.key == pygame.K_F4:
                    entities.append(drake(datadir, clock))
                elif event.key == pygame.K_F5:
                    entities.append(floaty_sheep(datadir, clock))
                elif event.key == pygame.K_p:
                    pause = not pause
                elif event.key == pygame.K_PERIOD and pause:
                    do_frame = True

        if resize_event:
            handle_resize(resize_event.w, resize_event.h)
            screen_center = (resize_event.w // 2, resize_event.h // 2)
            background.xyuv[:, :2] = [[0, 0], [0, resize_event.h],
                                      [resize_event.w, resize_event.h], [resize_event.w, 0]]
            backgroundbuf[:] = background.xyuv

        if (not pause) or do_frame:
            for event in key_events:
                keyboard.dispatch(event)

            location = components.entity.location
            delta = numpy.array(location)
            motion_a = components.entity.motion_a
            motion_v = components.entity.motion_v
            active_tl = components.entity.active_tl
            active_br = components.entity.active_br
            passive_tl = components.entity.passive_tl
            passive_br = components.entity.passive_br
            instances = components.entity._all[:components.entity._nentities]
            do_translate = components.entity.translate_all

            GROUNDED = intern('grounded')
            motion_a[:] = (0, constants.G)
            clock.dispatch(tick_event)
            for thing in entities:
                thing.tags.discard(GROUNDED)
            motion_v[:] += motion_a

            collisions.resolve_passive_active_collisions(instances, active_tl, active_br, passive_tl, passive_br)
            attempts = 0
            adjust_significant = True
            rppc = collisions.resolve_passive_passive_collisions
            rwc = collisions.resolve_wall_collisions
            grounded_mask = numpy.zeros((len(instances),), dtype=bool)
            stop = numpy.empty((len(instances),2), dtype=bool)
            adjust, sides = rwc(motion_v, passive_tl, passive_br, walls_tlbr[0], walls_tlbr[1])
            numpy.logical_or.reduce(sides.reshape(-1, 2, 2), out=stop, axis=2)
            motion_v[stop] = 0
            do_translate(motion_v[:])
            while attempts < 20 and adjust_significant:
                adjust, sides, done_impulse = rppc(motion_v, passive_tl, passive_br)
                grounded_mask |= sides[:,3]
                adjust *= 0.5
                do_translate(adjust)
                adjust_significant = not numpy.allclose(adjust, 0, atol=0.125)
                adjust_significant |= done_impulse > 0.125
                del adjust, sides
                adjust, sides = rwc(motion_v, passive_tl, passive_br, walls_tlbr[0], walls_tlbr[1])
                adjust_significant |= not numpy.allclose(adjust, 0, atol=0.5)
                do_translate(adjust)
                numpy.logical_or.reduce(sides.reshape(-1, 2, 2), out=stop, axis=2)
                motion_v[stop] = 0
                grounded_mask |= sides[:,3]

                attempts += 1

            for thing in numpy.compress(grounded_mask, instances):
                thing.tags.add(GROUNDED)

            do_frame = False
            ticks_done += 1

        dead = []

        gl.glLoadIdentity()
        gl.glEnableVertexAttribArray(0)
        gl.glUseProgram(spriteprog.id)
        gl.glBindTexture(gl.GL_TEXTURE_2D, background.texid)
        spriteprog['texture'] = 0

        with backgroundbuf.bound:
            gl.glVertexAttribPointer(0, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
            gl.glDrawArrays(gl.GL_TRIANGLE_FAN, 0, 4)

        # Now move camera
        camera_location = (screen_center - numpy.round(entities[0].location)) + (0, camera_offset)
        gl.glTranslated(camera_location[0], camera_location[1], 0.0)

        for thing in entities:
            if thing.hitpoints <= 0 or thing.location[1] > 10000:
                dead.append(thing)
                continue

        for thing in dead:
            scream.play()
            if thing.name == 'Player':
                thing.hitpoints = 100
                thing.location[:] = (500, -10)
                thing.motion_v[:] = 0
                if thing.physics is not None:
                    thing.physics.last_position[:] = thing.location
            else:
                entities.remove(thing)
                thing.dispose()

        xyuv = numpy.empty((4, 4), dtype=numpy.float32)
        texid = [0] * len(entities)
        with entitybuf.bound:
            for n, thing in enumerate(entities):
                xyuv[:] = thing.graphics.sprite.xyuv
                xy = xyuv[:, 0:2]
                xy[:] += thing.graphics.anchor
                xy[:] += thing.location
                numpy.round(xy, out=xy)
                offset = n * 16
                entitybuf[offset:] = xyuv
                texid[n] = thing.graphics.sprite.texid
                #print('Loaded data for entity', n, xyuv, 'texid', texid[n])

            gl.glVertexAttribPointer(0, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)

            for n, t in enumerate(texid):
                gl.glBindTexture(gl.GL_TEXTURE_2D, t)
                gl.glDrawArrays(gl.GL_TRIANGLE_FAN, n * 4, 4)

        # draw walls
        gl.glUseProgram(wallprog.id)
        wallprog['color'] = (162.0/255.0, 153.0/255.0, 118.0/255.0, 1.0)
        with wallbuf.bound:
            gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
            gl.glDrawArrays(gl.GL_QUADS, 0, len(walls) * 8)

        # draw some shaders
        gl.glUseProgram(dragonprog.id)
        gl.glBindTexture(gl.GL_TEXTURE_2D, dragonsprite_scales.texid)
        gl.glActiveTexture(gl.GL_TEXTURE0 + 1)
        gl.glBindTexture(gl.GL_TEXTURE_1D, dragonpalette)
        gl.glActiveTexture(gl.GL_TEXTURE0)
        dragonprog['texture'] = 0
        dragonprog['palette'] = 1
        dragonprog['perturb'] = (ticks_done % 1024) / 128
        dragonprog['shift'] = ticks_done / 600
        with dragonbuf.bound:
            gl.glVertexAttribPointer(0, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
            gl.glDrawArrays(gl.GL_TRIANGLE_FAN, 0, 4)

        # now draw the rest of the f****n' dragon
        gl.glUseProgram(spriteprog.id)
        gl.glBindTexture(gl.GL_TEXTURE_2D, dragonsprite_contours.texid)
        spriteprog['texture'] = 0
        with contourbuf.bound:
            gl.glVertexAttribPointer(0, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
            gl.glDrawArrays(gl.GL_TRIANGLE_FAN, 0, 4)

        if debug_draw:
            gl.glUseProgram(wallprog.id)
            wallprog['color'] = (0.89, 0.89, 0.89, 1.0)
            quads = numpy.zeros((len(entities), 4, 2), dtype=numpy.float32)
            quads[:, 0, :] = components.entity.passive_tl
            quads[:, 2, :] = components.entity.passive_br
            quads[:, 1, 0] = quads[:, 0, 0]
            quads[:, 1, 1] = quads[:, 2, 1]
            quads[:, 3, 0] = quads[:, 2, 0]
            quads[:, 3, 1] = quads[:, 0, 1]
            gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, quads.ctypes.data)
            gl.glDrawArrays(gl.GL_QUADS, 0, quads.size // 2)

        gl.glColor3f(1, 1, 1)
        gl.glEnable(gl.GL_TEXTURE_2D)

        #screen.fill((120, 50, 50), pygame.Rect(0, 10, player1.hitpoints * 2, 10))
        #screen.fill((120, 50, 50), pygame.Rect(1000 - player2.hitpoints * 2, 10, player2.hitpoints * 2, 10))

        pygame.display.flip()

        delta = time.clock() - start
        if delta < constants.FRAME:
            time.sleep(constants.FRAME - delta)
Exemple #14
0
 def transform(self):
     #glLoadIdentity()
     glRotated(-self.angle_x, 1, 0, 0)
     glRotated(-self.angle_y, 0, 1, 0)
     glTranslated(-self.x, -self.y, -self.z)