Exemplo n.º 1
0
class RenderWorld:
    '''This is the class that renders blocks (and the floor that they sit on). Camera angles are handled by another class'''
    WINDOW_WIDTH = 400
    WINDOW_HEIGHT = 400
    
    
    def __init__(self, file_name):
        '''Sets everything up: camera, modes, lighting, and the list of blocks'''
        self.camera = Camera()
        self.set_up_graphics()
        self.makeLights()
        self.objects = LoadWorld.load(file_name)
#        glMaterialfv(GL_FRONT, GL_SPECULAR, [1, 1, 1, 1])
#        glMaterialfv(GL_FRONT, GL_SHININESS, [50])

        glClearColor(.529,.8078,.980,0)

        glutDisplayFunc(self.display)
        glutKeyboardFunc(self.keyPressed)
        glutMainLoop()

    def set_up_graphics(self):
        '''Sets up the gl modes that are necessary'''
        glutInit()
        glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH)
        glutInitWindowSize(self.WINDOW_WIDTH, self.WINDOW_HEIGHT)
        glutCreateWindow('World!')
        
        glMatrixMode(GL_PROJECTION)
        gluPerspective(45,1,.15,100)
        glMatrixMode(GL_MODELVIEW)
        
        glEnable(GL_DEPTH_TEST)

    def makeLights(self):
        '''Sets up the light sources and their positions. We have an ambient light and two sets of specular/diffuse lights'''
        self.diffuse_pos1 = (50,5,0,1)
        glLightfv(GL_LIGHT0, GL_DIFFUSE, (.5, .5, .5, 1))
        glLightfv(GL_LIGHT0, GL_POSITION, self.diffuse_pos1)
        
        glLightfv(GL_LIGHT1, GL_AMBIENT, (.2, .2, .2, 1))
        glLightfv(GL_LIGHT1, GL_POSITION, (0, 0, 1, 0))
        
        glLightfv(GL_LIGHT2, GL_SPECULAR, (.8, .8, .8, 1))
        glLightfv(GL_LIGHT2, GL_POSITION, self.diffuse_pos1)

        self.diffuse_pos2 = (0,1,0,1)
        glLightfv(GL_LIGHT3, GL_DIFFUSE, (.5, .5, .5, 1))
        glLightfv(GL_LIGHT3, GL_POSITION, self.diffuse_pos2)
        glLightfv(GL_LIGHT4, GL_SPECULAR, (.8, .8, .8, 1))
        glLightfv(GL_LIGHT4, GL_POSITION, self.diffuse_pos2)

        glEnable(GL_LIGHTING)
        glEnable(GL_LIGHT0)
        glEnable(GL_LIGHT1)
        glEnable(GL_LIGHT2)

    def display(self, x=0, y=0):
        '''Called for every refresh; redraws the floor and blocks and based on the camera angle'''
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()
        
        self.camera.renderCamera()        
        self.renderLightSource()        
        self.makeFloor()
        #Transparent blocks!
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)



        for obj in self.objects:

            glPushMatrix()

            if obj.get_type() == "block":
                self.draw_block(obj)

            elif obj.get_type() == "key":
                self.draw_key(obj)

            glPopMatrix()
        glDisable(GL_BLEND)

        glFlush()


    def draw_block(self, obj):
                #Set the blocks shininess, ambient, diffuse, and specular reflections. The blocks are slightly transparent.
        color = obj.get_color()
        pos = obj.get_pos()
        #glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, 75)
        glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, [color[0], color[1], color[2], 1])
        glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, [.4, .4, .4, 1])
        #glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, [.9, .9, .9, .7])
        glTranslate(pos[0],pos[1],pos[2])
        glutSolidCube(2)

    def draw_key(self, obj):
        color = obj.get_color()
        pos = obj.get_pos()
        glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, [color[0], color[1], color[2], .7])
        glTranslate(pos[0],pos[1],pos[2])
                #glutSolidTorus(.05, .25, 3, 3)
        glutSolidCone(.1, 2.0, 30, 4)


    def keyPressed(self, key, x, y):
        '''Called when a key is pressed'''
        if key == 'a':
            self.camera.strafe(-.1)
        elif key == 'd':
            self.camera.strafe(.1)
        elif key == 'w':
            self.camera.walk(-.1)
        elif key == 's':
            self.camera.walk(.1)
        elif key == 'j':
            self.camera.rotate(0,3,0)
        elif key == 'l':
            self.camera.rotate(0,-3,0)
        elif key == 'i':
            self.camera.rotate(3,0,0)
        elif key == 'k':
            self.camera.rotate(-3,0,0)
        elif key == ' ':
            self.camera.height(.1)
        elif key == 'c':
            self.camera.height(-.1)
        self.display()

    def renderLightSource(self):
        '''Resets the light sources to the right position'''
        glLightfv(GL_LIGHT0, GL_POSITION, self.diffuse_pos1)
        glLightfv(GL_LIGHT2, GL_POSITION, self.diffuse_pos2)
        glLightfv(GL_LIGHT3, GL_POSITION, self.diffuse_pos2)
        glLightfv(GL_LIGHT4, GL_POSITION, self.diffuse_pos2)
        
    def makeFloor(self):
        '''Makes a floor of size size and places an image (texture) on it'''
        glEnable(GL_TEXTURE_2D)
        size = 50
        image = Image.open("OtherMods/checkerboard.bmp")
	
        ix = image.size[0]
        iy = image.size[1]
        image = image.tostring("raw", "RGBX", 0, -1)

        glPixelStorei(GL_UNPACK_ALIGNMENT,1)
        glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
        glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
        glBegin(GL_QUADS)
        glTexCoord2f(0.0, 0.0) ; glVertex(-size,-.5,-size)
        glTexCoord2f(1.0, 0.0) ; glVertex(size,-.5,-size)
        glTexCoord2f(1.0, 1.0) ; glVertex(size,-.5,size)
        glTexCoord2f(0.0, 1.0) ; glVertex(-size,-.5,size)
        glEnd()
        glDisable(GL_TEXTURE_2D)
Exemplo n.º 2
0
class RenderCube:
    '''This is the class that renders a rainbow cube
    Camera angles are handled by Camera.py.
    '''
    WINDOW_WIDTH = 700
    WINDOW_HEIGHT = 700
    MAP_SIZE =100

    def __init__(self):
        '''Sets up camera, modes, lighting, sounds, and objects.'''
        self.set_up_graphics()
        self.makeLights()
        self.camera = Camera(0,0,5)
        self.verts=self.GenArray()
        self.colors=self.GenArray('color')

        glClearColor(1,1,1,0)

        glutIdleFunc(self.display)
        glutDisplayFunc(self.display)

        glutIgnoreKeyRepeat(GLUT_KEY_REPEAT_OFF)
        glutKeyboardFunc(self.keyPressed)
        glutKeyboardUpFunc(self.keyUp)

        glutSetCursor(GLUT_CURSOR_NONE)
        glutPassiveMotionFunc(self.mouseMove)

        glutMainLoop()

    def set_up_graphics(self):
        '''Sets up OpenGL to provide double buffering, RGB coloring,
        depth testing, the correct window size, and a title.'''
        glutInit()
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
        glutInitWindowSize(self.WINDOW_WIDTH, self.WINDOW_HEIGHT)
        glutCreateWindow('RainbowCube!')

        glMatrixMode(GL_PROJECTION)
        gluPerspective(45,1,.15,100)
        glMatrixMode(GL_MODELVIEW)

        glEnable(GL_DEPTH_TEST)

    def makeLights(self):
        '''Sets up the light sources and their positions. We have an
        ambient light and two sets of specular/diffuse lights.'''
        self.diffuse_pos1 = (50,5,0,1)
        glLightfv(GL_LIGHT0, GL_DIFFUSE, (.5, .5, .5, 1))
        glLightfv(GL_LIGHT0, GL_POSITION, self.diffuse_pos1)

        glLightfv(GL_LIGHT1, GL_AMBIENT, (.2, .2, .2, 1))
        glLightfv(GL_LIGHT1, GL_POSITION, (0, 0, 1, 0))

        glLightfv(GL_LIGHT2, GL_SPECULAR, (.8, .8, .8, 1))
        glLightfv(GL_LIGHT2, GL_POSITION, self.diffuse_pos1)

        self.diffuse_pos2 = (0,1,0,1)
        glLightfv(GL_LIGHT3, GL_DIFFUSE, (.5, .5, .5, 1))
        glLightfv(GL_LIGHT3, GL_POSITION, self.diffuse_pos2)
        glLightfv(GL_LIGHT4, GL_SPECULAR, (.8, .8, .8, 1))
        glLightfv(GL_LIGHT4, GL_POSITION, self.diffuse_pos2)

        glEnable(GL_LIGHTING)
        glEnable(GL_LIGHT0)
        glEnable(GL_LIGHT1)
        glEnable(GL_LIGHT2)

    def display(self, x=0, y=0):
        '''Called for every refresh; redraws the cube at current position
        based on the camera angle.'''
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()

        self.camera.move()
        self.camera.renderCamera()
        self.renderLightSource()
        glPushMatrix()
        # Set the object shininess, ambient, diffuse, and
        # specular reflections.
        glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, 75)
        glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, [.4, .4, .4, 1])
        glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, [.9, .9, .9, .8])

        glTranslate(0,0,0)
        self.MakeCube()
        glPopMatrix()
        glutSwapBuffers()

    def mouseMove(self, x, y):
        '''Called when the mouse is moved.'''
        factor = 2
        
        tmp_x = (self.camera.mouse_x - x)/factor
        tmp_y = (self.camera.mouse_y - y)/factor
        if tmp_x > self.camera.ROTATE:
            tmp_x = self.camera.ROTATE
        self.camera.rotate(0, tmp_x, 0)
        x = self.WINDOW_WIDTH/2
        y = self.WINDOW_HEIGHT/2
        glutWarpPointer(x, y)
        self.camera.mouse_x = x
        self.camera.mouse_y = y
        
    def keyPressed(self, key, x, y):
        '''Called when a key is pressed.'''
        if key.lower() in self.camera.keys:
            self.camera.keys[key.lower()] = True
        if glutGetModifiers() == GLUT_ACTIVE_SHIFT:
            self.camera.keys["shift"] = True
        if key == 'j':
            self.camera.rotate(0,3,0)
        elif key == 'l':
            self.camera.rotate(0,-3,0)
        elif key == 'i':
            self.camera.rotate(3,0,0)
        elif key == 'k':
            self.camera.rotate(-3,0,0)
        elif key == ' ':
            self.camera.height(.1)
        elif key == 'c':
            self.camera.height(-.1)
        elif key == 'x':
            exit(0)

    def keyUp(self, key, x, y):
        '''Called when a key is released.'''
        self.camera.keys[key.lower()] = False
        if not glutGetModifiers() == GLUT_ACTIVE_SHIFT:
            self.camera.keys["shift"] = False

    def renderLightSource(self):
        '''Resets the light sources to the right position.'''
        glLightfv(GL_LIGHT0, GL_POSITION, self.diffuse_pos1)
        glLightfv(GL_LIGHT2, GL_POSITION, self.diffuse_pos2)
        glLightfv(GL_LIGHT3, GL_POSITION, self.diffuse_pos2)
        glLightfv(GL_LIGHT4, GL_POSITION, self.diffuse_pos2)
        
    def GenArray(self, mode='vert',pts=POINTS):
        vert_ls=[]
        if mode=='color':
            for m in range(pts):
                for n in range(pts):
                    for i in range(pts):
                        tmp_tup=(i*.1,n*.1,m*.1,1)
                        vert_ls.append(tmp_tup)
        elif mode=='vert':
            for m in range(pts):
                for n in range(pts):
                    for i in range(pts):
                        tmp_tup=(i*.1,n*.1,m*.1)
                        vert_ls.append(tmp_tup)
        return vert_ls

    def MakeCube(self):
        '''Makes the desired cube.'''
        #TODO: GET COLORS WORKING/ PAD PIXELS
        ind=[]
        for i in range(len(self.verts)):
            ind.append(i)
        glEnableClientState(GL_COLOR_ARRAY)
        glEnableClientState(GL_VERTEX_ARRAY)
        glVertexPointer(3, GL_FLOAT, 0, self.verts)
        glColorPointer(4, GL_FLOAT, 0, self.colors)
        glBegin(GL_POINTS)
        for i in range(len(self.verts)):
            glArrayElement(i)
        glEnd()
        glDrawElements(GL_POINTS, len(self.verts), GL_UNSIGNED_INT,ind )
        glDrawArrays(GL_POINTS, 0, len(self.verts))
        glDisableClientState(GL_VERTEX_ARRAY)
        glDisableClientState(GL_COLOR_ARRAY)



    def get_visible(self, lst):
        '''Only draws the points sitting in front of the camera.
        Everything behind it is left undrawn.'''
        #works off a cube class that has all the points in it with methods to call information about dist, 
        to_use = []
        for point in lst:
            c = point.dist
            x,z = self.camera.project_move_other()
            b = self.camera.get_camera_distance(x, 0, z)
            a = point.get_dist(x, 0, z)
            angle = 0
            try:
                num = ((b**2)+(c**2)-(a**2))/(2*b*c)
                angle = math.acos(num)/math.pi*180
            except:
                pass
            if angle > 90:
                to_use.append(item)
        return to_use
Exemplo n.º 3
0
class RenderWorld:
    '''This is the class that renders maze.
    Camera angles are handled by Camera.py.
    '''
    
    WINDOW_WIDTH = 1000
    WINDOW_HEIGHT = 1000
    SCALE = 1
    X_FACTOR = 1
    Y_FACTOR = 1
    Z_FACTOR = 1
    SEA_LEVEL = 4
    HEIGHT_SCALE = 32

    def __init__(self, transaction):
        '''Sets up camera, modes, lighting, sounds, and objects.'''
        f = open(CONFIG)
        lines = f.read().split("\n")
        self.QUALITY = int(lines[0].split()[1])
        self.MAP_SIZE = int(lines[1].split()[1])
        self.SKYBOX_SIZE = float(lines[2].split()[1])/3
        self.HEIGHT_SCALE = int(float(lines[3].split()[1])*self.MAP_SIZE)
        f.close()
        
        self.set_up_convert()
        self.tex_holder = TextureHolder()
        self.index_list = []
        self.lock = threading.RLock()
        self.need_lists = False
        
        self.trans = transaction
        #self.skybox = Skybox((5000, 5000, 5000))
        #self.sky_index = self.skybox.createCallList(1, 3)
        #self.skybox = Skybox((len(self.heights[0])*self.X_FACTOR, self.Y_FACTOR, len(self.heights)*self.Z_FACTOR))
               
    def set_up(self):
        self.set_up_graphics()
        self.set_up_lighting()
        self.set_up_glut()
        water_path = 'data/textures/water/water.bmp'
        self.tex_holder.hold_my_texture(water_path, 'water')        
        self.camera = Camera(10,20,-10)
        
        self.curr_time = time.time()
        self.count = 0
        self.poly_view = False
        self.load_skybox()
        self.building_index_list = []
        #self.create_building(5,3,-5)


    def set_up_glut(self):
        glutIdleFunc(self.display)
        glutDisplayFunc(self.display)

        glutIgnoreKeyRepeat(GLUT_KEY_REPEAT_OFF)
        glutKeyboardFunc(self.keyPressed)
        glutKeyboardUpFunc(self.keyUp)

        glutSetCursor(GLUT_CURSOR_NONE)
        glutPassiveMotionFunc(self.mouseMove)

        #glGenLists(50)
        #glNewList(1, GL_COMPILE)
        #glNewList(1, GL_COMPILE)
    
    def start_loop(self):
        glutMainLoop()

    def to_gl(self, axis, oldnum):
        if axis == 'x':
            return self.convert.convert_for_triangle('x', oldnum)
        else:
            return self.convert.convert_for_triangle('z', oldnum)

    def create_render_newlist(self):
        self.need_lists = False
        new_list = []
        w_list = []
        #print "trying to render"
        #print self.trans.location_var
        for location, values in self.trans.location_var.items():
            #print "RENDERING IN OPEN GL", location
            tex_file_name, face_norms, vert_norms, heights, offsetx, offsetz, textname, textid = values
            #print vert_norms
            
            self.texture = self.tex_holder.hold_my_texture(tex_file_name, textname)
    
            #offsetx *= .995
            #offsetz *= .995 
            index = glGenLists(1)
            glNewList(index, GL_COMPILE)
            #print "new texture applied"
            self.tex_holder.applyTexture(self.texture)
            zdivide = float(self.MAP_SIZE)
            xdivide = float(self.MAP_SIZE)
            #go by rows
            for z in range(len(heights)-1):
                glBegin(GL_TRIANGLE_STRIP)
                for x in range(len(heights[z])):
                    #start at (0,1)
                    point1x = self.to_gl('x', x)    #first point x value in opengl coordinate
                    point1z = self.to_gl('z', z+1)  #first point z value in opengl coordinate
                    
                    glTexCoord2f(point1x/xdivide, -point1z/zdivide)
                    #print "f1:", point1x/divide, "f2:", -point1z/divide

                    pt = (point1x+offsetx, heights[x][z+1], point1z-offsetz)
                    m_point = (point1x, heights[x][z+1], point1z)
                    norm = vert_norms[m_point]
                    glNormal3f(norm[0],norm[1],norm[2])
                    glVertex3f(pt[0],pt[1],pt[2])
                    #############################################
                    #second point (0,0)

                    point2x = self.to_gl('x',x)     #second point x value in opengl coordinate
                    point2z = self.to_gl('z',z)     #second point z value in opengl coordinate
                    
                    glTexCoord2f(point2x/xdivide, -point2z/zdivide)

                    #print "f1:", point2x/divide, "f2:", -point2z/divide

                    pt = (point2x+offsetx, heights[x][z], point2z-offsetz)
                    m_point = (point2x, heights[x][z], point2z)
                    norm = vert_norms[m_point]
                    glNormal3f(norm[0],norm[1],norm[2])
                    glVertex3f(pt[0],pt[1],pt[2])
                    
                glEnd()
            #print z
            glEndList()

            '''Water plane'''
            indexw = glGenLists(1)
            glNewList(indexw, GL_COMPILE)
            glDisable(GL_LIGHTING)
        

            self.tex_holder.applyTexture('water')
            tile_size = self.tex_holder.images['water'].size
            
            xlen = float(self.convert.gl_x)
            zlen = float(self.convert.gl_z)
            glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
            glEnable (GL_BLEND)
            glColor4f(1,1,1,.5)
            glBegin(GL_QUADS)

            glTexCoord2f(0, 0)
            glVertex3f(0+offsetx, self.convert.sea_level, 0-offsetz)

            glTexCoord2f(tile_size[0]/xlen/10, 0)
            glVertex3f(xlen+offsetx, self.convert.sea_level, 0-offsetz)

            glTexCoord2f(tile_size[0]/xlen/10, tile_size[1]/zlen/10)
            glVertex3f(xlen+offsetx, self.convert.sea_level, -zlen-offsetz)

            glTexCoord2f(0, tile_size[1]/zlen/10)
            glVertex3f(0+offsetx, self.convert.sea_level, -zlen-offsetz)
            glEnd()
            glDisable(GL_BLEND)
            glEnable(GL_LIGHTING)

            glEndList()
            
            new_list.append(index)
            w_list.append(indexw)


        self.land_index_list = new_list
        self.water_index_list = w_list
        #self.index_list = new_list

    def set_up_graphics(self):
        '''Sets up OpenGL to provide double buffering, RGB coloring,
        depth testing, the correct window size, perspective
        rendering/fulcrum clipping, and a title.'''
        glutInit()
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
        glutInitWindowSize(self.WINDOW_WIDTH, self.WINDOW_HEIGHT)
        glutCreateWindow('Terrains!')

        glMatrixMode(GL_PROJECTION)

        gluPerspective(45,1,.1,8000)
        glMatrixMode(GL_MODELVIEW)

        #glClearColor(.529,.8078,.980,0)
        glEnable(GL_NORMALIZE)

        glEnable (GL_DEPTH_TEST)

        glShadeModel(GL_SMOOTH)
        #glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)

        glEnable(GL_FOG)
        glFogi (GL_FOG_MODE, GL_EXP2)
        glFogfv (GL_FOG_COLOR, (.8,.8,.8,1))
        glFogf (GL_FOG_DENSITY, .02)
        glHint (GL_FOG_HINT, GL_FASTEST)
        self.last_time = 0
        #glEnable(GL_POINT_SMOOTH)
    
    def renderLightSource(self):
        '''Resets the light sources to the right position.'''
        glLightfv(GL_LIGHT0, GL_POSITION, self.diffuse_pos1)

    def set_up_lighting(self):
        self.diffuse_pos1 = (0,.5,-1,0)
        glLightfv(GL_LIGHT0, GL_DIFFUSE, (1, 1, 1, 1))
        glLightfv(GL_LIGHT0, GL_POSITION, self.diffuse_pos1)

        
        glLightfv(GL_LIGHT1, GL_AMBIENT, (1, 1, 1, .5))
        glLightfv(GL_LIGHT1, GL_POSITION, (1,1,1,1))

    def set_up_convert(self):
        #heightmap, texture, gl
        self.convert = Convert((1, 1, 1), (self.QUALITY, 1, self.QUALITY), (1*self.SCALE, self.HEIGHT_SCALE*self.SCALE, 1*self.SCALE), self.MAP_SIZE)
        

    def load_map(self, heightmap_filename):
        self.load = LoadTerrain(heightmap_filename, self.convert, self.tex_holder)
        self.heights = self.load.load()
        self.map_index = self.load.createRenderList(self.heights)

    def load_skybox(self):
        #self.skybox = Skybox((len(self.heights[0])*self.X_FACTOR, self.Y_FACTOR, len(self.heights)*self.Z_FACTOR))
        scale = (self.convert.gl_x+self.convert.gl_z)*self.SKYBOX_SIZE
        self.skybox = Skybox(self.tex_holder, (scale,scale,scale))
        self.sky_index = self.skybox.createCallList(1, 3)

    def create_building(self, x, y, z):
        self.load = Structure(self.tex_holder)
        self.building_index_list.append([self.load.create_structure(), (x,y,z)])
        print self.building_index_list

    def display(self, x=0, y=0):
        '''Called for every refresh; redraws the floor and objects
        based on the camera angle. Calls collision detection, handles
        the appropriate objects for keys, doors, etc.'''
        #print "loopdy loop"
        # print self.curr_time - time.time()
        f_rate = 1.0/60
        if self.last_time+f_rate <= time.time():
            self.last_time = time.time()

            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

            glLoadIdentity()        
            glDisable(GL_LIGHTING)
            self.camera.renderRotateCamera()
            glTranslate(-self.skybox.x/2, -1-self.camera.pos_Y, -self.skybox.z/2)
            glCallList(self.sky_index)

            if abs(self.curr_time - time.time()) >= 1:
                print "FPS:", self.count
                print time.time()
                self.count = 0
                self.curr_time = time.time()
            else:
                self.count+=1
        
            if self.need_lists:
                self.create_render_newlist()

            #self.lock.acquire()
                

            glLoadIdentity()
        #Put camera and light in the correct position
            self.camera.move()
            self.camera.renderRotateCamera()
            self.camera.renderTranslateCamera()

            glEnable(GL_LIGHTING)
            glEnable(GL_LIGHT0)
            glEnable(GL_LIGHT1)
            self.renderLightSource()
            
            for index in self.land_index_list:
            #print "INDEX:", index
                glCallList(index)

            for index in self.water_index_list:
                glCallList(index)

            for index in self.building_index_list:
                glCallList(index[0])
            
            
            glDisable(GL_TEXTURE_2D)
            glutSwapBuffers()

    def renderLightSource(self):
        '''Resets the light sources to the right position.'''
        if self.camera.pos_Y <= self.convert.sea_level:
            glLightfv(GL_LIGHT0, GL_DIFFUSE, (0, .2, 1, 1))
        else:
            glLightfv(GL_LIGHT0, GL_DIFFUSE, (1, 1, 1, 1))
        glLightfv(GL_LIGHT0, GL_POSITION, self.diffuse_pos1)

       
    def mouseMove(self, x, y):
        '''Called when the mouse is moved.'''
        factor = 3
        
        tmp_x = (self.camera.mouse_x - x)/factor
        tmp_y = (self.camera.mouse_y - y)/factor
        if tmp_x > self.camera.ROTATE:
            tmp_x = self.camera.ROTATE
        self.camera.rotate(tmp_y, tmp_x, 0)
        x = self.WINDOW_WIDTH/2
        y = self.WINDOW_HEIGHT/2
        glutWarpPointer(x, y)
        self.camera.mouse_x = x
        self.camera.mouse_y = y
        
    def keyPressed(self, key, x, y):
        '''Called when a key is pressed.'''
        if key.lower() in self.camera.keys:
            self.camera.keys[key.lower()] = True
        if glutGetModifiers() == GLUT_ACTIVE_SHIFT:
            self.camera.keys["shift"] = True
        if key == 'p' and not self.poly_view:
            glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
            self.poly_view = True
        elif key == 'p' and self.poly_view:
            glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
            self.poly_view = False
        elif key == 't':
            exit(9)
        if key.lower() == 'q':
            self.camera.WALK *= 1.2
            self.camera.SPRINT *= 1.2
        if key.lower() == 'e':
            self.camera.WALK *= .8
            self.camera.SPRINT *= .8

    def keyUp(self, key, x, y):
        '''Called when a key is released.'''
        self.camera.keys[key.lower()] = False
        if not glutGetModifiers() == GLUT_ACTIVE_SHIFT:
            self.camera.keys["shift"] = False
Exemplo n.º 4
0
class TestRender:
    '''This is the class that renders maze.
    Camera angles are handled by Camera.py.
    '''
    WINDOW_WIDTH = 700
    WINDOW_HEIGHT = 700
    SCALE = .5
    MAP_SIZE =100
    X_FACTOR = 1
    Y_FACTOR = 1
    Z_FACTOR = 1
    MAP_SIZE = 100
    SEA_LEVEL = 4

    def __init__(self):
        self.set_up_graphics()
        self.load_object()
	self.set_up_glut()
        self.camera = Camera(0,60,0)
	self.camera.rotate(-75,-150,0)
	self.poly_view = False	
        self.start_loop()


    def set_up_glut(self):
        glutIdleFunc(self.display)
        glutDisplayFunc(self.display)

        glutIgnoreKeyRepeat(GLUT_KEY_REPEAT_OFF)
        glutKeyboardFunc(self.keyPressed)
        glutKeyboardUpFunc(self.keyUp)

        glutSetCursor(GLUT_CURSOR_NONE)
        glutPassiveMotionFunc(self.mouseMove)
	
	#glGenLists(50)
	#glNewList(1, GL_COMPILE)
	#glNewList(1, GL_COMPILE)
    
    def start_loop(self):	
	glutMainLoop()

    def set_up_graphics(self):
        glutInit()
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
        glutInitWindowSize(self.WINDOW_WIDTH, self.WINDOW_HEIGHT)
        glutCreateWindow('Terrains!')

        glMatrixMode(GL_PROJECTION)

        gluPerspective(45,1,.1,500)
        glMatrixMode(GL_MODELVIEW)

        glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glEnable (GL_BLEND)
        
        
        glClearColor(.529,.8078,.980,0)
        glEnable(GL_NORMALIZE)

        glEnable (GL_DEPTH_TEST)

        #glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
    
    def load_object(self):
        self.load = Structure()
        self.structure = self.load.create_structure()

    def load_object2(self):
        self.load = Grass()
        self.structure = self.load.create_grass_list()

    def display(self, x=0, y=0):

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()
        #Put camera and light in the correct position
        self.camera.move()
	self.camera.renderRotateCamera()
        self.camera.renderTranslateCamera()
        glCallList(self.structure)
	
        
        glDisable(GL_TEXTURE_2D)
        glutSwapBuffers()
       
    def mouseMove(self, x, y):
        '''Called when the mouse is moved.'''
        factor = 2
        
        tmp_x = (self.camera.mouse_x - x)/factor
        tmp_y = (self.camera.mouse_y - y)/factor
        if tmp_x > self.camera.ROTATE:
            tmp_x = self.camera.ROTATE
        self.camera.rotate(tmp_y, tmp_x, 0)
        x = self.WINDOW_WIDTH/2
        y = self.WINDOW_HEIGHT/2
        glutWarpPointer(x, y)
        self.camera.mouse_x = x
        self.camera.mouse_y = y
        
    def keyPressed(self, key, x, y):
        '''Called when a key is pressed.'''
        if key.lower() in self.camera.keys:
            self.camera.keys[key.lower()] = True
        if glutGetModifiers() == GLUT_ACTIVE_SHIFT:
            self.camera.keys["shift"] = True
        if key == 'p' and not self.poly_view:
            glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
            self.poly_view = True
        elif key == 'p' and self.poly_view:
            glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
            self.poly_view = False
        elif key == 't':
            exit(0)
        if key.lower() == 'q':
            self.camera.WALK *= 1.2
            self.camera.SPRINT *= 1.2
        if key.lower() == 'e':
            self.camera.WALK *= .8
            self.camera.SPRINT *= .8

    def keyUp(self, key, x, y):
        '''Called when a key is released.'''
        self.camera.keys[key.lower()] = False
        if not glutGetModifiers() == GLUT_ACTIVE_SHIFT:
            self.camera.keys["shift"] = False
Exemplo n.º 5
0
class LivePlot(pyglet.window.Window):
    ## Setup Functions --------------------------------------------------------
    def __init__(self, server, *args, **kwargs):
        super(LivePlot, self).__init__(*args, **kwargs)
        
        self.keyboard = key.KeyStateHandler()
        self.push_handlers(self.keyboard)
        
        self.setup_context()
        self.setup_scene()

        self.frequency = 60.5
        pyglet.clock.schedule_interval(self.step, 1/self.frequency)
        
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect(server)

    def setup_context(self):
        glClearColor(0, 0, 0, 1)

        glEnable(GL_DEPTH_TEST)
        glDepthMask(GL_TRUE)
        
        glDisable(GL_CULL_FACE)

        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        #glEnable(GL_MULTISAMPLE_ARB)
        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
        
        glEnable(GL_POLYGON_SMOOTH)
        glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST)
        glEnable(GL_POINT_SMOOTH)
        glHint(GL_POINT_SMOOTH_HINT, GL_NICEST)
        
        #glEnable(GL_LINE_SMOOTH)
        #glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)

    def setup_scene(self):
        self.fps = []
        self.fps_display = pyglet.text.Label(
                '',
                font_name = 'Courier', font_size = 16, bold = True,
                color = (255, 255, 255, 100),
                x = 5, y = 0,
                anchor_x = 'left', anchor_y = 'bottom'
        )
        
        self.camera_mode_display = pyglet.text.Label(
                '',
                font_name = 'Courier', font_size = 16, bold = True,
                color = (255, 255, 255, 200),
                x = 0, y = 0,
                anchor_x = 'right', anchor_y = 'bottom'
        )

        self.camera = Camera(50, [[1],[1],[3000]])
        self.set_exclusive_mouse(True)
        self.camera.look_at(np.array([[0],[0],[0]]))

        self.cameras = []
        self.markers = []
        
        self.cur_view = -1

        self.batch        = pyglet.graphics.Batch()
        self.background   = pyglet.graphics.OrderedGroup(0)
        self.foreground   = pyglet.graphics.OrderedGroup(1)
        
        self.floor_grid   = self.batch.add(1, pyglet.gl.GL_LINES,  self.background, 'v3f', 'c4f')
        self.axes         = self.batch.add(1, pyglet.gl.GL_LINES,  self.foreground, 'v3f', 'c4f')
        self.camera_cones = self.batch.add(1, pyglet.gl.GL_LINES,  self.foreground, 'v3f', 'c4f')
        self.markers      = self.batch.add(1, pyglet.gl.GL_POINTS, self.foreground, 'v3f', 'c4f')

        floor_grid = gridLines((-80000, -80000, 0), (160000, 160000, 0), (1000, 1000), [0.15, 0.15, 0.15, 1])
        self.floor_grid.resize(len(floor_grid[0]) // 3)
        self.floor_grid.vertices = floor_grid[0]
        self.floor_grid.colors   = floor_grid[1]
        
        axes = drawAxes((0, 0, 0), 1000)
        self.axes.resize(len(axes[0]) // 3)
        self.axes.vertices = axes[0]
        self.axes.colors   = axes[1]


    ## Step function, called every tick ---------------------------------------
    def step(self, dt):
        self.fps.append(1/dt)
        self.fps = self.fps[int(-self.frequency):]
        self.fps_display.text = '{:.2f}'.format(sum(self.fps)/len(self.fps))
        
        if self.camera.mode == Camera.FREE:
            self.camera_mode_display.text = "FREE"
        elif self.camera.mode == Camera.FOLLOW:
            self.camera_mode_display.text = "FOLLOW"
        elif self.camera.mode == Camera.XY:
            self.camera_mode_display.text = "XY"
        elif self.camera.mode == Camera.FIXED:
            self.camera_mode_display.text = "FIXED"
        
        ready,_,_ = select.select([self.sock], [], [], 0)
        #ready = False
        if ready:
            msg = getMessage(ready[0])

            for t,d in msg.iteritems():
                if t == "cameras":
                    self.cameras = d
                    self.camera.update_views(self.cameras)
                    
                    cone_color_cycle = [[1.0, 0.3, 0.3, 0.3], \
                                        [0.3, 1.0, 0.3, 0.3], \
                                        [0.3, 0.3, 1.0, 0.3]]
                    area_color_cycle = [[1.0, 0.3, 0.3, 0.5], \
                                        [0.3, 1.0, 0.3, 0.5], \
                                        [0.3, 0.3, 1.0, 0.5]]
                    
                    verts  = []
                    colors = []
                    for cam in d:
                        v,c = drawCameraCone(cam, cone_color_cycle[0], area_color_cycle[0])
                        verts  += v
                        colors += c
                        
                        cone_color_cycle = cone_color_cycle[1:] + cone_color_cycle[:1]
                        area_color_cycle = area_color_cycle[1:] + area_color_cycle[:1]
                    
                    self.camera_cones.resize(len(verts) // 3)
                    self.camera_cones.vertices = verts
                    self.camera_cones.colors   = colors
                        
                elif t == "markers":
                    markers = []
                    for m in d:
                        markers += list(m['mark'])
                        
                    self.markers.resize(len(d))
                    self.markers.vertices = markers
                    self.markers.colors   = [0, 0, 1, 1] * len(d)
        
        
        vc = np.array([[6000 * dt], [6000 * dt], [6000 * dt]])
        vc *= np.array([[self.keyboard[key.W]      - self.keyboard[key.S]], \
                        [self.keyboard[key.D]      - self.keyboard[key.A]], \
                        [self.keyboard[key.LSHIFT] - self.keyboard[key.LCTRL]]])
        
        self.camera.translate(vc)

            
        # Hack for pyglet bug
        try:
            self.switch_to()
            self.dispatch_event('on_draw')
            self.flip()
        except AttributeError:
            pass


    ## Rendering --------------------------------------------------------------
    def render(self):
        w,h = self.get_size()
        self.camera.prerender(w, h)
        
        rot = time.time() * 0.5
        
        glLineWidth(1)
        glPointSize(10)
        glDisable(GL_DEPTH_TEST)
        self.batch.draw()
        
        self.camera.postrender()
        
    def render_2d(self):
        glMatrixMode(GL_PROJECTION)
        glPushMatrix()
        glLoadIdentity()
        
        w,h = self.get_size()
        glOrtho(0, w, 0, h, -1.0, 2.0)
        
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glLoadIdentity()
        
        ## Draw Text
        glDisable(GL_DEPTH_TEST)
        self.fps_display.draw()
        self.camera_mode_display.draw()
        glEnable(GL_DEPTH_TEST)
        
        glPopMatrix()
        
        glMatrixMode(GL_PROJECTION)
        glPopMatrix()


    ## Events -----------------------------------------------------------------
    ## Input events
    def on_key_press(self, symbol, modifiers):
        pass
    
    def on_key_release(self, symbol, modifiers):
        if symbol == key.ESCAPE:
            self.close()
        elif symbol == key.F:
            if not self.fullscreen:
                pos = self.get_location()
                screens = pyglet.window.get_platform().get_default_display().get_screens()
                
                for s in screens:
                    if pos[0] >= s.x and \
                       pos[0] < s.x + s.width and \
                       pos[1] >= s.y and \
                       pos[1] < s.y + s.height:
                           screen = s
                           break
                    
                self.set_fullscreen(True, screen)
            else:
                self.set_fullscreen(False)
        elif symbol == key._1:
            self.camera.set_mode(Camera.FREE)
            self.set_exclusive_mouse(True)
        elif symbol == key._2:
            self.camera.set_mode(Camera.FOLLOW)
            self.set_exclusive_mouse(False)
        elif symbol == key._3:
            self.camera.set_mode(Camera.XY)
            self.set_exclusive_mouse(False)
        elif symbol == key._4:
            self.camera.set_mode(Camera.FIXED)
            self.set_exclusive_mouse(False)
        elif symbol == key.SPACE:
            self.camera.next_view()
    
    def on_mouse_motion(self, x, y, dx, dy):
        self.camera.rotate(-dx/700, dy/700)
    
    
    ## Window events
    def on_resize(self, width, height):
        glViewport(0, 0, width, height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        
        fov = 50
        aspect = width / height

        if width < height:
            fov = 360/math.pi * math.atan(math.tan(fov * math.pi/360) / aspect)
                    
        gluPerspective(fov, aspect, 0.1, 200000)
        
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        
        # Update text labels
        self.camera_mode_display.x = width - 5

        return pyglet.event.EVENT_HANDLED

    def on_draw(self):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        
        self.render()
        self.render_2d()